Skip to content

EAGLE and EAGLE-2

At a glance

EAGLE-1 and EAGLE-2: one draft decoder layer on the model's features, with a static or dynamic draft tree.

Registered name Family Saves Lossless Trainable Configuration
eagle drafting latency yes layer EagleConfig

Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: untested · trtllm: no · vllm: real

EAGLE (Li et al., 2024a) drafts at the level of features. Its drafter is one decoder layer with its own attention and KV cache. At position t it reads fc([E[x_t]; f_{t-1}]), where f_{t-1} is the base model's last hidden state after the final norm when token t - 1 was processed by the base model, and the layer's own previous output otherwise. The base model's LM head turns the layer's output into the next draft token, so each draft costs one small layer and one LM head call. The base model verifies the drafts in one forward pass and keeps the longest prefix it agrees with, which makes greedy decoding lossless. EAGLE-2 (Li et al., 2024b) keeps the same head and replaces the static draft tree with a dynamic one that expands the most probable branches. Only the draft layer is trained.

economize trains the layer by default with HASS (Zhang et al., 2025), which adds a top-K distillation term and unrolls the drafter on its own outputs during training. HASS changes only the objective, so its heads save, load and decode as EAGLE heads.

Setup

Every tutorial starts from the same model and prompt:

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

import economize

device = "cuda" if torch.cuda.is_available() else "cpu"
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map=device)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
ids = tokenizer("Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. "
                "How many clips did Natalia sell altogether?", return_tensors="pt").input_ids.to(device)

Training data is a flat file of uint32 token ids, the format of nanoGPT-style pretraining shards, and calibration data is a [N, S] tensor of token ids. Both are made here from GSM8K:

import numpy as np
from datasets import load_dataset

texts = [f"{row['question']}\n{row['answer']}" for row in load_dataset("openai/gsm8k", "main", split="train")]
tokens = np.concatenate([tokenizer(t + tokenizer.eos_token).input_ids for t in texts]).astype(np.uint32)
tokens[: len(tokens) * 9 // 10].tofile("train.bin")
tokens[len(tokens) * 9 // 10 :].tofile("val.bin")

calibration = torch.from_numpy(tokens[: 128 * 2048].astype(np.int64)).view(128, 2048)

Quick start

from economize.techniques.eagle import EagleConfig

model = economize.apply(base, EagleConfig(), decoding=economize.DecodeConfig(cycle_length=6))

result = model.decode(ids[0], 64)
print(tokenizer.decode(result.tokens))
print(result.mean_accepted)            # accepted drafts per verification
print(result.cost_summary())           # base model calls, draft steps and layer-tokens

cycle_length=6 drafts five tokens per verification. A new head accepts almost none of them, and the output is still exactly the base model's greedy output, because every token is verified. model.generate takes the usual transformers arguments:

out = model.generate(ids, max_new_tokens=64)

Training

fit trains the draft layer on the frozen base model. The default objective for eagle is hass:

from economize.train import fit, fixed_windows

result = fit(model, "train.bin", steps=2000, batch_size=8, seq_len=1024, seed=0,
             eval_data=fixed_windows("val.bin", 64, 1024), output_dir="runs/eagle")
print(result.eval)                      # teacher-forced KL and agreement per draft step

HassDistill sets the number of unrolled steps (the paper uses 3), the size and weight of the top-K term, and whether a step's input carries the gradient of the step before it. detach_steps=False gives EAGLE-3's training-time test plus the top-K term:

from economize.techniques.hass import HassDistill

fit(model, "train.bin", HassDistill(technique="eagle", steps=3, top_k=10, top_k_weight=1.0), steps=2000,
    batch_size=8, seq_len=1024)

The original EAGLE recipe distills one step at a time. The generic objective step_distill with steps=1 comes closest to it:

from economize.train.objectives import StepDistill

fit(model, "train.bin", StepDistill(technique="eagle", steps=1, ce_weight=0.1), steps=2000, batch_size=8,
    seq_len=1024)

Training shows how to train on the base model's own answers and on several GPUs.

Saving and loading

model.save_pretrained("eagle_head")
model.detach()

model = economize.load(base, "eagle_head", decoding=economize.DecodeConfig(cycle_length=6))

The authors' heads (yuhuili/EAGLE-*) load from their repository folder onto their base model:

from huggingface_hub import snapshot_download

vicuna = AutoModelForCausalLM.from_pretrained("lmsys/vicuna-7b-v1.3", dtype=torch.bfloat16, device_map="cuda")
model = economize.load(vicuna, snapshot_download("yuhuili/EAGLE-Vicuna-7B-v1.3"),
                       decoding=economize.DecodeConfig(cycle_length=6))

Decoding options

EAGLE-2 is the same head with the draft policy dynamic_tree (Dynamic draft trees):

eagle2 = economize.DecodeConfig(
    cycle_length=7, draft_policy="dynamic_tree", draft_policy_options={"depth": 6, "topk": 10, "total_tokens": 60}
)
model.decode(ids[0], 64, decoding=eagle2)

Sampling at a temperature above zero stays lossless with the rejection verifier:

sampling = economize.DecodeConfig(cycle_length=6, verifier="rejection")
sampled = model.generate(ids, max_new_tokens=64, do_sample=True, temperature=0.7, top_p=0.9, decoding=sampling)

Combining with other techniques

The head composes with techniques that are not themselves drafters, such as weight quantization and a quantized KV cache. FR-Spec restricts its draft vocabulary.

from economize.techniques.kv_quant.kivi import KIVIConfig
from economize.techniques.quant import QuantConfig

model.detach()
model = economize.apply(
    AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda"),
    QuantConfig(format="int8"),
    KIVIConfig(bits=4),
    EagleConfig(),
    calibration=calibration,
    decoding=economize.DecodeConfig(cycle_length=6),
)

Serving

A trained head is served by vLLM's EAGLE proposer. economize.serving.to_vllm writes the target, the drafter folder (a one-layer Llama draft config with the fc and layers.0 tensors) and a plan with method="eagle". A head with an fc bias, the default, runs on a subclass of vLLM's EagleLlamaForCausalLM that economize's vLLM plugin registers. vLLM verifies one chain per request, so an EAGLE-2 head drafts num_speculative_tokens steps of its most likely token. to_sglang writes the same head as SGLang's LlamaForCausalLMEagle folder for its EAGLE algorithm; that path has not been run on SGLang yet and is reported as untested. The authors' own heads run on both engines without economize.

Configuration

EagleConfig dataclass

EagleConfig(intermediate_size: int | None = None, num_heads: int | None = None, num_kv_heads: int | None = None, head_dim: int | None = None, attention_bias: bool | None = None, rope_theta: float | None = None, rope_scaling: JSONObject | None = None, partial_rotary_factor: float = 1.0, max_position_embeddings: int | None = None, rms_norm_eps: float | None = None, zero_source_first: bool = False, train_steps: int = 7, checkpoint_steps: bool = False, param_dtype: str = 'float32', fc_bias: bool = True)

Hyperparameters of an EAGLE-1 draft head (Li et al., 2024, arXiv 2401.15077), which EAGLE-2 (arXiv 2406.16858) drafts with a dynamic tree.

At position t the drafter runs one decoder layer with its own attention and KV cache on fc([E[x_t]; f_{t-1}]), where f_{t-1} is the model's last hidden state of token t - 1 after the final norm (the feature EAGLE extrapolates) when that token was processed exactly, and the layer's own output at t - 1 otherwise. The model's LM head reads the layer's output directly (without the final norm) and drafts token t + 1. The layer has no input norm. Its shape, rotary table and training options are those of :class:~economize.techniques._draft_layer.DraftLayerConfig.

EAGLE-2 is this head with DecodeConfig(draft_policy="dynamic_tree"); the official heads (yuhuili/EAGLE-*) serve both.

Attributes:

Name Type Description
fc_bias bool

A bias on fc (the official default; yuhuili/EAGLE-LLaMA3-Instruct-8B has none).

References

  • Li, Y., Wei, F., Zhang, C., & Zhang, H. (2024a). EAGLE: Speculative sampling requires rethinking feature uncertainty. In International Conference on Machine Learning. https://doi.org/10.48550/arXiv.2401.15077
  • Li, Y., Wei, F., Zhang, C., & Zhang, H. (2024b). EAGLE-2: Faster inference of language models with dynamic draft trees. In Conference on Empirical Methods in Natural Language Processing. https://doi.org/10.48550/arXiv.2406.16858
  • Zhang, L., Wang, X., Huang, Y., & Xu, R. (2025). Learning harmonized representations for speculative sampling. In International Conference on Learning Representations. https://doi.org/10.48550/arXiv.2408.15766