Skip to navigation

Speculative Decoding

View as MarkdownOpen in Claude

Speculative decoding speeds up generation in NIM LLM and VLM by having a small, fast draft predict several tokens ahead, which the large target model then verifies in a single forward pass.

When the draft is right, you get multiple tokens for roughly the cost of one; when it is wrong, the target falls back to normal decoding, so output is never degraded. For a conceptual primer, refer to NVIDIA’s blog post An Introduction to Speculative Decoding for Reducing Latency in AI Inference.

The NIM_SPECDEC_* and NIM_DRAFT_MODEL_PATH controls apply to both vLLM and SGLang. Use the configuration keys and arguments supported by the inference engine in your image.

Key Terms

The following terms are used throughout this page:

  • Target model — the large, accurate model you are serving.
  • Draft — the small, fast predictor. It can be a separate model (EAGLE3), extra heads built into the target (MTP), or a histogram of matching token sequences in the prompt (n-gram).
  • Acceptance rate — the fraction of drafted tokens the target accepts. Higher is better; it is highly dependent on the workload (coding, math, writing, and so on).
  • Acceptance length — the average number of tokens accepted per step.

Speculative decoding uses more memory and computation to reduce latency. It helps most when a GPU has spare compute capacity, such as at low to moderate concurrency. Under saturated load with no spare compute, it can fail to improve throughput, and can reduce it. Always measure on your own traffic. Refer to Benchmark it Yourself.

How a NIM Chooses a Method

A model profile can include a default speculative-decoding method. The available methods depend on the model and backend:

  1. MTP (multi-token prediction) uses the prediction heads in the base model. It requires no separate model download.
  2. EAGLE3 uses a published NVIDIA draft with a useful acceptance rate for the model. The draft downloads through the same path as the checkpoint. Refer to NVIDIA’s published drafts: Speculative Decoding Modules collection. Confirm that the draft format is supported by the engine in your image.
  3. n-gram reuses token sequences from the prompt. It requires no separate model download.

The following table lists the native method identifiers:

MethodvLLM speculative_config.methodSGLang speculative_algorithm
n-gramngramNGRAM
MTPmtpNEXTN
EAGLE3eagle3EAGLE3

The shipped method is a supported, validated option, not necessarily the optimal one for your workload. Speculative-decoding performance is workload-specific, and an EAGLE3 draft tuned to your traffic will usually beat the default. You can override the built-in configuration or bring your own draft model at any time. Refer to Bring Your Own Draft Model. Memory footprint can also drive that choice: speculative decoding always costs extra GPU memory, and the amount differs sharply by method (refer to the note below the table).

The methods differ in what they load and how much extra GPU memory they need. The following table compares extra model and GPU memory cost:

MethodExtra ModelExtra GPU Memory
n-gramNoNegligible. It uses a histogram to find matching token sequences in the prompt.
MTPNoLow. It uses a few extra prediction heads on the target model.
EAGLE3Yes (a small draft)Higher. It uses a separate draft model with its own weights and KV cache.

Speculative decoding needs spare GPU memory. Every method drafts and verifies several tokens per step, so enabling it costs more memory than serving the target alone, and the extra footprint grows EAGLE3 >> MTP > n-gram (refer to the table above). Confirm the GPU has headroom before turning it on, especially for EAGLE3, whose separate draft model accounts for most of the cost. If you run out of GPU memory, reduce the KV cache size with NIM_KVCACHE_PERCENT, reduce concurrency, or use another method that needs less memory. The effective memory budget and allocation order depend on the backend and model. Refer to GPU memory troubleshooting.

Enable or Disable the Built-In Method

You can enable or disable speculative decoding at runtime with the same profile.

The profile sets the default. If the profile includes a speculative decoding configuration, NIM uses it. Otherwise, NIM serves without speculative decoding. NIM_SPECDEC_ENABLE overrides that default.

The following table describes the effect of each variable:

VariableValuesEffect
NIM_SPECDEC_ENABLEunset (default)Use the selected profile’s built-in speculative decoding configuration, if present.
1Enable speculative decoding if the profile includes a configuration or you supply one through NIM_SPECDEC_ARGS. If no configuration is available, NIM logs a warning and serves without speculative decoding.
0Force speculative decoding off for every profile.
NIM_SPECDEC_ARGSJSON objectOverride the built-in config (refer to Override the Built-In Configuration). Consumed only when speculative decoding is active; on its own it does not activate it.

To enable or disable the built-in method, complete the following steps:

  1. Optional: Leave NIM_SPECDEC_ENABLE unset to use the selected profile’s default.

  2. To force speculative decoding off for a profile that ships it on by default, set NIM_SPECDEC_ENABLE=0.

    export IMG=nvcr.io/nim/<org>/<nim>:<tag> # your NIM image
    export LOCAL_NIM_CACHE=~/.cache/nim
    mkdir -p "$LOCAL_NIM_CACHE"
    docker run --gpus all --shm-size=16GB \
    -e NGC_API_KEY \
    -e NIM_SPECDEC_ENABLE=0 \
    -v "$LOCAL_NIM_CACHE:/opt/nim/.cache" \
    -p 8000:8000 \
    $IMG
  3. Set NIM_SPECDEC_ENABLE=1 to force the built-in method on regardless of the profile’s default.

    A profile that ships an EAGLE3 draft stages the draft weights alongside the checkpoint, so they are cached with the model and present whether or not speculative decoding is active (the toggle only gates whether the draft is used). If NIM_DRAFT_MODEL_PATH specifies a remote URI, NIM downloads the draft at launch only when speculative decoding is active. An absolute local path requires no network access.

If the profile includes an EAGLE3 draft, download-to-cache caches the draft weights alongside the model checkpoint. NIM loads the draft locally at startup, so no network access is needed. If NIM_DRAFT_MODEL_PATH specifies a remote URI or the profile specifies a draft only through draft_uri, NIM normally fetches it at startup. Starting with release 2.1.7, NIM can load a cached draft_uri draft from Hugging Face without network access if the URI pins the draft to a full commit SHA. A draft at an absolute local path also requires no network access. For instructions to cache or use a local draft in an air-gapped deployment, refer to Profiles with a Speculative-Decoding Draft Model. Set NIM_SPECDEC_ENABLE=0 to serve without speculative decoding.

Override the Built-In Configuration

NIM_SPECDEC_ARGS is a JSON object containing runtime configuration keys for the selected backend. It overrides the model’s default speculative decoding configuration. Use it to tune parameters or switch methods (for example, force n-gram on a model that ships MTP).

The following examples reuse IMG and LOCAL_NIM_CACHE from Enable or Disable the Built-In Method. If you run these examples separately, export those values first. Run the argument setup and launch commands in the same Bash session.

To override the built-in configuration, complete the following steps:

  1. Set NIM_SPECDEC_ENABLE=1 so speculative decoding is active.

  2. Pass the override JSON in NIM_SPECDEC_ARGS.

    export NIM_SPECDEC_ARGS='{"speculative_config": "{\"method\": \"ngram\", \"num_speculative_tokens\": 3, \"prompt_lookup_max\": 4, \"prompt_lookup_min\": 1}"}'
    docker run --gpus all --shm-size=16GB \
    -e NGC_API_KEY \
    -e NIM_SPECDEC_ENABLE=1 \
    -e NIM_SPECDEC_ARGS \
    -v "$LOCAL_NIM_CACHE:/opt/nim/.cache" \
    -p 8000:8000 \
    $IMG

Configure Speculative Decoding for Model-Free Deployments

If the selected profile for a model-free deployment (NIM_MODEL_PATH) has no speculative decoding configuration, supply one through arguments for the inference engine in your image.

Use n-gram (No Draft Model)

Select the arguments for your backend. Then run the shared launch command to enable n-gram decoding without a draft model.

SPECDEC_ARGS=(--speculative-config '{"method": "ngram", "num_speculative_tokens": 3, "prompt_lookup_max": 4, "prompt_lookup_min": 1}')
docker run --gpus all --shm-size=16GB \
-e NGC_API_KEY \
-v "$LOCAL_NIM_CACHE:/opt/nim/.cache" \
-p 8000:8000 \
-e NIM_MODEL_PATH=hf://meta-llama/Llama-3.1-8B-Instruct \
$IMG \
"${SPECDEC_ARGS[@]}"

Use MTP (Model with Built-In MTP Heads)

Select the arguments for your backend. Then run the shared launch command for a model that includes MTP heads.

SPECDEC_ARGS=(--speculative-config '{"method": "mtp", "num_speculative_tokens": 1}')
docker run --gpus all --shm-size=16GB \
-e NGC_API_KEY \
-v "$LOCAL_NIM_CACHE:/opt/nim/.cache" \
-p 8000:8000 \
-e NIM_MODEL_PATH=ngc://<org>/<model>:<tag> \
$IMG \
"${SPECDEC_ARGS[@]}"

Bring Your Own Draft Model

EAGLE3 and other methods that use an external draft require a separate draft model. Set NIM_DRAFT_MODEL_PATH to the draft source and refer to the draft by its subdirectory name. Use the model key of --speculative-config on vLLM or --speculative-draft-model-path on SGLang. NIM stages the draft in that subdirectory and rewrites the reference to the local path before launch.

Like NIM_MODEL_PATH, NIM_DRAFT_MODEL_PATH accepts a URI with an ngc://, hf://, s3://, or gs:// prefix, or an absolute local path. NIM caches remote drafts and supports local paths in air-gapped deployments.

To bring your own draft model, complete the following steps:

  1. Set NIM_MODEL_PATH to the target model and NIM_DRAFT_MODEL_PATH to the draft source. Confirm that the draft format and context length are compatible with the target model and backend.

  2. Select the EAGLE3 arguments for your backend and use eagle3_draft as the subdirectory name. Then run the shared launch command.

    SPECDEC_ARGS=(--speculative-config '{"method": "eagle3", "model": "eagle3_draft", "num_speculative_tokens": 3}')
    docker run --gpus all --shm-size=16GB \
    -e NGC_API_KEY \
    -v "$LOCAL_NIM_CACHE:/opt/nim/.cache" \
    -p 8000:8000 \
    -e NIM_MODEL_PATH=hf://meta-llama/Llama-3.1-8B-Instruct \
    -e NIM_DRAFT_MODEL_PATH=hf://<org>/<your-eagle3-draft> \
    $IMG \
    "${SPECDEC_ARGS[@]}"

    The eagle3_draft name does not need to match the remote repository name. To override the draft on a model-specific NIM instead, set NIM_DRAFT_MODEL_PATH while speculative decoding is active (the profile’s default, or forced with NIM_SPECDEC_ENABLE=1). An explicit draft source takes precedence over the one shipped with the NIM.

Create Your Own Draft Model

The best draft for your workload is usually an EAGLE3 model trained on it. NVIDIA publishes ready-to-use EAGLE3 drafts for common models in the Speculative Decoding Modules collection, or you can train your own. Refer to the guide to training a speculative-decoding model. Export the trained draft in a format that your inference engine supports, and serve it using NIM_DRAFT_MODEL_PATH.

Use a Local Draft Model (Air-Gapped)

For air-gapped deployments, point NIM_DRAFT_MODEL_PATH at an absolute local directory holding the draft (its config.json and weights). The draft is linked into the workspace with no network access, the same way a local target model is served. Mount the directory into the container and use its in-container path:

SPECDEC_ARGS=(--speculative-config '{"method": "eagle3", "model": "eagle3_draft", "num_speculative_tokens": 3}')
docker run --gpus all --shm-size=16GB \
-v "$LOCAL_NIM_CACHE:/opt/nim/.cache" \
-v /data/models/llama-3.1-8b:/models/target \
-v /data/models/eagle3-draft:/models/draft \
-p 8000:8000 \
-e NIM_MODEL_PATH=/models/target \
-e NIM_DRAFT_MODEL_PATH=/models/draft \
$IMG \
"${SPECDEC_ARGS[@]}"

The target loads from its local path or from a populated /opt/nim/.cache, and the draft links from /models/draft. You do not need NGC_API_KEY or HF_TOKEN. Keep the eagle3_draft directory name in the backend arguments. NIM places the local draft in that workspace subdirectory and rewrites the reference to the absolute path at launch.

Benchmark it Yourself

Benchmark with representative traffic before choosing a method. NVIDIA AIPerf collects acceptance rate, acceptance length, and throughput from the server’s Prometheus metrics. Pass --server-metrics http://localhost:8000/v1/metrics to collect these metrics. For more information about AIPerf, refer to the NVIDIA AIPerf repository.

Benchmark with SPEED-Bench (Per-Category Acceptance)

SPEED-Bench is NVIDIA’s dataset for evaluating speculative decoding across 11 semantic domains (coding, math, writing, and so on). Prepare the data, then profile per category and assemble a matrix report:

SPEED_BENCH_DIR="./datasets/speed-bench"
curl -LsSf https://raw.githubusercontent.com/NVIDIA-NeMo/Skills/refs/heads/main/nemo_skills/dataset/speed-bench/prepare.py \
| python3 - --output_dir $SPEED_BENCH_DIR
CATEGORIES="coding humanities math multilingual qa rag reasoning roleplay stem summarization writing"
for cat in $CATEGORIES; do
aiperf profile \
--model <served-model-name> \
--endpoint-type chat --streaming \
--url localhost:8000 \
--custom-dataset-type speed_bench_${cat} \
--input-file ${SPEED_BENCH_DIR}/qualitative.jsonl \
--server-metrics http://localhost:8000/v1/metrics \
--osl 4096 --extra-inputs temperature:0 --concurrency 16 \
--output-artifact-dir ./artifacts/speed_bench_${cat}
done
aiperf speed-bench-report ./artifacts/ --format both # acceptance length matrix
aiperf speed-bench-report ./artifacts/ --metric accept_rate # acceptance rate matrix
aiperf speed-bench-report ./artifacts/ --metric throughput # throughput matrix

To measure the speedup, run the same matrix with NIM_SPECDEC_ENABLE=0. Acceptance is zero in this run. Compare the throughput tables from the two runs.

Replay Your Own Traffic

To benchmark your production traffic, record requests with NIM’s built-in payload capture and replay it with AIPerf.

To replay captured traffic, complete the following steps:

  1. Capture real requests by enabling payload capture (off by default; it records exact prompts; refer to the payload capture reference). With format: mooncake_payload, NIM writes a trace with one record per request in the form {"timestamp": <ms>, "payload": <request>}.

    docker run --gpus all --shm-size=16GB \
    -e NGC_API_KEY \
    -e NIM_SPECDEC_ENABLE=1 \
    -e NIM_CAPTURE_ENABLE=1 \
    -e NIM_CAPTURE_ARGS='{"path": "/captures/traffic.jsonl", "format": "mooncake_payload", "endpoint_pattern": "^/v1/chat/completions$"}' \
    -v /data/captures:/captures \
    -p 8000:8000 \
    $IMG

    The endpoint_pattern scopes capture to one endpoint. AIPerf replays each payload verbatim to the single --endpoint-type you pass below, so a trace must contain one endpoint’s payloads; refer to the payload capture reference for replaying completion traffic.

  2. Replay the captured trace with AIPerf and collect the server’s speculative decoding metrics.

    aiperf profile \
    --model <served-model-name> \
    --endpoint-type chat --streaming \
    --url localhost:8000 \
    --custom-dataset-type mooncake_trace \
    --input-file /data/captures/traffic.jsonl \
    --server-metrics http://localhost:8000/v1/metrics

    AIPerf loads a tokenizer for the model to compute token metrics. If AIPerf cannot fetch it, such as for a private model or an air-gapped host, pass --tokenizer <dir> for a local tokenizer directory or use --tokenizer builtin.

  3. Read the results. The AIPerf console report shows time to first token, request latency, and output token throughput. For speculative decoding acceptance, use the server metrics collected with --server-metrics and exported as server_metrics_export.csv and server_metrics_export.json. NIM also serves these metrics at /v1/metrics. Metric names depend on the backend.

    The following table describes the vLLM speculative-decoding counters:

    CounterMeaning
    vllm:spec_decode_num_draft_tokens_totalDraft tokens proposed
    vllm:spec_decode_num_accepted_tokens_totalDraft tokens accepted
    vllm:spec_decode_num_drafts_totalDraft steps

    On vLLM, acceptance rate (AR) is the number of accepted draft tokens divided by the number proposed. Acceptance length (AL), the mean number of tokens emitted per step, is one plus the number of accepted draft tokens divided by the number of draft steps.

    On SGLang, read sglang:spec_accept_rate and sglang:spec_accept_length. These are windowed gauges, so sample them during sustained load.

    Run the benchmark again with NIM_SPECDEC_ENABLE=0 to compare throughput and latency on the same traffic.

Because capture stores the real payloads (not hashed or synthetic prompts), the replay reflects your true workload. For raw_payload capture, use --custom-dataset-type raw_payload instead. Refer to the payload capture reference and the AIPerf SPEED-Bench tutorial.

Best Practices

Use the following practices when you enable speculative decoding:

  • Measure acceptance and throughput on representative traffic before you commit to a method. Refer to Benchmark it Yourself.
  • Confirm GPU memory headroom before you enable speculative decoding, especially for EAGLE3.
  • Prefer an EAGLE3 draft trained on your workload when the shipped default is not optimal.
  • For air-gapped deployments, cache bundled drafts in advance with download-to-cache. Starting with release 2.1.7, use download-to-cache --model-uri to cache a draft_uri draft on Hugging Face that is pinned to a full commit SHA. For other drafts and for release 2.1.6, set NIM_DRAFT_MODEL_PATH to a local copy. Refer to Profiles with a Speculative-Decoding Draft Model.
  • Scope payload capture to one endpoint when you plan a single AIPerf replay run.

Next Steps

After you enable a speculative-decoding method, capture production traffic and replay it to measure speedup. For more information, refer to Payload Capture and the Environment Variables reference for NIM_SPECDEC_ENABLE, NIM_SPECDEC_ARGS, and NIM_DRAFT_MODEL_PATH.