๐Ÿค–AI/ML

Speculative Decoding

Speculative Decoding

An inference acceleration technique that generates drafts with a small model and verifies them with a large model. Achieves 2-3x speedup while maintaining output quality.

๐Ÿ“– Detailed Explanation

Speculative Decoding is an LLM inference acceleration technique in which a small, fast "draft model" generates several tokens in advance, and a large, accurate "target model" verifies them all at once. Based on an idea similar to CPU branch prediction, it yields a large gain when the prediction is correct and a small loss when it is wrong. The key point is the mathematical guarantee that the target model's output distribution is 100% preserved even when the draft is wrong.

It was proposed in 2022 in DeepMind's paper "Fast Inference from Transformers via Speculative Decoding." Conventional autoregressive generation was slow because it required a forward pass of the huge model for every single token. A 70B model can generate only 10-20 tokens per second. Speculative Decoding resolves this bottleneck through clever parallelization. Similar optimizations are reportedly also applied internally in commercial models such as Google's Gemini and Anthropic's Claude.

How it works: 1) The draft model generates k tokens (e.g., "The quick brown fox") 2) The target model computes the logits for k+1 positions at once (parallel forward) 3) The draft token at each position is verified by acceptance sampling 4) At the point of mismatch, a corrected token is generated from the target distribution. In this process, tokens are probabilistically accepted/rejected according to the acceptance probability, guaranteeing the same distribution as generation by the target model alone.

Major inference engines such as vLLM, TensorRT-LLM, Hugging Face TGI, and llama.cpp support it. The draft model should be about 1/10 to 1/5 the size of the target (e.g., Llama 70B + Llama 8B), and it must use the same tokenizer. In predictable patterns such as code generation, JSON output, and translation, the acceptance rate reaches 70-90%, making a 3-4x speedup possible. Variants such as Self-Speculative Decoding, Medusa (multiple heads), and EAGLE are also being actively researched.

๐Ÿ’ป Code Example

# Speculative Decoding ๊ฐœ๋… ๊ตฌํ˜„ (๊ฐ„์†Œํ™”)
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

def speculative_decode(prompt, target_model, draft_model, tokenizer,
                       k=5, max_tokens=100):
    """
    k: draft model์ด ํ•œ ๋ฒˆ์— ์ƒ์„ฑํ•  ํ† ํฐ ์ˆ˜
    """
    input_ids = tokenizer.encode(prompt, return_tensors='pt')
    generated = input_ids.clone()

    for _ in range(max_tokens // k):
        # 1. Draft model๋กœ k๊ฐœ ํ† ํฐ ๋น ๋ฅด๊ฒŒ ์ƒ์„ฑ
        draft_ids = generated.clone()
        for _ in range(k):
            with torch.no_grad():
                logits = draft_model(draft_ids).logits[:, -1, :]
                next_token = logits.argmax(dim=-1, keepdim=True)
                draft_ids = torch.cat([draft_ids, next_token], dim=-1)

        draft_tokens = draft_ids[:, generated.shape[1]:]  # ์ƒˆ๋กœ ์ƒ์„ฑ๋œ k๊ฐœ

        # 2. Target model๋กœ ํ•œ ๋ฒˆ์— ๊ฒ€์ฆ (๋ณ‘๋ ฌ!)
        with torch.no_grad():
            # draft_ids ์ „์ฒด๋ฅผ ํ•œ ๋ฒˆ์— forward
            target_logits = target_model(draft_ids).logits

        # 3. ์ผ์น˜ํ•˜๋Š” ํ† ํฐ๊นŒ์ง€๋งŒ accept
        accepted = 0
        for i in range(k):
            target_pred = target_logits[:, generated.shape[1] + i - 1, :].argmax()
            draft_pred = draft_tokens[:, i]
            if target_pred == draft_pred:
                accepted += 1
            else:
                # ๋ถˆ์ผ์น˜: target์˜ ์˜ˆ์ธก์œผ๋กœ ๊ต์ฒด
                generated = torch.cat([generated, target_pred.unsqueeze(0).unsqueeze(0)], dim=-1)
                break
        else:
            # ๋ชจ๋‘ ์ผ์น˜: k๊ฐœ ์ „๋ถ€ accept
            generated = draft_ids

        if tokenizer.eos_token_id in generated[0]:
            break

    return tokenizer.decode(generated[0])

# vLLM์—์„œ Speculative Decoding ์‚ฌ์šฉ (์‹ค์ œ ํ”„๋กœ๋•์…˜)
from vllm import LLM, SamplingParams

llm = LLM(
    model="meta-llama/Llama-3-70b-instruct",
    speculative_model="meta-llama/Llama-3-8b-instruct",  # Draft model
    num_speculative_tokens=5,  # ํ•œ ๋ฒˆ์— ์ถ”์ธกํ•  ํ† ํฐ ์ˆ˜
    tensor_parallel_size=4
)

sampling_params = SamplingParams(temperature=0.0, max_tokens=500)
output = llm.generate("Explain quantum computing:", sampling_params)
# ์ผ๋ฐ˜ ๋””์ฝ”๋”ฉ ๋Œ€๋น„ 2-3x ๋น ๋ฆ„!

# === Medusa (Multi-Head Speculative Decoding) ===
# ๋ณ„๋„ draft model ์—†์ด target model์— ์ถ”๊ฐ€ head๋ฅผ ๋ถ™์ž„
from transformers import AutoModelForCausalLM
import torch.nn as nn

class MedusaHead(nn.Module):
    """Medusa: ๊ฐ head๊ฐ€ ๋‹ค์Œ n๋ฒˆ์งธ ํ† ํฐ์„ ์˜ˆ์ธก"""
    def __init__(self, hidden_size, vocab_size, num_heads=4):
        super().__init__()
        self.heads = nn.ModuleList([
            nn.Sequential(
                nn.Linear(hidden_size, hidden_size),
                nn.SiLU(),
                nn.Linear(hidden_size, vocab_size)
            )
            for _ in range(num_heads)
        ])

    def forward(self, hidden_states):
        # ๊ฐ head๊ฐ€ +1, +2, +3, +4 ์œ„์น˜ ํ† ํฐ ์˜ˆ์ธก
        return [head(hidden_states) for head in self.heads]

# Medusa ์žฅ์ : ๋ณ„๋„ draft model ๋กœ๋“œ ๋ถˆํ•„์š”, ๋ฉ”๋ชจ๋ฆฌ ์ ˆ์•ฝ
# ๋‹จ์ : ์ถ”๊ฐ€ head ํ•™์Šต ํ•„์š”

# === ์„ฑ๋Šฅ ์ธก์ • ์˜ˆ์‹œ ===
import time

def benchmark_generation(model, prompt, max_tokens=100, runs=5):
    """ํ† ํฐ ์ƒ์„ฑ ์†๋„ ์ธก์ •"""
    times = []
    for _ in range(runs):
        start = time.perf_counter()
        output = model.generate(prompt, max_tokens=max_tokens)
        elapsed = time.perf_counter() - start
        times.append(elapsed)

    tokens_per_sec = max_tokens / (sum(times) / len(times))
    return tokens_per_sec

# ์ผ๋ฐ˜ ๋””์ฝ”๋”ฉ vs Speculative Decoding ๋น„๊ต
# ์ผ๋ฐ˜: ~15 tokens/sec (70B model)
# Speculative: ~40-50 tokens/sec (with 8B draft)

# === Draft ๋ชจ๋ธ ์„ ํƒ ๊ฐ€์ด๋“œ ===
# Target ๋ชจ๋ธ    | ์ถ”์ฒœ Draft ๋ชจ๋ธ        | Acceptance Rate
# Llama 70B      | Llama 8B               | 70-85%
# Llama 405B     | Llama 70B ๋˜๋Š” 8B      | 60-80%
# Mixtral 8x22B  | Mistral 7B             | 65-80%
# GPT-4          | GPT-3.5 Turbo (๋‚ด๋ถ€)   | 75-90%

# === EAGLE (Lossless Acceleration) ===
# EAGLE๋Š” ๋ณ„๋„ draft ๋ชจ๋ธ ๋Œ€์‹  target ๋ชจ๋ธ์˜ hidden states๋ฅผ ์žฌํ™œ์šฉ
# ์žฅ์ : ์ถ”๊ฐ€ ๋ชจ๋ธ ๋กœ๋“œ ๋ถˆํ•„์š”, ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ์ 
# ๋‹จ์ : ์ถ”๊ฐ€ head ํ•™์Šต ํ•„์š”

# === Self-Speculative Decoding ===
# ๋™์ผ ๋ชจ๋ธ์˜ ์ดˆ๊ธฐ ๋ ˆ์ด์–ด๋งŒ ์‚ฌ์šฉํ•ด์„œ draft ์ƒ์„ฑ
# ์ž‘์€ ์„œ๋ธŒ๋„ท์ด ๋น ๋ฅด๊ฒŒ ์˜ˆ์ธก, ์ „์ฒด ๋ชจ๋ธ์ด ๊ฒ€์ฆ

# === ์–ธ์ œ Speculative Decoding์ด ํšจ๊ณผ์ ์ธ๊ฐ€? ===
# 1. ์ฝ”๋“œ ์ƒ์„ฑ (์˜ˆ์ธก ๊ฐ€๋Šฅํ•œ ๋ฌธ๋ฒ• ๊ตฌ์กฐ)
# 2. JSON/XML ์ถœ๋ ฅ (์ •ํ˜•ํ™”๋œ ํฌ๋งท)
# 3. ๋ฒˆ์—ญ (์ž…๋ ฅ๊ณผ ์ถœ๋ ฅ ๊ตฌ์กฐ ์œ ์‚ฌ)
# 4. ์ˆ˜ํ•™ ๊ณ„์‚ฐ (๊ฒฐ์ •๋ก ์  ํŒจํ„ด)

# ๋น„ํšจ์œจ์ ์ธ ๊ฒฝ์šฐ:
# - ์ฐฝ์˜์  ๊ธ€์“ฐ๊ธฐ (์˜ˆ์ธก ์–ด๋ ค์›€)
# - ๋†’์€ temperature ์ƒ˜ํ”Œ๋ง
# - ์•„์ฃผ ์งง์€ ์ถœ๋ ฅ

# === Lookahead Decoding (๋ณ‘๋ ฌ ๊ฒ€์ฆ ๋ณ€ํ˜•) ===
# ์—ฌ๋Ÿฌ ํ›„๋ณด ๊ฒฝ๋กœ๋ฅผ ๋™์‹œ์— ํƒ์ƒ‰
# Tree-based speculation์œผ๋กœ ๋” ๋†’์€ acceptance rate

# === TensorRT-LLM์—์„œ ์‚ฌ์šฉ ===
# NVIDIA TensorRT-LLM๋„ Speculative Decoding ์ง€์›
# config์—์„œ speculative_decoding ํ™œ์„ฑํ™”

# === Acceptance Rate ๋ชจ๋‹ˆํ„ฐ๋ง ===
def monitor_acceptance_rate(draft_ids, target_ids, window=100):
    """์‹ค์‹œ๊ฐ„ acceptance rate ์ถ”์ """
    accepted = sum(d == t for d, t in zip(draft_ids, target_ids))
    rate = accepted / len(draft_ids)
    print(f"Acceptance Rate: {rate:.1%}")
    # rate < 50%๋ฉด draft ๋ชจ๋ธ ๋ณ€๊ฒฝ ๊ณ ๋ ค
    return rate

# === ๋น„์šฉ ์ ˆ๊ฐ ๊ณ„์‚ฐ ===
# Target model: 70B, 15 tokens/sec, $10/1M tokens
# Draft model: 8B, 100 tokens/sec, $1/1M tokens
# Acceptance rate: 75%
# ํ‰๊ท  ์ถ”์ธก ํ† ํฐ: 5๊ฐœ ์ค‘ 3.75๊ฐœ ์ˆ˜๋ฝ
# ์†๋„ ํ–ฅ์ƒ: (1 + 3.75) / (1 + 1) = 2.4๋ฐฐ
# ๋น„์šฉ: target ํ˜ธ์ถœ ํšŸ์ˆ˜ 60% ๊ฐ์†Œ

# === ์ฃผ์š” ์ถ”๋ก  ์—”์ง„ ์ง€์› ํ˜„ํ™ฉ ===
# | ์—”์ง„          | ์ง€์› | ๋น„๊ณ                       |
# |--------------|-----|--------------------------|
# | vLLM         | O   | speculative_model ํŒŒ๋ผ๋ฏธํ„ฐ |
# | TensorRT-LLM | O   | config ์„ค์ •               |
# | llama.cpp    | O   | --speculative ํ”Œ๋ž˜๊ทธ      |
# | HF TGI       | O   | speculation_config        |
# | Ollama       | X   | ๋ฏธ์ง€์› (2024.12 ๊ธฐ์ค€)      |

# === ์‹ค์ „ ํŠœ๋‹ ํŒ ===
# 1. num_speculative_tokens: 5๊ฐ€ ๊ธฐ๋ณธ, 8๊นŒ์ง€ ์‹คํ—˜
# 2. ์ •ํ˜• ์ถœ๋ ฅ(JSON)์—์„œ ๋” ๊ณต๊ฒฉ์ ์œผ๋กœ (10+)
# 3. ์ฐฝ์˜์  ๊ธ€์“ฐ๊ธฐ๋Š” 3 ์ดํ•˜๋กœ ๋ณด์ˆ˜์ ์œผ๋กœ
# 4. ์‹ค์‹œ๊ฐ„ ๋ชจ๋‹ˆํ„ฐ๋ง์œผ๋กœ acceptance rate ์ถ”์ 

# === Batch Speculative Decoding ===
# ์—ฌ๋Ÿฌ ์š”์ฒญ์„ ๋ฐฐ์น˜๋กœ ์ฒ˜๋ฆฌํ•  ๋•Œ๋„ ์ ์šฉ ๊ฐ€๋Šฅ
# continuous batching๊ณผ ์กฐํ•ฉํ•˜์—ฌ throughput ๊ทน๋Œ€ํ™”

# === Prompt Lookup Decoding ===
# ์ž…๋ ฅ ํ”„๋กฌํ”„ํŠธ์—์„œ ๋ฐ˜๋ณต๋˜๋Š” ํŒจํ„ด์„ draft๋กœ ํ™œ์šฉ
# ์ฝ”๋“œ ์ˆ˜์ •, ๋ฌธ์„œ ํŽธ์ง‘ ๋“ฑ์—์„œ ํšจ๊ณผ์ 
# ๋ณ„๋„ draft ๋ชจ๋ธ ์—†์ด ์ž…๋ ฅ ์ž์ฒด๊ฐ€ ํžŒํŠธ ์—ญํ• 

# === DistillSpec ===
# Target ๋ชจ๋ธ์„ teacher๋กœ draft ๋ชจ๋ธ ์ฆ๋ฅ˜(distillation)
# ํƒœ์Šคํฌ ํŠนํ™”๋œ draft ๋ชจ๋ธ๋กœ acceptance rate ํ–ฅ์ƒ

๐Ÿ—ฃ๏ธ Say It Like This in Practice

๐Ÿ’ฌ In an LLM Serving Optimization Meeting
"If we apply Speculative Decoding, Llama 70B inference gets 2x faster. We can use an 8B model as the draft, and it's important to use the same tokenizer. In vLLM, you just need to add the speculative_model parameter."
๐Ÿ’ฌ In an Interview
"With Speculative Decoding, a small draft model guesses k tokens, and a large target model verifies them in parallel. The key point is that the target's output distribution is 100% maintained. Even if the draft is wrong, the target corrects it, so only the speed improves with no quality degradation."
๐Ÿ’ฌ In a Cost Reduction Discussion
"Speculative Decoding is especially effective for structured tasks such as code generation or JSON output. There are many predictable patterns, so the acceptance rate comes out at 70-80%, and inference costs drop by nearly half."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Common Mistakes & Cautions

โŒ
Tokenizer mismatch between Draft and Target

If different tokenizers are used, token boundaries do not align, making verification impossible. Be sure to use the same tokenizer (the same model family).

โŒ
Setting k too large

If k (the number of speculative tokens) is too large, rejections increase and it can actually become slower. Typically 4-8 is optimal, and tuning per task is required.

โœ…
The right way

Use models from the same family (e.g., Llama 70B + Llama 8B), start with k=5, and monitor the acceptance rate. We recommend using proven frameworks such as vLLM and TGI.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More