Skip to content

Kangaroo

At a glance

Kangaroo (Liu et al., 2024): self-speculative drafting through a shallow sub-network and an adapter.

Registered name Family Saves Lossless Trainable Configuration
kangaroo drafting latency yes adapter_net KangarooConfig

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

Kangaroo (Liu et al., 2024) drafts with a shallow sub-network of the model. A draft step runs the model's first exit_layer layers on the last token, then a small adapter (one attention layer with its own KV cache and two RMS norms, no MLP), and reads the next token from the model's LM head. The adapter is the only trained part. It learns to map the shallow hidden state to one the LM head can read, so a draft costs exit_layer of the model's layers plus one attention layer. The second early exit of the paper stops drafting once the drafter's top probability falls below a threshold, which economize implements as the decoder's dynamic draft length (min_confidence). The model verifies each cycle's drafts in one forward pass, so greedy decoding is lossless.

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

The paper exits after the second layer and stops drafting below a top probability of 0.6:

from economize.techniques.kangaroo import KangarooConfig

model = economize.apply(base, KangarooConfig(exit_layer=2),
                        decoding=economize.DecodeConfig(cycle_length=7, min_confidence=0.6))

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

cycle_length=7 allows up to six drafts per verification, and min_confidence ends a cycle earlier. A new adapter accepts few drafts, but the output is the model's greedy output in every case. The adapter's steps appear in the call log as kangaroo_adapter events of the module kangaroo, next to the draft events of the shallow layers.

Training

Kangaroo has no default objective, so fit takes one by name. step_distill unrolls several draft steps on the drafter's own outputs and matches each to the model's next-token distribution. It trains the adapter only:

from economize.train import fit, fixed_windows

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

StepDistill sets the number of unrolled steps, their weights, the divergence and an optional cross-entropy term:

from economize.train import StepDistill

fit(model, "train.bin", StepDistill(steps=6, step_decay=0.8, divergence="kl", ce_weight=0.1), steps=2000,
    batch_size=8, seq_len=1024)

Saving and loading

model.save_pretrained("kangaroo_adapter")
model.detach()

model = economize.load(base, "kangaroo_adapter",
                       decoding=economize.DecodeConfig(cycle_length=7, min_confidence=0.6))

Decoding options

A larger min_confidence drafts fewer tokens per cycle with a higher acceptance rate. Without it every cycle drafts cycle_length - 1 tokens. Sampling stays lossless with the rejection verifier:

model.decode(ids[0], 64, decoding=economize.DecodeConfig(cycle_length=7, min_confidence=0.8))

sampling = economize.DecodeConfig(cycle_length=7, min_confidence=0.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

Kangaroo composes with techniques that are not drafters. Weight quantization runs first, so the adapter drafts for the quantized model:

from economize.techniques.quant import QuantConfig

print(economize.compatible("kangaroo", "quant"))  # True

model.detach()
model = economize.apply(
    AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda"),
    QuantConfig(format="int8"),
    KangarooConfig(exit_layer=2),
    decoding=economize.DecodeConfig(cycle_length=7, min_confidence=0.6),
)

Serving

economize's vLLM plugin serves the drafter, with layers 1..l shared with the served model and the adapter on its own KV pages. vLLM drafts a fixed number of tokens, so the confidence exit is not served. SGLang has no export for Kangaroo:

from economize.backends.vllm import serving

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

Configuration

KangarooConfig dataclass

KangarooConfig(exit_layer: int = 2, num_heads: int | None = None, num_kv_heads: int | None = None, head_dim: int | None = None, rms_norm_eps: float | None = None, attention_bias: bool | None = None, param_dtype: str = 'float32', stop_threshold: float | None = 0.6, max_draft: int = 6)

Hyperparameters of a Kangaroo drafter (Liu et al., NeurIPS 2024, arXiv 2404.18911).

A draft step runs the model's first exit_layer (l) layers on the last token, then the adapter (one attention layer with its own KV cache and two RMS norms, no MLP) and the model's LM head. Only the adapter is trained. Kangaroo's second early exit, which stops drafting once the drafter's top-1 probability falls below a threshold (0.6 in the paper), is the decoder's dynamic draft length (DecodeConfig.min_confidence). It is on by default: :func:economize.apply without decoding drafts up to max_draft tokens per cycle and stops at stop_threshold (see :meth:KangarooTechnique.decode_config).

Attributes:

Name Type Description
exit_layer int

l, the last model layer of a draft step (1 <= l < L; the paper's 2 for 7B models).

num_heads int | None

Attention heads of the adapter (None: the model's last full-attention layer's).

num_kv_heads int | None

Key/value heads of the adapter (None: as num_heads' source).

head_dim int | None

Head width of the adapter (None: the model's; another width needs a rotary table of that width, which the model does not have).

rms_norm_eps float | None

Epsilon of the adapter's norms (None: the model's).

attention_bias bool | None

Biases on the q/k/v projections (None: as the model's first layer).

param_dtype str

Storage and compute dtype of the adapter: "float32" (default) or "model".

stop_threshold float | None

Top-1 probability below which a cycle stops drafting (the paper's 0.6; None: draft the full cycle).

max_draft int

Draft tokens per cycle at most (the paper's gamma = 6, so cycles of 7 tokens).

References

  • Liu, F., Tang, Y., Liu, Z., Ni, Y., Han, K., & Wang, Y. (2024). Kangaroo: Lossless self-speculative decoding via double early exiting. In Advances in Neural Information Processing Systems. https://doi.org/10.48550/arXiv.2404.18911