Skip to content
MattralPublic

About

Lossless speculative decoding for HuggingFace causal language models, with a static-cache CUDA-graph fast path.

Topics

Resources

Contributing

Stars

17 stars

Watchers

1 watching

Forks

Repository files navigation

FlashSpec

Lossless speculative decoding for HuggingFace causal language models, with a static-cache CUDA-graph fast path.

PyPI Python CI Docs DOI License

What it is

FlashSpec wraps an existing HuggingFace causal LM and a smaller drafter that shares its tokenizer: the drafter proposes tokens, your model checks them in one forward pass, and the output is your model's own. Sampling keeps your model's distribution, and greedy mode gives the same tokens up to fp16 ties (correctness).

The measured scope is one Colab Tesla T4 running Qwen/Qwen2.5-1.5B-Instruct verified by Qwen/Qwen2.5-0.5B-Instruct at batch 1, where FlashSpec with default settings was faster than HuggingFace generate compiled the same way in every measured cell (results). The same config also ran as single runs on Modal T4, A100 and H100 GPUs, each on a different host; those are not general results for any GPU (other GPUs). No other model pair has been measured. FlashSpec is a single-device library with a small HTTP server, not a serving stack.

When to use it

Use it when:

  • you run a HuggingFace causal LM on a CUDA GPU, one request at a time (batch 1);
  • you have a smaller drafter with the same tokenizer, or your outputs copy from the prompt (code edits, quoting), where the built-in prompt-lookup drafter needs no second model;
  • you need your model's exact output, not an approximation of it.

Not yet:

  • CPU. The recorded CPU end-to-end runs were slower than plain decoding (history).
  • Batch > 1. Larger batches use a generic loop that reads the device several times per step and has not been measured.
  • First-call latency. On CUDA the first generate compiles and captures CUDA graphs, which can take minutes. compile=False skips that, but in the release run the eager path was slower than compiled HuggingFace (every method).
  • Other model pairs. Not measured. Other GPUs have only the single Modal runs above.

Install

pip install flashspec
extra adds when you want it
flashspec[gpu] Triton (Linux only) The compiled path; Linux CUDA builds of PyTorch already ship Triton.
flashspec[serve] FastAPI, uvicorn, httpx, accelerate The OpenAI-compatible server.
flashspec[asm] flashspec-asm-kernel (Linux x86-64) An experimental CPU kernel; no end-to-end speedup.

You need Python 3.11 or later, PyTorch 2.2 or later and transformers 4.40 or later. Source installs, Windows and macOS: docs/install.md.

Container image. Each release is also a server image on GitHub Container Registry, built from the PyPI release on CUDA 13.0 and run as a non-root user. It needs an NVIDIA GPU and the NVIDIA Container Toolkit, and by default serves the measured pair in fp16 on port 8000.

docker pull ghcr.io/mattral/flashspec:0.3.2
docker run --gpus all -p 8000:8000 ghcr.io/mattral/flashspec:0.3.2

Quickstart

This loads the measured model pair, decodes greedily, and prints the text and the speed. With one model drafter the default drafter_strategy="auto" runs composite-g6-f2: prompt lookup when the context has a match, else the drafter (see Choose a drafter). Without CUDA it falls back to CPU and float32, which is slow.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from flashspec import FlashSpecConfig, SamplingConfig, SpeculativeEngine
from flashspec.engine import HuggingFaceDrafter, TargetModel
target_id, drafter_id = "Qwen/Qwen2.5-1.5B-Instruct", "Qwen/Qwen2.5-0.5B-Instruct"  # same tokenizer
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
dtype = torch.float16 if device.type == "cuda" else torch.float32
load = lambda name: AutoModelForCausalLM.from_pretrained(name, torch_dtype=dtype).to(device)
target = TargetModel(target_id, device, dtype, model=load(target_id))
drafter = HuggingFaceDrafter(drafter_id, device, dtype, model=load(drafter_id))
config = FlashSpecConfig(device=str(device), sampling=SamplingConfig(temperature=0.0))  # greedy
engine = SpeculativeEngine(config, [drafter], target)
tokenizer = AutoTokenizer.from_pretrained(target_id)
prompt = tokenizer("def fibonacci(n):", return_tensors="pt").input_ids.to(device)
engine.generate(prompt, max_new_tokens=128)  # the first call on CUDA compiles (can take minutes)
result = engine.generate(prompt, max_new_tokens=128)
print(tokenizer.decode(result.output_ids[0, : result.n_tokens_generated], skip_special_tokens=True))
print(f"{result.tokens_per_second:.1f} tok/s, acceptance {result.acceptance_rate:.2f}")
print("drafter strategy:", engine.drafter_strategy)  # composite-g6-f2 with one model drafter

output_ids has shape (batch, max_new_tokens) and pads a row that stopped early with -1; n_tokens_generated counts the real tokens. TargetModel and HuggingFaceDrafter take the loaded modules through model=; without it, TargetModel loads with device_map, which needs accelerate.

Recipes

The recipes reuse target, drafter, device, prompt and tokenizer from the quickstart.

Choose a drafter

Three kinds, all lossless: a model drafter (HuggingFaceDrafter, as in the quickstart); prompt lookup (NgramDrafter), which continues the most recent earlier match of the last 1 to 3 tokens and needs no second model; and a composite, which uses prompt lookup when the context has a match and the model drafter otherwise. FlashSpecConfig.drafter_strategy picks the arms when you do not pass arms= (the server's --drafter-strategy takes the same names):

strategy what drafts each step drafters to pass
"auto" (default) "composite-g6-f2" with one model drafter, else the "bandit" path one or more
"bandit" one arm per drafter at sampling.gamma, chosen online (experimental) one or more
"composite-g4" prompt lookup up to 4 tokens on a match, else the model drafter drafts 4 a model drafter
"composite-g6-f2" prompt lookup up to 6 tokens on a match, else the model drafter drafts 2 a model drafter

A composite runs at batch 1 with variant "rejection" or "greedy"; under "auto", other calls use the model drafter at sampling.gamma, and an explicit composite raises. Lookup steps use Algorithm 1 with a one-hot draft distribution, so they stay lossless. engine.drafter_strategy and engine.drafter_strategy_reason say what ran and why, and drafter_strategy="bandit" restores the 0.2.0 behaviour.

from flashspec import BanditConfig
from flashspec.engine import NgramDrafter

greedy = SamplingConfig(temperature=0.0)
composite = FlashSpecConfig(device=str(device), drafter_strategy="composite-g6-f2", sampling=greedy)
engine = SpeculativeEngine(composite, [drafter, NgramDrafter()], target)
result = engine.generate(prompt, max_new_tokens=64)
print(engine.arms, [step.drafter for step in result.arm_steps])  # drafter used at each step

lookup_only = FlashSpecConfig(device=str(device), drafter_strategy="bandit",  # one arm per drafter
                              bandit=BanditConfig(n_arms=1), sampling=greedy)
lookup = SpeculativeEngine(lookup_only, [NgramDrafter()], target)

The default was picked by a rule fixed before its run, and which drafter is fastest depends on the prompts (how the default was chosen). Several arms plus a selector (UCB1Selector(n_arms=k) or ThompsonSelector(n_arms=k) from flashspec.bandit, passed as SpeculativeEngine's fourth argument) let a bandit choose online; that is experimental (bandit).

Greedy or sampling

greedy = SamplingConfig(temperature=0.0)            # same tokens as model.generate(do_sample=False)
sampled = SamplingConfig(temperature=0.7, seed=0)   # Algorithm 1: same distribution as the target
drafter.set_temperature(0.7)                        # draft at the target's temperature
config = FlashSpecConfig(device=str(device), sampling=sampled)
engine = SpeculativeEngine(config, [drafter], target)
result = engine.generate(prompt, max_new_tokens=64)

The default is temperature=1.0, which samples. temperature=0.0 selects greedy. seed makes one call reproducible; seed=None uses the global RNG. variant="typical" is lossy and is not on the fast path.

Turn compile off

config = FlashSpecConfig(device=str(device), compile=False, sampling=SamplingConfig(temperature=0.0))
engine = SpeculativeEngine(config, [drafter], target)
print(engine.compiled, "|", engine.compile_decision.reason)

The default compile="auto" turns the compiled path on when the device is CUDA and Triton is installed. The engine logs one line saying which path runs and why. Set compile=False before a compiled engine has run on the same TargetModel and drafter: the compiled path moves those wrappers onto static caches, and they stay there. The server takes --compile off.

Run the OpenAI-compatible server

pip install "flashspec[serve]"
python -m flashspec.serve --target Qwen/Qwen2.5-1.5B-Instruct --drafter Qwen/Qwen2.5-0.5B-Instruct \
    --device cuda:0 --dtype float16 --temperature 0

The server has POST /v1/chat/completions, POST /v1/completions, GET /health and GET /metrics, on one process and one device, with no streaming and no continuous batching. Temperature and gamma are fixed at start; a request with another temperature is rejected. Every flag: server flags; the container image and a request: docs/examples.md.

Use your own drafter

Any HuggingFace causal LM with the target's tokenizer works as HuggingFaceDrafter(model_id, device, dtype, model=...). Anything else implements the DraftModel protocol; a worked example, the rules it must follow and the registry are in docs/examples.md.

API at a glance

The compute dtype is the one the model wrappers load with or are given; FlashSpecConfig.dtype is recorded with the config and not applied.

Generated from the code by scripts/readme_api.py; a test fails when it is stale. Fields and signatures are in the API reference.

API What it does
flashspec.FlashSpecConfig Top-level FlashSpec runtime configuration.
flashspec.SamplingConfig Configuration for speculative sampling.
flashspec.BanditConfig Configuration for the online bandit draft selector.
flashspec.SpeculativeEngine Adaptive speculative-decoding inference engine.
flashspec.SpeculativeEngine.generate Run the speculative decoding generation loop.
flashspec.GenerationResult Result of a single SpeculativeEngine.generate call.
flashspec.engine.TargetModel Wrapper around a HuggingFace CausalLM used as the speculative verifier.
flashspec.engine.HuggingFaceDrafter Draft model backed by a HuggingFace causal LM.
flashspec.engine.load_drafters Instantiate drafters in arm order.
flashspec.engine.NgramDrafter Prompt-lookup drafter: continue the most recent earlier match of the last n tokens.
flashspec.engine.ArmSpec One bandit arm.
flashspec.bandit.UCB1Selector UCB1 bandit selector for adaptive draft-model selection.
flashspec.bandit.ThompsonSelector Thompson sampling bandit selector for draft-model selection.
flashspec.engine.DraftModel Protocol that every draft model must satisfy.
flashspec.register Class decorator that registers a draft model under name.
flashspec.TRITON_AVAILABLE True only on Linux with Triton installed.

Defaults that change behaviour:

  • compile="auto": the compiled path (static KV cache, CUDA graphs) runs when the device is CUDA and Triton is installed.
  • temperature=1.0: the default samples (variant="rejection"); temperature=0.0 is greedy.
  • drafter_strategy="auto": one model drafter runs "composite-g6-f2"; otherwise one arm per drafter at gamma=4.
  • BanditConfig(n_arms=2): a BanditConfig you pass must match the number of arms.
  • device="cuda:0" and max_new_tokens=512 unless you set them.

Server flags: docs/api/index.md.

Results

Bar chart of tokens per second on a Tesla T4 for compiled FlashSpec, compiled HuggingFace generate and eager HuggingFace generate, on HumanEval and MT-Bench, greedy and T=0.7 (bundle 3c43e08, default settings). The values are in the table below.

Measured at git 3c43e08 on one Tesla T4: Qwen/Qwen2.5-1.5B-Instruct verified by Qwen/Qwen2.5-0.5B-Instruct, fp16, batch 1, drafter strategy composite-g6-f2, 10 prompts per set, 128 new tokens. Numbers are rounded to 3 significant figures.

dataset mode FlashSpec tok/s compiled HF tok/s vs compiled HF greedy match
humaneval greedy 84.2 50.8 1.67 9/10
humaneval T=0.7 75.7 50.4 1.50 n/a
mt_bench greedy 65.6 51.6 1.27 8/10
mt_bench T=0.7 63.1 50.2 1.26 n/a

vs compiled HF is the median of per-prompt speedups over HuggingFace generate on a static cache compiled the same way (CUDA graphs); above 1 means FlashSpec was faster. Greedy match counts prompts whose tokens equal compiled HuggingFace's, token for token; sampled rows have none to count.

Cold start: the first compiled call in this run took 3 min 43 s (compilation and CUDA-graph capture); the table excludes it.

Eager FlashSpec, eager and assisted HuggingFace, acceptance and forward cost for the same run, at full precision: docs/benchmarks.md.

The chart (scripts/readme_chart.py) and the table read the same stored JSONs under benchmarks/results/gpu/3c43e08. Provenance, earlier bundles and microbenchmarks: docs/benchmarks.md.

Other GPUs on Modal

The 0.3.0 release config ran unchanged on Modal at git ed20144: 2 runs on Tesla T4, 1 run on NVIDIA A100-SXM4-40GB and 1 run on NVIDIA H100 80GB HBM3, with the decision rules written into the configs before any run. Each is a single run of 10 prompts per set (128 new tokens, composite-g6-f2), and each landed on a different host, so none is a general result for its GPU, and at batch 1 a difference between GPUs is also a difference between hosts. Each cell is the median of per-prompt speedups of compiled FlashSpec over compiled HuggingFace generate (Rule A), with the ratio of median throughputs in brackets, rounded to 3 significant figures.

run (GPU) humaneval greedy humaneval T=0.7 mt_bench greedy mt_bench T=0.7
t4-control-1 (Tesla T4) 1.67 (1.68) 1.54 (1.55) 1.22 (1.22) 1.25 (1.22)
t4-control-2 (Tesla T4) 1.69 (1.68) 1.53 (1.52) 1.28 (1.28) 1.27 (1.26)
a100 (NVIDIA A100-SXM4-40GB) 1.43 (1.43) 1.42 (1.43) 1.09 (1.10) 1.08 (1.08)
h100 (NVIDIA H100 80GB HBM3) 1.18 (1.14) 1.14 (1.14) 1.04 (0.985) 1.03 (1.03)

Hosts (the sandbox masks the CPU model name):

run cloud and region CPU family MHz
t4-control-1 GCP, ap-southeast GenuineIntel family 6 model 85, 14 CPUs 2000
t4-control-2 AWS, us-west GenuineIntel family 6 model 85, 18 CPUs 3127
a100 OCI, us-east AuthenticAMD family 25 model 1, 18 CPUs 3249
h100 not reported, eu-south GenuineIntel family 6 model 143, 18 CPUs 2995

In h100, mt_bench greedy, the two statistics disagree: the median of per-prompt ratios is 1.04, but the median throughputs are 272 tok/s for compiled FlashSpec and 276 tok/s for compiled HF (ratio 0.985), so that cell is not evidence either way.

Rule B failed: 2 of 2 Modal T4 runs did not reproduce the Colab run (3c43e08) within S = 4.97%, the largest compiled-HF difference between earlier Colab T4 sessions (11 of 16 median-throughput differences exceed it). So the Modal rows are not comparable with the Colab T4 table above, and GPUs are compared only within Modal.

Two panels. Left: compiled FlashSpec over compiled HuggingFace generate per dataset and mode, for the Colab T4 and each Modal run, with a dashed line at 1. Right: compiled FlashSpec median tokens per second for the same runs. The values are in the tables in this section.

Left: compiled FlashSpec over compiled HuggingFace generate per cell; the filled dot is the median of per-prompt ratios (Rule A), the open diamond beside it the ratio of median throughputs (informational), and the dashed line marks 1. Right: compiled FlashSpec median tokens per second. Every point is a single run of 10 prompts per set, and each Modal run landed on a different host (cloud, region and CPU clock differ; the CPU model is masked), so at batch 1 a difference between GPUs is also a difference between hosts. The Colab T4 is bundle 3c43e08; the Modal runs are at ed20144. Rule B failed, so the Colab T4 is shown for reference, not as a baseline for the Modal runs.

Everything else (Rule B per cell, run-to-run spread, output identity with the Colab run, cross-GPU throughput ratios, full-precision values) is in report.md.

How it works

Each batch-1 step does four things:

  1. The drafter proposes gamma tokens, with gamma forwards on its own KV cache (a lookup drafter runs no model).
  2. The target runs one forward over the pending token and the gamma drafts.
  3. The accept/reject test runs on the device: Algorithm 1 rejection sampling at temperature > 0, or the longest prefix that matches the target's argmax at temperature 0.
  4. One device-to-host read returns the accept count and the next token, and both caches are cropped by bookkeeping, with no extra forward.

With compile on, both models run on static KV caches and the fixed-shape decode and verify calls replay as CUDA graphs. Diagrams, batching and the proof sketch: docs/architecture.md.

Correctness

  • Sampling is lossless. Rejection sampling follows Algorithm 1 of Leviathan et al. (2023): a draft token x is kept with probability min(1, p(x)/q(x)), and a rejection samples from max(0, p - q), normalised, so the output follows your model's distribution for any drafter. CI checks this with chi-squared tests: model drafters and prompt lookup, which also show the checks fail on deliberately wrong residuals.
  • Greedy equals HuggingFace. At temperature 0 the output is model.generate(do_sample=False) token for token; CI checks it in float32 on CPU (test_greedy_gold.py).
  • The fp16 caveat. On a GPU in fp16, kernels of different shapes can round an exact tie between the top two tokens differently, so greedy output can differ from HuggingFace at such a tie. A T4 diagnostic found every path token-exact in fp32 and every fp16 divergence at an exact top-2 tie (diagnostic JSON). The greedy-match column above counts matching prompts; the release run's mismatches are such ties (details).
  • variant="typical" is lossy. "rejection" and "greedy" are the lossless variants.

Status and limitations

FlashSpec is alpha, version 0.3.2.

  • Measured scope. The Colab T4 run in Results: one model pair, fp16, batch 1, default settings. The Modal runs are single runs on different hosts, and Rule B failed, so they are not general results for their GPUs. Other model pairs and batch sizes are not measured; the Llama-3-8B H100 numbers in the docs are design targets.
  • The first call compiles (minutes on CUDA); later calls reuse the graphs, and the tables exclude that call.
  • Batch > 1 uses a generic loop that forwards only the largest group of rows sharing a context length.
  • Single device. One process and one GPU or CPU; the server has no streaming, paged KV cache or continuous batching.
  • Windows and macOS. pip install flashspec works, but Triton is Linux-only, so the compiled path is Linux + CUDA only.
  • Experimental: the bandit selector, which did not beat the best fixed arm in its measured run (docs/bandit.md), and the Triton and assembly kernels, which are not on the generation path (docs/kernels.md).
  • Not scheduled: a contextual bandit, a larger target and the batch > 1 path (docs/postponed.md).

Citing

Cite the preprint, 10.5281/zenodo.20766119 (Zenodo, June 2026); BibTeX-ready metadata is in CITATION.cff. paper/flashspec.tex is a later draft that has not been deposited.

Contributing

See CONTRIBUTING.md. make test runs the unit and integration suites on CPU, with no GPU needed. Test commands, the repository layout and links to the papers and notebooks are in docs/development.md. Changes are in the CHANGELOG; an index for AI agents is in llms.txt.

License

Apache 2.0. See LICENSE.

About

Lossless speculative decoding for HuggingFace causal language models, with a static-cache CUDA-graph fast path.

Topics

Resources

Contributing

Stars

17 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages