Skip to content

EAGLE-3

At a glance

EAGLE-3 (Li et al., 2025): one draft decoder layer with its own attention and KV cache.

Registered name Family Saves Lossless Trainable Configuration
eagle3 drafting latency yes fc, layer, norm, lm_head Eagle3Config

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

EAGLE-3 (Li et al., 2025) is a drafter of one decoder layer that sits next to the model. It fuses the model's hidden states at a low, a middle and a high layer of the previous token into one vector, reads it together with the embedding of the current token, and drafts the next token through its own norm and LM head. Each draft step feeds the layer's output back in place of the fused vector, so a chain of drafts costs one small layer per token. The model then verifies the whole chain in one forward pass and keeps the longest prefix it agrees with, which makes greedy decoding lossless. The layer is trained with the training-time test, which unrolls several draft steps on the drafter's own outputs.

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

A new EAGLE-3 head attaches with economize.apply. Here it drafts from the 32768 tokens that are most frequent in the calibration data, which makes its LM head about five times smaller than the model's:

from economize.techniques.eagle3 import Eagle3Config
from economize.techniques.frspec import frequency_order

model = economize.apply(base, Eagle3Config(draft_vocab=32768), decoding=economize.DecodeConfig(cycle_length=6))
model.techniques["eagle3"].set_draft_vocab(frequency_order(calibration, base.config.vocab_size)[:32768])

result = model.decode(ids[0], 64)
print(tokenizer.decode(result.tokens))
print(result.mean_accepted)            # accepted drafts per verification

cycle_length=6 drafts five tokens per verification. An untrained head accepts almost none of them; the output is nevertheless exactly the model's greedy output, because every token is verified. model.generate takes the usual transformers arguments and returns the same tokens as base.generate:

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

Training

fit trains the parameters the technique adds, on the frozen model. For EAGLE-3 the default objective is the training-time test eagle3_ttt with SpecForge's optimizer settings (AdamW at 1e-4 without weight decay, gradients clipped to 0.5):

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/eagle3")
print(result.eval)                      # teacher-forced KL and agreement per draft step

The objective object sets the number of unrolled steps, their weights and the divergence:

from economize.techniques.eagle3.objective import Eagle3TTT

fit(model, "train.bin", Eagle3TTT(steps=7, step_decay=0.8, divergence="kl"), steps=2000, batch_size=8,
    seq_len=1024)

A drafter accepts more tokens when it trains on the model's own answers. Training shows how to generate them with generate_self_distillation and how to train with the transformers Trainer or with accelerate on several GPUs.

Saving and loading

model.save_pretrained("eagle3_head")
model.detach()

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

Published EAGLE-3 heads (the authors', SpecForge, AngelSlim and RedHatAI speculators) load onto their base model in the same way:

llama = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B-Instruct", dtype=torch.bfloat16,
                                             device_map="cuda")
model = economize.load(llama, "yuhuili/EAGLE3-LLaMA3.1-Instruct-8B", decoding=economize.DecodeConfig(cycle_length=6))

Decoding options

The draft policy decides the shape of the drafts. EAGLE-3's dynamic draft tree, which expands the most probable branches, is the policy dynamic_tree (Dynamic draft trees):

tree = 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=tree)

Sampling at a temperature above zero stays lossless with the rejection verifier, which accepts drafts by speculative sampling:

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

EAGLE-3 composes with most techniques that are not themselves drafters (economize.compatible tells which). Weight transforms run first, so a quantized model is drafted for as it is served:

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),
    Eagle3Config(draft_vocab=32768),
    calibration=calibration,
    decoding=economize.DecodeConfig(cycle_length=6),
)

Serving

vLLM and SGLang serve the head with their own EAGLE-3 implementation. The export writes the head in their format, including the reduced vocabulary, and returns the engine arguments:

from economize.backends.vllm import serving

plan = serving.to_vllm(model, "out/qwen-eagle3", num_speculative_tokens=5)
llm = plan.llm()

Configuration

Eagle3Config dataclass

Eagle3Config(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', aux_layers: tuple[int, ...] | None = None, head: str = 'own', draft_vocab: int | None = None, norm_before_residual: bool = False)

Hyperparameters of an EAGLE-3 draft head (Li et al., 2025, arXiv 2503.01840).

The drafter fuses the model's hidden states at aux_layers (the outputs of those blocks, 0 being the token embedding) of token t - 1 with fc into one vector g, and runs one decoder layer with its own attention and KV cache on [norm(E[x_t]); norm(g)] at position t. The layer's output drafts token t + 1 and replaces g at the next draft step. The draft layer's shape, rotary table and training options are those of :class:~economize.techniques._draft_layer.DraftLayerConfig.

Attributes:

Name Type Description
aux_layers tuple[int, ...] | None

Layers whose states are fused (None: (2, L // 2, L - 3), the paper's choice).

head str

"own" (EAGLE-3: own final norm and LM head, initialized from the model's) or "shared" (the model's frozen final norm and LM head).

draft_vocab int | None

Size of the own head's vocabulary (None: the model's). Draft token i is model token i + d2t[i]; :meth:Eagle3Technique.set_draft_vocab chooses the tokens.

norm_before_residual bool

The residual of the attention block is the normalized g (SpecForge option).

layers

layers(num_layers: int) -> tuple[int, ...]

The fused layers for a model with num_layers blocks.

References

  • Li, Y., Wei, F., Zhang, C., & Zhang, H. (2025). EAGLE-3: Scaling up inference acceleration of large language models via training-time test (arXiv:2503.01840). arXiv. https://doi.org/10.48550/arXiv.2503.01840