API Reference
flashspec
FlashSpec — Adaptive speculative-decoding inference engine.
Adaptive speculative-decoding inference engine with Triton-optimised verification and online bandit draft selection.
Public API surface (AGENTS.md §13.2 — do not modify without explicit approval):
flashspec.SpeculativeEngine
flashspec.GenerationResult
flashspec.FlashSpecConfig
flashspec.BanditConfig
flashspec.SamplingConfig
flashspec.MetricsConfig
flashspec.register (draft model decorator)
flashspec.get_drafter
flashspec.list_drafters
References
.. [1] Leviathan et al. (2023), "Fast Inference from Transformers via Speculative Decoding", arXiv:2211.17192. .. [2] Myet (2025), "FlashSpec: Adaptive Speculative Decoding with Online Bandit Draft Selection and Triton-Optimised Verification".
SpeculativeEngine
Adaptive speculative-decoding inference engine.
Orchestrates the full speculative decoding loop:
1. Bandit selects a draft model arm.
2. Draft model proposes gamma tokens autoregressively.
3. Target model scores all gamma positions in one forward pass.
4. Sampling algorithm accepts/rejects draft tokens and samples residual.
5. Bandit is updated with the acceptance outcome.
6. Metrics are updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
FlashSpecConfig
|
Full engine configuration. |
required |
drafters
|
list[DraftModel]
|
List of draft model instances, one per bandit arm. |
required |
target
|
TargetModel
|
The target (verifier) model instance. |
required |
bandit
|
DraftSelector
|
Online bandit selector for adaptive arm selection. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
Output distribution correctness (Algorithm 1, Leviathan et al. 2023) is
verified by tests/integration/test_e2e_sampling.py (KS test, α=0.01,
N=10,000). This is a CI hard gate.
Examples:
Source code in flashspec/engine/speculative.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
generate(input_ids, max_new_tokens=None)
Run the speculative decoding generation loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
Tensor
|
Prompt token IDs. Shape: |
required |
max_new_tokens
|
int or None
|
Maximum tokens to generate. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
GenerationResult
|
Contains output token IDs and generation metrics (acceptance rate, tokens per second). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
The output distribution of this method is provably identical to
autoregressive sampling from the target model (Leviathan et al., 2023
Theorem 1). This invariant is enforced by the KS-test gate in
tests/integration/test_e2e_sampling.py at α=0.01, N=10,000.
The generation loop follows these steps on each iteration:
- Bandit selects a draft model arm.
- Draft model proposes
gammatokens autoregressively. - Target model scores all
gammapositions in one forward pass with temperature applied before log-softmax (§7). - Rejection sampling accepts/rejects tokens (Algorithm 1).
- Bandit is updated with the acceptance outcome.
- Metrics are updated.
- Accepted tokens are appended to the context.
Examples:
Source code in flashspec/engine/speculative.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
GenerationResult
dataclass
Result of a single :meth:SpeculativeEngine.generate call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_ids
|
Tensor
|
Generated token IDs. Shape: |
required |
n_tokens_generated
|
int
|
Total number of new tokens in |
required |
acceptance_rate
|
float
|
Mean draft-token acceptance rate (alpha) for this call. |
required |
tokens_per_second
|
float
|
Wall-clock tokens per second for this call. |
required |
Source code in flashspec/engine/speculative.py
FlashSpecConfig
Bases: BaseModel
Top-level FlashSpec runtime configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drafter_name
|
str
|
Registry key of the draft model to use (e.g. |
required |
target_name
|
str
|
HuggingFace model identifier (or local path) for the target model. |
required |
device
|
str
|
PyTorch device string, e.g. |
required |
dtype
|
('float32', 'bfloat16', 'float16')
|
Compute dtype for model forward passes. |
"float32"
|
max_new_tokens
|
int
|
Maximum tokens to generate per call. |
required |
bandit
|
BanditConfig
|
Bandit algorithm settings. |
required |
sampling
|
SamplingConfig
|
Speculative sampling settings. |
required |
metrics
|
MetricsConfig
|
Metrics collection settings. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in flashspec/utils/config.py
BanditConfig
Bases: BaseModel
Configuration for the online bandit draft selector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strategy
|
('ucb1', 'thompson', 'oracle')
|
Which bandit algorithm to use. |
"ucb1"
|
window_size
|
int
|
Number of recent rounds to include in windowed statistics. Set to 0 to disable windowing (use all history). |
required |
n_arms
|
int
|
Number of draft-model arms available to the bandit. |
required |
ucb_exploration_constant
|
float
|
Exploration constant for UCB1 (the factor multiplying √(2 log t / n_k)). Default 1.0 matches the theoretical UCB1 derivation. |
required |
thompson_prior_alpha
|
float
|
Initial α of the Beta prior for Thompson sampling. |
required |
thompson_prior_beta
|
float
|
Initial β of the Beta prior for Thompson sampling. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in flashspec/utils/config.py
SamplingConfig
Bases: BaseModel
Configuration for speculative sampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gamma
|
int
|
Speculation length — number of draft tokens proposed per step. |
required |
temperature
|
float
|
Sampling temperature applied to target logits before log-softmax. Must be positive; use 1.0 for unscaled probabilities. |
required |
top_p
|
float
|
Nucleus sampling threshold. Set to 1.0 to disable. |
required |
seed
|
int or None
|
Random seed for reproducibility. |
required |
variant
|
('rejection', 'typical')
|
Sampling algorithm variant. |
"rejection"
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in flashspec/utils/config.py
MetricsConfig
Bases: BaseModel
Configuration for metrics collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
track_acceptance
|
bool
|
Whether to track per-step token acceptance rates. |
required |
track_throughput
|
bool
|
Whether to track tokens/s and MFU. |
required |
track_latency
|
bool
|
Whether to track p50/p95/p99 step latency. |
required |
latency_window
|
int
|
Rolling window size for latency percentile computation. |
required |
Source code in flashspec/utils/config.py
register(name)
Class decorator that registers a draft model under name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Registry key (e.g. |
required |
Returns:
| Type | Description |
|---|---|
Callable
|
The decorator function; returns the decorated class unchanged so the class can still be used normally after decoration. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
The registry is a module-level dict _REGISTRY. Names are
case-sensitive. External packages can also register drafters via Python
entry points under the flashspec.drafters group without modifying
this module (see §4.4 of AGENTS.md).
Examples:
Source code in flashspec/engine/drafter.py
get_drafter(name)
Look up a registered draft model class by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Registry key, as used in :func: |
required |
Returns:
| Type | Description |
|---|---|
type[DraftModel]
|
The registered class (not an instance; caller must instantiate it). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
Notes
Triggers :func:_load_entry_points on every call so that external packages
installed after the interpreter started are discovered automatically.
The lookup is O(1) dict access after entry-point loading.
Examples:
Source code in flashspec/engine/drafter.py
list_drafters()
Return all registered drafter names in alphabetical order.
Returns:
| Type | Description |
|---|---|
list[str]
|
Sorted list of registry keys. |
Notes
Triggers :func:_load_entry_points to discover any externally registered
drafters before returning the list. The list reflects the state of the
registry at call time; it is not a live view.
Examples: