economize.decoding¶
The draft-and-refresh loop and its pluggable parts: drafters, verifiers, draft-length policies and token selectors.
Decoding: the draft-and-refresh loop and its pluggable parts.
- :class:
CycleDecoderruns batched, ragged generation with an optional :class:Drafter. - :data:
VERIFIERS(greedy, rejection, typical, accept_all) decide which drafts survive an exact pass. - :data:
POLICIES(fixed, confidence, dynamic_tree, sequoia, specexec) decide when a row stops drafting within a cycle, or (the tree policies) turn a chain drafter that implements :class:TreeStepDrafterinto a tree drafter: EAGLE-2 dynamic trees, static Sequoia trees, or SpecExec's best-first search. - Token selectors (:class:
GreedySelector, :class:TopPSampler) turn logits into tokens; the optional capability protocols (:class:BatchSelector, :class:DistributionSelector, :class:BatchDistributions, :class:SeededSelector) say what else a custom selector can do. - :class:
StopCheckerturns a :data:StopConditioninto the check run after every committed token. - :class:
CostLogrecords every model call for cost accounting. - :class:
DecodeGraphsholds the CUDA graphs and static cache of a decoder withcuda_graphs=True. - :class:
DepthStepsruns the decode steps of a dynamic-depth technique without its skipped layers.
BatchDistributions
¶
Bases: Protocol
A selector that gives the distributions of many rows in one call (its choice ignores the history).
distributions
¶
distributions(logits: Tensor) -> Tensor
The distribution of every row of logits [..., V], [..., V].
BatchSelector
¶
Bases: Protocol
A selector that chooses for many rows in one call (its choice ignores the history).
DistributionSelector
¶
Bases: Protocol
A selector that exposes the probabilities __call__ samples from.
distribution
¶
distribution(logits: Tensor, history: Tensor) -> Tensor
The distribution [V] behind the choice after history.
SeededSelector
¶
Bases: Protocol
A sampling selector with its own random stream on every device it samples on.
DecodeConfig
dataclass
¶
DecodeConfig(cycle_length: int = 4, lossless: bool | None = None, min_confidence: float | None = None, verifier: str | None = None, draft_policy: str | None = None, verifier_options: Mapping[str, object] = dict(), cuda_graphs: bool = False, sync_interval: int = 8, record_confidence: bool = False, record_distributions: bool = False, draft_loop_graph: bool = False, draft_policy_options: Mapping[str, object] = dict(), prefill_chunk: int | None = None, window_cache: bool = False)
How a model with a drafting technique generates text.
One cycle runs the unmodified model once, in parallel, over all tokens that have not been through an exact
pass yet. This pass also yields one exact next token. Then the drafter proposes up to cycle_length - 1
further tokens cheaply.
Attributes:
| Name | Type | Description |
|---|---|---|
cycle_length |
int
|
Tokens per cycle ( |
lossless |
bool | None
|
Verify drafts against the exact pass and keep only those the model itself would have produced
(speculative decoding, output identical to greedy decoding). With |
min_confidence |
float | None
|
Stop drafting early when the drafter's top probability falls below this value (the first draft of a cycle is always made). |
verifier |
str | None
|
Advanced. Name of a registered verifier, used instead of the one |
draft_policy |
str | None
|
Advanced. Name of a registered draft-length policy, overriding |
verifier_options |
Mapping[str, object]
|
Advanced. Keyword options of the verifier, e.g. |
cuda_graphs |
bool
|
Record the draft steps and the exact passes of a chain decoder as CUDA graphs and replay them (CUDA only). Configurations a graph cannot express (draft trees, dynamic-depth layer policies, KV-cache techniques, recurrent layers) fall back to eager execution per call. |
sync_interval |
int
|
Ordinary decoding ( |
record_confidence |
bool
|
Log the drafter's top probability of every drafted token in
:attr: |
record_distributions |
bool
|
Compare the drafter's distribution with the verifier's at every drafted token of a
chain draft and log |
draft_loop_graph |
bool
|
With |
draft_policy_options |
Mapping[str, object]
|
Advanced. Keyword options of the draft policy, e.g.
|
prefill_chunk |
int | None
|
Run the prefill of prompts longer than this many tokens in consecutive chunks of this size
(activations and attention scores then scale with the chunk, not the prompt). The tokens and logits are
those of one pass up to rounding. It needs prompts of equal length, a drafter that reads only the hidden
states of the last accepted tokens (:attr: |
window_cache |
bool
|
With |
from_dict
classmethod
¶
from_dict(data: Mapping[str, object]) -> DecodeConfig
The options written by :meth:to_dict. Missing fields take their defaults; fields this release does not
know (saved by a newer one) are dropped with an :class:~economize.errors.UnknownFieldWarning.
CostEvent
dataclass
¶
CostEvent(kind: str, tokens: int, position: int, first_layer: int, last_layer: int, step: int | None = None, module: str | None = None, layers: tuple[int, ...] | None = None)
One model call.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
What the call did, one of the :class: |
tokens |
int
|
Tokens processed in parallel. |
position |
int
|
Position of the first token. |
first_layer |
int
|
First decoder layer run (1-indexed). |
last_layer |
int
|
Last decoder layer run. |
step |
int | None
|
Index of a draft step within its cycle, counted from 0 for every row ( |
module |
str | None
|
|
layers |
tuple[int, ...] | None
|
The decoder layers run when they are not one contiguous range (a draft that skips layers), in
which case |
CostKind
¶
The kinds of call the library records. Kinds are plain strings, so a technique may record kinds of its own.
EXACT
class-attribute
instance-attribute
¶
EXACT: Final = 'exact'
The unmodified model over one or more tokens.
DRAFT_WASTED
class-attribute
instance-attribute
¶
DRAFT_WASTED: Final = 'draft_wasted'
A draft step whose proposal a draft policy discarded.
REPLAY
class-attribute
instance-attribute
¶
REPLAY: Final = 'replay'
Exact tokens run again to bring the recurrent states of a hybrid model in line with the committed tokens.
DRAFT_CATCHUP
class-attribute
instance-attribute
¶
DRAFT_CATCHUP: Final = 'draft_catchup'
A separate draft network run over committed tokens it has not seen, before it drafts.
DRAFT_OBSERVE
class-attribute
instance-attribute
¶
DRAFT_OBSERVE: Final = 'draft_observe'
A draft module run over committed tokens to update its own cache (EAGLE-3, MTP).
CostLog
dataclass
¶
CostLog(events: list[CostEvent] = list())
Every model call of one generation, in order.
record
¶
record(kind: str, tokens: int, position: int, first_layer: int, last_layer: int, step: int | None = None, *, module: str | None = None, layers: tuple[int, ...] | None = None) -> None
Append one call (see :class:CostEvent for the fields).
record_footprint
¶
record_footprint(kind: str, tokens: int, position: int, footprint: LayerFootprint, step: int | None = None) -> None
Append one call over the layers of footprint.
mark_last_wasted
¶
mark_last_wasted() -> None
Mark the last event as wasted (its proposal was discarded).
truncate
¶
truncate(length: int) -> None
Keep the first length events (drops calls a finished row made while the rest of the batch ran on).
truncate_after_step
¶
truncate_after_step(step: int, start: int = 0) -> None
Drop the events that follow draft step step among the events from index start on (the cycle's
first event). Keeps every event when that step was not recorded.
A drafter may log other calls besides its draft steps (the draft model's catch-up), so the cut cannot be counted in events.
summary
¶
summary(num_layers: int, prompt_tokens: int, generated: int) -> CostSummary
Aggregate counts, including layer applications relative to plain decoding of the same output.
Plain decoding runs all L layers once over the prompt and once over every generated token but the last,
(prompt_tokens + generated - 1) * L layer applications in total. layer_tokens counts the decoded
model's layers only. Layers of separate networks have other sizes, so they are counted per network in
module_layer_tokens (price both with :class:~economize.bench.CostModel).
as_tuples
¶
as_tuples(kinds: Mapping[str, str] | None = None) -> list[tuple[str, int, int]]
The (kind, tokens, position) of every event, with kinds renamed by kinds (kinds it does not name
keep theirs). Layers and modules are dropped. Used to compare economize's log with another decoder's.
CostSummary
¶
Bases: TypedDict
The aggregate counts of :meth:CostLog.summary.
LayerFootprint
dataclass
¶
LayerFootprint(first_layer: int, last_layer: int, module: str | None = None, layers: tuple[int, ...] | None = None)
The layers one call runs, as a drafter declares them for the cost log.
Attributes:
| Name | Type | Description |
|---|---|---|
first_layer |
int
|
First decoder layer run (1-indexed). |
last_layer |
int
|
Last decoder layer run ( |
module |
str | None
|
The separate network the layers belong to, |
layers |
tuple[int, ...] | None
|
The layers run when they are not one contiguous range. |
of
classmethod
¶
of(layers: Iterable[int], module: str | None = None) -> LayerFootprint
The footprint of an arbitrary set of layers, stored as a range when it is one.
none
classmethod
¶
none(module: str | None = None) -> LayerFootprint
No decoder layers (a drafter without layers of its own, or one that runs only heads).
DepthSteps
¶
DepthSteps(runner: LayerRunner, policy: LayerPolicy, graphs: DecodeGraphs | None, *, overrides: Mapping[int, Module] | None = None, head: Callable[[Tensor], Tensor] | None = None, device_decisions: bool = True)
One-token decode steps of one row under a layer policy that implements the step interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
runner
|
LayerRunner
|
Runs the model's layers (all on one device). |
required |
policy
|
LayerPolicy
|
The decoder's layer policy ( |
required |
graphs
|
DecodeGraphs | None
|
The decoder's CUDA graphs; |
required |
overrides
|
Mapping[int, Module] | None
|
Modules that replace decoder layers (by 1-based index), as in
:meth: |
None
|
head
|
Callable[[Tensor], Tensor] | None
|
Turns the output of the last layer |
None
|
device_decisions
|
bool
|
Let a policy that supports it decide on the device (one graph and one synchronization
per step); |
True
|
Attributes:
| Name | Type | Description |
|---|---|---|
graphed |
Whether the steps are recorded as CUDA graphs ( |
|
device |
Whether the steps are device-decided (see the module docstring). |
|
pool |
_POOL_HANDLE | None
|
Memory pool of the step graphs (set by the decoder's :class: |
reset
¶
reset() -> None
Drop every recorded graph (the decoder's cache was rebuilt or its graph state changed).
The device is synchronized first, as in :meth:StaticStep.reset: no replay may still run when its graph is
destroyed.
applies
staticmethod
¶
applies(gen: Generation, draft: Draft) -> bool
Whether the next pass of gen is a step this engine runs: one row, one pending token, no drafts.
step
¶
step(gen: Generation) -> Pass
The exact pass over the pending token of the single row of gen.
DynamicTreeDrafter
¶
DynamicTreeDrafter(inner: Drafter, options: TreeOptions)
Bases: TreeSearchDrafter
A chain :class:TreeStepDrafter that proposes EAGLE-2 dynamic trees (made by :class:DynamicTreePolicy).
The cost log records the root's step as one draft call of one token at the root's position, every further
depth d as one draft call of topk tokens at the position of depth d (both over the inner drafter's
footprint), and the exact pass as a call over the total_tokens + 1 tree tokens.
With CUDA graphs the inner drafter's chain step runs from its own graphs and every tree step from a graph per
depth (the shapes depend only on the batch size, topk and the depth).
DynamicTreePolicy
¶
DynamicTreePolicy(config: DecodeConfig)
Bases: TreePolicy
Drafts an EAGLE-2 dynamic tree with any :class:TreeStepDrafter (see the module docstring).
Options (DecodeConfig.draft_policy_options): depth (default cycle_length - 1), topk (default 10,
as in EAGLE-2) and total_tokens (default 60, or every candidate of a smaller tree). The tree replaces the
chain, so no row stops early.
TreeOptions
dataclass
¶
TreeOptions(depth: int, topk: int, total_tokens: int)
The shape of a dynamic draft tree.
Attributes:
| Name | Type | Description |
|---|---|---|
depth |
int
|
Levels of candidates below the root (the longest path the exact pass can accept). |
topk |
int
|
Frontier width per level and children per frontier node. |
total_tokens |
int
|
Nodes of the draft tree the exact pass verifies (the economize attention kernel takes a tree
pass of up to 64 queries, i.e. |
forwarded
property
¶
forwarded: int
Nodes every proposal runs through the drafter besides the root: (depth - 1) * topk.
candidates
property
¶
candidates: int
Candidates every proposal ranks: topk at depth 1 and topk**2 at every further depth.
from_config
classmethod
¶
from_config(config: DecodeConfig) -> TreeOptions
The options in config.draft_policy_options.
Defaults follow the EAGLE-2 reference code: topk=10 and total_tokens=60, with depth set to
cycle_length - 1. A shallow tree with fewer than 60 candidates (cycle_length=2: topk of them)
verifies all of them by default, so every cycle length works without options.
TreeStepDrafter
¶
Bases: Protocol
A drafter that can run one draft step over the frontier of a draft tree.
A tree policy calls :meth:tree_begin at the start of every proposal, runs the root with the drafter's ordinary
:meth:~economize.decoding.Drafter.step, reads the per-row state that step left with :meth:tree_state, and then
calls :meth:tree_step once per draft step of the tree.
supports_tree_steps
¶
supports_tree_steps() -> bool
Whether this drafter, as configured, implements :meth:tree_step (a drafter may support it for some
configurations only).
tree_begin
¶
tree_begin(request: DraftRequest) -> None
Prepare a proposal for request (flush the costs of :meth:observe, check that the drafter observed
an exact pass).
tree_state
¶
tree_state() -> tuple[Tensor, ...]
The per-row state [B, ...] tensors that the root's draft step produced and its children read (an empty
tuple for a stateless drafter).
tree_step
¶
tree_step(tokens: Tensor, parents: Tensor, base: Tensor, *states: Tensor) -> tuple[Tensor, tuple[Tensor, ...]]
One draft step over the frontier of a tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
The frontier's tokens |
required |
parents
|
Tensor
|
The parents of every node the tree forwarded so far |
required |
base
|
Tensor
|
First slot after the committed prefix |
required |
states
|
Tensor
|
The state of every frontier node's parent |
()
|
Returns:
| Type | Description |
|---|---|
Tensor
|
The float logits after every frontier node |
tuple[Tensor, ...]
|
shapes as |
tuple[Tensor, tuple[Tensor, ...]]
|
synchronization, so it can be recorded as a CUDA graph. |
DecodeGraphs
¶
DecodeGraphs(runner: LayerRunner, capture: Sequence[int], pass_phase: Phase, *, granularity: int = 128)
The CUDA graphs and the static KV cache of one decoder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
runner
|
LayerRunner
|
Runs the model's layers. |
required |
capture
|
Sequence[int]
|
Layers whose hidden states the exact passes return (the drafter's observed layers). |
required |
pass_phase
|
Phase
|
Phase of the exact passes after the prefill ( |
required |
granularity
|
int
|
Cache capacities are rounded up to a multiple of this, so that generations of similar lengths share one cache and its graphs (the attention cost of a step grows with the capacity). |
128
|
supports_cache
staticmethod
¶
supports_cache(kind: str) -> bool
Whether exact passes over a cache of kind kind can be graphed (:func:static_cache_class).
wrap
¶
wrap(fn: Callable[..., _R], /, *, private: bool = False) -> StaticStep[_R]
fn (a function of tensors without host synchronization) as a graphed step of this decoder.
The step's graphs are dropped whenever the cache is rebuilt. A private step records into a memory pool of
its own: its owner may reset it at any time (e.g. to keep a bounded set of graphs for many step variants),
which a step on the shared pool must never do while the decoder's other graphs replay.
cache_for
¶
The static cache for a generation of batch_size rows that needs capacity positions, with the
window cache ring for its sliding layers if given.
A generation that needs more positions than the current cache holds (or another ring) gets a new cache, and every graph recorded on the old one is dropped.
bind
¶
bind(cache: KVCache) -> None
Run the passes of the next generation on cache: the static cache of :meth:cache_for or a graph-safe
wrapper of it. Graphs recorded over another cache object are dropped, so a wrapper that lives as long as the
static cache keeps them.
exact
¶
exact(tokens: Tensor, positions: Tensor, valid: Tensor, picks: Tensor, frontier: list[int | None]) -> tuple[ExactPass, Tensor]
An exact chain pass over tokens [B, S] at positions (valid marks real tokens) and the
float logits of the final states at the columns picks [B, K], replayed from a graph. Row b writes
from slot frontier[b] on (its first position).
The returned pass has a :class:~economize.runtime.LayerContext like an eager one (drafters read the pass's
positions and padding in :meth:Drafter.observe); its tensors are the graph's buffers.
tree
¶
tree(tokens: Tensor, parents: Tensor, base: Tensor, valid: Tensor, frontier: list[int | None]) -> tuple[ExactPass, Tensor]
An exact pass over the nodes of draft trees (tokens, parents and valid [B, T], the trees
stored from slot base [B] on, see :meth:~economize.runtime.TreeLayout.build) and the float logits of
every node, replayed from a graph (one per batch size and tree width). frontier is base as a list.
CycleDecoder
¶
CycleDecoder(runner: LayerRunner, drafter: Drafter | None, config: DecodeConfig, *, layer_policy: LayerPolicy | None = None, observers: Sequence[VerifyObserver] = (), wrap_cache: Callable[[KVCache], KVCache] | None = None, graph_safe: bool = True)
Decodes with the unmodified model plus an optional drafter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
runner
|
LayerRunner
|
Runs the model's layers. |
required |
drafter
|
Drafter | None
|
Proposes tokens between exact passes. Required when |
required |
config
|
DecodeConfig
|
Decoding options. |
required |
layer_policy
|
LayerPolicy | None
|
Applied to every exact pass (dynamic-depth techniques). |
None
|
observers
|
Sequence[VerifyObserver]
|
Called with a :class: |
()
|
wrap_cache
|
Callable[[KVCache], KVCache] | None
|
Wraps the KV cache of every generation (KV-cache techniques, e.g. quantized or sparse caches). |
None
|
graph_safe
|
bool
|
Whether the attached techniques allow CUDA graphs ( |
True
|
Attributes:
| Name | Type | Description |
|---|---|---|
active_drafter |
Drafter | None
|
The drafter that runs, |
capture |
tuple[int, ...]
|
Layers whose hidden states every exact pass returns: the observed layers of :attr: |
graphs |
DecodeGraphs | None
|
The decoder's CUDA graphs and static cache, |
depth_steps |
DepthSteps | None
|
With |
Raises:
| Type | Description |
|---|---|
ConfigError
|
|
decode
¶
decode(prompt: Tensor, max_new_tokens: int, selector: TokenSelector | None = None, stop: StopCondition = None) -> DecodeResult
Generate up to max_new_tokens tokens after prompt (a 1-D LongTensor of token ids).
decode_batch
¶
decode_batch(prompts: Sequence[Tensor] | Tensor, max_new_tokens: int | Sequence[int], selector: TokenSelector | None = None, stop: StopCondition = None, *, selectors: Sequence[TokenSelector | None] | None = None, stops: Sequence[StopCondition] | None = None) -> list[DecodeResult]
Generate tokens after each prompt (1-D LongTensors of any lengths, or the rows of a 2-D tensor) and return one result per prompt, in order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompts
|
Sequence[Tensor] | Tensor
|
The prompts. |
required |
max_new_tokens
|
int | Sequence[int]
|
Most new tokens, for all rows or one number per row. |
required |
selector
|
TokenSelector | None
|
Token selector of every row (greedy when |
None
|
stop
|
StopCondition
|
Stop condition of every row. |
None
|
selectors
|
Sequence[TokenSelector | None] | None
|
One selector per row; a |
None
|
stops
|
Sequence[StopCondition] | None
|
One stop condition per row; a |
None
|
DecodeResult
dataclass
¶
DecodeResult(tokens: Tensor, cost: CostLog, acceptance: list[tuple[int, int]] = list(), prompt_length: int = 0, num_layers: int = 0, confidence: list[list[float]] = list(), match: list[list[list[float]]] = list(), row: int = 0)
Output of :meth:~economize.decoding.CycleDecoder.decode for one row.
Attributes:
| Name | Type | Description |
|---|---|---|
tokens |
Tensor
|
Generated tokens, |
cost |
CostLog
|
Every model call made for this row. |
acceptance |
list[tuple[int, int]]
|
One |
prompt_length |
int
|
Number of prompt tokens. |
num_layers |
int
|
Decoder layers of the model. |
confidence |
list[list[float]]
|
With :attr: |
match |
list[list[list[float]]]
|
With :attr: |
row |
int
|
Index of this result's prompt in its batch ( |
cost_summary
¶
cost_summary() -> CostSummary
Aggregate cost of this generation (see :meth:CostLog.summary).
ConfidenceStop
¶
ConfidenceStop(config: DecodeConfig)
Bases: DraftPolicy
Stop a row when the drafter's top probability drops below min_confidence (never on the first draft,
so every cycle drafts at least one token).
FixedLength
¶
FixedLength(config: DecodeConfig)
Draft
dataclass
¶
Draft(tokens: Tensor, lengths: list[int], parents: Tensor | None = None, probs: Tensor | None = None, confidence: Tensor | None = None, logits: Tensor | None = None, candidates: list[int] | None = None)
The tokens a drafter proposes for every row in one cycle.
A chain draft lists the tokens that follow the last committed token in order. A tree draft lists nodes in
topological order: parents[b, i] is the index of node i's parent, -1 for a child of the last
committed token.
Attributes:
| Name | Type | Description |
|---|---|---|
tokens |
Tensor
|
Proposed tokens |
lengths |
list[int]
|
Number of proposed tokens (nodes) of every row; |
parents |
Tensor | None
|
Parent node of every node |
probs |
Tensor | None
|
The distribution every token was drawn from |
confidence |
Tensor | None
|
The drafter's top probability at every token |
logits |
Tensor | None
|
The drafter's float logits at every token |
candidates |
list[int] | None
|
For a tree draft, the number of leading nodes of every row the verifier may accept; the
nodes after them (up to |
Drafter
¶
Bases: ABC
Proposes tokens between exact passes for a batch of rows.
A drafter lives for one generation. The loop calls :meth:begin once, then, every cycle, :meth:observe with
the exact pass, :meth:observe_logits with its logits and :meth:propose for new drafts. Rows that finish are
dropped with :meth:reorder.
Simple drafters implement :meth:step (one token per row) and inherit :meth:propose, which repeats it while
the :class:~economize.decoding.DraftRequest wants more tokens. Drafters that make several tokens per call or
trees override :meth:propose.
Attributes:
| Name | Type | Description |
|---|---|---|
source_layers |
tuple[int, ...]
|
Layers whose exact hidden states the drafter reads ( |
layer_span |
tuple[int, int]
|
First and last decoder layer one :meth: |
footprint |
LayerFootprint | None
|
The layers one :meth: |
streams_prompt |
bool
|
Whether the drafter needs nothing of the prompt beyond what :meth: |
observed_layers
property
¶
observed_layers: tuple[int, ...]
Layers the exact pass captures for :meth:observe (source_layers unless overridden).
begin
abstractmethod
¶
begin(runner: LayerRunner, cache: KVCache, batch_size: int) -> None
Called once per generation, before the first exact pass.
observe
abstractmethod
¶
observe(exact: ExactPass, columns: Tensor) -> None
Adopt the exact states of the last accepted token of every row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exact
|
ExactPass
|
The latest exact pass ( |
required |
columns
|
Tensor
|
Column of each row's last accepted token in that pass, |
required |
step
¶
step(tokens: Tensor, positions: Tensor, valid: Tensor | None) -> Tensor
Process tokens [B] at positions [B] and return float logits [B, V] for the next
position. Rows with valid false ([B], None when all are active) have stopped drafting; their
output is ignored and they must not change the cache.
propose
¶
propose(request: DraftRequest) -> Draft
Draft tokens for every row, up to its budget in request.
observe_logits
¶
observe_logits(logits: Tensor) -> None
Read the exact logits of the latest pass, after :meth:observe and before finished rows are dropped.
logits is [B, T + 1, V] (float): for a tree pass entry 0 follows the root and entry i + 1
follows node i of the draft, non-candidate nodes included (see :attr:Draft.candidates). Lookahead
decoding takes its next Jacobi window from it. The default ignores it.
reorder
¶
reorder(rows: Tensor) -> None
Keep the batch rows rows (a 1-D LongTensor) in this order. Drafters with per-row state override it.
draft_capacity
¶
draft_capacity(cycle_length: int) -> int
Most tokens (tree nodes) one :meth:propose call makes per row (the loop sizes its buffers with it).
enable_graphs
¶
enable_graphs(wrap: GraphWrap) -> bool
Opt in to CUDA graphs (DecodeConfig.cuda_graphs); return whether the drafter did.
The decoder calls this once, before the first generation. wrap(fn) turns a function of tensors into a
callable that records fn as a CUDA graph per input signature and replays it (see
:class:~economize.runtime.StaticStep). A drafter that opts in routes its draft steps through such a callable
and keeps everything the step reads or writes besides its inputs at fixed addresses across calls: per-row
state lives in persistent buffers that are updated in place, and the cache handed to :meth:begin is the
same object in every generation. The default declines, and the drafter runs eagerly.
drafts_trees
¶
drafts_trees(verifier: Verifier) -> bool
Whether :meth:propose returns draft trees when verifier checks the drafts.
The decoder rejects a tree drafter whose verifier cannot verify trees before it decodes, and wrappers that restrict chain drafts (FR-Spec) reject it before it drafts. The default drafts chains; tree drafters override it.
DraftPolicy
¶
DraftPolicy(config: DecodeConfig)
Bases: ABC
Decides, after each draft step, which rows stop drafting.
Attributes:
| Name | Type | Description |
|---|---|---|
may_stop |
bool
|
:meth: |
stops
abstractmethod
¶
stops(index: int, logits: Tensor) -> Tensor | None
Rows that stop after draft step index (counted from 0 within the cycle), given that step's logits
[B, V]: a bool tensor [B], or None for no row. A stop discards the step's proposal.
wrap
¶
The drafter the decoder drafts with under this policy, given the technique's drafter.
The default returns drafter unchanged. A policy that changes the shape of the draft itself (a dynamic
draft tree, for example) returns a wrapper and raises :class:~economize.ConfigError for a drafter or
verifier it cannot work with. The decoder calls it once, before it checks the verifier and the drafter
against each other.
TokenSelector
¶
Bases: Protocol
Chooses the next token from logits.
Required:
greedy: the choice is deterministic given the logits and the history,__call__(logits[V], history[n]) -> int.
Optional capabilities (select_many, distribution, distributions, generator_for) are protocols
of their own in :mod:economize.decoding.capabilities; a selector gains one by defining the member. A plain
generator attribute is still honoured when it lives on the logits' device.
__call__
¶
__call__(logits: Tensor, history: Tensor) -> int
logits [V] predict the token after history (all tokens so far, prompt included, [n]).
Verifier
¶
Verifier(config: DecodeConfig)
Bases: ABC
Turns one exact pass into accepted drafts plus one token chosen from the exact logits.
Attributes:
| Name | Type | Description |
|---|---|---|
commits_drafts |
bool
|
Drafts become final as they are proposed (lossy decoding); the exact pass then sees no unverified drafts. |
requires_greedy |
bool
|
Verification is exact only for a deterministic selector. |
needs_draft_probs |
bool
|
:meth: |
supports_trees |
bool
|
:meth: |
lossless |
bool
|
Every committed token is distributed exactly as the selector applied to the exact logits (for
greedy decoding: equals the token of step-by-step decoding). |
default_options |
Mapping[str, object]
|
The options the verifier takes from |
draft
¶
draft(logits: Tensor, selector: TokenSelector, history: Tensor) -> tuple[int, Tensor | None]
The draft token after history given drafter logits [V], and the distribution it was drawn from
(None unless :attr:needs_draft_probs).
draft_many
¶
draft_many(logits: Tensor, selector: TokenSelector) -> tuple[Tensor, Tensor | None] | None
:meth:draft for every row of logits [B, V] in one call: tokens [B] and their distributions
[B, V] (or None). Returns None when the selector needs the history; the caller then drafts row
by row.
verify
abstractmethod
¶
verify(logits: Tensor, drafts: list[int], probs: Tensor | None, selector: TokenSelector, history: Tensor, end: int) -> tuple[int, int]
Check the k drafts of one row against exact logits [k + 1, V].
Row i of logits predicts the token at position end + i, whose history is history[:end + i]
(history holds the drafts at their positions). probs [k, V] are the draft distributions when
:attr:needs_draft_probs. Returns the number of accepted drafts a and the token that follows them.
verify_batch
¶
verify_batch(logits: Tensor, draft: Draft, selector: TokenSelector, seq: Tensor, ends: Sequence[int]) -> tuple[Tensor, Tensor]
:meth:verify for a batch of chain drafts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
|
required |
draft
|
Draft
|
The chain drafts. |
required |
selector
|
TokenSelector
|
The token selector. |
required |
seq
|
Tensor
|
All tokens so far |
required |
ends
|
Sequence[int]
|
Number of committed tokens of every row. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Accepted drafts |
Tensor
|
verifies row by row; subclasses vectorize it. |
verify_tree
¶
verify_tree(logits: Tensor, draft: Draft, selector: TokenSelector) -> tuple[list[list[int]], list[int]]
Verify tree drafts. logits [B, T + 1, V]: entry 0 follows the last committed token, entry
i + 1 follows node i. Returns, per row, the accepted path (node indices, root first) and the token
after it.
VerifyEvent
dataclass
¶
VerifyEvent(row: int, start: int, tokens: Tensor, next_token: int, drafted: int, accepted: int, hidden: dict[int, Tensor] = dict())
What an observer registered with :meth:economize.EfficientModel.add_verify_observer receives after every exact
pass, once per row.
Attributes:
| Name | Type | Description |
|---|---|---|
row |
int
|
Index of the row in the batch passed to |
start |
int
|
Position of the first token of |
tokens |
Tensor
|
The tokens of the exact pass that are now committed (pending tokens and accepted drafts), |
next_token |
int
|
The token the verifier chose after them (sampled from the exact logits); it is committed unless decoding stopped before it. |
drafted |
int
|
Number of drafts this pass verified ( |
accepted |
int
|
Number of those drafts that were accepted. |
hidden |
dict[int, Tensor]
|
Exact hidden states of |
WrappableDrafter
¶
Bases: Protocol
A drafter another drafter can wrap (FR-Spec's draft vocabulary, the fallback of hybrid drafting).
Besides the members of :class:Drafter, which the wrapper forwards, a wrappable drafter promises two things
the wrapper relies on. Every chain token it proposes goes through
:meth:~economize.decoding.DraftRequest.extend, the only place a wrapper sees and can restrict the logits a token
is chosen from; a drafter that writes tokens into the request's sequence itself (prompt lookup) cannot be
wrapped. :meth:drafts_trees says truthfully whether it will return a tree, so a wrapper that handles chains
only can refuse before drafting. FR-Spec checks both promises after every proposal and raises
:class:~economize.ConfigError when one is broken. Every :class:Drafter has these members; the protocol names
the contract a wrapper depends on.
DraftRequest
¶
DraftRequest(seq: Tensor, ends: Sequence[int], budgets: Sequence[int], *, selector: TokenSelector, verifier: Verifier, policy: DraftPolicy, costs: Sequence[CostLog], footprint: LayerFootprint | None = None, layer_span: tuple[int, int] | None = None, selectors: Sequence[TokenSelector] | None = None, record_confidence: bool = False, record_distributions: bool = False, draft_loop_graph: bool = False)
One cycle of drafting for a batch of rows.
The loop builds a request after every exact pass and hands it to :meth:Drafter.propose. A chain drafter
reads :attr:tokens, :attr:positions and :attr:valid, runs one step and passes the step's logits to
:meth:extend, until :attr:drafting is false. :meth:extend records the cost of the step, applies the draft
policy, chooses the tokens with the selector (through the verifier, which may keep the draft distribution) and
writes them into the sequence buffer at their positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seq
|
Tensor
|
All tokens so far |
required |
ends
|
Sequence[int]
|
Number of committed tokens of every row; row |
required |
budgets
|
Sequence[int]
|
Most tokens every row may draft in this cycle. |
required |
selector
|
TokenSelector
|
The token selector of the generation. |
required |
verifier
|
Verifier
|
The verifier of the generation (it chooses draft tokens through :meth: |
required |
policy
|
DraftPolicy
|
The draft-length policy. |
required |
costs
|
Sequence[CostLog]
|
The cost log of every row. |
required |
footprint
|
LayerFootprint | None
|
The layers one draft step runs, for the cost log (usually
:func: |
None
|
layer_span
|
tuple[int, int] | None
|
First and last decoder layer one draft step runs; the older spelling of |
None
|
selectors
|
Sequence[TokenSelector] | None
|
One selector per row when the rows choose tokens differently (overrides |
None
|
record_confidence
|
bool
|
Keep the softmax maximum of every step's logits for the drafted tokens
(:attr: |
False
|
record_distributions
|
bool
|
Keep every step's logits for the drafted tokens (:attr: |
False
|
draft_loop_graph
|
bool
|
The drafter may run a whole chain proposal as one CUDA graph
(:meth: |
False
|
scratch
property
¶
scratch: int
Column of :attr:seq that absorbs the writes of rows that are not drafting.
extend
¶
extend(logits: Tensor) -> None
Turn one draft step's float logits [B, V] (the next token of every row) into draft tokens.
graphed_chain_steps
¶
graphed_chain_steps() -> int | None
The number of greedy draft steps k a drafter may run at once and hand to :meth:extend_tokens, or
None when the proposal must go step by step through :meth:extend.
It is k when draft_loop_graph is set, no row has drafted yet, every row drafts the same k > 0
tokens, the draft policy never stops early, every row chooses greedily through the verifier's default
:meth:~Verifier.draft_many (so a step's draft is the arg-max of its logits) and no step's logits are
kept.
extend_tokens
¶
extend_tokens(tokens: Tensor, confidence: Tensor | None = None) -> None
Append k draft tokens [B, k] to every row at once (k from :meth:graphed_chain_steps), with
the softmax maximum of every step [B, k] when :attr:record_confidence is set.
The cost log and the sequence buffer end up as after k calls of :meth:extend whose logits had these
tokens as their arg-max.
GreedySelector
¶
TopPSampler
¶
TopPSampler(temperature: float = 1.0, top_p: float = 1.0, seed: int = 0, device: str | device | None = None)
Temperature and nucleus sampling from private, seeded generators.
The sampler keeps one generator per device it samples on, created on first use and seeded with seed, so a
run is reproducible whichever device holds the logits, and drawing never moves the logits across devices. The
verifiers draw their acceptance coins from the same generator (:meth:generator_for).
With a lossless decoding configuration it needs the "rejection" verifier; lossless=False samples every
draft as it is proposed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperature
|
float
|
Softmax temperature. |
1.0
|
top_p
|
float
|
Smallest set of tokens whose probability mass reaches |
1.0
|
seed
|
int
|
Seed of every generator. |
0
|
device
|
str | device | None
|
Optional device whose generator is created up front (others are created on first use). |
None
|
generator
property
¶
generator: Generator | None
The first generator created (None before the first draw); prefer :meth:generator_for.
generator_for
¶
generator_for(device: device) -> Generator
The generator that draws on device, created and seeded on first use.
select_many
¶
select_many(logits: Tensor) -> Tensor
One sample per row of logits [B, V], [B] (for one row the same draw as __call__).
distribution
¶
distribution(logits: Tensor, history: Tensor) -> Tensor
The distribution __call__ samples from, [V] float.
distributions
¶
distributions(logits: Tensor) -> Tensor
The distribution __call__ samples from for every row of logits [..., V], float.
AcceptanceProfile
dataclass
¶
AcceptanceProfile(hits: ndarray = (lambda: zeros((0, 0)))(), trials: ndarray = (lambda: zeros((0, 0)))())
Counts of the exact model's token ranks among the drafter's candidates at accepted tree nodes.
Attributes:
| Name | Type | Description |
|---|---|---|
hits |
ndarray
|
|
trials |
ndarray
|
|
add
¶
add(level: int, children: int, outcome: int | None) -> None
One accepted node of depth level with children children, whose exact token was its rank-outcome
child (None: none of them).
rates
¶
rates(per_depth: bool = False) -> tuple[float, ...] | tuple[tuple[float, ...], ...]
The acceptance vector (pooled over depths), or one vector per depth: hits / trials (0 where there
were no trials). The result can be passed as the acceptance option of the sequoia policy.
SequoiaDrafter
¶
SequoiaDrafter(inner: Drafter, tree: StaticTree, *, record_acceptance: bool = False)
Bases: TreeSearchDrafter
A chain :class:~economize.decoding.TreeStepDrafter that proposes one fixed tree per cycle (made by
:class:SequoiaPolicy).
The root runs through the inner drafter's chain step; every further depth d with nodes that have children runs
those nodes (the frontier) in one tree step. The cost log records the root's step as one draft call of one
token and the step of depth d as one call of the frontier's width, both over the inner drafter's footprint.
With CUDA graphs the root's expansion and every depth's step run from graphs (their shapes are fixed by the tree).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inner
|
Drafter
|
The chain drafter. |
required |
tree
|
StaticTree
|
The tree. |
required |
record_acceptance
|
bool
|
Keep :attr: |
False
|
SequoiaPolicy
¶
SequoiaPolicy(config: DecodeConfig)
Bases: TreePolicy
Drafts one Sequoia tree per cycle with any :class:~economize.decoding.TreeStepDrafter.
Options (DecodeConfig.draft_policy_options; lists are stored as tuples):
acceptance: the acceptance vector (or one per depth) to build the tree from with :func:sequoia_tree;total_tokens(default 32),depth(defaultcycle_length - 1),verify_latencyanddraft_latencyas there.paths: an explicit tree as rank paths, instead ofacceptance.record_acceptance: count, after every exact pass, which rank the exact token had at every accepted node (:attr:SequoiaDrafter.acceptance; one host synchronization per cycle).
StaticTree
dataclass
¶
StaticTree(paths: tuple[Path, ...], expected: float | None = None)
A draft tree of fixed shape, its nodes in breadth-first order.
Attributes:
| Name | Type | Description |
|---|---|---|
paths |
tuple[Path, ...]
|
Rank path of every node ( |
expected |
float | None
|
Expected tokens per cycle under the acceptance rates the tree was built for (root included),
|
parents
property
¶
parents: tuple[int, ...]
Breadth-first index of every node's parent, -1 for a child of the root.
ranks
property
¶
ranks: tuple[int, ...]
Rank of every node among its siblings (the last entry of its path).
forwarded
property
¶
forwarded: int
Nodes a proposal runs through the drafter besides the root: the nodes with children.
from_paths
classmethod
¶
from_paths(paths: Sequence[Sequence[int]], expected: float | None = None) -> StaticTree
The tree of the rank paths paths (any order; every prefix of a path must be a path too).
children
¶
children() -> list[list[int]]
Breadth-first indices of every node's children, the root's last (index -1).
SearchOptions
dataclass
¶
SearchOptions(depth: int, width: int, topk: int, total_tokens: int, decay: float = 0.95)
The budget of a SpecExec tree search.
Attributes:
| Name | Type | Description |
|---|---|---|
depth |
int
|
Largest depth of a draft node; the search runs |
width |
int
|
Candidates expanded per search step (at most |
topk |
int
|
Children every expanded candidate adds to the pool. |
total_tokens |
int
|
Nodes of the draft tree the exact pass verifies. |
decay |
float
|
Factor in |
candidates
property
¶
candidates: int
Size of the pool after the search: topk + steps * width * topk.
from_config
classmethod
¶
from_config(config: DecodeConfig) -> SearchOptions
The options in config.draft_policy_options (depth defaults to cycle_length - 1).
SpecExecDrafter
¶
SpecExecDrafter(inner: Drafter, options: SearchOptions)
Bases: TreeSearchDrafter
A chain :class:~economize.decoding.TreeStepDrafter that proposes SpecExec trees (made by
:class:SpecExecPolicy).
The cost log records the root's step as one draft call of one token and search step s as one call of
width tokens at the position of depth s (the deepest a node of that step can be), both over the inner
drafter's footprint. With CUDA graphs the root's expansion and every search step run from graphs (one per step:
the pool grows by a fixed amount per step), and so does the final selection.
SpecExecPolicy
¶
SpecExecPolicy(config: DecodeConfig)
Bases: TreePolicy
Drafts a SpecExec tree with any :class:~economize.decoding.TreeStepDrafter (see the module docstring).
Options (DecodeConfig.draft_policy_options): depth (default cycle_length - 1), width (default 8),
topk (default 8), total_tokens (default 60) and decay (default 0.95).
StopChecker
¶
StopChecker(stop: StopCondition)
A :data:StopCondition checked after every committed token.
The decoding loops (:class:~economize.decoding.CycleDecoder, :mod:economize.distributed.ssd) normalise a user's
stop condition into one of these once and call it after each commit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stop
|
StopCondition
|
Stop token id(s), a predicate on all tokens so far, or |
required |
__call__
¶
__call__(token: int, row: Tensor, position: int) -> bool
Whether token, just committed at position of row (the device row of all tokens), stops.
TreePolicy
¶
TreePolicy(config: DecodeConfig)
Bases: DraftPolicy
A draft policy that drafts a tree with any :class:TreeStepDrafter (a subclass builds the wrapper).
The tree replaces the chain, so no row stops early (:attr:may_stop is false).
check_drafter
¶
Raise :class:~economize.ConfigError unless drafter can step over trees that verifier verifies.
A tree policy chooses draft tokens by rank, so it has no draft distribution to offer a verifier that needs one (rejection sampling), and it wraps chain drafters only.
TreeSearchDrafter
¶
TreeSearchDrafter(inner: Drafter, policy_name: str)
Bases: Drafter
A chain :class:TreeStepDrafter that proposes draft trees; subclasses implement :meth:propose.
The wrapper forwards the inner drafter's members (its layers, footprint and any attribute it does not define itself), runs the root through the inner drafter's chain step, and turns every verified tree pass into the chain of the accepted path before the inner drafter observes it, so a chain drafter keeps the state it knows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inner
|
Drafter
|
The chain drafter. |
required |
policy_name
|
str
|
Name of the draft policy that made this drafter, for error messages. |
required |
max_depth
abstractmethod
property
¶
max_depth: int
Depth of the deepest node a proposal can draft (the longest path the exact pass can accept).
propose
abstractmethod
¶
propose(request: DraftRequest) -> Draft
One draft tree per row (see :class:~economize.decoding.Drafter).
AcceptAllVerifier
¶
AcceptAllVerifier(config: DecodeConfig)
Bases: Verifier
Lossy decoding: drafts are final, the exact pass refreshes the cache and emits one exact token.
GreedyVerifier
¶
GreedyVerifier(config: DecodeConfig)
Bases: Verifier
Lossless speculative decoding for deterministic selectors: accept the longest prefix of drafts that the selector reproduces on the exact logits, then append the selector's own token.
RejectionVerifier
¶
RejectionVerifier(config: DecodeConfig)
Bases: Verifier
Lossless speculative sampling.
Every draft x is drawn from the selector's distribution q on the drafter's logits. The exact pass gives
the selector's distribution p; x is accepted with probability min(1, p(x) / q(x)). The first rejected
draft is replaced by a sample from the normalized residual max(p - q, 0). When every draft is accepted the
selector samples one more token from the exact logits. The tokens then follow the distribution of sampling from
the model without drafts.
A draft without a distribution (probs is None: a deterministic drafter such as n-gram lookup, or a
drafter that takes its argmax) is treated as drawn from a one-hot q on itself: it is accepted with
probability p(x), and a rejection samples from p with x removed. This is the same rule and stays
lossless.
The selector needs distribution(logits, history) (and distributions(logits) for the batched path); its
generator for the logits' device (:func:~economize.decoding.capabilities.selector_generator) drives every draw.
verify_tree
¶
verify_tree(logits: Tensor, draft: Draft, selector: TokenSelector) -> tuple[list[list[int]], list[int]]
Recursive rejection sampling down the tree (SpecInfer, Miao et al., 2024).
At every node the children are tried in order. Child i (token x, drawn from q_i) is accepted
with probability min(1, p(x) / q_i(x)); after a rejection p becomes the normalized residual
max(p - q_i, 0). q_i is draft.probs[b, i], the distribution the drafter drew the child from
given its earlier siblings (a one-hot on x when draft.probs is None: deterministic drafts). When
every child is rejected the next token is drawn from the residual; an accepted leaf draws it from its own
exact distribution. The output follows the selector's distribution exactly, whatever the tree.
TypicalVerifier
¶
TypicalVerifier(config: DecodeConfig)
Bases: Verifier
Typical acceptance (Medusa, Cai et al., 2024), a lossy verifier for sampling.
With p the selector's distribution on the exact logits and H(p) = -sum p log(p + 1e-5) its entropy, a
draft x is accepted when p(x) > min(threshold, alpha * exp(-H(p))). The drafts are the drafter's most
likely tokens. The token after the accepted drafts is sampled from p restricted to the tokens above the same
threshold. Low-entropy (confident) positions accept only likely tokens, high-entropy positions accept more.
A deterministic selector gives a one-hot p, which makes this verifier identical to "greedy".
For a draft tree the accepted path is the deepest node whose path is accepted throughout (the first such node on a tie), as in Medusa's choice of the longest accepted candidate.
Options (DecodeConfig.verifier_options): threshold (Medusa's posterior_threshold, default 0.09)
and alpha (posterior_alpha, default 0.3).
cutoff
¶
cutoff(p: Tensor) -> Tensor
The acceptance threshold of every distribution p [..., V], [...].
draft_footprint
¶
draft_footprint(drafter: Drafter | WrappableDrafter) -> LayerFootprint
The layers one draft step of drafter runs: its :attr:~Drafter.footprint, else its
:attr:~Drafter.layer_span.
measure_acceptance
¶
measure_acceptance(model: _Decodes, prompts: Sequence[Tensor], max_new_tokens: int, *, depth: int = 6, width: int = 8, per_depth: bool = False, decoding: Mapping[str, object] | None = None) -> tuple[float, ...] | tuple[tuple[float, ...], ...]
The acceptance vector of model's drafter on prompts, for the acceptance option of sequoia.
Decodes the prompts with the probe tree of :func:probe_paths (depth deep, width children per spine node)
and counts at every accepted node which of the drafter's ranks the exact token had.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
_Decodes
|
An :class: |
required |
prompts
|
Sequence[Tensor]
|
Prompt token ids. |
required |
max_new_tokens
|
int
|
Tokens generated per prompt. |
required |
depth
|
int
|
Depth of the probe tree. |
6
|
width
|
int
|
Ranks measured per node. |
8
|
per_depth
|
bool
|
Return one vector per depth of the parent node. |
False
|
decoding
|
Mapping[str, object] | None
|
Further :class: |
None
|
sequoia_tree
¶
sequoia_tree(acceptance: Sequence[float] | Sequence[Sequence[float]], total_tokens: int, depth: int, *, verify_latency: Sequence[float] | None = None, draft_latency: float = 0.0) -> StaticTree
The Sequoia tree for the acceptance rates acceptance (see the module docstring).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acceptance
|
Sequence[float] | Sequence[Sequence[float]]
|
|
required |
total_tokens
|
int
|
Largest number of draft nodes. |
required |
depth
|
int
|
Largest depth. |
required |
verify_latency
|
Sequence[float] | None
|
Entry |
None
|
draft_latency
|
float
|
Seconds of one draft step (one per depth of the tree), used with |
0.0
|
Returns:
| Type | Description |
|---|---|
StaticTree
|
The tree, its :attr: |