Scripts¶
Complete scripts from the examples/ directory of the
repository. Each takes --help and runs on a GPU when one is visible, on the CPU otherwise. The tests run all of
them on a CPU with tiny settings (tests/examples/test_scripts.py).
python examples/prepare_data.py --out data
python examples/train_drafter.py --technique eagle3 --data data --out runs/eagle3
python examples/generate.py --drafter runs/eagle3/final
Tokenize a dataset¶
examples/prepare_data.py
"""Tokenize a Hugging Face dataset into the flat token files that training and calibration read.
python examples/prepare_data.py # GSM8K question + answer
python examples/prepare_data.py --dataset HuggingFaceFW/fineweb-edu --config sample-10BT \\
--template "{text}" --limit 200000 --out data/fineweb
Writes ``<out>/train.bin`` and ``<out>/val.bin`` (uint32 token ids, documents separated by the EOS token), the
format of nanoGPT-style pretraining shards. Training draws random windows of ``train.bin``.
"""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B", help="whose tokenizer to use")
parser.add_argument("--dataset", default="openai/gsm8k")
parser.add_argument("--config", default="main")
parser.add_argument("--split", default="train")
parser.add_argument("--template", default="{question}\n{answer}", help="format string over the dataset columns")
parser.add_argument("--limit", type=int, help="use only the first LIMIT rows")
parser.add_argument("--val-fraction", type=float, default=0.1)
parser.add_argument("--out", default="data", type=Path)
args = parser.parse_args()
tokenizer = AutoTokenizer.from_pretrained(args.model)
split = args.split if args.limit is None else f"{args.split}[:{args.limit}]"
rows = load_dataset(args.dataset, args.config, split=split)
texts = [args.template.format(**row) + tokenizer.eos_token for row in rows]
tokens = np.concatenate([np.asarray(ids, dtype=np.uint32) for ids in tokenizer(texts).input_ids])
cut = int(len(tokens) * (1 - args.val_fraction))
args.out.mkdir(parents=True, exist_ok=True)
tokens[:cut].tofile(args.out / "train.bin")
tokens[cut:].tofile(args.out / "val.bin")
print(f"{len(rows)} documents, {cut} training and {len(tokens) - cut} validation tokens in {args.out}/")
if __name__ == "__main__":
main()
Generate with a drafter¶
examples/generate.py
"""Lossless generation with a drafter, compared with the model alone.
python examples/generate.py # untrained EAGLE-3 head (lossless, slower)
python examples/generate.py --drafter runs/eagle3/final # a trained drafter (see train_drafter.py)
python examples/generate.py --drafter me/qwen2.5-0.5b-eagle3 # or one from the Hugging Face Hub
The drafter only proposes tokens: with greedy verification the output is the output of the model alone.
"""
from __future__ import annotations
import argparse
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import economize
from economize.techniques.eagle3 import Eagle3Config
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B")
parser.add_argument("--drafter", help="economize checkpoint (local or Hub); default: untrained EAGLE-3 head")
parser.add_argument("--prompt", default="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?")
parser.add_argument("--max-new-tokens", type=int, default=128)
parser.add_argument("--cycle-length", type=int, default=6, help="one exact pass + up to N-1 draft steps")
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
args = parser.parse_args()
dtype = torch.bfloat16 if args.device.startswith("cuda") else torch.float32
base = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype).to(args.device)
tokenizer = AutoTokenizer.from_pretrained(args.model)
ids = tokenizer(args.prompt, return_tensors="pt").input_ids.to(args.device)
start = time.perf_counter()
reference = base.generate(ids, max_new_tokens=args.max_new_tokens, do_sample=False)[0, ids.shape[1]:]
base_seconds = time.perf_counter() - start
decoding = economize.DecodeConfig(cycle_length=args.cycle_length)
if args.drafter:
model = economize.load(base, args.drafter, decoding=decoding)
else:
model = economize.apply(base, Eagle3Config(), decoding=decoding)
start = time.perf_counter()
result = model.decode(ids[0], args.max_new_tokens)
seconds = time.perf_counter() - start
print(tokenizer.decode(result.tokens))
n = min(len(reference), len(result.tokens))
print(f"\nidentical to the model alone: {torch.equal(reference[:n].cpu(), result.tokens[:n].cpu())}")
print(f"accepted drafts per cycle: {result.mean_accepted:.2f}")
print(f"wall-clock speedup: {base_seconds / seconds:.2f}x (eager PyTorch, see benchmark.py)")
for key, value in result.cost_summary().items():
print(f" {key}: {value}")
if __name__ == "__main__":
main()
Lossless sampling and batches¶
examples/sampling.py
"""Lossless sampling and batched decoding.
python examples/sampling.py --temperature 0.7 --top-p 0.9
The ``rejection`` verifier accepts sampled drafts so that the output keeps the model's own sampling distribution.
``decode_batch`` decodes prompts of different lengths together, each with its own sampler and stop condition.
"""
from __future__ import annotations
import argparse
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import economize
from economize.techniques.eagle3 import Eagle3Config
PROMPTS = ("The capital of France is", "def fibonacci(n):", "Photosynthesis converts")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B")
parser.add_argument("--drafter", help="economize checkpoint (local or Hub); default: untrained EAGLE-3 head")
parser.add_argument("--temperature", type=float, default=0.7)
parser.add_argument("--top-p", type=float, default=0.9)
parser.add_argument("--max-new-tokens", type=int, default=64)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
args = parser.parse_args()
dtype = torch.bfloat16 if args.device.startswith("cuda") else torch.float32
base = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype).to(args.device)
tokenizer = AutoTokenizer.from_pretrained(args.model)
decoding = economize.DecodeConfig(cycle_length=4, verifier="rejection")
if args.drafter:
model = economize.load(base, args.drafter, decoding=decoding)
else:
model = economize.apply(base, Eagle3Config(), decoding=decoding)
# Through transformers' generate API.
ids = tokenizer(PROMPTS[0], return_tensors="pt").input_ids.to(args.device)
out = model.generate(ids, max_new_tokens=args.max_new_tokens, do_sample=True, temperature=args.temperature,
top_p=args.top_p)
print("generate:", tokenizer.decode(out[0, ids.shape[1]:]), "\n")
# Batched, one sampler per row.
prompts = [tokenizer(p, return_tensors="pt").input_ids[0].to(args.device) for p in PROMPTS]
selectors = [economize.TopPSampler(temperature=args.temperature, top_p=args.top_p, seed=args.seed + i,
device=args.device) for i in range(len(prompts))]
results = model.decode_batch(prompts, args.max_new_tokens, selectors=selectors,
stops=[tokenizer.eos_token_id] * len(prompts))
for prompt, result in zip(PROMPTS, results):
print(f"{prompt!r} -> {tokenizer.decode(result.tokens)!r} ({result.mean_accepted:.2f} accepted per cycle)")
if __name__ == "__main__":
main()
Train a drafter¶
examples/train_drafter.py
"""Train a drafter on a frozen model and save it as an economize checkpoint.
python examples/prepare_data.py --out data
python examples/train_drafter.py --technique eagle3 --data data --steps 2000 --out runs/eagle3
python examples/train_drafter.py --technique early_exit --data data --steps 2000 --out runs/early_exit
python examples/train_drafter.py --technique eagle3 --self-distill 2000 ... # train on the model's own answers
accelerate launch examples/train_drafter.py --accelerate ... # data-parallel on several GPUs
Only the drafter's parameters train; the base weights stay untouched, so decoding with the result stays lossless.
Load the result with ``economize.load(base, "runs/eagle3/final")`` or ``python examples/generate.py --drafter ...``.
"""
from __future__ import annotations
import argparse
from pathlib import Path
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import economize
from economize.techniques.eagle3 import Eagle3Config
from economize.techniques.early_exit import EarlyExitConfig
from economize.techniques.medusa import MedusaConfig
from economize.train import fit, fixed_windows, generate_self_distillation
TECHNIQUES = {
"eagle3": lambda: Eagle3Config(),
"medusa": lambda: MedusaConfig(num_heads=4),
"early_exit": lambda: EarlyExitConfig(exit_layer=6, head="readout"),
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B")
parser.add_argument("--technique", choices=sorted(TECHNIQUES), default="eagle3")
parser.add_argument("--data", type=Path, default=Path("data"), help="directory with train.bin and val.bin")
parser.add_argument("--self-distill", type=int, metavar="N",
help="train on the model's answers to the first N GSM8K questions instead of train.bin")
parser.add_argument("--steps", type=int, default=2000)
parser.add_argument("--batch-size", type=int, default=8)
parser.add_argument("--seq-len", type=int, default=1024)
parser.add_argument("--lr", type=float, help="default: the objective's own learning rate")
parser.add_argument("--eval-windows", type=int, default=64)
parser.add_argument("--eval-seq-len", type=int,
help="length of the validation windows (default: --seq-len)")
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--out", type=Path, default=Path("runs/drafter"))
parser.add_argument("--accelerate", action="store_true", help="run under accelerate launch")
parser.add_argument("--push-to-hub", metavar="REPO", help="upload the trained drafter, e.g. me/qwen-eagle3")
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
args = parser.parse_args()
dtype = torch.bfloat16 if args.device.startswith("cuda") else torch.float32
base = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype)
if not args.accelerate:
base.to(args.device)
model = economize.apply(base, TECHNIQUES[args.technique]())
print(f"{args.technique}: {sum(p.numel() for p in model.technique_parameters()):,} trainable parameters")
data: object = str(args.data / "train.bin")
if args.self_distill:
from datasets import load_dataset
tokenizer = AutoTokenizer.from_pretrained(args.model)
rows = load_dataset("openai/gsm8k", "main", split=f"train[:{args.self_distill}]")
data = generate_self_distillation(base, tokenizer, [row["question"] for row in rows],
max_new_tokens=args.seq_len // 2, batch_size=args.batch_size)
eval_data = fixed_windows(args.data / "val.bin", args.eval_windows, args.eval_seq_len or args.seq_len)
result = fit(model, data, steps=args.steps, batch_size=args.batch_size, seq_len=args.seq_len, lr=args.lr,
seed=args.seed, eval_data=eval_data,
output_dir=args.out, accelerate=args.accelerate)
print(f"final loss {result.losses[-1]:.4f}, saved to {result.final_path}")
for name, value in (result.eval or {}).items():
shown = [round(float(v), 4) for v in value[:4]] if isinstance(value, (list, tuple)) else value
print(f" eval {name}: {shown}")
if args.push_to_hub:
model.push_to_hub(args.push_to_hub, private=True)
if __name__ == "__main__":
main()
Compress the weights¶
examples/compress.py
"""Prune, factorize, quantize or sparsify a model's weights and measure the perplexity it costs.
python examples/prepare_data.py --out data
python examples/compress.py --method wanda-2:4
python examples/compress.py --method gptq-int4 --method teal-40 # several, applied in order
These techniques rewrite the base weights once, when they attach (lossy). Most need calibration data; the papers
use 128 sequences of 2048 tokens. 2:4 pruning stores semi-structured sparse tensors on a CUDA GPU (sm80 or newer)
and the quantization methods store packed codes for a CUDA kernel, so both need a GPU; 2:4 pruning cannot be
combined with low rank or quantization (a later step cannot rewrite the sparse tensors). Depth pruning and low rank
also run on a CPU.
"""
from __future__ import annotations
import argparse
import math
from pathlib import Path
import torch
from transformers import AutoModelForCausalLM
import economize
from economize.techniques.lowrank import LowRankConfig
from economize.techniques.prune import DepthPruneConfig, PruneConfig
from economize.techniques.quant import QuantConfig
from economize.techniques.sparsity import TealConfig
from economize.train import fixed_windows
METHODS = {
"shortgpt-4": lambda: DepthPruneConfig(method="shortgpt", num_blocks=4),
"sleb-4": lambda: DepthPruneConfig(method="sleb", num_blocks=4),
"magnitude-2:4": lambda: PruneConfig(method="magnitude", sparsity="2:4"),
"wanda-2:4": lambda: PruneConfig(method="wanda", sparsity="2:4"),
"sparsegpt-2:4": lambda: PruneConfig(method="sparsegpt", sparsity="2:4"),
"svd_llm-20": lambda: LowRankConfig(method="svd_llm", compression=0.2),
"rtn-int4": lambda: QuantConfig(format="int4", method="rtn", group_size=128),
"gptq-int4": lambda: QuantConfig(format="int4", method="gptq", group_size=128, act_order=True),
"awq-int4": lambda: QuantConfig(format="int4", method="awq", group_size=128),
"fp8": lambda: QuantConfig(format="fp8", group_size=None),
# The sparse TEAL kernel needs a 16-bit CUDA model; on a CPU the masked dense reference gives the same perplexity.
"teal-40": lambda: TealConfig(sparsity=0.4, backend="auto" if torch.cuda.is_available() else "dense"),
}
@torch.no_grad()
def perplexity(model: torch.nn.Module, windows: torch.Tensor, device: str) -> float:
losses = [model(row[None].to(device), labels=row[None].to(device)).loss.float().item() for row in windows]
return math.exp(sum(losses) / len(losses))
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B")
parser.add_argument("--method", action="append", choices=sorted(METHODS), help="repeatable (default: wanda-2:4)")
parser.add_argument("--data", type=Path, default=Path("data"), help="directory with train.bin and val.bin")
parser.add_argument("--calibration", default="128x2048", help="calibration sequences x tokens")
parser.add_argument("--eval", default="32x1024", help="perplexity windows x tokens of val.bin")
parser.add_argument("--save", type=Path, help="save the compressed model's economize checkpoint here")
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
args = parser.parse_args()
dtype = torch.bfloat16 if args.device.startswith("cuda") else torch.float32
base = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype).to(args.device)
n, s = map(int, args.calibration.split("x"))
calibration = fixed_windows(args.data / "train.bin", n, s)
n_eval, s_eval = map(int, args.eval.split("x"))
windows = fixed_windows(args.data / "val.bin", n_eval, s_eval)
before = perplexity(base, windows, args.device)
methods = args.method or ["wanda-2:4"]
model = economize.apply(base, *(METHODS[m]() for m in methods), calibration=calibration)
after = perplexity(model, windows, args.device) # EfficientModel forwards like the model it wraps
print(f"{' + '.join(methods)}: perplexity {before:.3f} -> {after:.3f} ({after / before - 1:+.1%})")
if args.save:
model.save_pretrained(args.save)
if __name__ == "__main__":
main()
Combine techniques¶
examples/combine.py
"""Stack weight compression, a compressed KV cache and a trained drafter in one model.
python examples/prepare_data.py --out data
python examples/combine.py --steps 2000 --out runs/combined
Weight transforms apply first, then the drafter trains on the compressed model it will draft for. Decoding is
lossless with respect to the compressed model: the drafter changes the speed, the weight and KV techniques change
the output. The int4 and int8 kernels need a CUDA GPU; on a CPU the script factorizes the weights (SVD-LLM) instead.
"""
from __future__ import annotations
import argparse
from pathlib import Path
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import economize
from economize.techniques.eagle3 import Eagle3Config
from economize.techniques.kv_quant import KIVIConfig
from economize.techniques.lowrank import LowRankConfig
from economize.techniques.quant import DraftQuantConfig, QuantConfig
from economize.train import fit, fixed_windows
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B")
parser.add_argument("--data", type=Path, default=Path("data"), help="directory with train.bin and val.bin")
parser.add_argument("--calibration", default="128x2048", help="calibration sequences x tokens")
parser.add_argument("--steps", type=int, default=2000)
parser.add_argument("--batch-size", type=int, default=8)
parser.add_argument("--seq-len", type=int, default=1024)
parser.add_argument("--max-new-tokens", type=int, default=128)
parser.add_argument("--out", type=Path, default=Path("runs/combined"))
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
args = parser.parse_args()
dtype = torch.bfloat16 if args.device.startswith("cuda") else torch.float32
base = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype, attn_implementation="sdpa").to(args.device)
tokenizer = AutoTokenizer.from_pretrained(args.model)
n, s = map(int, args.calibration.split("x"))
calibration = fixed_windows(args.data / "train.bin", n, s)
gpu = args.device.startswith("cuda")
model = economize.apply(
base,
QuantConfig(format="int4", method="gptq", group_size=128) if gpu # int4 GPTQ base weights
else LowRankConfig(method="svd_llm", compression=0.2), # factored base weights on a CPU
KIVIConfig(bits=4), # 4-bit KV cache
Eagle3Config(), # an EAGLE-3 drafter
*([DraftQuantConfig(format="int8")] if gpu else []), # int8 weights for the drafter only
calibration=calibration,
decoding=economize.DecodeConfig(cycle_length=6, min_confidence=0.3),
)
print("attached:", ", ".join(model.techniques))
fit(model, str(args.data / "train.bin"), steps=args.steps, batch_size=args.batch_size, seq_len=args.seq_len,
seed=0, output_dir=args.out)
prompt = "Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May."
ids = tokenizer(prompt, return_tensors="pt").input_ids[0].to(args.device)
result = model.decode(ids, args.max_new_tokens, stop=tokenizer.eos_token_id)
print(tokenizer.decode(result.tokens))
print(f"\naccepted drafts per cycle: {result.mean_accepted:.2f}")
for key, value in result.cost_summary().items():
print(f" {key}: {value}")
print(f" kv_compression: {model.techniques['kivi'].cost_summary(result)['kv_compression']}")
if __name__ == "__main__":
main()
Benchmark¶
examples/benchmark.py
"""Time drafters against plain decoding on a standard prompt suite, with modelled costs.
python examples/benchmark.py --drafter runs/eagle3/final --drafter lookup --prompts spec-bench --cuda-graphs
Each ``--drafter`` is an economize checkpoint (local or Hub) or the name of a training-free drafter (``lookup``).
Reports the measured speedup over ``transformers``' greedy ``generate``, the accepted drafts per cycle and the
cost that ``economize.bench.CostModel`` assigns to the logged calls on a given GPU. A drafter with a network of its
own (an EAGLE-3 layer, a draft model) is priced as decoder layers of the target's width, as many as its calls run.
"""
from __future__ import annotations
import argparse
from dataclasses import replace
from typing import Any
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import economize
from economize.bench import CallSpec, CostModel, ModelShape, benchmark_generation, load_prompts
from economize.decoding import CostLog
from economize.techniques.lookup import LookupConfig
TRAINING_FREE = {"lookup": lambda: LookupConfig(max_ngram=3, max_proposal=10)}
def module_costs(config: Any, logs: list[CostLog]) -> CostModel:
"""A cost model of ``config`` that prices every separate network in ``logs`` as layers of the target's width."""
depth: dict[str, int] = {}
for log in logs:
for event in log.events:
if event.module is not None:
depth[event.module] = max(depth.get(event.module, 1), *(event.layers or (event.last_layer,)))
shape = ModelShape.from_config(config)
modules = {name: CallSpec(shape=replace(shape, num_layers=layers, layer_types=shape.layer_types[:layers],
layer_parts=shape.layer_parts[:layers]))
for name, layers in depth.items()}
return CostModel(shape, modules=modules)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B")
parser.add_argument("--drafter", action="append", default=[], help="repeatable (default: lookup)")
parser.add_argument("--prompts", default="gsm8k", choices=["gsm8k", "humaneval", "spec-bench"])
parser.add_argument("--limit", type=int, default=20, help="number of prompts")
parser.add_argument("--max-new-tokens", type=int, default=256)
parser.add_argument("--cycle-length", type=int, default=6)
parser.add_argument("--repeats", type=int, default=3)
parser.add_argument("--cuda-graphs", action="store_true", help="needs a CUDA device")
parser.add_argument("--hardware", default="a100-80gb", help="GPU of the cost model")
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
args = parser.parse_args()
dtype = torch.bfloat16 if args.device.startswith("cuda") else torch.float32
base = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype).to(args.device)
tokenizer = AutoTokenizer.from_pretrained(args.model)
prompts = [p.to(args.device) for p in load_prompts(args.prompts, limit=args.limit).tokenize(tokenizer, chat=False)]
n = args.max_new_tokens
plain = benchmark_generation(lambda p: base.generate(p[None], max_new_tokens=n, do_sample=False)[0, p.numel():],
prompts, repeats=args.repeats)
print(f"{'drafter':32s} {'speedup':>8s} {'accepted':>9s} {'modelled':>9s} (modelled: roofline on {args.hardware})")
print(f"{'none (transformers generate)':32s} {1.0:8.2f}")
decoding = economize.DecodeConfig(cycle_length=args.cycle_length, cuda_graphs=args.cuda_graphs)
for name in args.drafter or ["lookup"]:
if name in TRAINING_FREE:
model = economize.apply(base, TRAINING_FREE[name](), decoding=decoding)
else:
model = economize.load(base, name, decoding=decoding)
timing = benchmark_generation(lambda p, model=model: model.decode(p, n).tokens, prompts, repeats=args.repeats,
warmup_per_prompt=1 if args.cuda_graphs else 0)
results = [model.decode(p, n) for p in prompts]
costs = module_costs(base.config, [r.cost for r in results])
accepted = sum(r.mean_accepted for r in results) / len(results)
modelled = sum(costs.relative(r.cost, r.prompt_length, len(r.tokens), hardware=args.hardware)["speedup"]
for r in results) / len(results)
print(f"{name:32s} {timing.speedup_over(plain):8.2f} {accepted:9.2f} {modelled:9.2f}")
model.detach()
if __name__ == "__main__":
main()
A new training objective¶
examples/custom_objective.py
"""Add a new training objective by registration and train a drafter with it.
python examples/prepare_data.py --out data
python examples/custom_objective.py --steps 2000
The objective here trains an early-exit drafter with cross-entropy on the model's greedy token. An objective names
the parameters it trains, what it needs from the frozen teacher pass, and its loss; ``fit`` does the rest
(optimizer, schedule, mixed precision, checkpoints, several GPUs).
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
from pathlib import Path
from typing import ClassVar
import torch
import torch.nn.functional as F
from transformers import AutoModelForCausalLM
import economize
from economize.techniques.early_exit import EarlyExitConfig
from economize.train import (
Objective,
ObjectiveOutput,
OptimDefaults,
ParamGroup,
TeacherRequest,
fit,
register_objective,
)
@register_objective("exit_top1_ce")
@dataclass
class ExitTop1CE(Objective):
defaults: ClassVar[OptimDefaults] = OptimDefaults(lr=1e-3, warmup_steps=10)
def parameter_groups(self, model):
return [ParamGroup("exit", list(model.techniques["early_exit"].parameters()))]
def teacher_request(self, model):
return model.techniques["early_exit"].train_request(model).merge(TeacherRequest(logits=True))
def loss(self, model, batch, teacher):
draft = model.techniques["early_exit"].train_logits(model, batch, teacher)[1]
ce = F.cross_entropy(draft.flatten(0, 1).float(), teacher.logits.argmax(-1).flatten())
return ObjectiveOutput(ce, {"ce": ce.detach()})
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B")
parser.add_argument("--data", type=Path, default=Path("data"), help="directory with train.bin")
parser.add_argument("--steps", type=int, default=2000)
parser.add_argument("--batch-size", type=int, default=8)
parser.add_argument("--seq-len", type=int, default=1024)
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
args = parser.parse_args()
dtype = torch.bfloat16 if args.device.startswith("cuda") else torch.float32
base = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype).to(args.device)
model = economize.apply(base, EarlyExitConfig(exit_layer=6))
result = fit(model, str(args.data / "train.bin"), "exit_top1_ce", steps=args.steps, batch_size=args.batch_size,
seq_len=args.seq_len, log_every=max(1, args.steps // 20))
print(f"cross-entropy: {result.losses[0]:.3f} -> {result.losses[-1]:.3f}")
if __name__ == "__main__":
main()
Serve with vLLM¶
examples/serve_vllm.py
"""Serve a trained EAGLE-3 drafter with vLLM's speculative decoding.
pip install "economize[vllm]"
python examples/serve_vllm.py --drafter runs/eagle3/final --export qwen-eagle3
vllm serve Qwen/Qwen2.5-0.5B --speculative-config \
"$(python examples/serve_vllm.py --drafter runs/eagle3/final --export qwen-eagle3 --export-only)"
The export writes the head in vLLM's EAGLE-3 layout, so vLLM drafts with its own EAGLE-3 implementation. Sampling
stays lossless at any temperature: ``speculative_config`` sets vLLM's probabilistic drafting and standard rejection
sampling. Serving needs a CUDA device.
"""
from __future__ import annotations
import argparse
import json
import torch
from transformers import AutoModelForCausalLM
import economize
from economize.backends import vllm as economize_vllm
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B")
parser.add_argument("--drafter", required=True, help="economize checkpoint of a drafter (local or Hub)")
parser.add_argument("--export", default="vllm-drafter", help="folder the vLLM drafter is written to")
parser.add_argument("--draft-tokens", type=int, default=5, help="draft tokens per verification (cycle length - 1)")
parser.add_argument("--temperature", type=float, default=0.7)
parser.add_argument("--export-only", action="store_true", help="only export and print the speculative_config")
args = parser.parse_args()
base = AutoModelForCausalLM.from_pretrained(args.model, dtype=torch.bfloat16)
economize_vllm.export_drafter(economize.load(base, args.drafter), args.export)
speculative_config = economize_vllm.speculative_config(args.export, args.draft_tokens)
print(json.dumps(speculative_config))
del base
if args.export_only:
return
from vllm import LLM, SamplingParams
llm = LLM(model=args.model, speculative_config=speculative_config, dtype="bfloat16")
prompts = ["The capital of France is", "def fibonacci(n):", "Photosynthesis converts"]
for output in llm.generate(prompts, SamplingParams(temperature=args.temperature, max_tokens=128)):
print(repr(output.prompt), "->", repr(output.outputs[0].text))
if __name__ == "__main__":
main()