Skip to content

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:CycleDecoder runs 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:TreeStepDrafter into 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:StopChecker turns a :data:StopCondition into the check run after every committed token.
  • :class:CostLog records every model call for cost accounting.
  • :class:DecodeGraphs holds the CUDA graphs and static cache of a decoder with cuda_graphs=True.
  • :class:DepthSteps runs 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).

select_many

select_many(logits: Tensor) -> Tensor

One choice per row of logits [B, V], [B].

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.

generator_for

generator_for(device: device) -> Generator

The generator that draws on device.

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 (N). 1 is ordinary decoding.

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 False every draft is kept and the exact pass only refreshes the cache (lossy, cheaper). None (the default) means True unless verifier names another verifier. An explicit True is enforced when the decoder is built: a lossy verifier ("accept_all", "typical") or an attached lossy technique that changes the exact pass itself (a compressed or evicting KV cache, dynamic depth, a sparse prefill) raises :class:~economize.errors.ConfigError. Weight and activation techniques define the model the exact pass runs, so they combine with True: the output is that of step-by-step decoding of the transformed model.

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 lossless picks.

draft_policy str | None

Advanced. Name of a registered draft-length policy, overriding min_confidence.

verifier_options Mapping[str, object]

Advanced. Keyword options of the verifier, e.g. {"threshold": 0.09, "alpha": 0.3} for verifier="typical". Each verifier documents and checks its own options.

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 (cycle_length=1) reads the new tokens back to the host and checks the stop conditions every sync_interval steps, so the GPU never waits for the host in between. A row that stopped earlier is cut at its stop token: tokens and cost logs are those of reading every step, and a stopped row costs at most sync_interval - 1 extra steps of compute. A sampler shared by several rows may draw different random numbers after one of them stops (the distribution is the same). Verify observers need every step and imply 1.

record_confidence bool

Log the drafter's top probability of every drafted token in :attr:DecodeResult.confidence <economize.decoding.DecodeResult.confidence> (for calibration metrics). It costs one softmax over the draft logits per draft step, kept on the device and read back once per row when the row finishes; tokens and acceptance are unchanged.

record_distributions bool

Compare the drafter's distribution with the verifier's at every drafted token of a chain draft and log [top-1 agreement, KL(verifier || drafter), TV] in :attr:DecodeResult.match <economize.decoding.DecodeResult.match>. Both distributions are a sampling selector's (temperature and truncation applied) when it exposes them, the plain softmax otherwise; the drafter's are the ones it sampled from when the verifier needs them. It keeps every draft step's logits on the device until the exact pass; tokens and acceptance are unchanged.

draft_loop_graph bool

With cuda_graphs, record a whole chain proposal of k draft steps as one CUDA graph (one graph per k) for drafters that support it, with the greedy choice of every step computed by a fused LM-head kernel that never writes the logits. It applies to greedy drafting at a fixed draft length (no min_confidence, no record_distributions) where every row drafts the same number of tokens; other proposals run step by step. Decoding stays lossless; a draft differs from the step-by-step one only where two logits lie within the rounding of the head's matrix product.

draft_policy_options Mapping[str, object]

Advanced. Keyword options of the draft policy, e.g. {"depth": 6, "topk": 8, "total_tokens": 60} for draft_policy="dynamic_tree". Each policy documents and checks its own options. Lists (also nested ones, as JSON gives them) are stored as tuples, so the configuration stays hashable.

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:Drafter.streams_prompt <economize.decoding.Drafter.streams_prompt>), no layer policy, no verify observer and a model without recurrent layers. A KV-cache technique sees the chunks as one pass over the whole prompt.

window_cache bool

With prefill_chunk, keep the sliding-window layers in a ring of slightly more than their window (:class:~economize.runtime.RingSpec) instead of a slot per position, so long prompts fit on fewer devices. Chains only (no draft trees); the cache must declare supports_ring. Tokens are those of the full cache. A KV-cache technique then acts on the full-length layers only, since the ring already bounds the sliding ones.

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:CostKind constants or a technique's own kind.

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 (None for other calls, and for draft steps a drafter records without :meth:~economize.decoding.DraftRequest.extend and without a step). The loop uses it to drop the steps a row made after it finished.

module str | None

None when the layers are the decoded model's own. Otherwise the name of the separate network that ran ("draft_model", "eagle3", "mtp", "medusa"), and the layers are that network's, counted from 1. A network without decoder layers (Medusa heads) records an empty range.

layers tuple[int, ...] | None

The decoder layers run when they are not one contiguous range (a draft that skips layers), in which case first_layer and last_layer are its smallest and largest entries.

layer_indices property

layer_indices: tuple[int, ...]

The decoder layers the call ran, in order.

layer_tokens property

layer_tokens: int

Decoder-layer applications, the unit in which the cost of a call is compared.

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 class-attribute instance-attribute

DRAFT: Final = 'draft'

One draft step.

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.

count

count(kind: str) -> int

Number of events of kind.

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 (first_layer - 1 for none).

module str | None

The separate network the layers belong to, None for the decoded model (see :class:CostEvent).

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 (supports_steps).

required
graphs DecodeGraphs | None

The decoder's CUDA graphs; None runs the steps eagerly.

required
overrides Mapping[int, Module] | None

Modules that replace decoder layers (by 1-based index), as in :meth:~economize.runtime.LayerRunner.run (a draft view's layer copies).

None
head Callable[[Tensor], Tensor] | None

Turns the output of the last layer [1, 1, d] into what a step returns (default: the model's float logits [1, 1, V]); a drafter passes its own head ([1, V] draft logits).

None
device_decisions bool

Let a policy that supports it decide on the device (one graph and one synchronization per step); False keeps the host-decided steps.

True

Attributes:

Name Type Description
graphed

Whether the steps are recorded as CUDA graphs (graphs given and the model on a CUDA device; else the same steps run eagerly, on the decoder's static cache if it has one).

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:~economize.runtime.GraphPool).

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.

draft

draft(cache: KVCache, token: Tensor, position: int) -> Tensor

A draft step: the output of :attr:head for the token [1, 1] at position, whose K/V the layers it runs write into cache (the next exact pass overwrites them). Runs in the caller's phase.

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. total_tokens <= 63).

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 [B, W].

required
parents Tensor

The parents of every node the tree forwarded so far [B, n], the frontier being the last W; parents[b, i] is the index of node i's parent among them, -1 for a child of the root. Node i sits at slot base + i and at position base plus its depth below the root's children. The frontier may hold nodes of different depths.

required
base Tensor

First slot after the committed prefix [B] (the position of the root's children).

required
states Tensor

The state of every frontier node's parent [B, W, ...], in the order of :meth:tree_state.

()

Returns:

Type Description
Tensor

The float logits after every frontier node [B, W, V] and the frontier's own states (same order and

tuple[Tensor, ...]

shapes as states). The step writes the frontier's keys and values to its slots and has no host

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 ("decode" or "refresh").

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

num_graphs property

num_graphs: int

Graphs recorded so far (over all steps).

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

cache_for(capacity: int, batch_size: int, ring: RingSpec | None = None) -> KVCache

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 config.cycle_length > 1.

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:VerifyEvent per row after every exact pass.

()
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 (config.cuda_graphs). Graphs also need a CUDA model on one device, a cache kind with a static variant (:meth:DecodeGraphs.supports_cache), no recurrent layers, no layer_policy unless it implements the step interface (:attr:~economize.runtime.LayerPolicy.supports_steps) and cycle_length = 1, and no wrap_cache unless it has a true graph_safe attribute (a :class:~economize.core.cache_wrapping.CacheWrapping of graph-safe KV-cache techniques); otherwise the decoder runs eagerly.

True

Attributes:

Name Type Description
active_drafter Drafter | None

The drafter that runs, None with cycle_length = 1 (ordinary decoding ignores it).

capture tuple[int, ...]

Layers whose hidden states every exact pass returns: the observed layers of :attr:active_drafter. The eager passes and the graphed passes capture exactly these.

graphs DecodeGraphs | None

The decoder's CUDA graphs and static cache, None when it runs eagerly. They are kept across :meth:decode_batch calls, so reuse one decoder for repeated generations.

depth_steps DepthSteps | None

With config.cuda_graphs, cycle_length = 1 and a layer policy that implements the step interface, the engine that runs its one-token decode steps without the skipped layers (:class:~economize.decoding.DepthSteps, graphed when :attr:graphs is set); else None.

Raises:

Type Description
ConfigError

cycle_length > 1 without a drafter, lossless=True with a lossy verifier, a verifier that both commits drafts and claims to verify trees, or a drafter that drafts trees (:meth:~economize.decoding.Drafter.drafts_trees) with a verifier that cannot verify them. Unknown verifier options raise from the verifier.

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).

None
stop StopCondition

Stop condition of every row.

None
selectors Sequence[TokenSelector | None] | None

One selector per row; a None entry uses selector. Rows that share a selector object are drafted and verified together.

None
stops Sequence[StopCondition] | None

One stop condition per row; a None entry uses stop.

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, [n] (prompt excluded).

cost CostLog

Every model call made for this row.

acceptance list[tuple[int, int]]

One (drafted, accepted) pair per verified cycle (lossless decoding only).

prompt_length int

Number of prompt tokens.

num_layers int

Decoder layers of the model.

confidence list[list[float]]

With :attr:DecodeConfig.record_confidence <economize.DecodeConfig.record_confidence>, one list per entry of acceptance: the drafter's top probability at each drafted token (nan where unknown, [] for a cycle whose drafter did not report it, e.g. trees or prompt lookup). Empty otherwise.

match list[list[list[float]]]

With :attr:DecodeConfig.record_distributions <economize.DecodeConfig.record_distributions>, one list per entry of acceptance: [top-1 agreement, KL(verifier || drafter), TV] at each drafted token, conditioned on the same prefix (the drafts before it), from :func:~economize.decoding.commit.distribution_match ([] for a cycle whose drafter did not report its logits). Empty otherwise.

row int

Index of this result's prompt in its batch (0 for :meth:~economize.EfficientModel.decode); the per-row statistics of the techniques (technique.cost_summary(result)) are looked up under it.

mean_accepted property

mean_accepted: float

Accepted drafts per verified cycle.

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)

Bases: DraftPolicy

Always draft cycle_length - 1 tokens.

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 [B, T] on the model's device, left-aligned and padded with -1.

lengths list[int]

Number of proposed tokens (nodes) of every row; lengths[b] <= T.

parents Tensor | None

Parent node of every node [B, T] for a tree draft, None for a chain.

probs Tensor | None

The distribution every token was drawn from [B, T, V], for verifiers that need it (:attr:Verifier.needs_draft_probs).

confidence Tensor | None

The drafter's top probability at every token [B, T] (float32, nan where unknown), when :attr:DecodeConfig.record_confidence is set and the drafter drafts through :meth:~economize.decoding.DraftRequest.extend; None otherwise.

logits Tensor | None

The drafter's float logits at every token [B, T, V] (float32), when :attr:DecodeConfig.record_distributions is set and the drafter drafts through :meth:~economize.decoding.DraftRequest.extend; None otherwise.

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 lengths[b]) run in the exact pass for the drafter's own use (the Jacobi window of lookahead decoding, read back in :meth:Drafter.observe_logits) and are never accepted. They may hang anywhere in the tree; no candidate descends from one. None (the default) makes every node a candidate. See :meth:verifiable.

width property

width: int

T, the largest number of tokens of any row.

empty classmethod

empty(batch_size: int, device: device | str) -> Draft

A draft without tokens.

select

select(rows: Sequence[int]) -> Draft

The drafts of the batch rows rows, in this order.

verifiable

verifiable() -> Draft

The part of the draft the verifier checks: every row's first candidates[b] nodes (the whole draft when :attr:candidates is None). Candidates come first in topological order, so the part is a tree of its own.

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 (0 is the token embedding).

layer_span tuple[int, int]

First and last decoder layer one :meth:step runs, for cost accounting.

footprint LayerFootprint | None

The layers one :meth:step runs when :attr:layer_span cannot say it: layers that are not one range, or the layers of a separate network (module). None uses :attr:layer_span; read it through :func:draft_footprint.

streams_prompt bool

Whether the drafter needs nothing of the prompt beyond what :meth:observe gives it for the last prompt token and the K/V it writes into the shared cache itself. Only such drafters allow a chunked prefill (:attr:DecodeConfig.prefill_chunk <economize.decoding.DecodeConfig.prefill_chunk>), whose exact pass holds the hidden states of the last chunk alone.

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 (exact.hidden holds :attr:observed_layers).

required
columns Tensor

Column of each row's last accepted token in that pass, [B] on the model's device.

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 can return rows to stop. False lets the loop skip the call.

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

wrap(drafter: Drafter, verifier: Verifier) -> Drafter

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:draft returns the distribution each draft was drawn from, and :meth:verify reads it.

supports_trees bool

:meth:verify_tree is implemented.

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). DecodeConfig.lossless=True refuses a verifier that sets it to False.

default_options Mapping[str, object]

The options the verifier takes from DecodeConfig.verifier_options, with their defaults. :attr:options holds the merged values; an unknown option is a :class:ConfigError.

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

[B, T + 1, V]; row b uses its first draft.lengths[b] + 1 entries.

required
draft Draft

The chain drafts.

required
selector TokenSelector

The token selector.

required
seq Tensor

All tokens so far [B, *] (drafts at their positions).

required
ends Sequence[int]

Number of committed tokens of every row.

required

Returns:

Type Description
Tensor

Accepted drafts [B] and the following token [B] (LongTensors on the logits' device). The default

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 decode.

start int

Position of the first token of tokens.

tokens Tensor

The tokens of the exact pass that are now committed (pending tokens and accepted drafts), [n].

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 (0 for the prefill and for lossy decoding).

accepted int

Number of those drafts that were accepted.

hidden dict[int, Tensor]

Exact hidden states of tokens at the drafter's layers, {layer: [n, d]} (0 is the embedding; empty without a drafter).

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 [B, capacity + 1], indexed by position; the last column is a scratch column for rows that are not drafting. Drafted tokens are written into it.

required
ends Sequence[int]

Number of committed tokens of every row; row b drafts from position ends[b] on.

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:Verifier.draft).

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:~economize.decoding.protocols.draft_footprint of the drafter).

None
layer_span tuple[int, int] | None

First and last decoder layer one draft step runs; the older spelling of footprint for a contiguous range of the decoded model's layers. Give exactly one of the two.

None
selectors Sequence[TokenSelector] | None

One selector per row when the rows choose tokens differently (overrides selector).

None
record_confidence bool

Keep the softmax maximum of every step's logits for the drafted tokens (:attr:Draft.confidence), on the device.

False
record_distributions bool

Keep every step's logits for the drafted tokens (:attr:Draft.logits), on the device.

False
draft_loop_graph bool

The drafter may run a whole chain proposal as one CUDA graph (:meth:graphed_chain_steps, DecodeConfig.draft_loop_graph).

False

scratch property

scratch: int

Column of :attr:seq that absorbs the writes of rows that are not drafting.

layer_span property

layer_span: tuple[int, int]

First and last layer of :attr:footprint.

active property

active: list[bool]

Which rows still draft in this cycle.

drafting property

drafting: bool

Some row still drafts.

tokens property

tokens: Tensor

The token every row processes next (its last token), [B].

positions property

positions: Tensor

Position of :attr:tokens, [B].

valid property

valid: Tensor | None

Rows that draft in this step [B] (bool), None when all do.

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.

draft

draft() -> Draft

The chain drafts made so far.

GreedySelector

Most likely token.

select_many

select_many(logits: Tensor) -> Tensor

The argmax of every row of logits [B, V], [B].

distribution

distribution(logits: Tensor, history: Tensor) -> Tensor

A one-hot distribution on the most likely token, [V] float.

distributions

distributions(logits: Tensor) -> Tensor

One-hot distributions on the most likely token of every row of logits [..., V], float.

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 top_p (1.0 keeps all).

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

hits[l, r]: accepted nodes of depth l whose exact next token was the drafter's rank-r token.

trials ndarray

trials[l, r]: accepted nodes of depth l that had a child of rank r in the tree.

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:acceptance up to date after every exact pass.

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 (default cycle_length - 1), verify_latency and draft_latency as there.
  • paths: an explicit tree as rank paths, instead of acceptance.
  • 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 ((0, 2) is the third most likely child of the most likely child of the root), sorted by depth and then lexicographically, so that a parent precedes its children and the children of a node follow in rank order.

expected float | None

Expected tokens per cycle under the acceptance rates the tree was built for (root included), None for an explicit tree.

size property

size: int

Nodes besides the root (the draft tokens of a cycle).

depth property

depth: int

Depth of the deepest node.

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 depth - 1 steps after the root's.

width int

Candidates expanded per search step (at most topk).

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 (0, 1] on the probability of every further depth (decay_factor of the official code, which defaults to 0.95; 1 ranks by the drafter's probabilities alone).

steps property

steps: int

Search steps after the root's draft step.

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 None (never stops).

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

check_drafter(drafter: Drafter, verifier: Verifier) -> None

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:~economize.EfficientModel with a drafter that supports tree steps.

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:~economize.DecodeConfig fields (for example cuda_graphs).

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]]

acceptance[r], the probability that the exact model's token after an accepted node is the drafter's r-th most likely token; or one such vector per depth of the parent (the root's first, the last reused below).

required
total_tokens int

Largest number of draft nodes.

required
depth int

Largest depth.

required
verify_latency Sequence[float] | None

Entry i: seconds of a base pass over i + 1 tokens (at least total_tokens + 1 entries). With it the tree maximizes expected tokens per second over all sizes and depths; without it the tree maximizes expected tokens per cycle.

None
draft_latency float

Seconds of one draft step (one per depth of the tree), used with verify_latency.

0.0

Returns:

Type Description
StaticTree

The tree, its :attr:StaticTree.expected set.