Speculative Decoding Guide¶
This guide shows how to use Speculative Decoding with vLLM Ascend. Speculative decoding is a technique which improves inter-token latency in memory-bound LLM inference.
Overview¶
vLLM Ascend implements speculative decoding through a proposer-verifier architecture:
- Proposer (
vllm_ascend/worker/v2/spec_decode/): Generates draft (speculative) tokens using various methods — from simple n-gram matching to neural-network-based draft models. - Rejection Sampler (
vllm_ascend/worker/v2/spec_decode/): Verifies draft tokens against the target model's output, accepting matches and rejecting mismatches, with optional block verification configured throughspeculative_config.rejection_sample_method.
The following speculative decoding methods are supported:
| Method | Description |
|---|---|
ngram |
Match n-grams from the prompt |
medusa |
Medusa heads embedded in the target model |
eagle |
EAGLE-based draft model |
eagle3 |
EAGLE-3 based draft model |
mtp |
Multi-Token Prediction with shared embedding head |
dflash |
Block diffusion-based parallel draft model |
dspark |
Semi-autoregressive block drafting with a sequential Markov logit-bias head |
draft_model |
Generic external draft LLM |
extract_hidden_states |
Extract hidden states for EAGLE training |
Common Configuration¶
All speculative decoding methods are configured through the speculative_config parameter when initializing the model or starting the server:
method(str, required): The speculative decoding method. Must be one of the supported method names listed in the table above.num_speculative_tokens(int, required): Number of speculative tokens to generate per forward pass. Auto-filled from the draft model'sn_predictconfig (e.g., MTP) when available. > Note: For PD Separation deployment,num_speculative_tokensshould be subject to one of the following conditions: > > 1. Hybrid Mamba models (e.g., Qwen-Next and Qwen3.5 series):num_speculative_tokensshould be equal on P nodes and D nodes. > 2. Other models:num_speculative_tokenson P nodes should be 1, andnum_speculative_tokenson D nodes should be greater or equal to 1.model(str, optional): Path or HF repo ID for the draft model. Required foreagle,eagle3,dflash,medusa, anddraft_model. Automatically resolved formtp(reuses target model),ngram, andextract_hidden_states.draft_tensor_parallel_size(int, optional): Tensor parallelism size for the draft model. Can only be1or the same as the target model's tensor parallel size.disable_padded_drafter_batch(bool, default:False): Disable input padding for speculative decoding. If set toTrue, speculative input batches can contain sequences of different lengths, which may only be supported by certain attention backends. Note: Only effective witheagle,eagle3,mtp,dflash,draft_model, andextract_hidden_statesmethods.
Offline inference — pass speculative_config as a Python dict to LLM():
from vllm import LLM
llm = LLM(
model="path/to/target/model",
speculative_config={
"method": "eagle3",
"model": "path/to/draft/model",
"num_speculative_tokens": 3,
},
)
Online serving — pass --speculative-config (or -sc) as a JSON string:
vllm serve path/to/target/model \
--speculative-config '{"method": "eagle3", "model": "path/to/draft/model", "num_speculative_tokens": 3}'
Note
On Ascend NPUs, the npu_fused_infer_attention_score operator supports a maximum of 16 tokens per decode round. Therefore, (num_speculative_tokens + 1) must be ≤ 16.
Speculating by matching n-grams in the prompt¶
The following code configures vLLM Ascend to use speculative decoding where proposals are generated by matching n-grams in the prompt.
-
Offline inference
from vllm import LLM, SamplingParams prompts = [ "The future of AI is", ] sampling_params = SamplingParams(temperature=0.8, top_p=0.95) llm = LLM( model="meta-llama/Meta-Llama-3.1-8B-Instruct", tensor_parallel_size=1, speculative_config={ "method": "ngram", "num_speculative_tokens": 5, "prompt_lookup_max": 4, }, ) outputs = llm.generate(prompts, sampling_params) for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
Speculating using EAGLE based draft models¶
The following code configures vLLM Ascend to use speculative decoding where proposals are generated by an EAGLE (Extrapolation Algorithm for Greater Language-model Efficiency) based draft model.
-
Offline inference
from vllm import LLM, SamplingParams prompts = [ "The future of AI is", ] sampling_params = SamplingParams(temperature=0.8, top_p=0.95) llm = LLM( model="meta-llama/Meta-Llama-3.1-8B-Instruct", tensor_parallel_size=4, distributed_executor_backend="mp", enforce_eager=True, speculative_config={ "method": "eagle", "model": "yuhuili/EAGLE-LLaMA3.1-Instruct-8B", "draft_tensor_parallel_size": 1, "num_speculative_tokens": 2, }, ) outputs = llm.generate(prompts, sampling_params) for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") -
Online inference
A few important things to consider when using the EAGLE based draft models:
-
The EAGLE draft models available in the HF repository for EAGLE models should be loaded and used directly by vLLM. This functionality was added in PR #4893. If you are using a vLLM version released before this pull request was merged, please update to a more recent version.
-
The EAGLE based draft models need to be run without tensor parallelism (i.e. draft_tensor_parallel_size is set to 1 in
speculative_config), although it is possible to run the main model using tensor parallelism (see example above). -
When using EAGLE-3 based draft model, option "method" must be set to "eagle3". That is, to specify
"method": "eagle3"inspeculative_config. -
After enabling EAGLE, the main model needs to verify
(1 + K)tokens generated by the main model and the draft model in one decoding process. And the fullgraph mode will fix the number of tokens during the verification stage, socudagraph_capture_sizesmust be a list of capture sizes, where each size is calculated asn * (K + 1)for each batch sizenyou want to support. For instance, to support batch sizes from 1 to 4 withnum_speculative_tokens = 4,cudagraph_capture_sizesshould be set to[5, 10, 15, 20].
Speculating using MTP¶
MTP (Multi-Token Prediction) boosts inference performance by parallelizing the prediction of multiple tokens, shifting from single-token to multi-token generation. This approach significantly increases generation throughput and achieves multiplicative acceleration in inference speed — all without compromising output quality.
-
Offline inference
from vllm import LLM, SamplingParams prompts = [ "The future of AI is", ] sampling_params = SamplingParams(temperature=0.8, top_p=0.95) llm = LLM( model="deepseek-ai/DeepSeek-V3.2-Exp-W8A8", tensor_parallel_size=16, enable_expert_parallel=True, max_model_len=36768, max_num_seqs=10, quantization="ascend", trust_remote_code=True, gpu_memory_utilization=0.9, compilation_config={"cudagraph_mode": "FULL_DECODE_ONLY"}, speculative_config={ "method": "mtp", "num_speculative_tokens": 2, "disable_padded_drafter_batch": False, }, ) outputs = llm.generate(prompts, sampling_params) for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") -
Online inference
vllm serve /deepseek-ai/DeepSeek-V3.2-Exp-W8A8 \ --port 20004 \ --data-parallel-size 1 \ --tensor-parallel-size 16 \ --enable-expert-parallel \ --seed 1024 \ --served-model-name dsv3 \ --max-model-len 36768 \ --max-num-batched-tokens 5000 \ --max-num-seqs 10 \ --quantization ascend \ --trust-remote-code \ --gpu-memory-utilization 0.9 \ --compilation-config '{"cudagraph_mode": "FULL_DECODE_ONLY"}' \ --speculative-config '{"num_speculative_tokens": 2, "method":"mtp", "disable_padded_drafter_batch": false}'
Note
Due to the fact that only a single layer of weights is exposed in DeepSeek's MTP, accuracy and performance are not effectively guaranteed in scenarios where num_speculative_tokens > 1 (especially ≥ 3).
In the fullgraph mode with num_speculative_tokens > 1, the capture size of each ACLGraph must be an integer multiple of (num_speculative_tokens + 1).
Speculating using DFlash¶
The following code configures vLLM Ascend to use speculative decoding where proposals are generated by a DFlash block diffusion-based parallel draft model.
-
Offline inference
from vllm import LLM, SamplingParams from vllm.config import CompilationConfig prompts = [ "The future of AI is", ] sampling_params = SamplingParams(temperature=0.8, top_p=0.95) llm = LLM( model="Qwen/Qwen3-8B", tensor_parallel_size=1, distributed_executor_backend="mp", max_model_len=4096, max_num_seqs=16, gpu_memory_utilization=0.8, enable_prefix_caching=False, speculative_config={ "method": "dflash", "model": "z-lab/Qwen3-8B-DFlash-b16", "num_speculative_tokens": 7, }, compilation_config=CompilationConfig(cudagraph_mode="FULL_DECODE_ONLY"), ) outputs = llm.generate(prompts, sampling_params) for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") -
Online inference
vllm serve Qwen/Qwen3-8B \ --tensor-parallel-size 1 \ --max-model-len 4096 \ --max-num-seqs 256 \ --gpu-memory-utilization 0.8 \ --no-enable-prefix-caching \ --compilation-config '{"cudagraph_mode": "FULL_DECODE_ONLY"}' \ --speculative-config '{"method": "dflash", "model": "z-lab/Qwen3-8B-DFlash-b16", "num_speculative_tokens": 7}'
Speculating using DFlash2¶
The following code configures vLLM Ascend to use speculative decoding where proposals are generated by a DFlash2 draft model. DFlash2 keeps DFlash's parallel block-drafting input layout, but instead of taking the per-position argmax token, the draft proposes a top-k candidate set for every draft position and a candidate-selector head walks the highest-scoring path through the candidate lattice.
There is no separate dflash2 method value: keep "method": "dflash" — when
the draft checkpoint's architecture is DFlash2DraftModel (e.g.
z-lab/Qwen3.8-27B-DFlash2), the DFlash2 drafter is selected automatically.
-
Offline inference
from vllm import LLM, SamplingParams from vllm.config import CompilationConfig prompts = [ "The future of AI is", ] sampling_params = SamplingParams(temperature=0.8, top_p=0.95) llm = LLM( model="Qwen/Qwen3.8-27B", tensor_parallel_size=2, max_model_len=2048, gpu_memory_utilization=0.9, enable_prefix_caching=False, speculative_config={ "method": "dflash", "model": "z-lab/Qwen3.8-27B-DFlash2", "num_speculative_tokens": 8, }, compilation_config=CompilationConfig( cudagraph_mode="PIECEWISE", cudagraph_capture_sizes=[9] ), ) outputs = llm.generate(prompts, sampling_params) for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") -
Online inference
vllm serve Qwen/Qwen3.8-27B \ --tensor-parallel-size 2 \ --max-model-len 2048 \ --max-num-seqs 16 \ --gpu-memory-utilization 0.9 \ --no-enable-prefix-caching \ --compilation-config '{"cudagraph_mode": "PIECEWISE", "cudagraph_capture_sizes": [9]}' \ --speculative-config '{"method": "dflash", "model": "z-lab/Qwen3.8-27B-DFlash2", "num_speculative_tokens": 8}'
How it works¶
Each decode step drafts one block of num_speculative_tokens tokens in
parallel, exactly like DFlash: one bonus query (the last verified token,
the anchor) followed by K masked queries.
- The draft model runs the block in one forward pass. Its decoder layers wrap the attention and MLP sublayers with learned block-causal grouped convolutions that mix information across the K+1 query positions.
- The draft's hidden states go through the target model's LM head
(shared, unquantized): the full-vocabulary logits are top-k'd per draft
position, giving
selector_top_kcandidate tokens per step. - A candidate selector head scores every edge of the candidate lattice: a per-candidate unary logit plus a bilinear term between predecessor and successor token codebooks and the projected hidden state.
- A path walk picks the highest-scoring chain of candidates starting from the anchor token — greedily, or with Gumbel-max sampling at the request temperature when probabilistic draft sampling is enabled. The selected path's scores are also scattered back into full-vocabulary draft logits for the rejection sampler.
A few important things to consider when using DFlash2 draft models:
-
Draft sampling: DFlash2 drafts greedily by default. Set
"draft_sample_method": "probabilistic"to sample the draft path at the request temperature. LM-head TP does not support probabilistic draft sampling:vllm serve Qwen/Qwen3.8-27B \ --tensor-parallel-size 2 \ --max-model-len 2048 \ --max-num-seqs 1 \ --no-enable-prefix-caching \ --compilation-config '{"cudagraph_mode":"FULL_DECODE_ONLY","cudagraph_capture_sizes":[9]}' \ --speculative-config '{"method": "dflash", "model": "z-lab/Qwen3.8-27B-DFlash2", "num_speculative_tokens": 8}' -
Draft graphs: DFlash2 supports full ACL graphs when the target enables
FULL_DECODE_ONLYorFULL_AND_PIECEWISEand the draft'senforce_eageris unset or false. -
Graph capture sizes: each decode step runs
(1 + K)tokens per request, so every capture size must ben * (num_speculative_tokens + 1)for each batch sizenyou want to support —[9]above, for batch size 1 withnum_speculative_tokens = 8. Fornum_speculative_tokensof 4, 5, or 6, use multiples of 5, 6, or 7, respectively. Choose a draft length supported by the checkpoint. -
The draft must use the target's unquantized LM head: the candidate top-k is taken over the full-vocabulary logits, so a reduced draft vocabulary is not supported.
-
The selector parameters (
selector_top_k,selector_rank, ...) come from the draft checkpoint'sdflash_configand need no user configuration.
Speculating using LiLiCorr¶
LiLiCorr is a DFlash variant that reranks the per-position top-k candidate
lattice before target-model verification. It requires a dedicated
LiLiCorrDraftModel checkpoint trained for the target model; a regular DFlash
or DFlash2 checkpoint cannot be substituted. The configured
num_speculative_tokens should equal the checkpoint's trained block size minus
one (the example below assumes a block size of eight). Shorter lengths down to
one token are supported, but may reduce acceptance; measure them with your
checkpoint and workload. Longer lengths are unsupported.
LiLiCorr requires eager draft execution on Ascend. Set the nested speculative
enforce_eager option to true. The target model retains its independently
configured execution mode.
vllm serve <target-model> \
--tensor-parallel-size 1 \
--max-model-len 4096 \
--no-enable-prefix-caching \
--speculative-config '{"method":"dflash","model":"<matching-lilicorr-checkpoint>","num_speculative_tokens":7,"enforce_eager":true}'
Both the plain and convolutional LiLiCorr checkpoint variants are supported.
The real-weight CI test pairs Qwen/Qwen3.8-27B with the ModelScope draft
niannianxu/Qwen3.8-27B-LiLiCorr-block8-epoch0, using TP=2 and seven
speculative tokens. Both models are listed in the A2/A3 download catalog.
After the CI model-download job has populated the cache, run:
VLLM_USE_MODELSCOPE=True pytest -v \
tests/e2e/pull_request/two_card/model_runner_v2/test_qwen3_8_lilicorr.py
The test compares greedy output token IDs with target-only decoding for both draft sampling modes, exercises nonzero-temperature probabilistic drafting, and checks draft/acceptance metric consistency. Acceptance length is recorded for calibration; no unmeasured throughput or acceptance-rate threshold is set.
Standard tensor parallelism is supported. Fine-grained embedding/LM head TP
and PCP vocabulary weight sharding are currently unsupported; the candidate
path requires the standard TP vocabulary layout.
Use the checkpoint's own dflash_config values for candidate top-k and
convolution geometry; these values are part of the trained model and should
not be tuned at serving time.
Both draft_sample_method: "greedy" and "probabilistic" use the correlator's
conditional scores. Probabilistic drafting supplies the realized proposal
distribution to the rejection sampler and uses a separate random stream from
target sampling. Compare acceptance length and throughput for both modes with
your workload. Quantized draft projections require a quantization format
supported by Ascend; NVIDIA ModelOpt NVFP4 exports are not portable merely
because the upstream LiLiCorr loader accepts them.
For a latency comparison on NPU, use real checkpoint weights and run the same batch and sequence lengths without speculative decoding, with greedy drafts, and with probabilistic drafts. For example:
vllm bench latency --model <target-model> \
--batch-size 8 --input-len 1024 --output-len 128 \
--num-iters-warmup 5 --num-iters 30 --output-json lilicorr-latency.json \
--speculative-config '{"method":"dflash","model":"<matching-lilicorr-checkpoint>","num_speculative_tokens":7,"enforce_eager":true,"draft_sample_method":"probabilistic"}'
Repeat at the production batch sizes and context lengths, keeping TP size, target execution mode, and prefix caching settings fixed. Measure acceptance length and serving throughput alongside latency; synthetic prompts alone do not establish the production speedup.
Speculating using DSpark¶
The following code configures vLLM Ascend to use speculative decoding where proposals are generated by a DSpark semi-autoregressive block drafter with a sequential Markov logit-bias head.
On 950DT Products, GLM (GlmMoeDsaForCausalLM) targets paired with
Qwen3DSparkModel GQA drafts can use the device-length CANN FlashAttn backend.
This requires FP16/BF16 queries and unquantized draft KV cache. When all draft
layers use FlashAttn, the runner can skip the speculative CPU length
synchronization; PP, PCP, DCP, KV transfer, sparse KV offload, and adaptive
verification retain their existing synchronization path.
For GQA draft heads of size 192, the backend zero-pads Q/K/V to 256 for the CANN kernel, keeps the original attention scale, and trims the output back to 192. Model weights and logical head sizes are unchanged. These draft KV cache pages use one third more storage than unpadded 192-wide pages, and padding adds work; this backend does not guarantee higher speculative acceptance rates.
GLM also supports DSpark with MLA drafts (Glm5DSparkForCausalLM), which can
use the device-length FlashMLA backend on the same hardware.
This requires FP16/BF16 queries and unquantized KV cache with matching dtype.
When the draft selects FlashMLA, the runner can skip speculative CPU length
synchronization under the same conditions as the GQA path; FIA fallback retains
exact CPU length synchronization.
FlashMLA currently requires local Q heads and local Q heads * DCP size in
{8, 12, 64, 96}, with latent/RoPE dimensions of 512/64. The 64-head GLM draft
therefore uses FIA at TP2/TP4. KV NZ and PCP are unsupported. When the target
KV cache is FP8, set "kv_cache_dtype": "bfloat16" in --speculative-config
for a BF16 draft.
Warning
When enable_adaptive_verification is enabled, vLLM Ascend does not support fully eager execution or pure PIECEWISE graph mode for the target model. The same restriction applies in vLLM.
In vLLM Ascend, adaptive verification cannot be combined with PP, PCP, DCP, LM head TP, or LoRA.
Commercial use is restricted.
-
Offline inference
from vllm import LLM, SamplingParams from vllm.config import CompilationConfig prompts = [ "The future of AI is", ] sampling_params = SamplingParams(temperature=0.8, top_p=0.95) llm = LLM( model="Qwen/Qwen3-8B", tensor_parallel_size=1, distributed_executor_backend="mp", max_model_len=4096, max_num_seqs=8, gpu_memory_utilization=0.8, enable_prefix_caching=False, speculative_config={ "method": "dspark", "model": "deepseek-ai/dspark_qwen3_8b_block7", "num_speculative_tokens": 7, "enforce_eager": True, }, compilation_config=CompilationConfig(cudagraph_mode="FULL_DECODE_ONLY"), ) outputs = llm.generate(prompts, sampling_params) for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") -
Online inference
vllm serve Qwen/Qwen3-8B \ --tensor-parallel-size 1 \ --max-model-len 4096 \ --max-num-seqs 8 \ --gpu-memory-utilization 0.8 \ --no-enable-prefix-caching \ --compilation-config '{"cudagraph_mode": "FULL_DECODE_ONLY"}' \ --speculative-config '{"method": "dspark", "model": "deepseek-ai/dspark_qwen3_8b_block7", "num_speculative_tokens": 7, "enforce_eager": true}'
Adaptive verification¶
Adaptive verification lets DSpark choose how many draft tokens to verify for each request at every decode step. Requests with higher confidence can keep a longer draft, while low-confidence drafts are shortened to avoid unnecessary target-model computation. It is disabled by default and requires a DSpark model with a confidence head.
Enable it in speculative_config:
vllm serve Qwen/Qwen3-8B \
--compilation-config '{"cudagraph_mode": "FULL_DECODE_ONLY"}' \
--speculative-config '{
"method": "dspark",
"model": "deepseek-ai/dspark_qwen3_8b_block7",
"num_speculative_tokens": 7,
"enable_adaptive_verification": true
}'
Hybrid Gated DeltaNet targets¶
The GDN path supports variable verification lengths, including steps that admit no draft tokens. Zero-draft decode requests retain the previous step's accepted-token offset so convolution and recurrent attention resume from the correct state. ACL Graph capture uses the same speculative path for one-token rows, and padding requests have zero-length GDN queries.
Adaptive GDN verification directly reuses vLLM's Triton recurrent implementation with a two-dimensional state table. Its row stride is independent of the current query length, so a one-token query can restore the state from an earlier step that accepted multiple tokens. The fixed-length path keeps the native recurrent operator. This adaptive path requires triton-ascend and is not supported by the 310P recurrent backend.
Ascend declares the device/host query-length mismatch capability and the bounded
variable-length decode graph capability in its own backend and metadata builder.
It does not depend on inheriting those declarations from upstream GDN classes.
The variable-length graph bound is 1 + num_speculative_tokens with adaptive
verification enabled; the 310P backend explicitly rejects this capability.
Use a matching vLLM revision with the strided recurrent API and adaptive-verification
initialization hooks and the convolution kernel interface used by the paired
vLLM checkout, together with a DSpark checkpoint
trained for the target model. For Qwen hybrid targets, including
Qwen3.8-27B, set num_speculative_tokens to the draft checkpoint's supported
length and enable enable_adaptive_verification as above. Keep full decode graphs
enabled; do not set the target's enforce_eager=True. M-RoPE positions continue
to use vLLM's model-state implementation and the compacted device query boundaries.
Ascend reuses vLLM's confidence estimates, cost profiling, budget allocator, and rejection sampler. Newer vLLM Triton budget allocators are used directly; legacy torch budget allocators run eagerly on Ascend. No change to sampling probabilities or model weights is required.
Validate each target/draft pair on the intended NPU and CANN version. Compare plain decoding, fixed-length DSpark, and adaptive DSpark with the same precision, TP size, concurrency, prompt/output lengths, and cache settings, after warmup. Check output quality and actual admitted draft counts as well as throughput. Adaptive GDN uses strided Triton convolution and recurrent updates with device query boundaries. This supports FULL-graph padding and a previously accepted block followed by a shorter verification query without copying the state cache. On A2, fixed verification queries of at least nine tokens also use the strided recurrent update as a workaround for native NaNs observed with BF16 and eight draft tokens. This threshold records the observed failing configuration, not a general hardware limit. A3 and A5 retain their native fixed-verification path; adaptive verification uses the strided path independently of this workaround. The fixed-path workaround can be removed after the replacement native operator stack passes the recurrent numerical and state-update regression tests on A2.
The FIA path copies admitted query boundaries back to the host for partial draft budgets. Full and zero budgets already have exact host boundaries and skip that synchronization; include the remaining synchronization cost in profiling. The upstream recurrent kernel may also have different performance from the native operator on each NPU generation; measure the complete target step, rather than inferring a speedup from the reduced verification token count alone.
Performance note (Ascend): The benefits of adaptive verification depend on the workload.
In low-latency scenarios, enabling adaptive verification may degrade performance.
In high-throughput scenarios (host), performance may degrade when the proxy or API server is the bottleneck.
In high-throughput scenarios (device), workloads with very high draft token acceptance rates may see no additional benefit.
Performance troubleshooting (Ascend):
- In high-throughput scenarios, performance gains from adaptive verification may sometimes fall short of expectations. In such cases, start by investigating the cause at the actual serving concurrency.
For DSpark on Ascend, DEBUG logs report scheduled and admitted draft counts,
confidence estimates, and the profiled verification costs. The Ascend runtime
configuration can reset worker logging to INFO; set
runtime_config.ascend_log.modules.vllm.logger to DEBUG in
--additional-config for a diagnostic run. Remove that override for performance
measurements. If the confidence head produces non-finite estimates, they are
treated as 1 for budget selection; compare adaptive outputs with fixed and
non-speculative outputs on NPU before relying on performance results.
For more details, see the vLLM community documentation.
Extracting Hidden States¶
The extract_hidden_states method is a special speculative decoding mode that does not perform actual speculation. Instead, it extracts hidden states from specified layers of the target model and saves them to disk. This is primarily used for collecting training data for EAGLE-style draft models. The dumps are then used to train EAGLE/EAGLE-3 drafts.
Note
This method produces only 1 output token per request. The primary output is the hidden states saved to disk, not the generated text.
-
Offline inference
import tempfile from safetensors import safe_open from vllm import LLM, SamplingParams def main(): with tempfile.TemporaryDirectory() as tmpdir: llm = LLM( model="Qwen/Qwen3-8B", tensor_parallel_size=1, speculative_config={ "method": "extract_hidden_states", "num_speculative_tokens": 1, "draft_model_config": { "hf_config": { # Layer indices to extract hidden states from "eagle_aux_hidden_state_layer_ids": [2, 18, 34], } }, }, kv_transfer_config={ "kv_connector": "ExampleHiddenStatesConnector", "kv_role": "kv_producer", "kv_connector_extra_config": { "shared_storage_path": tmpdir, }, }, ) prompts = ["Hello, how are you?", "What is machine learning?"] sampling_params = SamplingParams(max_tokens=1) outputs = llm.generate(prompts, sampling_params) for output in outputs: print("Prompt:", output.prompt) print("Prompt token ids:", output.prompt_token_ids) hidden_states_path = output.kv_transfer_params.get("hidden_states_path") print("Hidden states saved to:", hidden_states_path) with safe_open(hidden_states_path, "pt") as f: token_ids = f.get_tensor("token_ids") hidden_states = f.get_tensor("hidden_states") print("Shape:", hidden_states.shape) # Shape: (num_tokens, num_layers, hidden_size) if __name__ == "__main__": main() -
Online inference
For improved performance, it is recommended to use a RAM-mounted file system such as
/dev/shm/for online usage in which the client cleans up the files soon after they are generated.vllm serve Qwen/Qwen3-8B \ --tensor-parallel-size 1 \ --speculative-config '{"method": "extract_hidden_states", "num_speculative_tokens": 1, "draft_model_config": {"hf_config": {"eagle_aux_hidden_state_layer_ids": [2, 18, 34]}}}' \ --kv-transfer-config '{"kv_connector": "ExampleHiddenStatesConnector", "kv_role": "kv_producer", "kv_connector_extra_config": {"shared_storage_path": "/dev/shm/hidden_states"}}'
Key configuration parameters:
-
num_speculative_tokens: Must be set to1. This method does not perform actual speculation, so the value is fixed. -
eagle_aux_hidden_state_layer_ids: List of layer indices from which to extract hidden states. For example,[2, 18, 34]extracts from layers 2, 18, and 34. -
kv_connector: Must be set to"ExampleHiddenStatesConnector"to enable saving hidden states to disk. -
kv_role: Must be set to"kv_producer"for the extraction mode. -
shared_storage_path: Directory where hidden states will be saved as.safetensorsfiles (one per request).
Dynamic Speculative Decoding¶
Dynamic Speculative Decoding adapts the number of draft tokens (K) at runtime, instead of always using a fixed num_speculative_tokens. This helps keep speculative decoding beneficial as concurrency changes. vLLM Ascend provides one approach:
- Batch-size based (Autoregressive): select a shared K from concurrency ranges via
num_speculative_tokens_per_batch_size.
Batch-size based (Autoregressive)¶
This approach selects a shared speculative length K from the current concurrency (batch size). It is intended for autoregressive draft methods such as MTP, EAGLE / EAGLE-3, DFlash, and n-gram.
Why is it needed?¶
SD methods need to verify K tokens for each sequence during decoding. As batch size (BS) increases, the effective batch becomes BS * K, which increases the compute requirement during verification. When BS * K goes beyond a critical batch size, speculative decoding can hurt decode speed (TPOT). Batch-size based Dynamic SD tunes K to an optimal value so that speculative decoding remains beneficial.
Use cases¶
- Variable concurrency on the same deployment: K decreases as concurrency increases.
- RL rollout workloads that start with high BS and later shrink to a few long-tail requests: K can increase again toward the end of the rollout.
- Currently supports MTP, EAGLE-3, DFlash, n-gram, and similar methods. DSpark and
MTP + DCP + DSDare currently not supported on this path.
--speculative-config schema¶
To use Batch-size based Dynamic SD, add num_speculative_tokens_per_batch_size to the speculative config of a supported method. It is a list of lists, where each entry is [start_bs, end_bs, optimal_K]: when concurrency is within [start_bs, end_bs], optimal_K draft tokens are used. For example:
--speculative-config '{
"method": "eagle",
"model": "yuhuili/EAGLE-LLaMA3.1-Instruct-8B",
"num_speculative_tokens": 3,
"num_speculative_tokens_per_batch_size": [
[1, 64, 3],
[65, 128, 1],
[129, 512, 0]
]
}'
implies that:
- K=3 will be used when the concurrency is in range [1, 64]
- 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.
Online examples¶
Dynamic SD Eagle Drafter¶
vllm serve meta-llama/Llama-3.1-8B-Instruct \
--speculative-config '{
"method": "eagle",
"model": "yuhuili/EAGLE-LLaMA3.1-Instruct-8B",
"num_speculative_tokens": 3,
"num_speculative_tokens_per_batch_size": [
[1, 64, 3],
[65, 128, 1],
[129, 512, 0]
]
}'
Dynamic SD Eagle3 Drafter¶
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_per_batch_size": [
[1, 16, 5],
[17, 32, 4],
[33, 64, 3],
[65, 128, 1],
[129, 512, 0]
]
}'
Block Verification¶
Block verification jointly verifies a block of draft tokens using cumulative target-to-draft probability ratios and samples a recovery token from the corresponding residual distribution. This can increase the accepted draft length while preserving the target sampling distribution. Performance gains depend on the draft model and workload.
To enable block verification, set "rejection_sample_method": "block" in speculative_config, alongside your existing proposer settings. The default remains "standard"; omit this field or set it to "standard" to disable block verification.
Offline inference:
from vllm import LLM, SamplingParams
llm = LLM(
model="path/to/target/model",
speculative_config={
"method": "eagle3",
"model": "path/to/draft/model",
"num_speculative_tokens": 3,
"rejection_sample_method": "block",
},
)
outputs = llm.generate(["The future of AI is"], SamplingParams(temperature=0.8))
Online serving:
vllm serve path/to/target/model \
--speculative-config '{"method": "eagle3", "model": "path/to/draft/model", "num_speculative_tokens": 3, "rejection_sample_method": "block"}'
Block verification supports both greedy and probabilistic draft sampling. Target requests with temperature=0 retain greedy verification behavior. It cannot be combined with synthetic rejection sampling; do not set synthetic_acceptance_rates or synthetic_acceptance_length when using "block".
Entropy Verify¶
vLLM Ascend provides an optional optimization for the rejection sampler in speculative decoding: Entropy Verify. It trades a small amount of output precision for improved inference throughput.
Warning
Entropy Verify modifies the token acceptance criteria and may cause minor precision degradation (e.g., slightly different output tokens compared to the standard rejection sampler). Evaluate the quality impact on your specific workload before enabling them in production.
Enable Entropy Verify with additional_config.rejection_sampler_config.enable_entropy_verify=true.
Entropy Verify adjusts the acceptance threshold based on the entropy of the target distribution:
- High entropy (uncertain distribution) → lower effective threshold → more tokens accepted
- Low entropy (confident distribution) → higher effective threshold → stricter rejection
This entropy-aware threshold is controlled by two parameters:
posterior_threshold(default:0.95, range:(0, 1]): The upper bound of the modified threshold. Even when entropy is very low, the effective threshold will not exceed this value.posterior_alpha(default:0.4, range:>= 0): Controls how strongly entropy influences the threshold. A higher alpha makes the threshold more sensitive to entropy changes, resulting in a higher acceptance rate for speculative tokens but also greater precision loss. You need to tune this value based on your specific model and dataset. When alpha is0, entropy has no effect and the threshold equalsposterior_threshold.
Entropy is computed from the target logits after sampling parameters (such as temperature, top-k/top-p and penalties) are applied, for both raw and processed logprobs modes. Each draft position uses its own threshold min(exp(-entropy * posterior_alpha), posterior_threshold). Greedy requests retain their existing behavior, and synthetic rejection sampling uses its configured acceptance rates. Use Entropy Verify with rejection_sample_method="standard"; upstream "block" verification and Entropy Verify are mutually exclusive.
Usage¶
Keep your proposer configuration and add:
vllm serve <model> \
--speculative-config '{"method": "mtp", "num_speculative_tokens": 3, "rejection_sample_method": "standard"}' \
--additional-config '{"rejection_sampler_config": {"enable_entropy_verify": true, "posterior_threshold": 0.95, "posterior_alpha": 0.4}}'
Use a model with MTP support for this example, or retain your existing supported proposer settings. To disable Entropy Verify, set enable_entropy_verify to false (the default).
Experimental GLM KDA RecoverSSM¶
GLM-5.3-Flash supports experimental KDA RecoverSSM on A3 and A5. It reconstructs the accepted recurrent state after speculative decoding instead of keeping a recurrent checkpoint for every draft token. The default remains the native AscendC KDA path.
Enable this path with upstream vLLM's --use-replayssm option, which defaults
to disabled. See the vLLM serving CLI reference
and CacheConfig API reference
for the upstream option. Upstream describes Mamba2 ReplaySSM under this flag;
the GLM KDA behavior and requirements in this section are provided by the
Ascend integration.
Add the following options to your GLM serving command. Keep the parallelism, quantization, KV-cache dtype, and memory settings appropriate for your model and devices:
--use-replayssm \
--speculative-config '{"method": "deepseek_mtp", "num_speculative_tokens": 5}' \
--compilation-config '{"cudagraph_mode": "FULL_DECODE_ONLY"}'
RecoverSSM requires speculative decoding, PP=1 and DCP=1. PCP is limited to Prefill producers with TP=1; PCP Decode consumers and colocated PCP execution are not supported. Stochastic rounding must be disabled.
For direct prefill-to-decode transfer, use MooncakeConnectorV2 or
MooncakePullConnector with matching model weights, speculative window,
cache dtypes, convolution layout and RecoverSSM settings on both sides.
PCP producers may use a different KDA head-shard count from Decode consumers:
Mooncake gathers the producer head shards into each receiving consumer's state.
Use SD convolution state layout [state_len, conv_dim] on both roles when
their KDA head-shard counts differ.
For example, an eight-device Prefill role and an eight-device Decode role can
use the following layout with --use-replayssm and MTP5 on both sides:
| Setting | Prefill | Decode |
|---|---|---|
| Tensor parallel size | 1 | 1 |
| Prefill context parallel size | 8 | 1 |
| Data parallel size | 1 | 8 |
| Expert parallelism | Enabled (EP8) | Enabled (EP8) |
| KV role | kv_producer |
kv_consumer |
| Target and draft execution | Eager | FULL_DECODE_ONLY |
In this example, set --enforce-eager on Prefill and keep its draft eager as well. Each Decode
DP rank receives all eight KDA head shards for its assigned requests; DP ranks
do not divide one request's recurrent state. Keep the same prefix-caching
configuration on both roles.
PCP does not require --enforce-eager for the entire P model. Its KDA path has
an eager dispatch boundary, allowing the surrounding model to be compiled.
Validate the selected P graph configuration separately for your deployment.
For external prefix-cache storage and recovery with RecoverSSM, use
AscendStoreConnector with the Memcache or Mooncake backend. When combining
external prefix caching with direct prefill-to-decode transfer, use
MultiConnector to combine the Store connector with the transfer connector.
Follow the cache-layout and parallelism requirements in the
AscendStore deployment guide and, for Mooncake
layerwise hybrid pooling, the
hybrid attention guide.
Warning
This feature is experimental. Floating-point differences can change generated tokens; evaluate model accuracy and performance for your workload before use.
Removing --use-replayssm selects the native KDA path.
Synthetic Rejection Sampling¶
In addition to the default standard rejection sampling (which accepts a draft token when target_prob / draft_prob >= uniform), vLLM Ascend supports synthetic rejection sampling. In this mode each draft token at position i is accepted with a configured probability rates[i], compared against a uniform random draw — independent of the target/draft probability match. The first rejected position stops the request and emits a recovered token; if every draft token is accepted, the bonus token is appended.
Why use it¶
Synthetic mode decouples the verifier's acceptance logic from draft-model quality, letting you drive the speculative-decoding pipeline at a controlled, fixed acceptance rate. It is useful for:
- Benchmarking the verify path (kernel + sampler + token assembly) throughput/latency at a known acceptance rate, without depending on a well-trained drafter.
- Kernel validation — because acceptance reduces to
uniform < rate, the result is fully determined by the inputs. The e2e test compares the Ascend Triton kernel (SYNTHETIC_MODE=True) against the PyTorch reference under identical inputs, so the two must agree bit-for-bit. - Stress-testing the high-acceptance regime of the speculative pipeline.
Warning
Synthetic mode accepts draft tokens regardless of whether they match the target distribution, so the generated output is not semantically correct. Use it for benchmarking and validation only, never for production serving.
How to use¶
Synthetic mode is configured through speculative_config, alongside the proposer settings:
rejection_sample_method(str, default:"standard"): set to"synthetic"to enable.synthetic_acceptance_rates(list[float], optional): per-position acceptance rates. Must have lengthnum_speculative_tokens, each entry in[0, 1], and be monotonically non-increasing.synthetic_acceptance_length(float, optional): target mean acceptance length in[1, num_speculative_tokens + 1], resolved internally to an equivalentsynthetic_acceptance_ratesschedule. Mutually exclusive withsynthetic_acceptance_rates; exactly one must be provided whenrejection_sample_method == "synthetic".
Offline inference:
from vllm import LLM
llm = LLM(
model="path/to/target/model",
speculative_config={
"method": "eagle3",
"model": "path/to/draft/model",
"num_speculative_tokens": 3,
"rejection_sample_method": "synthetic",
"synthetic_acceptance_rates": [0.9, 0.6, 0.3],
},
)
Online serving:
vllm serve path/to/target/model \
--speculative-config '{"method": "eagle3", "model": "path/to/draft/model", \
"num_speculative_tokens": 3, "rejection_sample_method": "synthetic", \
"synthetic_acceptance_rates": [0.9, 0.6, 0.3]}'
Ascend-specific notes¶
Upstream vLLM's synthetic path draws the per-token uniform numbers with tl_rand64 (fp64) directly inside the Triton kernel. NPU Triton does not support tl_rand64/fp64, so vLLM Ascend reimplements synthetic mode in vllm_ascend/worker/v2/spec_decode/rejection_sampler_utils.py: the uniform draw is generated inside _probabilistic_rejection_kernel with SYNTHETIC_MODE=True, using a 1-element-block fp32 tl.rand clamped to [2^-31, 1) — equivalent to upstream's includes_zero=False semantics. Both greedy and sampling temperatures are supported, and the first rejected position is followed by a resampled/bonus token from the target distribution, as in standard mode.
The configuration interface (rejection_sample_method, synthetic_acceptance_rates, synthetic_acceptance_length) is shared with standard mode.