Speculative Decoding#

Speculative decoding is a technique for accelerating LLM inference at low batch sizes. A lightweight drafting mechanism proposes candidate tokens, and the target model verifies them in a single forward pass. Tokens that match are accepted, reducing the number of sequential forward passes needed.

Quick Start#

The maximum draft length is controlled by max_draft_len. EAGLE 3 and single-layer MTP-Eagle (use_mtp_vanilla=False) can optionally generate a dynamic draft tree with use_dynamic_tree=True. For supported linear drafting modes, advanced runtime controls can adjust draft length or disable speculation as the batch size or acceptance rate changes. See Advanced runtime controls for supported modes, examples, and current limitations.

Draft/Target#

Draft/target is the simplest form of speculative decoding. In this approach, an arbitrary draft model is used to produce draft tokens. It is important to make sure that the draft and target models were trained with the same tokenizer, else the acceptance rate is extremely low and performance is regressed.

from tensorrt_llm.llmapi import DraftTargetDecodingConfig

# Option 1: Use a HuggingFace Hub model ID (auto-downloaded)
speculative_config = DraftTargetDecodingConfig(
    max_draft_len=3, speculative_model="yuhuili/EAGLE3-LLaMA3.1-Instruct-8B")

# Option 2: Use a local path
# speculative_config = DraftTargetDecodingConfig(
#     max_draft_len=3, speculative_model="/path/to/draft_model")

llm = LLM("/path/to/target_model", speculative_config=speculative_config, disable_overlap_scheduler=True)

EAGLE 3#

The EAGLE 3 algorithm is described in the paper EAGLE-3: Scaling up Inference Acceleration of Large Language Models via Training-Time Test. By default, each request uses a single sequence (linear chain) of draft tokens with length max_draft_len. Optionally, dynamic tree draft generation can be enabled to improve acceptance rates — see Dynamic Tree Mode below.

The following draft model checkpoints can be used for EAGLE 3:

from tensorrt_llm.llmapi import Eagle3DecodingConfig

model = "meta-llama/Llama-3.1-8B-Instruct"
speculative_model = "yuhuili/EAGLE3-LLaMA3.1-Instruct-8B"

speculative_config = Eagle3DecodingConfig(
    max_draft_len=3,
    speculative_model=speculative_model)

llm = LLM(model, speculative_config=speculative_config)

EAGLE 3 can be combined with the Suffix Automaton enhancement for improved acceptance rates on repetitive content. See the SA section below for details.

Dynamic Tree Mode#

Dynamic tree mode enables tree-structured draft generation for EAGLE 3 and MTP-Eagle, where the drafter expands multiple candidate tokens at each layer instead of a single token. This can improve acceptance rates compared to linear drafting at the cost of additional compute per generation step.

With MTPDecodingConfig, dynamic trees require a checkpoint with exactly one MTP layer and use_mtp_vanilla=False (MTP-Eagle). Vanilla MTP and multi-layer MTP checkpoints do not support this dynamic-tree path. The MTP-Eagle dynamic-tree path supports greedy decoding only; non-greedy sampling is unsupported.

To enable dynamic tree mode, set use_dynamic_tree=True on Eagle3DecodingConfig or a supported MTP-Eagle MTPDecodingConfig and provide the following parameters:

  • use_dynamic_tree (bool): Enables dynamic tree draft generation.

  • dynamic_tree_max_topK (int): Maximum number of tokens to expand per node at each draft layer.

  • max_total_draft_tokens (int, optional): Total draft token budget for the tree. Must satisfy max_draft_len <= max_total_draft_tokens <= dynamic_tree_max_topK * max_draft_len. Defaults to dynamic_tree_max_topK * max_draft_len if not set.

When use_dynamic_tree=True, the dynamic tree CUDA buffers are pre-allocated based on the LLM’s max_batch_size, which is propagated internally and must not be passed directly to the speculative decoding configuration.

from tensorrt_llm.llmapi import Eagle3DecodingConfig

speculative_config = Eagle3DecodingConfig(
    max_draft_len=6,
    speculative_model="yuhuili/EAGLE3-LLaMA3.1-Instruct-8B",
    use_dynamic_tree=True,
    dynamic_tree_max_topK=10,
    max_total_draft_tokens=60,
)

llm = LLM("/path/to/target_model", speculative_config=speculative_config)

Note

Dynamic tree mode is currently not supported for models that use sliding window attention or MLA (Multi-Latent Attention), such as DeepSeek and gpt-oss models.

max_concurrency and draft_len_schedule support linear drafting only. Do not combine either option with use_dynamic_tree=True; the combination can fail during startup or CUDA graph warmup.

NGram#

Warning

NGram speculative decoding is deprecated and will be removed in January 2027. Use standalone Suffix Automaton speculative decoding (SADecodingConfig) instead.

The NGram method is an implementation of this Prompt Lookup Decoding algorithm.

When the NGram algorithm is used, TRT-LLM will maintain a map from token prefixes to candidate draft sequences. For example, the 3-gram [“The “, “ future “, “ is”] could map to the draft sequence [” bright”, “ because”]. The prefixes are token sequences that are extracted from the prompt and the tokens generated by the target model. The NGram pool and matching procedure can be tuned with the following options:

  • max_draft_len: Maximum draft candidate length.

  • max_matching_ngram_size: Maximum prompt suffix length to match with keys in the pool.

  • is_public_pool: If true, a single ngram pool is shared for all requests. Otherwise, each request has its own ngram pool.

  • is_keep_all: If true, draft candidates will be retained in the pool forever. Otherwise, only the largest draft candidate is retained.

  • is_use_oldest: If true, the oldest draft candidate is always proposed for a given match. Otherwise, the newest draft candidate is used. Only applicable if is_keep_all == True because is_keep_all == False means we’ll only ever have a single value for each key.

from tensorrt_llm.llmapi import NGramDecodingConfig

speculative_config = NGramDecodingConfig(
    max_draft_len=3, max_matching_ngram_size=4, is_public_pool=True)

llm = LLM("/path/to/target_model", speculative_config=speculative_config, disable_overlap_scheduler=True)

MTP#

MTP is supported by DeepSeek models and other architectures that ship native MTP modules, including Qwen3.8 MoE, Qwen3.5 MoE, and Step-3.x. MTP can be tuned with the following configuration options:

  • max_draft_len: Maximum draft candidate length.

  • num_nextn_predict_layers: Number of MTP modules to use. Currently must match max_draft_len.

  • use_relaxed_acceptance_for_thinking: If true, use relaxed decoding for reasoning models in the thinking phase. In this mode, speculation requirements are relaxed for the thinking phase - a draft token may be accepted if it appears in a candidate set constructed with relaxed_topk and relaxed_delta.

  • relaxed_topk: The top K tokens are sampled from the target model’s logits to create the initial candidate set for relaxed decoding.

  • relaxed_delta: Used to further filter the top K candidate set for relaxed decoding. We remove tokens t for which log(P(top 1 token)) - log(P(t)) > relaxed_delta.

from tensorrt_llm.llmapi import MTPDecodingConfig

speculative_config = MTPDecodingConfig(max_draft_len=3)

llm = LLM("/path/to/deepseek_model", speculative_config=speculative_config)

MTP can be combined with the Suffix Automaton enhancement for improved acceptance rates on repetitive content. See the SA section below for details.

PARD#

PARD (PARallel Draft) is a target-independent speculative decoding method that predicts all draft tokens in a single forward pass using mask tokens. Unlike MTP or EAGLE 3 which generate drafts one token at a time, PARD produces K draft tokens in parallel.

Reference: PARD: Parallel Drafting for Speculative Decoding

  • max_draft_len: Maximum draft candidate length.

  • speculative_model: Path or HuggingFace model ID for the PARD draft model.

  • mask_token_id: Token ID used as the mask token for parallel prediction. If not set, it is read from the draft model config.

from tensorrt_llm.llmapi import PARDDecodingConfig

speculative_config = PARDDecodingConfig(
    max_draft_len=4, speculative_model="/path/to/pard_model")

llm = LLM("/path/to/target_model", speculative_config=speculative_config)

PARD can be combined with the Suffix Automaton enhancement for improved acceptance rates on repetitive content. See the SA section below for details.

DFlash#

DFlash is a target-dependent speculative decoding method that uses hidden states from specific target model layers as cross-attention context in the draft model to predict multiple draft tokens in parallel.

Reference: DFlash: Distilled Flash Speculative Decoding

  • max_draft_len: Maximum draft candidate length.

  • speculative_model: Path or HuggingFace model ID for the DFlash draft model.

  • mask_token_id: Token ID used as the mask token for parallel prediction. If not set, it is read from the draft model config.

  • target_layer_ids: List of target model layer indices whose hidden states are captured for cross-attention in the draft model. If not set, read from the draft model config.

  • attention_backend: Cross-attention backend for the draft model, independent of the drafter’s standard attention modules. "VANILLA" (the default) uses FlashAttention with a contiguous context K/V cache and runs anywhere. "TRTLLM" uses TRTLLM-Gen FMHA (via FlashInfer) over a paged context K/V cache held by the KV cache manager (see Draft KV cache) and supports SM100/SM103 only. "FA4" uses the flash-attn CuTe DSL kernels on the same paged cache and supports SM90 only.

from tensorrt_llm.llmapi import DFlashDecodingConfig

speculative_config = DFlashDecodingConfig(
    max_draft_len=4,
    speculative_model="/path/to/dflash_model",
    attention_backend="TRTLLM",
)

llm = LLM("/path/to/target_model", speculative_config=speculative_config)

DFlash draft KV cache#

With attention_backend="TRTLLM", TRTLLM target attention, and the default KVCacheManagerV2, the drafter’s layers are allocated in the target’s KV cache manager. Target and draft layers share one page table, so one KV budget covers both and each request’s draft pages are allocated, padded and freed with its target pages. The draft layers keep the drafter’s own dtype, so an FP8 target KV cache (kv_cache_config.dtype: fp8) is paired with a BF16 draft cache.

In disaggregated serving, direct worker launches require TRTLLM_DISAGG_SHARED_DRAFT_KV=1 (or auto, which shares wherever the layout allows it) on both the context and generation workers to enable shared draft-KV transfer. The disaggregated_mpi_worker launcher enables this setting automatically when its config lists both context and generation servers, both enable compatible speculation, and they shard attention alike: the same tensor_parallel_size, where enable_attention_dp counts as 1 because every rank keeps all KV heads. A config that lists only one side (for example, a context-only MPI world) leaves sharing off unless the variable is 1. A two-sided config with attention DP on both sides and different tensor_parallel_size values shards attention alike too, so it also shares; set TRTLLM_DISAGG_SHARED_DRAFT_KV=0 to keep separate draft KV caches.

When sharing is enabled, the context server’s draft pages are transferred to the generation server with the target pages, so the drafter starts generation with the prompt context instead of an empty one. This requires the draft layers to have the target’s rank-local KV-head count; the draft dtype and head dimension may differ, except that an NVFP4 target KV cache requires an identical draft layout unless both caches are K-only (MLA). Both servers must use the same layout.

Hybrid recurrent/attention targets whose cache manager opts in (Kimi K3) also hold a standalone DSpark drafter’s layers, after their own. In every case the drafter decides whether it shares: it declares whether its block attention reads the manager’s pages at the run’s tokens_per_block (DFlashForCausalLM.reads_managed_ctx_pages). By default only attention_backend="TRTLLM" does, at the page sizes its trtllm-gen kernels support; a drafter whose other backends read paged context declares that itself.

The drafter keeps a separate draft KV cache manager instead when any of the following applies: context parallelism larger than 1 (helix context parallelism is shared only with a drafter that reads a helix-sharded context), a per-layer KV-head count on the target or drafter, a specialized KV cache manager that does not opt in (for example, most hybrid Mamba models), Gemma 4 hybrid attention, or, in disaggregated serving, a draft layout that cannot be transferred with the target’s. When the layers are shared, the worker log reports target and draft KV layers share one KV cache manager at startup.

DFlash 2 is also supported. The same DFlashDecodingConfig can be used for DFlash 2; no extra arguments are required.

LiLiCorr checkpoints use the same DFlashDecodingConfig. The draft checkpoint selects LiLiCorr through architectures: ["LiLiCorrDraftModel"], dflash_config.projector_type: "lilicorr", or dflash_config.lilicorr_enabled: true. Its candidate scorer correlates the per-position top-k proposals before target verification. Load the matching target separately through LLM(model=...) and set speculative_model to the drafter. Both models must share the token vocabulary and embedding width; the captured target layers must match the drafter’s training. The drafter currently uses the generic GQA DFlash backbone; MLA and Laguna-specific draft layers require separate adapters.

Set max_draft_len to at most block_size - 1; for an eight-position checkpoint, use up to seven draft tokens. Projection quantization follows the checkpoint’s global or per-module metadata, including excluded modules. The loader accepts dense, FP8, NVFP4 and W4A16 NVFP4 projections. Backbone QKV projections must remain unquantized; checkpoints with quantized backbone QKV are rejected during loading. It preserves a checkpoint-owned output head when has_own_lm_head is set. Grouped convolutions are loaded when declared by the checkpoint. Draft attention is non-causal, including symmetric windows on sliding-attention layers; causal LiLiCorr checkpoints are rejected. The draft attention backend retains the hardware restrictions listed above.

LiLiCorr builds proposal rows along a greedy candidate path. With stochastic draft sampling, a sampled token can differ from the predecessor used to score the next row. Rejection sampling uses the actual proposal distributions, preserving the target distribution, but acceptance can decrease.

User-provided drafting#

Warning

User-provided drafting is deprecated and will be removed in January 2027.

A completely user-defined drafting method can be supplied with a UserProvidedDecodingConfig that includes

  • max_draft_len: Maximum draft candidate length.

  • drafter: An object of type Drafter that implements the prepare_draft_tokens method (see User-provided drafting 7.)

  • resource_manager: An optional ResourceManager object (see User-provided drafting 4.)

from tensorrt_llm.llmapi import UserProvidedDecodingConfig

speculative_config = UserProvidedDecodingConfig(
    max_draft_len=3, drafter=MyDrafter())

llm = LLM("/path/to/target_model", speculative_config=speculative_config)

Suffix Automaton (SA) Enhancement#

The Suffix Automaton (SA) is a model-free, GPU-based pattern-matching draft enhancer. It finds suffix matches in previously generated tokens and proposes draft tokens when the match is long enough. SA is very accurate when it matches (exact pattern repetition), while neural methods are better for novel content — combining them gives the best of both worlds.

SA can be combined with the following speculative decoding techniques:

  • MTP (MTPDecodingConfig)

  • EAGLE 3 (Eagle3DecodingConfig)

  • PARD (PARDDecodingConfig)

To enable SA combination, set sa_config=SAEnhancerConfig(...) on the speculative config. The threshold field controls the minimum suffix match length required to override the neural draft (default: 4).

from tensorrt_llm.llmapi import Eagle3DecodingConfig, SAEnhancerConfig

speculative_config = Eagle3DecodingConfig(
    max_draft_len=4,
    speculative_model="/path/to/eagle3_model",
    sa_config=SAEnhancerConfig(threshold=4))

llm = LLM("/path/to/target_model", speculative_config=speculative_config)

SA can also be used as a standalone speculative decoding technique via SADecodingConfig:

from tensorrt_llm.llmapi import SADecodingConfig

speculative_config = SADecodingConfig(max_draft_len=4)

llm = LLM("/path/to/target_model", speculative_config=speculative_config)

Advanced runtime controls#

Batch-size-based draft lengths#

These batch-size controls are advanced options; draft_len_schedule is an experimental developer interface. Use them with the mode and configuration restrictions below. max_concurrency and draft_len_schedule are mutually exclusive: configure one at startup, and the runtime selects the draft length for each scheduled batch.

Dynamic draft lengths are supported for the following linear drafting modes:

Configuration

Supported execution mode

MTPDecodingConfig

One-model MTP and MTP-Eagle

Eagle3DecodingConfig

One-model EAGLE 3

DraftTargetDecodingConfig

One-model draft/target

PARDDecodingConfig, DFlashDecodingConfig

PARD and DFlash

SADecodingConfig

Standalone Suffix Automaton (SA)

Here, one-model execution runs the target and drafter in one engine; it can still load a separate draft checkpoint. These controls do not provide support for legacy two-model execution paths. For EAGLE 3 and MTP, leave use_dynamic_tree=False.

Schedule keys are inclusive upper bounds on the scheduled batch size, including context and generation requests. The runtime uses the first key greater than or equal to the batch size. Above the largest key, the draft length is zero and speculation is disabled. For example:

speculative_config:
  decoding_type: Eagle3
  max_draft_len: 3
  speculative_model: /path/to/eagle3_model
  draft_len_schedule:
    4: 3
    8: 2

This uses three draft tokens at batch sizes 1–4, two at batch sizes 5–8, and disables speculation at batch size 9 and above. Speculation can resume when the batch size decreases.

Specify an explicit max_draft_len and a nonempty schedule. Keys must be positive integers, values must be nonnegative integers no greater than max_draft_len, and the smallest key must map exactly to max_draft_len. For example, max_draft_len: 4 with {8: 2, 32: 1} is rejected. With CUDA graphs enabled (cuda_graph_config is not None), setting a schedule automatically enables cuda_graph_config.enable_padding and merges its keys into cuda_graph_config.batch_sizes for graph coverage.

max_concurrency=N is a shortcut for a cutoff: for the supported modes above, it is translated to draft_len_schedule: {N: max_draft_len}. There are current limitations to this shortcut:

  • Set max_draft_len explicitly for MTP. If it is inferred later from the checkpoint, the translation is not repeated and the cutoff is ignored.

  • Rebuilding a translated configuration from serialized arguments loses the private translation marker and raises the mutual-exclusion error. This happens when applying model defaults (including Qwen3-Next, Qwen3.5, DeepSeek-V4, Nemotron-H, and Gemma 4) and when converting decoding_type: Eagle to Eagle3. Use an explicit draft_len_schedule with max_draft_len, and use Eagle3 directly.

For a cutoff at batch size four with three draft tokens, replace the example’s schedule with {4: 3} and keep max_concurrency unset. This avoids the shortcut’s translation limitations. For MTP, choose a max_draft_len supported by the checkpoint.

Other drafting configurations differ:

  • Deprecated NGram honors max_concurrency, but its drafter interprets schedule keys as lower bounds instead of the upper bounds described above. Do not use draft_len_schedule with NGram.

  • Deprecated user-provided drafting returns the supplied drafter unchanged. Fields on UserProvidedDecodingConfig are not forwarded to it; configure a custom Drafter directly and account for its schedule semantics.

  • DSpark does not implement these batch-size controls. Do not rely on either field to adjust or disable DSpark drafting.

Acceptance-rate cutoff#

For configurations that support disabling speculation, set both acceptance_rate_window_size=N (a positive integer) and acceptance_rate_threshold (between 0 and 1) to enable the rolling acceptance-rate cutoff. After at least N recorded samples, speculation is disabled permanently for that executor once the average of the latest N recorded acceptance ratios falls below the threshold. Unlike the batch-size cutoff, this does not re-enable speculation when conditions improve.

Warning

The cutoff can underestimate acceptance when a batch-size schedule shortens the draft: it can divide the accepted-token count by the larger reserved draft-token count instead of the number actually verified in that iteration. With the schedule above at batch size 5, accepting both verified draft tokens per request can therefore record 2/3. A window of 1 and a threshold of 0.9 then permanently disable speculation even though every verified draft token was accepted.

Dynamic trees have the same limitation: the recorded denominator can be the total tree-token budget rather than the verified path length. For example, accepting a complete six-token path in a 60-token tree can record 6/60, causing a threshold above 0.1 to permanently disable speculation.

Leave the acceptance-rate cutoff disabled when using dynamic trees, draft_len_schedule, or max_concurrency in the current implementation.

The feature is disabled when the window is unset or zero, or the threshold is unset. Model-specific restrictions still apply; for example, Kimi K3 helix rejects these acceptance-rate options.

Usage with trtllm-bench and trtllm-serve#

Note

Non-breaking: --config <file.yaml> is the preferred flag for passing a YAML configuration file. Existing workflows using --extra_llm_api_options <file.yaml> continue to work; it is an equivalent alias.

Speculative decoding options must be specified via --config config.yaml for both trtllm-bench and trtllm-serve. All speculative decoding options can be specified in this YAML file. An additional decoding_type option is used to specify the type of speculation to use. The available options are:

  • MTP

  • Eagle3

  • NGram (deprecated; use SA instead)

  • Draft_Target

  • PARD

  • DFlash

  • SA

Note: The PyTorch backend supports only Eagle3. decoding_type: Eagle is accepted as a backward-compatible alias for Eagle3, but EAGLE (v1/v2) draft checkpoints are incompatible.

The rest of the argument names/valid values are the same as in their corresponding configuration class described in the Quick Start section. For example, a YAML configuration could look like this:

# Using a HuggingFace Hub model ID (auto-downloaded)
speculative_config:
  decoding_type: Eagle3
  max_draft_len: 4
  speculative_model: yuhuili/EAGLE3-LLaMA3.1-Instruct-8B
# Or using a local path
speculative_config:
  decoding_type: Eagle3
  max_draft_len: 4
  speculative_model: /path/to/draft/model
# Dynamic tree mode
max_batch_size: 4
speculative_config:
  decoding_type: Eagle3
  max_draft_len: 6
  speculative_model: /path/to/eagle3_model
  use_dynamic_tree: true
  dynamic_tree_max_topK: 10
  max_total_draft_tokens: 60
# SA combination: enable Suffix Automaton enhancement with any supported technique
speculative_config:
  decoding_type: Eagle3
  max_draft_len: 4
  speculative_model: /path/to/draft/model
  sa_config:
    threshold: 4

Note

The field name speculative_model_dir can also be used as an alias for speculative_config.speculative_model. For example:

speculative_config:
  decoding_type: Eagle3
  max_draft_len: 4
  speculative_model_dir: /path/to/draft/model

DSpark attention projection precision#

TRTLLM_DSPARK_LINEAR_BACKEND=bf16|fp8 selects the attention projection precision of the embedded DeepSeek-V4 DSpark drafter. When unset, projections use FP8 on Rubin SM107 with TP=1 or attention DP, and BF16 otherwise. Set bf16 to use dequantized BF16 draft weights. An explicit fp8 selection requires TP=1 or attention DP; unsupported tensor-parallel mappings are rejected during initialization. Non-Rubin FP8 is opt-in and requires workload accuracy and acceptance-length validation. The variable applies only to DeepSeek-V4 drafters: DeepSeek-V4.1 DSpark always uses BF16 projections and rejects fp8.

Packed FP4 MLA wave planning#

TRTLLM_FP4_MLA_PACKED_WAVE_PLAN=1 enables the optional wave-simulation planner for packed FP4 MLA decode. The default is disabled (0); the rule-based split plan remains active. Validate end-to-end latency on the serving workload before enabling wave simulation.

Draft layer row picking#

On the first draft step of MTP-Eagle and single-layer EAGLE 3 one-model drafting, and on every MTP layer of vanilla MTP, a draft layer that supports it runs its attention on every input row (writing the draft KV cache of each) but the rest of the layer (norms, MLP or MoE) only on the one row per request the drafter reads: the last prompt row of a context request, the last accepted row of a generation request. Vanilla MTP does not pick rows under attention data parallelism, and MTP-Eagle does not pick them on the spec-decode fast paths. TLLM_SPEC_DISABLE_DRAFT_ROW_PICK=1 turns this off. The picked rows are numerically equivalent to the full layer’s but not bitwise identical for MoE draft layers, whose kernels may round differently at another row count, so an occasional draft token can differ.