Why this lab exists
Every LLM API you call — OpenAI, Anthropic, Groq — likely runs speculative decoding internally. When you get tokens back at 80 tokens/sec instead of 25 tokens/sec, speculative decoding is probably why. It is the single most impactful serving optimization for autoregressive LLMs discovered in the past decade.
The trick sounds almost too good: use a small, fast model to propose K tokens speculatively, then use the large, slow model to verify all K tokens in one forward pass. The output distribution is provably identical to running the large model alone — you get the same quality at 2-4x the throughput. No model changes. No quality degradation. Just arithmetic.
Until you’ve implemented the rejection sampling criterion yourself, until you’ve derived the geometric series that gives you the expected speedup, until you’ve watched the acceptance rate determine everything — you don’t truly understand why it works. This lab makes it concrete in three stages: from a 180-line draft-verify loop to tree attention that pushes speedup further.
What we’re building
A speculative decoding engine in Python, implemented across three stages. Each stage adds one concept and makes the speedup more measurable.
We build:
- Draft-then-verify core algorithm (v0):
speculative_step,AcceptanceRate - Batched decoding with
SpeedupStats(v1):BatchedSpeculativeDecoder, geometric-series speedup formula - Tree attention and self-speculative decoding (v2):
DraftTree,SelfSpeculator,AcceptanceMetrics - FastAPI server:
POST /generate,GET /stats - Spring AI Java integration:
SpeculativeClient, transparency demonstration
We explicitly skip (and why):
- Real GPU model weights: we use mock models with configurable distributions so the lab runs on any laptop in under 5 minutes
- Custom CUDA kernels: tree attention masking requires GPU-specific implementation; the algorithm is shown on CPU
- Training the draft model: we simulate a high-acceptance draft; training a real draft is covered in the LLM inference and LoRA labs
Mental model
The core intuition: the large target model’s forward pass is expensive whether it processes 1 token or K+1 tokens. The attention computation is O(n^2) in sequence length, but for short speculative drafts the batch dimension (K+1 additional tokens) costs almost nothing on GPU. So you get K+1 output distributions for roughly the price of 1.
Standard decoding (1 target call = 1 token):
Prompt → [Target FWD] → token_1
[Target FWD] → token_2
[Target FWD] → token_3
3 target calls → 3 tokens → speedup = 1.0
Speculative decoding (1 target call = up to K+1 tokens):
Prompt → [Draft FWD x5] → [t1, t2, t3, t4, t5] (fast, cheap)
→ [Target FWD x1] → verify positions 0..4 simultaneously
→ Accept t1, t2, t3 (rejected at t4) → resample t4'
→ bonus token at position 4
1 target call → 4 tokens → speedup = 4.0 for this step
The acceptance criterion is rejection sampling: accept draft token t at position i if uniform(0,1) < min(1, p_target(t) / p_draft(t)). When p_target and p_draft agree (both assign high probability to t), the token is accepted with probability near 1. When they disagree, the token is rejected and we resample from the corrected distribution max(0, p_target - p_draft) / Z.
This corrected distribution is the key: sampling from it produces the correct marginal distribution. The math guarantees that the output of speculative decoding has exactly the same distribution as the output of the target model alone — provably.
Prerequisites
- Python 3.12
- PyTorch (
pip install torch) - Basic understanding of LLM autoregressive generation — what a forward pass returns, how sampling works (the LLM Inference lab covers this)
- Familiarity with probability distributions — what
torch.multinomialdoes
No large model downloads needed. All stages use mock models that run in milliseconds. The TinyTransformerModelForSelfSpec in v2 is a genuine 2-layer transformer (64 hidden dim, 4 heads) but with only 256-token vocabulary, so it fits in kilobytes.
Stage-by-stage build
Stage 0 Draft + Verify Algorithm
- Implement DraftModel and TargetModel wrappers (get_probs, sample)
- Implement speculative_step(context_ids, draft, target, K=5): draft K tokens, verify in one pass, accept/reject
- Implement AcceptanceRate tracker: total_proposed, total_accepted, speedup_vs_standard
- Write 5 tests: always >= 1 token, 100% acceptance when draft==target, rejection resamples correctly, K=1 is standard decoding, accepted_tokens in [1, K+1]
The entire algorithm is one function: speculative_step. Understanding it means understanding all of speculative decoding — everything else is optimization.
Phase 1 — Draft:
draft_tokens = []
draft_probs = []
current_ctx = list(context_ids)
for _ in range(K):
probs = draft_model.get_probs(current_ctx) # fast
token = torch.multinomial(probs, num_samples=1)
draft_tokens.append(token)
draft_probs.append(probs[token].item())
current_ctx.append(token)This is just standard autoregressive sampling from the small draft model, K times. Each call is cheap — the draft model might be 10-100x smaller than the target.
Phase 2 — Verify (the key insight):
In a real transformer, one forward pass over context + K draft tokens produces K+1 output distributions simultaneously (one for each position). On GPU with sequence lengths under 100, adding K+1 tokens to a batch costs nearly nothing extra. Our mock simulates this with K+1 sequential calls — same semantics, same correctness, just slower.
verify_ctx = list(context_ids)
target_probs_list = []
for i in range(K):
tp = target_model.get_probs(verify_ctx) # would be batched in real system
target_probs_list.append(tp)
verify_ctx.append(draft_tokens[i])
target_bonus_probs = target_model.get_probs(verify_ctx)Phase 3 — Accept/reject:
for i in range(K):
token = draft_tokens[i]
ratio = p_target[i][token] / p_draft[i]
if uniform() < min(1.0, ratio):
accepted.append(token)
else:
# Resample from the corrected distribution
corrected = clamp(p_target[i] - p_draft_full[i], min=0) / Z
resampled = multinomial(corrected)
accepted.append(resampled)
break # discard remaining draft tokensThe corrected distribution max(0, p_target - p_draft) / Z is what preserves the output quality. Sampling from it on rejection ensures that the marginal distribution over the accepted token is exactly p_target, even though the draft proposed something else.
Phase 4 — Bonus:
Always add one token sampled from target_bonus_probs at the position after all accepted tokens. This guarantees progress of at least 1 token per target call, even if all K drafts are rejected.
The acceptance rate invariant:
The key test: when draft_model and target_model return identical distributions (e.g., both uniform), min(1, p_target/p_draft) = min(1, 1) = 1 — every draft token is accepted with probability 1. This means n_accepted == K always, and total_tokens == K + 1 (K accepted + 1 bonus). Your test verifies this over 50 steps: any deviation means the sampling or probability computation has a bug.
Stage 1 Batched Decoding + Speedup Stats
- Implement BatchedSpeculativeDecoder: decode_batch(prompts, max_tokens) -> (list[list[int]], SpeedupStats)
- Implement SpeedupStats: tokens_generated, draft_tokens_proposed, acceptance_rate, target_calls, speedup_vs_standard
- Implement expected_speedup(alpha, K) -> (1 - alpha^(K+1)) / (1 - alpha), plus expected_net_speedup and implied_alpha
- Write 6 tests: batch output count matches prompts, speedup > 1.0, target_calls <= tokens_generated, closed form = 3.867 at alpha=0.82 K=5, simulation matches the closed form, acceptance_rate==1 when draft==target
v1 extends the core algorithm to handle a batch of B prompts simultaneously and adds the statistics that make speedup concrete and measurable.
Why batching matters:
In GPU inference, the fixed overhead of a target model forward pass (loading weights from HBM, dispatch overhead) is roughly the same whether you run 1 sequence or B sequences in parallel. Standard decoding already exploits this: one batched forward pass emits one token for each of B sequences. Speculative decoding multiplies on top of that: one batched verification pass emits about E[tokens per call] tokens for each sequence. Batching and speculation are separate gains, so measure them separately.
Our implementation processes each sequence in decode_batch sequentially per step (Python has no GPU parallelism here), but we count statistics correctly: one “target call” per batch step, and one “sequence step” per active sequence per step. The speedup divides by sequence steps. Dividing by target calls would credit batching to speculation: 4 sequences at about 4 tokens each would look like a 16x “speedup”.
The speedup formula:
Let alpha be the probability that a draft token is accepted, given that the one before it was. The number of accepted drafts N is a truncated geometric variable: P(N >= i) = alpha^i for i <= K. Every step also emits exactly one more token: the corrected resample at the first rejection, or the bonus token when all K drafts pass. So:
E[tokens per target call] = 1 + alpha + alpha^2 + ... + alpha^K
= (1 - alpha^(K+1)) / (1 - alpha) [geometric series]At alpha=0.82, K=5:
1 + 0.82 + 0.6724 + 0.5514 + 0.4521 + 0.3707 = 3.867Standard decoding gives 1 token per target call, so at this acceptance rate speculative decoding needs 3.87x fewer target calls. This is the result from Leviathan et al. (2023).
SpeedupStats.speedup_vs_standard = tokens_generated / sequence_steps
This is the measurement, not the formula. Run decode_batch over many prompts and compare it against expected_speedup(alpha, K). Over 5,000 steps with this lab’s mock draft, measured tokens per call was 4.64, and the closed form at the observed per-token acceptance (0.895) gives 4.63.
One trap: SpeedupStats.acceptance_rate is accepted drafts divided by proposed drafts. That is not alpha. It equals (tokens_per_call - 1) / K, which is 0.57 at alpha=0.82. Use implied_alpha(tokens_per_call, K) to go from a measurement back to alpha.
target_calls counts steps, not tokens:
This is a common confusion. If one sequence generates 30 tokens with speedup=3.0, target_calls should be approximately 10, not 30. Each speculative_step call is exactly 1 target call. The tokens_generated / target_calls ratio is what shows the speedup.
Breakeven analysis:
Speculative decoding only helps if the draft model is fast enough. If the draft model costs d fraction of the target’s time and we run K drafts:
Net speedup = tokens_per_target_call / (1 + K * d)At d=0.10 (draft 10x cheaper) and K=5 with alpha=0.82:
Net speedup = 3.87 / (1 + 5*0.10) = 3.87 / 1.5 = 2.58xStill profitable. But at d=0.30 (draft only about 3x cheaper):
Net speedup = 3.87 / (1 + 5*0.30) = 3.87 / 2.5 = 1.55xStill a gain on paper, but small enough that a second model’s memory and serving complexity may not pay for it. This is why draft model selection matters enormously in production. expected_net_speedup(alpha, K, d) computes this.
Stage 2 Tree Attention + Self-Speculative
- Implement DraftTree dataclass and build_draft_tree(context, draft, width, depth)
- Implement verify_tree(context, roots, draft, target) -> TreeVerificationResult with best accepted path
- Implement TinyTransformerModelForSelfSpec: forward_with_early_exit returning draft and target logits
- Implement SelfSpeculator: speculative_step using early exit as draft
- Implement AcceptanceMetrics: mean_accepted, p50_accepted, p95_accepted, target_calls_per_1k_tokens
- Write 3 tests: tree draft generates W^D leaf paths, early exit produces valid logits, uniform tree accepts full depth
v2 pushes speculative decoding in two orthogonal directions: better draft coverage (tree attention) and no separate draft model (self-speculative).
Tree attention intuition:
Linear drafting proposes one path: [t1, t2, t3, t4, t5]. If t2 is rejected, you discard t3, t4, t5. But what if you had proposed 3 alternatives at position 2? At least one of them might be accepted, recovering the tokens that would be wasted.
Tree drafting explores a branching tree of candidates:
Depth 0: t0a, t0b (W=2 candidates)
Depth 1: t1aa, t1ab, t1ba, t1bb (4 nodes)
Depth 2: 8 leaf paths
Target verifies all 8 paths in one forward pass using tree attention masking:
- t0a only attends to context
- t1aa attends to context + t0a
- t1ab attends to context + t0a (same parent as t1aa)
- t1ba attends to context + t0b (different parent)
...The tree attention mask ensures each node only attends to its own ancestors, not to sibling branches. This is where the custom CUDA kernel requirement comes in — standard causal attention assumes a linear sequence, not a tree.
Our verify_tree checks all paths sequentially but picks the longest accepted path — the same result a GPU tree attention would produce.
Self-speculative decoding:
The simplest possible draft: stop the forward pass at an intermediate layer and use that layer’s output as the draft distribution. The full forward pass is the target.
# One forward pass, two exit points:
x = embed(tokens) + pos_embed(positions)
x = layer_0(x)
early_logits = early_unembed(x[:, -1, :]) # draft: after 1 layer
x = layer_1(x)
full_logits = full_unembed(x[:, -1, :]) # target: after 2 layersThe accept/reject criterion is identical. The efficiency gain: you don’t need to maintain a separate draft model, download extra weights, or warm up a separate GPU. The draft comes “for free” from the early layers of the model you’re already running.
In practice, self-speculative requires the model to be trained with an auxiliary early-exit head. Medusa (2024) extends this further with multiple decoding heads at different positions, each proposing a token at a different offset from the current position.
AcceptanceMetrics gives you percentile information:
mean_accepted is the average. But p95_accepted tells you what happens on easy inputs (in-domain, high-certainty tokens), while p50_accepted tells you the median. If p95_accepted = 4.8 and mean_accepted = 2.1, you have high variance — the acceptance rate fluctuates significantly across different input types. This is the signal to implement adaptive K.
target_calls_per_1k_tokens = 1000 / (mean_accepted + 1) is the headline infrastructure metric: how many target model calls do you need per 1000 output tokens? At mean_accepted=3.2, you need 1000 / 4.2 = 238 calls instead of 1000: 4.2x fewer target-model calls. The draft model’s cost comes on top, so the infrastructure saving is smaller.
Run it yourself
labs/speculative-decoding ↗
Python 3.12+pip or uvtorch>=2.3.0 (CPU-only, no GPU needed) - 1 Clone and install
git clone https://github.com/pushkarkumar-dev/system-design-labs cd system-design-labs/labs/speculative-decoding pip install -e '.[test]' - 2 Run all tests
python -m pytest tests/ -v - 3 Run core algorithm directly
python -c " import sys; sys.path.insert(0, '.') from src.models import MockSkewedModel, MockHighAcceptanceModel from src.v0_basic import speculative_step, AcceptanceRate import torch; torch.manual_seed(0) target = MockSkewedModel(concentration=0.3, seed=42) draft = MockHighAcceptanceModel(target, epsilon=0.18) tracker = AcceptanceRate() for _ in range(100): r = speculative_step([1,2,3,4,5], draft, target, K=5) tracker.update(r) print(f'Acceptance rate: {tracker.acceptance_rate:.3f}') print(f'Speedup vs std: {tracker.speedup_vs_standard:.2f}x') print(f'Target calls: {tracker.total_target_calls}') print(f'Tokens generated:{tracker.total_tokens_generated}') " - 4 Start the FastAPI server
uvicorn src.server:app --port 8000 - 5 Generate tokens and check speedup
curl -s -X POST http://localhost:8000/generate \ -H 'Content-Type: application/json' \ -d '{"prompt_tokens": [10, 20, 30], "max_tokens": 20, "K": 5}' | python -m json.tool - 6 Fetch aggregate stats
curl -s http://localhost:8000/stats | python -m json.tool
===== Test results =====
tests/test_speculative.py::TestV0Basic::test_always_at_least_one_token PASSED
tests/test_speculative.py::TestV0Basic::test_acceptance_100_percent_when_draft_equals_target PASSED
tests/test_speculative.py::TestV0Basic::test_rejection_resamples_from_adjusted_distribution PASSED
tests/test_speculative.py::TestV0Basic::test_k_equals_1_is_standard_decoding PASSED
tests/test_speculative.py::TestV0Basic::test_accepted_tokens_in_valid_range PASSED
tests/test_speculative.py::TestV1Batched::test_batched_generates_one_output_per_prompt PASSED
tests/test_speculative.py::TestV1Batched::test_speedup_greater_than_one PASSED
tests/test_speculative.py::TestV1Batched::test_target_calls_equals_steps_not_tokens PASSED
tests/test_speculative.py::TestV1Batched::test_expected_speedup_closed_form PASSED
tests/test_speculative.py::TestV1Batched::test_simulated_tokens_per_call_matches_closed_form PASSED
tests/test_speculative.py::TestV1Batched::test_acceptance_rate_computation_correct PASSED
tests/test_speculative.py::TestV2Tree::test_tree_draft_generates_multiple_paths PASSED
tests/test_speculative.py::TestV2Tree::test_self_speculator_early_exit_produces_valid_logits PASSED
tests/test_speculative.py::TestV2Tree::test_tree_verification_accepts_at_least_one_path PASSED
===== 100 speculative steps =====
Acceptance rate: 0.772
Speedup vs std: 4.86x
Target calls: 100
Tokens generated:486 Benchmarks
Apple M1 Ultra, 64 GB RAM, Python 3.13.7, torch 2.14.1 (CPU) — mock models | Metric | Result | Notes |
|---|---|---|
| Expected tokens per target call (per-token acceptance 0.82, K=5) | 3.87 tokens | calculated — (1 - 0.82^6) / (1 - 0.82) |
| Net speedup with a draft at 10% of target cost (acceptance 0.82, K=5) | 2.58 x | calculated — 3.87 / (1 + 5 x 0.10) |
| Target model calls per 100 tokens (acceptance 0.82, K=5) | 26 calls | calculated — 100 / 3.87 |
| Tokens per target call, mock draft (epsilon=0.18), 5,000 steps | 4.64 tokens | simulated — observed per-token acceptance 0.895; closed form gives 4.63 |
Rows marked calculated come from the closed form. The simulated row comes from the mock models in src/models.py, not a real draft/target pair, so it confirms the math rather than predicting production speed. We haven’t measured a real pair. Published wall-clock results depend heavily on the models and hardware: Leviathan et al. (2023) report 2-3x on T5-XXL, and Chen et al. (2023) report 2-2.5x on Chinchilla 70B.
Run python -c "from src.v1_batched import expected_speedup; [print(f'alpha={a:.2f}: {expected_speedup(a,5):.2f}x') for a in [0.6, 0.7, 0.8, 0.82, 0.9]]" to see expected tokens per target call at different acceptance rates.
Stress tests
Acceptance rate vs K: run 1000 speculative steps with K=1, 3, 5, 8, 10 and measure speedup_vs_standard at each K. You should see tokens per call increase with K (more draft tokens amortize the target call), then plateau as alpha^K becomes negligible. Net speedup peaks earlier because every extra draft token costs draft time: at alpha=0.82 with a draft at 10% of target cost, optimal_K(0.82, 0.10) returns 6 (2.61x net), and any K from 5 to 8 is within 2% of that.
Acceptance rate distribution: log n_accepted for each step over 1000 steps. Plot the distribution — it should be a truncated geometric with parameter alpha. Accepting all K drafts is the single most likely outcome (probability alpha^K = 0.82^5 = 0.37 at alpha=0.82). Some steps accept 0 draft tokens (probability 1-alpha = 0.18 for the first rejection). The distribution tells you the tail behavior.
Tree vs linear comparison: run 500 steps with linear draft (width=1, depth=5) and tree draft (width=2, depth=3) at the same target model. Compare mean_accepted_per_step. The tree should outperform linear at the same total draft token budget because it explores more paths. The difference narrows as acceptance rate increases.
Self-speculative layer depth: vary the early exit layer in SelfSpeculator from layer 0 to the penultimate layer. Measure acceptance rate at each exit point. You should see acceptance rate increase as the exit layer gets closer to the final layer (early exit is worse draft; final layer early exit approaches target quality). Plot this curve — it shows how many layers of the model are “wasted” on refinement that doesn’t change the top token.
Batch size scaling: run decode_batch with batch_size=1, 2, 4, 8 and fixed total tokens. In our CPU simulation, time scales linearly with batch_size (no GPU parallelism). But target_calls stays the same because we count one step as one target call regardless of batch size. This demonstrates how GPU batching would eliminate the batch_size scaling: the same number of target calls processes more prompts.
What the toy misses
- GPU kernel implementation Real speculative decoding requires custom CUDA kernels for tree attention masking — standard FlashAttention does not support tree-structured attention patterns. Our simulation uses CPU torch operations.
- Draft model selection The draft model must be fast enough that K drafts take less time than 1 target verification. If draft takes 20% of target time, K=5 drafts use one full target call — breaking even. Optimal K depends on draft latency ratio.
- Adaptive K selection DeepMind's Medusa and similar approaches adapt K dynamically: if acceptance rate drops below threshold (domain shift), reduce K to avoid wasteful drafting. Fixed K is suboptimal across diverse inputs.
- Lookahead decoding Lookahead decoding generates draft tokens from earlier positions in parallel without a separate draft model — using the Jacobi iteration approach. This requires no draft model but achieves lower acceptance rates than a trained draft.
- Output quality equivalence proof Standard speculative decoding produces exactly the same output distribution as target-only decoding (provably). But tree speculative decoding can introduce distribution shift if the acceptance criterion is not carefully derived.
- Production serving integration vLLM implements speculative decoding with paged attention — draft tokens must be allocated in pages that may be freed on rejection. Integrating with page management requires significant engineering.
Wiring it into a Java/Spring service
Wiring it into a Java/Spring service
org.springframework.ai:spring-ai-openai-spring-boot-starter:1.0.0 org.springframework.boot:spring-boot-starter-web:3.3.0 labs/speculative-decoding/java-integration Clone and run: cd labs/speculative-decoding/java-integration && mvn spring-boot:run Part A — SpeculativeClient: direct HTTP access
SpeculativeClient.java wraps our FastAPI server. It demonstrates the key property of speculative decoding from a caller’s perspective: the API is identical to standard decoding. You send a prompt, you receive tokens. The speedup is invisible to the caller.
public class SpeculativeClient {
public GenerateResponse generate(List<Integer> promptTokens) {
var body = new GenerateRequest(promptTokens, props.maxTokens(), props.k());
return http.post()
.uri("/generate")
.body(body)
.retrieve()
.body(GenerateResponse.class);
}
public StatsResponse stats() {
return http.get().uri("/stats").retrieve().body(StatsResponse.class);
}
}The response includes speedupVsStandard and acceptanceRate — metrics that are invisible to the caller during generation but available for monitoring. This is the correct production pattern: expose metrics via /stats, not in the generation response itself.
Part B — Speedup math in Java
The geometric series formula translates directly to Java:
double alpha = 0.82; // per-token acceptance probability
int K = 5; // speculation width
double tokensPerCall = 0.0;
for (int i = 0; i <= K; i++) {
tokensPerCall += Math.pow(alpha, i);
}
// tokensPerCall = 1 + 0.82 + 0.6724 + 0.5514 + 0.4521 + 0.3707 = 3.867
// = (1 - alpha^(K+1)) / (1 - alpha): accepted drafts + 1 corrected/bonus token
// Net of a draft at 10% of target cost: 3.867 / (1 + 5 * 0.10) = 2.58xThis is a useful back-of-envelope calculation for sizing inference infrastructure. If your target model costs 50ms per call and the draft adds 10% per draft token, each step costs 75ms and yields about 3.87 tokens, so effective latency per token drops from 50ms to about 19ms.
Part C — Spring AI ChatClient: transparency
The same ChatClient that calls our speculative decoding server would call OpenAI’s API or a standard non-speculative inference server with zero code changes:
ChatClient chatClient = chatClientBuilder.build();
// This is identical whether the backend uses speculative decoding or not.
// The output quality is the same; only throughput differs.
String response = chatClient.prompt(
"Explain speculative decoding in one sentence."
).call().content();Configure the backend in application.yml:
spring:
ai:
openai:
base-url: http://localhost:8000 # our server with speculative decoding
api-key: local-dummy-keyChange base-url to https://api.openai.com/v1 and api-key to your real key — the Java code is unchanged. This is why speculative decoding is a serving optimization, not a model change: it is completely transparent to the application layer.
Run it
# Terminal 1: start the Python speculative decoding server
cd labs/speculative-decoding
uvicorn src.server:app --port 8000
# Terminal 2: start the Spring Boot demo
cd labs/speculative-decoding/java-integration
mvn spring-boot:runExpected output:
=== Speculative Decoding Lab — Spring Integration Demo ===
--- Part 1: SpeculativeClient (direct HTTP) ---
Prompt tokens: [10, 20, 30, 40, 50]
Tokens generated: 40
Target calls: 9
Acceptance rate: 0.800
Speedup vs std: 5.00x
Aggregate stats (since server start):
Total tokens generated: 45
Total target calls: 9
Acceptance rate: 0.800
Speedup vs standard: 5.00x
Target calls per 1k tok: 200.0
--- Part 2: Speedup math (geometric series) ---
alpha=0.82, K=5
Geometric series: sum(alpha^i, i=0..5)
i=0: 0.8200^0 = 1.0000 (cumsum = 1.0000)
i=1: 0.8200^1 = 0.8200 (cumsum = 1.8200)
i=2: 0.8200^2 = 0.6724 (cumsum = 2.4924)
i=3: 0.8200^3 = 0.5514 (cumsum = 3.0438)
i=4: 0.8200^4 = 0.4521 (cumsum = 3.4959)
i=5: 0.8200^5 = 0.3707 (cumsum = 3.8666)
Expected accepted draft tokens: 2.867
Tokens per target call: 3.867 (accepted drafts + 1 corrected/bonus token)
Target-call reduction vs standard decoding: ~3.9x
Done. What surprised me
Where to go deeper
- Speculative Decoding paper (Chen et al. 2023): the original proof that output distribution is preserved — arxiv.org/abs/2302.01318
- SpecTr: Fast Speculative Decoding via Optimal Transport (2023): generalises the acceptance criterion to optimal transport — arxiv.org/abs/2310.15141
- Medusa: Multiple Decoding Heads: extends self-speculative with multiple heads at different positions — arxiv.org/abs/2401.10774
- vLLM speculative decoding docs: production implementation with paged attention integration — docs.vllm.ai/en/latest/models/spec_decode.html
- Spring AI docs: ChatClient abstraction, prompt templating, model swapping — docs.spring.io/spring-ai
Related labs and questions
- Previous in AI: LLM Inference Engine (lab
llm-inference) — KV cache, continuous batching, and paged attention that speculative decoding builds on - Previous in AI: Transformer From Scratch (lab
transformer) — the model architecture that creates the forward pass speculative decoding exploits - Next in AI: Local GenAI stack — running speculative decoding offline with Ollama and quantized models
- System design question: At what draft-to-target cost ratio does speculative decoding with K=5 break even? (Answer: if the draft costs more than 1/(K+1) = 16.7% of the target’s time, the overhead exceeds the gain — you need an even smaller draft model or lower K.)
- System design question: How does speculative decoding interact with beam search? (Speculative decoding is designed for greedy/temperature sampling, not beam search. Beam search maintains B candidate sequences simultaneously — speculative decoding can be applied per-beam, but the combinatorics make tree attention exponentially more expensive.)