Skip to content

economize.distributed

Decoding across several devices.

Decoding across several devices.

  • :class:AsyncSpeculativeDecoder: speculative speculative decoding (SSD). A draft model on a second GPU drafts the next round for the likeliest verification outcomes while the target verifies the current one; the output is exactly the target's (greedy, or speculative sampling).
  • :class:SpeculationWorker: the drafter side of SSD, extended by subclassing (:class:ModelWorker runs any causal LM with an economize architecture adapter).
  • :class:LinkedSpeculativeDecoder and :class:LinkedWorker: SSD with a drafter that runs part of the target's own computation and drafts from the target's exact states (for example :class:DraftLayerWorker for EAGLE-1/2 and EAGLE-3). :func:speculative_decoder builds the decoder of any drafter replica from the workers registered for its technique in :data:DRAFTER_WORKERS.
  • :mod:economize.distributed.tp: tensor parallelism through transformers' tp_plan under torchrun (plan checks and loading). A split model runs through its own forward and through economize's layer runner (economize's own decoding works on it with every adaptation); only SSD rejects split models.

DRAFT_LAYER_WORKERS module-attribute

The SSD workers of every draft-layer technique; a new one registers them under its name.

DraftLayerSpeculativeDecoder

DraftLayerSpeculativeDecoder(target: Module, drafter: DraftLayerWorker, config: SSDConfig | None = None)

Bases: LinkedSpeculativeDecoder

:class:~economize.distributed.AsyncSpeculativeDecoder with a :class:DraftLayerWorker that receives the target's exact states of the source layers for every committed token.

Parameters:

Name Type Description Default
target Module

The model whose output is reproduced, on its device.

required
drafter DraftLayerWorker

The draft-layer worker on another device.

required
config SSDConfig | None

Decoding settings (fanout is the worker's own).

None

Raises:

Type Description
ConfigError

drafter is not a :class:DraftLayerWorker.

DraftLayerWorker

DraftLayerWorker(model: Module, fanout: int = 2)

Bases: LinkedWorker[Tensor]

A draft-layer drafter on its own device, for :class:DraftLayerSpeculativeDecoder.

Parameters:

Name Type Description Default
model Module

A replica of the target with a draft-layer technique attached (economize.load or economize.apply), on the drafter's device. Only its embedding, the draft layer and the draft head (with EAGLE-1/2, or EAGLE-3 with head="shared", the model's final norm and LM head) run there.

required
fanout int

Candidates for the appended token per outcome.

2

Raises:

Type Description
ConfigError

The model has no draft-layer technique or is split by tensor parallelism.

GraphedDraftLayerSpeculativeDecoder

GraphedDraftLayerSpeculativeDecoder(target: Module, drafter: LinkedDrafter, config: SSDConfig | None = None, *, max_width: int = 64)

Bases: GraphedLinkedSpeculativeDecoder, DraftLayerSpeculativeDecoder

:class:DraftLayerSpeculativeDecoder with CUDA graphs on both devices.

Parameters:

Name Type Description Default
target Module

The model whose output is reproduced, on its device.

required
drafter LinkedDrafter

The graphed draft-layer worker on another device.

required
config SSDConfig | None

Decoding settings.

None
max_width int

Verification passes over more tokens run eagerly.

64

Raises:

Type Description
ConfigError

drafter is not a :class:GraphedDraftLayerWorker.

GraphedDraftLayerWorker

GraphedDraftLayerWorker(model: Module, fanout: int = 2, *, granularity: int = 128)

Bases: DraftLayerWorker

An :class:DraftLayerWorker that replays its chain steps and tree passes from CUDA graphs.

Every step attends over the whole cache (masked), so a graph depends only on the number of tokens of the step. The cache is kept across generations and rebuilt (dropping the graphs) when a generation needs more positions.

Parameters:

Name Type Description Default
model Module

See :class:DraftLayerWorker.

required
fanout int

See :class:DraftLayerWorker.

2
granularity int

Cache capacities are rounded up to a multiple of this.

128

DrafterWorkers dataclass

DrafterWorkers(worker: WorkerFactory, decoder: type[LinkedSpeculativeDecoder], graphed_worker: GraphedWorkerFactory | None = None, graphed_decoder: type[GraphedLinkedSpeculativeDecoder] | None = None)

The SSD classes of one drafting technique.

Attributes:

Name Type Description
worker WorkerFactory

The eager worker.

decoder type[LinkedSpeculativeDecoder]

The decoder that links worker to the target (its worker_class).

graphed_worker GraphedWorkerFactory | None

The worker with CUDA-graphed draft steps, if the technique has one.

graphed_decoder type[GraphedLinkedSpeculativeDecoder] | None

Its decoder, which also graphs the target's verification passes.

GraphedLinkedSpeculativeDecoder

GraphedLinkedSpeculativeDecoder(target: Module, drafter: LinkedDrafter, config: SSDConfig | None = None, *, max_width: int = 64)

Bases: LinkedSpeculativeDecoder

:class:~economize.distributed.linked.LinkedSpeculativeDecoder whose target replays its verification passes from CUDA graphs (:class:GraphedTargetWorker). Pair it with a worker that graphs its draft steps by naming that worker class in :attr:worker_class.

Parameters:

Name Type Description Default
target Module

The model whose output is reproduced, on its device.

required
drafter LinkedDrafter

The graphed worker on another device.

required
config SSDConfig | None

Decoding settings.

None
max_width int

Verification passes over more tokens run eagerly.

64

CapturingTargetWorker

CapturingTargetWorker(model: Module, layers: Iterable[int])

Bases: TargetWorker

The target of a :class:LinkedSpeculativeDecoder: a :class:TargetWorker that also keeps the states of layers from its last pass.

Attributes:

Name Type Description
start

Position of the first token of the last pass.

hidden dict[int, Tensor]

Its states {layer: [S, d]}.

states_at

states_at(position: int) -> dict[int, Tensor] | None

Exact states of the token at position if the last pass covered it.

LinkedDrafter

Bases: SpeculationWorker

What a :class:LinkedSpeculativeDecoder needs of its drafter: the layers to observe and a link.

Attributes:

Name Type Description
observed_layers tuple[int, ...]

Layers whose states the linked target keeps (0: the embeddings).

target CapturingTargetWorker | None

The linked target, or None (the worker then drafts open loop if it can).

link(target: CapturingTargetWorker) -> None

Take exact states from target from now on (see :class:LinkedSpeculativeDecoder).

LinkedSpeculativeDecoder

LinkedSpeculativeDecoder(target: Module, drafter: LinkedDrafter, config: SSDConfig | None = None)

Bases: AsyncSpeculativeDecoder

:class:~economize.distributed.AsyncSpeculativeDecoder with a :class:LinkedDrafter that receives the target's exact states of every committed token.

A subclass names its worker class in :attr:worker_class.

Parameters:

Name Type Description Default
target Module

The model whose output is reproduced, on its device.

required
drafter LinkedDrafter

The worker on another device.

required
config SSDConfig | None

Decoding settings (fanout is the worker's own).

None

Raises:

Type Description
ConfigError

drafter is not a :attr:worker_class.

LinkedWorker

LinkedWorker(device: device, fanout: int)

Bases: LinkedDrafter, Generic[StateT]

A linked drafter whose steps continue from per-position states, with the speculation and adoption all such drafters share.

The worker keeps the state of every position it may continue from in _states: the spine's own, then those of an adopted branch, overwritten by the target's exact ones as :meth:_pull brings them in. A subclass supplies the draft step and the cache moves.

Parameters:

Name Type Description Default
device device

The drafter's device.

required
fanout int

Candidates for the appended token per outcome.

required

AsyncSpeculativeDecoder

AsyncSpeculativeDecoder(target: Module, drafter: Module | SpeculationWorker, config: SSDConfig | None = None)

Lossless speculative decoding with a separate draft model that drafts ahead on its own device.

Parameters:

Name Type Description Default
target Module

The model whose output is reproduced, on its device.

required
drafter Module | SpeculationWorker

A draft model on another device (wrapped in a :class:ModelWorker), or any :class:SpeculationWorker.

required
config SSDConfig | None

Decoding settings.

None

Batch size is one: a round commits a different number of tokens per row, and SSD's gain is latency.

Raises:

Type Description
ConfigError

The verifier needs greedy decoding but temperature > 0.

generate

generate(prompt: Tensor, max_new_tokens: int, stop_tokens: StopCondition = None) -> SSDResult

Generate up to max_new_tokens tokens after prompt ([P] or [1, P] token ids).

Generation also ends after the first token that meets stop_tokens (a stop token id, a collection of them, or a predicate on all tokens so far; the token is kept), as in :class:~economize.decoding.CycleDecoder.

SSDConfig dataclass

SSDConfig(draft_length: int = 4, fanout: int = 2, mode: Mode = 'async', temperature: float = 0.0, top_p: float = 1.0, seed: int = 0, verifier: str | None = None, verifier_options: Mapping[str, object] = dict())

Settings of :class:AsyncSpeculativeDecoder.

Attributes:

Name Type Description
draft_length int

Drafts per round k.

fanout int

Guessed tokens per verification outcome (used by :class:ModelWorker built from a model).

mode Mode

"async" speculates on the outcome while the target verifies; "sync" is ordinary two-model speculative decoding with the same models (the reference SSD is measured against).

temperature float

0 decodes greedily; above 0 samples losslessly with speculative sampling.

top_p float

Nucleus mass when sampling.

seed int

Seed of the sampling generators. Every :meth:~AsyncSpeculativeDecoder.generate call starts them afresh from it, so repeated calls on one prompt return the same sample.

verifier str | None

Name of a registered verifier (see :data:~economize.decoding.VERIFIERS); None picks "greedy" at temperature 0 and "rejection" (speculative sampling) above it.

verifier_options Mapping[str, object]

Options of the verifier, as in :attr:DecodeConfig.verifier_options.

SSDResult dataclass

SSDResult(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, hits: int = 0, draft_cost: CostLog = CostLog())

Bases: DecodeResult

One generation: a :class:~economize.decoding.DecodeResult (acceptance holds (k, accepted) per round, cost the target's calls as "exact" events in target layers) plus the drafter's side.

Attributes:

Name Type Description
hits int

Rounds whose outcome the drafter had speculated (their next chain was ready).

draft_cost CostLog

The drafter's calls ("draft" events, in drafter layers).

accepted property

accepted: list[int]

Drafts the target kept in every round.

rounds property

rounds: int

Verification passes after the prompt.

hit_rate property

hit_rate: float

Share of rounds after which the next chain was already drafted.

acceptance_length property

acceptance_length: float

Tokens committed per verification pass (accepted drafts plus the target's own token).

summary

summary() -> dict[str, object]

The statistics above, the target's cost summary and the drafter's work.

The target's keys (exact_calls, layer_tokens, relative_layer_tokens, ...) count the target's passes only. The drafter's side: draft_steps and wasted_draft_steps count its draft steps, draft_layer_tokens the layers of the target's architecture it ran (a self-drafter's), and module_layer_tokens the layers of separate networks per network ("draft_model" for a separate draft LM, in its own layers). relative_layer_tokens_with_draft adds draft_layer_tokens to the target's work relative to plain decoding. A separate network's layers have another size, so price them with :class:~economize.bench.CostModel (draft=CallSpec(shape=...)) over :attr:cost and :attr:draft_cost.

ModelWorker

ModelWorker(model: Module, fanout: int = 2)

Bases: _CachedModel, SpeculationWorker

A causal LM drafter on its own device (any model with an economize architecture adapter and attention layers).

Parameters:

Name Type Description Default
model Module

The draft model, already on its device (e.g. cuda:1) and in eval mode.

required
fanout int

Candidates for the appended token per outcome. Every speculation drafts (k + 1) * fanout chains in parallel, one tree pass per depth.

2

Speculation dataclass

Speculation(base: int, candidates: Tensor, tokens: Tensor, logits: Tensor, probs: Tensor | None, ready: Tensor, event: Event | None = None)

The drafter's preparation for the outcomes of one verification.

An outcome is (a, y): the target accepts the first a drafts and appends y. For every a in 0..k the drafter guesses fanout candidates for y and drafts the next chain behind each of them.

Attributes:

Name Type Description
base int

Committed length when the round started (the spine's first draft sits at position base).

candidates Tensor

Guessed tokens y per outcome [k + 1, fanout] (device).

tokens Tensor

The next chain behind every candidate [k + 1, fanout, k].

logits Tensor

Its drafter logits [k + 1, fanout, k, V].

probs Tensor | None

Its sampling distributions, or None for greedy drafts.

ready Tensor

Host copy of candidates; read it after event completed.

event Event | None

Marks when ready holds the candidates (None on the CPU).

lookup

lookup(accepted: int, token: int) -> int | None

Index of token among the candidates of outcome accepted, or None (a miss).

hit

hit(accepted: int, token: int) -> Adoption | None

The branch behind the outcome (accepted, token), or None if it was not speculated (a miss).

SpeculationWorker

Bases: ABC

A drafter that drafts chains and speculates on verification outcomes.

The worker keeps its own cache. Between rounds it holds the committed prefix up to the last committed token (the root, at position n - 1) plus the spine's drafts d_1..d_{k-1} at positions n..n+k-2.

begin abstractmethod

begin(prompt: Tensor, capacity: int) -> None

Start a generation: a fresh cache of capacity positions and a pass over prompt [P].

draft abstractmethod

draft(context: Tensor, position: int, length: int, choose: Chooser) -> Spine

Draft length tokens one at a time after context [S]: committed tokens missing from the cache, the first at position, the last the root.

speculate abstractmethod

speculate(spine: Spine, base: int, choose: Chooser) -> Speculation

Prepare the next chain for the likeliest outcomes of verifying spine (first draft at base).

Must not wait for the device, so that it overlaps the target's verification.

adopt abstractmethod

adopt(speculation: Speculation, accepted: int, token: int) -> Spine | None

The next spine if the outcome (accepted, token) was speculated (then the cache holds its tokens at their positions), else None.

capacity_overhead

capacity_overhead(length: int) -> int

Cache positions beyond the generated sequence that one speculation of chains of length drafts needs.

The default fits the layout of :class:ModelWorker: the spine plus (length + 1) * fanout chains of length nodes. A worker that lays out its speculation differently overrides it.

Spine dataclass

Spine(tokens: Tensor, logits: Tensor, probs: Tensor | None = None)

The chain a round verifies: draft tokens and what the drafter chose them from.

Attributes:

Name Type Description
tokens Tensor

Draft tokens [k] on the drafter's device.

logits Tensor

Drafter logits [k, V]; row i produced tokens[i].

probs Tensor | None

Distributions the tokens were sampled from [k, V], None for greedy drafts.

TargetWorker

TargetWorker(model: Module)

Bases: _CachedModel

The target model on its device: one exact pass over the prompt, then one chain verification per round.

Parameters:

Name Type Description Default
model Module

The target model, already on its device.

required

begin

begin(prompt: Tensor, capacity: int) -> Tensor

Fresh cache and a pass over prompt [P]; returns the logits after the last prompt token [V].

verify

verify(tokens: Tensor, position: int) -> Tensor

Logits [S, V] after each of tokens [S], the first at position (writes their K/V).

drafter_workers

drafter_workers(model: Module) -> tuple[str, DrafterWorkers]

The registered workers of the drafting technique attached to model, and the name they are registered under: the technique's own, else that of its nearest base class with workers.

Raises:

Type Description
ConfigError

model has no drafting technique, or no class of its technique has registered workers.

speculative_decoder

speculative_decoder(target: Module, replica: Module, config: SSDConfig | None = None, *, fanout: int = 2, graphed: bool = False, granularity: int = 128, max_width: int = 64) -> LinkedSpeculativeDecoder

The SSD decoder of the drafting technique attached to replica, with its worker on replica's device.

Parameters:

Name Type Description Default
target Module

The model whose output is reproduced, on its device.

required
replica Module

A replica of the target with a drafting technique attached, on the drafter's device.

required
config SSDConfig | None

Decoding settings.

None
fanout int

Candidates for the appended token per outcome.

2
graphed bool

Replay the draft steps and the verification passes from CUDA graphs.

False
granularity int

Cache slots per captured graph of the graphed worker.

128
max_width int

Verification passes over more tokens run eagerly (graphed only).

64

Raises:

Type Description
ConfigError

No workers are registered for the technique, or graphed is set and it has no graphed ones.