The Evolution of LLM Inference: Decoding algorithms — Part 2
From the publisher’s feed, collected in the ZeroLabs newsroom.
This is the second part of the LLM inference article. For the first part please refer to PART 1 link. This article focuses mainly on decoding algorithms: how we moved from naive autoregressive decoding to speculative decoding, multi-head prediction, tree-based verification, draft-free speculative decoding and long-context speculative decoding. Memory and compute optimizations will also be mentioned later, because in real-world inference systems these techniques are used together.Content (Part 2):🚀 1. Draft-Free Speculative Decoding📖 2. Long-Context Speculative Decoding💾 3. Memory and Compute Optimizations🚀 1. Draft-Free Speculative DecodingWhat is it?Draft-free speculative decoding is a broader category of methods that avoid using a separate small draft model.Instead of the classic draft model → target model verification pipeline, these methods generate candidate tokens using signals from the target model itself, such as early layers, auxiliary heads, cached hidden states, token-level heuristics, or other internal prediction mechanisms.Multi-head speculative decoding methods such as MEDUSA and HYDRA can be viewed as a subset of draft-free speculative decoding, because they remove the separate external draft model.Why use draft-free speculative decoding?Classic speculative decoding works well, but it has practical issues:Need separate draft modelNeed target-draft tokenizer compatibilityNeed model serving for two modelsNeed memory for two KV cachesNeed draft model alignmentAcceptance rate may be lowDraft-free methods try to solve this by using the same model for both drafting and verification. This makes deployment simpler and avoids maintaining a second LLM.Main Categories of Draft-Free Speculative DecodingYou can divide draft-free methods into these practical categories:Draft-Free Speculative Decoding│├── 1. Multi-head / MTP-based drafting│ ├── Medusa│ └── Hydra│├── 2. Early-exit self-speculation│ └── LayerSkip│├── 3. Layer-skipping self-speculation│ └── SWIFT-like methods│└── 4. Hidden-state / feature-level drafting └── EAGLE-style methodsSome of these methods are fully training-free, while others require training auxiliary heads or adapting the model.The Multi-head/ MTP-based drafting (speculative decoding) was covered in previous PART 1 article.Let’s discuss early-exit, layer-skipping and hidden-state based speculative decoding briefly.Difference between early-exit methods and layer-skipping methods?Early exit uses a prefix of the model, while layer skipping uses a sparse path through the model.Early Exit:Uses the first k layers only. It exits early and predicts from that intermediate representation. Example: LayerSkip by META.Layer 1 → 2 → 3 → ... → kLayer Skipping:Still moves through the model depth, but skips some layers. Example SWIFT-like methodsLayer 1 → 4 → 8 → 12 → 16 → 24 → 32— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —1.1 Early-exit self-speculation: LayerSkip— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —A popular early-exit approach was introduced in the LayerSkip research paper. LayerSkip is an inference optimization method where a model can use only the first few layers to produce draft predictions.Instead of using:Full model = layers 1 → 2 → 3 → ... → 32LayerSkip uses:Early model = layers 1 → 2 → ... → 8to produce draft tokens.Then the remaining layers:layers 9 → 10 → ... → 32can verify or correct those tokens.So the same model acts as both:Draft model = early layersTarget model = full modelThis is why LayerSkip is usually called a self-speculative decoding method.LayerSkip, the same LM head is reused at different intermediate layers for early-exit prediction. This is different from Medusa/Hydra, which add extra prediction heads on top of the model.Figure 1: LayerSkip vs MedusaDrafting:Drafting is autoregressiveLayerSkip uses the first E layers as the internal draft model. To draft 4 tokens, it runs the early layers multiple times:Draft token 1:context → layers 1–8 → shared LM head → token x1Draft token 2:context + x1 → layers 1–8 → shared LM head → token x2Draft token 3:context + x1 + x2 → layers 1–8 → shared LM head → token x3Draft token 4:context + x1 + x2 + x3 → layers 1–8 → shared LM head → token x4Verification:Verification is parallel over drafted tokens. After the draft sequence exists:[x1, x2, x3, x4]LayerSkip verifies these tokens using the remaining layers:layers 9–32The paper’s key point is that verification does not recompute layers 1–8. It verifies and corrects using the remaining layers of the model, benefiting from shared compute and activations between drafting and verification.LayerSkip training:LayerSkip changes training so that intermediate layers are also trained to predict the next token. Without this training, early-layer hidden states are not reliable for prediction.LayerSkip uses layer dropout during training.The dropout rate is:lower for early layershigher for later layersSo later layers are skipped more often during training. This forces the model to rely more on earlier layers and improves early-exit accuracy.LayerSkip is most useful when:The model is trained for early exit.The draft tokens from early layers are accurate.The task has predictable local continuations.The acceptance rate is high.Memory budget is limited.You do not want to host a separate draft model.Good use cases:SummarizationCode generationStructured generationDomain-specific finetuned modelsIt is especially attractive for production because it avoids maintaining two separate models.Limitations:1. Needs special training or continual pretraining2. Exit layer must be tuned3. Draft length must be tuned4. Low acceptance rate can remove speedup5. Very hard reasoning tasks may need deeper layers6. Production implementation is more complex than normal decoding— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —1.2 Layer-skipping self-speculation: SWIFT— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —SWIFT forms a draft model by skipping selected intermediate layers of the target LLM and adapts this skipped-layer set on the fly during inference.Unlike LayerSkip, it does not require special training.Overview:Figure 2: LayerSkip vs SWIFTDrafting:In SWIFT drafting, some intermediate layers are skipped:input hidden state → L1 → L2 → skip L3 → L4 → skip L5 → ... → L32 → LM head → draft tokenThis layer-skipped model is cheaper because it performs fewer transformer block computations.Important detail:SWIFT does not create new draft heads.SWIFT does not train a smaller model.SWIFT does not use early-exit logits from an intermediate layer.Instead, it still runs to the final LM head, but the hidden state reaches the final layer after skipping some intermediate blocks.Which layers to skip?SWIFT observes that the best skipped-layer set is task-specific. A skipped-layer pattern that works for storytelling may not work for math reasoning. The paper shows that static layer-skipping patterns can degrade under domain shift.So SWIFT has an optimization phase.During this phase:1. Start with a default layer-skipping pattern.2. Generate some tokens.3. Use already generated target-model tokens as ground truth.4. Try candidate skipped-layer sets.5. Measure how well each candidate predicts the known generated tokens.6. Keep the best skipped-layer set.The paper calls this context-based layer set optimization. It uses the generated context window to evaluate candidate draft models without requiring external training data.Drafting is still autoregressive.The draft tokens are generated one by one by the layer-skipped model. But each draft step is cheaper because fewer layers are executed.SWIFT does not blindly draft a fixed number of tokens every time. For every draft token, it looks at the confidence of the draft model’s top prediction. If confidence becomes too low, SWIFT stops drafting early. The paper calls this early-stopping drafting.Verification:SWIFT verifies the all the draft token in one full-model forward pass. The full model computes probability distributions for all draft positions in parallel. Then speculative decoding acceptance/rejection logic (greedy or sampling logic) decides how many tokens can be accepted.Advantages:No extra training and no extra draft heads. It uses the same LLM, skips selected intermediate layers, drafts cheaply, and verifies with the full model.It is plug-and-play: SWIFT is easier to test on already-deployed models because it does not require changing the model weights.Disadvantages:Speedup is usually more modest than trained methods like Medusa/Hydra/LayerSkip, and implementation is more complex than it looks because layer skipping, KV cache reuse, and verification need inference-engine support.— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —1.3 Hidden layer / feature level drafting: EAGLE— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —EAGLE:EAGLE shifts drafting from token space to feature space. EAGLE focuses on the hidden representation right before the final transformer layer. It trains a small autoregressive head/drafter to predict the target model’s future near-final hidden features.Figure 3: EAGLEThe idea is:Instead of drafting future tokens directly, EAGLE predicts future high-level hidden features using the target model’s hidden features near the final layer, and then uses the target model’s LM head to convert those predicted features into token probabilities.Why use the hidden features?EAGLE states that the model’s hidden states are smoother and easier to extrapolate than raw discrete tokens.Drafting:EAGLE drafting is still autoregressive.It drafts tokens one by one using the lightweight EAGLE draft module. A tree of draft tokens are generated.Verification:EAGLE 2:EAGLE-2 uses dynamic draft tree. Original EAGLE uses a relatively static draft tree. This assumes that token acceptance mostly depends on the token’s depth in the draft.EAGLE-2 observes that acceptance is also context-dependent. Some contexts are easy:"The capital of France is ..."The draft model may be very confident, so we can speculate more aggressively.Other contexts are hard:"Prove the following theorem ..."The draft model may be uncertain, so a large draft tree wastes compute.EAGLE-2 uses the draft model’s confidence scores to estimate acceptance probability and dynamically adjust the draft tree.EAGLE 3:EAGLE-3 uses direct token prediction + multi-layer feature fusion.It also stops relying only on near-final-layer hidden features. Instead, it uses multi-layer feature fusion, combining information from low, middle, and high layers. So EAGLE-3 gives the drafter richer information.The EAGLE-3 abandons feature prediction in favor of direct token prediction and replaces reliance on top-layer features with multi-layer feature fusion.📖 2. Long-Context Speculative DecodingWhy normal speculative decoding is not enough?Problem 1: Draft model KV cache becomes too largeClassic speculative decoding uses:small draft model → proposes multiple tokenslarge target model → verifies them in parallelThis works well when the draft model is cheap and its KV cache is small.But in long-context inference, even the draft model may need to maintain and read a long KV cache. That means the draft model is no longer “cheap enough.”Problem 2: Draft model was trained mostly on short positionsMany draft models are trained on short sequences, often under 4K tokens. During long-context inference, the model may need to draft at positions like 64K or 128K. This creates a positional distribution shift. So the draft model may become less accurate, which lowers the acceptance rate.Problem 3: Tree verification becomes inefficientTree speculative decoding verifies many possible draft branches. But tree attention uses irregular masks. Existing optimized long-context attention kernels are usually designed for regular attention patterns, not arbitrary tree masks.How does long-context speculating decoding methods help?Long-context methods try to make the drafter cheaper using ideas like:1. Constant-size KV cache2. Hierarchical drafting3. Retrieved/local context onlyMeaning:Target model keeps full long context for correctness.Draft model uses cheaper approximate context for speed.Then the target model verifies the draft tokens using the real full context.Let’s discuss two popular methods here: LongSpec and Hierarchical drafting (Hierarchical speculative decoding)— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —2.1 Method 1: LongSpec— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —LongSpec is a long-context speculative decoding technique designed to make drafting efficient when the prompt or generated sequence is very long. Instead of giving the small drafter its own full long-context KV cache, LongSpec uses a constant-size drafter with sliding-window attention and cross-attention to the target model’s KV cache. This reduces memory overhead while still allowing speculative decoding to use long-context information during inference.Figure 4: LongSpec draft-and-verifyLong Spec Idea:Target model:Keeps full long-context KV cacheLongSpec draft model:Uses sliding-window self-attention for local contextUses cross-attention to target model KV cache for long contextDoes not keep a full growing KV cacheVerification:Uses target model with efficient hybrid tree attentionDraft model architecture:LongSpec’s draft model is not a normal standalone small LLM. It is a lightweight drafter designed for long-context inference.The draft model has two main attention parts:1. Sliding-window self-attention2. Cross-attention over target model KV cacheThe draft model only keeps a local window of recent tokens. This keeps the draft model’s own KV cache bounded.The obvious problem is: if the draft model only sees a local window, how does it know the long context?LongSpec solves this by adding cross-attention that reuses the target model’s KV cache. The target model already has a full KV cache because it must be used for verification anyway. LongSpec’s draft model uses that existing information rather than storing a second full cache.Inside the draft model, cross-attention queries the target model’s long-context KV cache:Q_draft = draft hidden stateK_target, V_target = target model KV cacheCross-attention:Attention(Q_draft, K_target, V_target)This lets the draft model access global context without maintaining its own full KV cache.LongSpec also shares the embedding layer and LM head between the draft and target model, reducing memory cost for large-vocabulary LLMs.Drafting and Verification:Like other speculative decoding methods, LongSpec can draft multiple candidate future tokens. It drafts tree of tokens, instead of generating only one linear path.Then the target model verifies this tree.Hybrid Tree Attention:This is one of LongSpec’s most important inference optimizations.Attention pattern is mixed:Prefix tokens:Regular attention, no tree mask neededSpeculative tree tokens:Irregular tree mask neededLongSpec separates these two parts.Conceptually:output_prefix = attention over long cached prefixoutput_tree = attention over draft tree tokens with maskfinal_attention_output = merge(output_prefix, output_tree)This is important because most of the attention cost comes from the long prefix. LongSpec lets that part use fast optimized kernels instead of forcing the entire attention operation into a slow tree-mask implementation.Useful for long-context tasks:Long-document summarizationRepository-level code completionLong-context QALong chain-of-thought reasoningAgentic workflows with large historiesLimitations:LongSpec is more complex than classic speculative decoding. You need a specially trained drafter, cross-attention into the target KV cache, position-index training tricks, and optimized tree-attention kernels.— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —2.2 Method 2: Hierarchical speculative decoding (TriForce)— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —TriForce is a popular method utilizing Hierarchical speculative decoding.Overview:Figure 5: TriForce (Hirarchical Speculative Decoding)Idea:Instead of using only one draft model, TriForce uses a hierarchy:1. A tiny draft model for very cheap initial drafting2. The target model with a small retrieved KV cache as an intermediate draft model3. The full target model with full KV cache as the final verifierTriForce is based on an observation:In long-context attention, the model often does not need to attend strongly to every previous token at every decoding step.Drafting and Verification:Step 1: The small draft model generates a few candidate future tokens.This step uses StreamingLLM cache. This keeps a small local/sink-token style context for the draft model.Example:Current sequence: x1 ... xtSmall model drafts:d1, d2, d3, d4TriForce generates a single draft token sequence, not a draft tree.Step 2: Target model verifies with a small retrieved KV cache.Target model + retrieved KV cacheverify d1, d2, d3, d4This gives better draft quality than the tiny model alone, because it uses the target model’s own weights. This is still faster than the full target model because it avoids reading the full long-context KV cache.This intermediate step is not merely a filter. It accepts the small model’s draft tokens until the first rejection, then samples a corrected token from the intermediate target model with retrieval KV cache and discards the remaining small-model draft tokens. The resulting corrected candidate sequence is then passed to the full target model with the complete KV cache for final lossless verification.Step 3: The full target model then verifies the candidate sequence using the complete KV cache. Similar to the Classic Speculative Decoding.Target model weights + full KV cacheVerify accepted candidate sequenceAdvantages:1. Training-freeNo need to train a special long-context draft model.2. Long-context friendlyDesigned for 128K-context models and beyond.3. High acceptance rateThe paper reports strong acceptance rates across temperatures.Limitations:System complexity is high: You need multiple caches, multiple verification stages, and careful cache updates. For short prompts, the KV-cache bottleneck is smaller, so the benefit may be limited. If the retrieved KV cache does not approximate the full context well, more draft tokens get rejected.💾 Memory and Compute OptimizationsThese are not the main focus of this article, because they are already well covered widely. But they are important because almost every decoding method depends on them. So here is a short summary of each.KV cacheIn transformer decoding, each token creates key and value vectors for attention. Without caching, the model would recompute keys and values for all previous tokens at every step. KV cache stores previous keys and values, so the model only computes the new token’s KV states. KV cache avoids recomputing past attention states.AdvantageIt gives a major speedup and is essential for LLM inference.DisadvantageKV cache becomes very large for long context, large batch size, and large models.Production statusVery important in production. Every serious LLM serving system uses KV cache.PagedAttention / KV memory managementKV cache is large and irregular. Each request has a different length. If KV cache is allocated naively, memory gets fragmented.PagedAttention, introduced in vLLM, treats the KV cache like virtual memory pages. Instead of storing each request’s KV cache as one large contiguous memory region, it splits the cache into fixed-size blocks that can be allocated, shared, and reused dynamically. This reduces memory fragmentation and allows the serving system to support more concurrent requests.AdvantageBetter memory utilization, larger batches, higher throughput.DisadvantageRequires specialized serving infrastructure.ToolsvLLM is the most famous example. SGLang and TensorRT-LLM also include advanced KV memory management.Production statusVery important in production. Especially for high-throughput serving.Continuous batchingIn real serving, many users send requests at different times. Some requests are short, some are long. Static batching wastes GPU time because finished sequences leave empty slots.Continuous batching dynamically adds new requests while old requests are still decoding. Continuous batching keeps the GPU busy.AdvantageHigher throughput and better GPU utilization.DisadvantageThe scheduler becomes more complex.Production statusVery important in production. This is a core serving-engine feature.Prefix cachingMany applications reuse the same prompt prefix: system prompt, tool instructions, RAG template, conversation history, or coding-agent context.Prefix caching stores KV cache for repeated prefixes and reuses it. vLLM documentation describes prefix caching as a popular optimization that avoids redundant prompt computation and is widely used in public endpoints and open-source inference frameworks.AdvantageCan reduce prefill cost significantly.DisadvantageOnly helps when prefixes repeat.ToolsvLLM, SGLang, TensorRT-LLM, OpenAI-style prompt caching APIs.Production statusImportant in production, especially for RAG, agents, and chat systems.Chunked prefillLLM inference has two phases:Prefill: process prompt tokensDecode: generate output tokensPrefill is compute-heavy. Decode is memory-bandwidth-heavy. Long prompts can block decode requests.Chunked prefill breaks large prompts into smaller chunks and mixes them with decode work. vLLM documentation says chunked prefill helps balance compute-bound prefill and memory-bound decode operations.AdvantageBetter latency and throughput balance.DisadvantageMore complex scheduling.ToolsvLLM, SGLang, TensorRT-LLM.Production statusImportant for serving long prompts.Quantization and FlashAttentionQuantization reduces precision: FP16/BF16 → FP8/INT8/INT4. This reduces memory bandwidth and allows larger models to fit on hardware.FlashAttention optimizes attention by reducing memory reads/writes.AdvantageLower latency, lower memory usage, higher throughput.DisadvantageQuantization can reduce quality if not calibrated well. Kernel support is hardware-dependent.ToolsTensorRT-LLM, vLLM, FlashAttention, FlashInfer, bitsandbytes, AutoGPTQ, AutoAWQ, llama.cpp.Production statusVery important in production. Especially for reducing model size and latency.Hope this was useful in understanding how decoding algorithms work, reduce LLM inference latency and why it is becoming an important part of modern serving systems.References:LayerSkip: Enabling Early Exit Inference and Self-Speculative DecodingSWIFT: On-the-Fly Self-Speculative Decoding for LLM Inference AccelerationEAGLE: Speculative Sampling Requires Rethinking Feature UncertaintyEAGLE-2: Faster Inference of Language Models with Dynamic Draft TreesEAGLE-3: Scaling up Inference Acceleration of Large Language Models via Training-Time TestLongSpec: Long-Context Lossless Speculative Decoding with Efficient Drafting and VerificationTriForce: Lossless Acceleration of Long Sequence Generation with Hierarchical Speculative DecodingThe Evolution of LLM Inference: Decoding algorithms — Part 2 was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.