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:ModelWorkerruns any causal LM with an economize architecture adapter). - :class:
LinkedSpeculativeDecoderand :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:DraftLayerWorkerfor EAGLE-1/2 and EAGLE-3). :func:speculative_decoderbuilds 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_planundertorchrun(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
¶
DRAFT_LAYER_WORKERS = DrafterWorkers(worker=DraftLayerWorker, decoder=DraftLayerSpeculativeDecoder, graphed_worker=GraphedDraftLayerWorker, graphed_decoder=GraphedDraftLayerSpeculativeDecoder)
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 ( |
None
|
Raises:
| Type | Description |
|---|---|
ConfigError
|
|
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 ( |
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
|
|
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: |
required |
fanout
|
int
|
See :class: |
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 |
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 |
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 ( |
target |
CapturingTargetWorker | None
|
The linked target, or |
link
¶
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 ( |
None
|
Raises:
| Type | Description |
|---|---|
ConfigError
|
|
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: |
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 |
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 |
fanout |
int
|
Guessed tokens per verification outcome (used by :class: |
mode |
Mode
|
|
temperature |
float
|
|
top_p |
float
|
Nucleus mass when sampling. |
seed |
int
|
Seed of the sampling generators. Every :meth: |
verifier |
str | None
|
Name of a registered verifier (see :data: |
verifier_options |
Mapping[str, object]
|
Options of the verifier, as in :attr: |
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 ( |
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. |
required |
fanout
|
int
|
Candidates for the appended token per outcome. Every speculation drafts |
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 |
candidates |
Tensor
|
Guessed tokens |
tokens |
Tensor
|
The next chain behind every candidate |
logits |
Tensor
|
Its drafter logits |
probs |
Tensor | None
|
Its sampling distributions, or |
ready |
Tensor
|
Host copy of |
event |
Event | None
|
Marks when |
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 |
logits |
Tensor
|
Drafter logits |
probs |
Tensor | None
|
Distributions the tokens were sampled from |
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 |
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
|
|
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 |