Skip to content

economize.runtime

Slot-addressed KV caches, attention masks, layer contexts, the layer runner and CUDA graphs.

Execution runtime: slot-addressed caches, attention masks, layer contexts, the layer runner, CUDA graphs and non-blocking host-to-device transfers.

CacheSpec dataclass

CacheSpec(capacity: int, batch_size: int = 1, kind: str = 'positional', ring: RingSpec | None = None)

What :meth:economize.runtime.LayerRunner.new_cache builds.

Attributes:

Name Type Description
capacity int

Number of usable positions per row (the buffers hold one more slot, the trash slot).

batch_size int

Number of rows.

kind str

Key of :data:CACHES; the model's adapter chooses it ("hybrid" for linear-attention layers).

ring RingSpec | None

The window cache of the sliding layers (only on caches that declare :attr:KVCache.supports_ring), or None.

HybridCache

HybridCache(spec: CacheSpec)

Bases: PositionalKVCache

K/V buffers for attention layers plus the states of recurrent layers (gated delta nets, Mamba-2).

It implements the part of the transformers cache API that these layers call (has_previous_state, layers[idx], get_conv_state, get_recurrent_state, is_recording_past, update_conv_state, update_recurrent_state) for Qwen3.5, Qwen3-Next and Nemotron-H, on transformers 5.13 and later. Each recurrent layer keeps a conv window [B, channels, kernel] and a recurrent state. States advance with every token they see, so a decoder that processes speculative tokens takes a :meth:snapshot before and restores it afterwards, then replays the accepted tokens.

layers property

layers: _LayerList

cache_params.layers[idx] of the transformers cache API. A fresh view per access: a stored one would form a reference cycle with the cache, which only the cyclic collector frees, so during training every micro-batch's caches (and the recurrent states they hold) would pile up on the GPU until it ran.

tensor_stores

tensor_stores() -> tuple[dict[int, Tensor], ...]

The key and value buffers, then the conv windows and recurrent states.

put_recurrent_state

put_recurrent_state(layer_idx: int, conv: Tensor | None, recurrent: Tensor | None) -> None

Store conv and recurrent as layer layer_idx's states as they are (None drops one).

recurrent_state

recurrent_state(layer_idx: int) -> tuple[Tensor | None, Tensor | None]

Conv and recurrent state of layer layer_idx (copies of the selected rows inside :meth:selecting).

Single-token steps of some layers update these tensors in place. Outside :meth:selecting the stored tensors themselves are handed out; inside, the copy handed out (one per layer and state, however often it is read) is written back when the block ends unless the layer stored a new state meanwhile.

has_previous_state

has_previous_state(layer_idx: int | None = None, state_idx: int | None = None) -> bool

Whether layer layer_idx has seen tokens (any layer when None).

get_conv_state

get_conv_state(layer_idx: int, state_idx: int = 0) -> Tensor | None

Conv window of layer layer_idx, or None before the layer has seen tokens (transformers >= 5.23 reads the states through these getters instead of layers[idx]).

get_recurrent_state

get_recurrent_state(layer_idx: int, state_idx: int = 0) -> Tensor | None

Recurrent state of layer layer_idx, or None before the layer has seen tokens.

is_recording_past

is_recording_past(layer_idx: int) -> bool

Always True: keeps single-token steps on the path that calls :meth:update_conv_state, so the stored window is replaced, never updated in place by the fused kernel (the same as record_past of layers[idx]).

update_conv_state

update_conv_state(conv_states: Tensor, layer_idx: int, state_idx: int = 0, conv_kernel_size: int | None = None, **kwargs: object) -> Tensor

Store the conv window of layer layer_idx and return what the layer convolves.

With conv_kernel_size (transformers >= 5.14), conv_states are the new conv inputs: the last conv_kernel_size inputs are stored and the inputs are returned with the stored ones prepended. Without it, conv_states is the new window itself, or, when it is narrower than the stored window (a single-token Mamba-2 step), the newest inputs, which are shifted into the window; the window is returned.

update_recurrent_state

update_recurrent_state(recurrent_states: Tensor, layer_idx: int, state_idx: int = 0, **kwargs: object) -> Tensor

Store the recurrent state after the current tokens.

snapshot

snapshot() -> RecurrentSnapshot

Copies of every conv and recurrent state (K/V buffers need none: masks hide stale slots).

restore

restore(snapshot: RecurrentSnapshot, rows: Tensor | None = None) -> None

Put the states of snapshot back, for every row or only for rows.

A state that did not exist when the snapshot was taken is dropped (rows=None) or zeroed in rows, which is how a layer that has not seen tokens behaves.

Raises:

Type Description
ConfigError

rows is given and the snapshot holds a state that the cache no longer has (the states of the other rows would be undefined); restore every row instead.

KVCache

KVCache(spec: CacheSpec)

Bases: SlotLayout, ABC

A cache that decoder layers write through update at slots chosen by the caller.

Layers are addressed by their 0-based layer_idx (the attribute Hugging Face attention modules pass).

ring property

ring: RingSpec | None

The window cache of the sliding layers, or None.

active_batch_size property

active_batch_size: int

Rows that layers see: the selected rows inside :meth:selecting, else the whole batch.

active_slots property

active_slots: Tensor

The slots set by the innermost :meth:writing_at.

key_positions

key_positions(device: device) -> Tensor

Position of the token stored in each slot of a chain layout, [num_slots] (slot i holds position i; the trash slot holds :data:UNSEEN_POSITION).

writing_at

writing_at(slots: Tensor) -> Iterator[KVCache]

Direct every write inside the block to slots: [S] (same slots in every row) or [B, S].

selecting

selecting(rows: Tensor) -> Iterator[KVCache]

Restrict reads and writes inside the block to the batch rows rows (a 1-D LongTensor).

Layers then see a cache of len(rows) rows. This is meant for rare corrections (re-running the accepted tokens of some rows of a hybrid model); the full-batch path copies nothing.

external_pass

external_pass(frontier: list[int | None]) -> AbstractContextManager[object]

A context around a replayed (CUDA graph) exact pass whose row b writes from slot frontier[b] on.

A graph cannot run the host code a cache may run at the boundary of an exact pass (see :class:~economize.techniques._kv.CacheWrapper), so the decoding loop runs it here, outside the graph, and writing_at inside the block skips it. A plain cache has none.

graph_state

graph_state() -> tuple[object, ...]

What the kernels a graph records over this cache depend on beyond its buffers' addresses.

A recorded graph is replayed only while this value is unchanged; a cache returns a new value when, for example, it stops handing packed codes to attention. A plain cache returns ().

update abstractmethod

update(key_states: Tensor, value_states: Tensor, layer_idx: int, *args: object, **kwargs: object) -> tuple[Tensor, Tensor]

Write layer layer_idx's K/V at the active slots and return its whole buffers (the attention keys).

read abstractmethod

read(layer_idx: int) -> tuple[Tensor, Tensor]

The buffers of layer layer_idx ([B, heads, num_slots, dim] each).

write

write(layer_idx: int, key_states: Tensor, value_states: Tensor) -> None

Write K/V at the active slots without returning the buffers (used to fill skipped layers).

has_layer abstractmethod

has_layer(layer_idx: int) -> bool

Whether layer layer_idx has written anything yet.

gather abstractmethod

gather(rows: Tensor, src: Tensor, dst: Tensor) -> None

Copy, in every layer, slots src[i, j] of row rows[i] to slots dst[i, j] (tree compaction).

reorder abstractmethod

reorder(rows: Tensor) -> None

Keep the batch rows rows in this order (drops finished rows when len(rows) is smaller).

snapshot

snapshot() -> RecurrentSnapshot

Copies of the states that masks cannot rewind (none for a K/V-only cache, see :attr:keeps_recurrent_state).

restore

restore(snapshot: RecurrentSnapshot, rows: Tensor | None = None) -> None

Put the states of snapshot back, for every row or only for rows (nothing for a K/V-only cache).

tensor_stores

tensor_stores() -> tuple[dict[int, Tensor], ...]

Every per-layer tensor store that makes up the cache's state, in a fixed order (none here).

:meth:detached and :meth:clone rebuild a cache by mapping these stores; subclasses that add stores extend the tuple.

detached

detached() -> KVCache

A cache of the same class over the detached tensors of this one (no copy): a stop-gradient view.

Raises:

Type Description
UnsupportedModelError

The class does not declare :attr:copyable (a TypeError).

clone

clone() -> KVCache

A cache of the same class over copies of this one's tensors (gradients flow back to the originals).

Raises:

Type Description
UnsupportedModelError

The class does not declare :attr:copyable (a TypeError).

recurrent_state

recurrent_state(layer_idx: int) -> tuple[Tensor | None, Tensor | None]

Conv window and recurrent state of layer layer_idx ((None, None) for a K/V-only cache).

put_recurrent_state

put_recurrent_state(layer_idx: int, conv: Tensor | None, recurrent: Tensor | None) -> None

Replace layer layer_idx's conv window and recurrent state for every row (None drops one).

Raises:

Type Description
UnsupportedModelError

The cache does not declare :attr:supports_state_edit (a TypeError).

PositionalKVCache

PositionalKVCache(spec: CacheSpec)

Bases: KVCache

Per-layer K/V buffers of shape [batch, heads, capacity + 1, dim], allocated on first write.

tensor_stores

tensor_stores() -> tuple[dict[int, Tensor], ...]

The key and value buffers.

RingSpec dataclass

RingSpec(layers: frozenset[int], window: int, slots: int, page: int = 256)

The window cache of sliding-window layers: a ring of :attr:slots slots instead of capacity + 1.

A sliding layer never attends further back than its window, so its buffer holds position p at slot p mod slots, followed by :attr:page extra slots: the first of them (slot :attr:slots) is the layer's trash slot, and the others are never written (they make the buffer a whole number of FlashAttention pages). Which position a ring slot holds depends on the pass, so ring layers get their key positions from :meth:key_positions and not from :meth:KVCache.key_positions.

A pass of Q tokens whose last token sits at P must find every key its queries see still in the ring, and no slot it reads may hold a token newer than P that the mask would take for an older one: the ring therefore needs slots - page >= Q + W + window - 2, with W the furthest a draft may run ahead of the committed tokens (rejected drafts stay in their slots). :meth:for_pass sizes it so.

Attributes:

Name Type Description
layers frozenset[int]

The ring layers (0-based layer_idx); every other layer keeps capacity + 1 slots.

window int

The sliding window of the ring layers (one value for all of them).

slots int

Ring slots R, a multiple of :attr:page.

page int

FlashAttention page size of the ring (FA2 reads paged buffers in multiples of 256 slots).

buffer_slots property

buffer_slots: int

Slots of a ring layer's buffer (the ring, its trash slot and the padding to a whole page).

for_pass classmethod

for_pass(layers: frozenset[int], window: int, queries: int, ahead: int, page: int = 256) -> RingSpec

The smallest ring for passes of up to queries tokens with drafts up to ahead tokens past the committed ones.

physical

physical(slots: Tensor, trash_slot: int) -> Tensor

The ring slots of the logical slots (positions, or the cache's trash_slot).

key_positions

key_positions(positions: Tensor) -> Tensor

The position each ring slot holds for a pass at positions [B, Q], as [B, buffer_slots].

Slot s holds the newest position up to the pass's last one, P_b, that maps to it (P_b - ((P_b - s) mod slots)); slots of negative positions, the trash slot and the padding get :data:UNSEEN_POSITION.

StaticKVCache

StaticKVCache(spec: CacheSpec)

Bases: PositionalKVCache

A :class:PositionalKVCache whose buffers keep their storage for the life of the cache (for CUDA graphs).

A captured CUDA graph reads and writes the buffers it saw at capture. This cache therefore never rebinds a buffer: it keeps one set of buffers per batch size, :meth:reorder to fewer rows copies the kept rows into the set of the smaller size (allocated on first use), and :meth:activate switches to the set of a new generation's batch size. Memory grows with the number of distinct batch sizes the cache has seen, one full set per size.

A new generation reuses the buffers without clearing them. The stale entries are harmless: a query sees only slots below its own position (and its own), and every one of them is written by the current generation before it is read.

batch_sizes property

batch_sizes: tuple[int, ...]

Batch sizes with a buffer set.

activate

activate(batch_size: int) -> None

Use the buffers of batch_size rows from now on (a new set is allocated on its first write).

ContextLayout dataclass

ContextLayout(positions: Tensor, slots: Tensor, valid: Tensor | None = None, tree: TreeLayout | None = None, consecutive: bool = False)

Where the tokens of a pass sit: the tensors that define a :class:LayerContext besides its model and cache.

A layout outlives the context it came from (e.g. as the output of a CUDA graph, whose context is rebuilt after every replay by :meth:LayerContext.from_layout).

Attributes:

Name Type Description
positions Tensor

Sequence position of every token [B, S] (padding tokens use 0).

slots Tensor

Cache slot every token writes [B, S] (padding tokens use the trash slot).

valid Tensor | None

Which tokens are real [B, S]; None when all are.

tree TreeLayout | None

Tree nodes among the keys, None for a chain.

consecutive bool

The real tokens of every row sit at consecutive positions starting at positions[:, 0], with padding only after them, in a chain layout (slot = position). Masks of such a pass are declared causal over a prefix of the cache (:func:economize.attention.flash.declare_prefix), which lets the attention run on FlashAttention under CUDA graphs. Set by the decoder's chain passes; single-token passes have it by construction.

LayerContext dataclass

LayerContext(adapter: ArchAdapter, cache: KVCache, positions: Tensor, slots: Tensor, valid: Tensor | None = None, tree: TreeLayout | None = None, token_inputs: dict[str, Tensor] = dict(), consecutive: bool = False, whole_sequences: bool = False, _masks: dict[tuple[AttentionSpec, device], Tensor | StructuredMask | None] = dict(), _rotary: dict[tuple[str, device, dtype], object] = dict(), _position_ids: dict[device, Tensor] = dict())

One pass of S tokens per row through some decoder layers.

Masks and rotary tables are built on first use and memoized per attention pattern and device, so a pass over L layers builds each distinct mask once.

Attributes:

Name Type Description
adapter ArchAdapter

The model's architecture adapter.

cache KVCache

The cache every layer reads and writes.

positions Tensor

Sequence position of every token, [B, S] (padding tokens use 0).

slots Tensor

Cache slot every token writes, [B, S] (padding tokens use the trash slot).

valid Tensor | None

Which tokens are real, [B, S]; None when all are.

tree TreeLayout | None

Tree nodes among the keys, for tree drafting and verification.

token_inputs dict[str, Tensor]

Extra per-token inputs [B, S, ...] that some families feed to every layer (Gemma-4's per-layer embeddings), filled by :meth:ArchAdapter.embed.

consecutive bool

See :attr:ContextLayout.consecutive.

whole_sequences bool

The pass runs every row over positions 0 .. S - 1 with no padding and no tree, and its layers attend over exactly those S keys (e.g. a :class:~economize.techniques.duo_attention.gates. SinglePassCache). When the model's attention implementation takes structured masks (:attr:~economize.arch.ArchAdapter.takes_structured_masks), layers whose kind has an entry in :data:~economize.runtime.mask.STRUCTURED_MASKS get that mask (a band, attended without a dense [S, S] mask) instead of a dense one.

layout property

layout: ContextLayout

The positions, slots, padding and tree of this pass.

length property

length: int

Tokens per row S.

from_layout classmethod

from_layout(adapter: ArchAdapter, cache: KVCache, layout: ContextLayout, token_inputs: dict[str, Tensor] | None = None, *, trusted: bool = True) -> LayerContext

The context of a pass laid out as layout (every constructor goes through here).

Parameters:

Name Type Description Default
token_inputs dict[str, Tensor] | None

Per-token inputs already computed for this pass (e.g. by the pass that produced the layout); empty by default, filled by :meth:ArchAdapter.embed.

None
trusted bool

Skip the bounds check (it synchronizes with the GPU).

True

chain classmethod

chain(adapter: ArchAdapter, cache: KVCache, positions: Tensor, valid: Tensor | None = None, *, trusted: bool = False, consecutive: bool = False, whole_sequences: bool = False) -> LayerContext

Tokens stored at the slot equal to their position (the layout of ordinary decoding).

Parameters:

Name Type Description Default
positions Tensor

[B, S], or [S] for the same positions in every row of the cache.

required
valid Tensor | None

[B, S] padding mask; padding tokens get position 0 and the trash slot.

None
trusted bool

Skip the bounds check (it synchronizes with the GPU; decoding loops pass True).

False
consecutive bool

The caller guarantees :attr:ContextLayout.consecutive (implied for S = 1).

False
whole_sequences bool

The caller guarantees :attr:whole_sequences (it needs valid=None).

False

Raises:

Type Description
ConfigError

whole_sequences with a padding mask.

for_tree classmethod

for_tree(adapter: ArchAdapter, cache: KVCache, tree: TreeLayout, valid: Tensor | None = None, *, trusted: bool = False) -> LayerContext

The nodes of tree as queries (valid marks real nodes).

select

select(indices: Tensor, valid: Tensor) -> LayerContext

The context of the tokens indices [B, K] (valid false for padding entries).

check

check() -> None

Raise :class:~economize.errors.ConfigError if a position or slot lies outside the cache.

mask

mask(spec: AttentionSpec, device: device) -> Tensor | StructuredMask | None

The attention mask for a layer with pattern spec on device, in the model's mask format.

Linear-attention and state-space layers get the [B, S] padding mask (None without padding), and token-wise layers None. A pass over :attr:whole_sequences may give attention layers a :class:~economize.attention.StructuredMask instead of a tensor.

rotary

rotary(rope: str, like: Tensor) -> object

Rotary table rope for this pass's positions, in the dtype and on the device of like.

position_ids

position_ids(device: device) -> Tensor

positions on device.

GraphPool

GraphPool(device: device | None = None, *, enabled: bool = True)

The steps of one owner that share a CUDA graph memory pool and drop their graphs together.

:meth:reset drops every graph and switches the steps to a fresh pool. Recording into the old pool is not possible: once all its graphs are destroyed, torch keeps the pool only while a tensor allocated in it is still alive (a replay output held by a caller), and a capture into such a pool fails an internal assertion (use_count > 0 in CUDACachingAllocator). The old pool's memory is returned when its last tensor dies.

Parameters:

Name Type Description Default
device device | None

Device the pool handles are created on (None: the current device).

None
enabled bool

False (CPU, debugging) makes every step run eagerly and creates no pool.

True

num_graphs property

num_graphs: int

Graphs recorded so far (over all steps, private ones included).

step

step(fn: Callable[..., _R], *, warmup: int = 2, enabled: bool = True, private: bool = False) -> StaticStep[_R]

fn as a :class:StaticStep on this pool (keyword arguments as for :class:StaticStep).

A private step records into a memory pool of its own, so its owner may :meth:StaticStep.reset it at any time without touching the graphs of the shared pool. The pool holds it weakly (a dropped step is forgotten) and still resets it in :meth:reset.

attach

attach(member: PoolMember) -> None

Let member record into this pool and drop its graphs with the steps' (it gets the current handle).

reset

reset() -> None

Drop the graphs of every step and record the next shared ones into a fresh pool.

PoolMember

Bases: Protocol

What a :class:GraphPool holds besides its :class:StaticStep objects (:meth:GraphPool.attach): an owner of graphs recorded into pool that drops them on :meth:reset.

StaticStep

StaticStep(fn: Callable[..., _R_co], *, warmup: int = 2, enabled: bool = True, pool: _POOL_HANDLE | None = None)

Bases: Generic[_R_co]

A function of tensors replayed from a CUDA graph per distinct input signature (shapes, dtypes, devices).

Outputs of a replay are the graph's static buffers: they are overwritten by the next call with the same signature, so callers clone what they keep.

Parameters:

Name Type Description Default
fn Callable[..., _R_co]

The step. Positional tensor arguments only; everything else goes into the closure.

required
warmup int

Eager calls per signature before capture (lazy allocations happen here). They run on the current stream. On a side stream, the caching allocator could hand the memory of a warm-up output back to that stream's work while the current stream still read it: KnapSpec, which warms up a step per new skip set in the middle of a generation, died on Gemma 4 with an illegal memory access that CUDA_LAUNCH_BLOCKING hid.

2
enabled bool

False always runs fn eagerly (debugging, CPU).

True
pool _POOL_HANDLE | None

Memory pool shared with other graphs (torch.cuda.graph_pool_handle()).

None

reset

reset() -> None

Drop every captured graph (after the wrapped function's persistent state was reallocated).

The devices of the graphs are synchronized first: the decoding loop does not wait for every replay, and no replay may still run when its graph and memory pool are destroyed (KnapSpec evicts skip-set graphs in the middle of a generation).

TreeLayout dataclass

TreeLayout(base: Tensor, slots: Tensor, positions: Tensor, visible: Tensor)

Where the nodes of a batch of draft trees live in the cache and which of them each query sees.

Slots below base hold the committed prefix of each row. Tree nodes occupy slots; every other slot at or above base is invisible.

Attributes:

Name Type Description
base Tensor

First slot not part of the committed prefix, [B].

slots Tensor

Cache slot of every node, [B, T] (padding nodes use the trash slot).

positions Tensor

Sequence position of every node (base plus its depth), [B, T].

visible Tensor

visible[b, q, t]: query q sees node t (its ancestors and itself), [B, Q, T].

build classmethod

build(parents: Tensor, base: Tensor, valid: Tensor | None = None, trash_slot: int = -1) -> TreeLayout

Layout of trees given by parents [B, T] (index of each node's parent, -1 for the root, parents before children), stored from slot base [B] on in node order. Padding nodes (valid false) go to trash_slot and are seen by nobody.

to

to(device: device) -> TreeLayout

The same layout with every tensor on device.

select

select(indices: Tensor) -> TreeLayout

The layout for the queries indices [B, K] (keys unchanged).

LayerAction

Bases: Enum

What happens to every token at one layer.

LayerPolicy

Bases: ABC

Chooses, before each layer, which tokens run it.

decide abstractmethod

decide(index: int, hidden: Tensor, ctx: LayerContext) -> Decision

Decision for layer index (1-indexed) given its input hidden [B, S, d].

after

after(index: int, hidden: Tensor, ctx: LayerContext) -> Tensor | None

Called with the output hidden of layer index.

Policies that track state (exit confidence) read it; a policy that returns a tensor replaces the hidden state passed on to the next layer (e.g. to freeze the rows that exited). The default returns None.

reorder

reorder(rows: Tensor) -> None

Keep only the batch rows rows (a LongTensor of row indices, in their new order) of any per-row state.

The decoding loop calls it whenever rows leave the batch after the prefill, so that per-row state kept across passes (e.g. where each row's prompt ends) stays aligned with the rows of later passes. The default does nothing.

reset

reset() -> None

Forget the previous generation (a decoder that records graphs keeps its policy across generations).

begin_step

begin_step(position: int) -> None

Start the decode step of the token at position (its absolute position in the row).

planned

planned(index: int) -> StepAction | None

The action at layer index, or None when it depends on :meth:probe (default: run).

probe

probe(index: int, hidden: Tensor) -> Tensor

A 1-D float tensor computed from the input hidden of layer index (recorded in a graph) that :meth:after_probe decides on. It may hold several values (e.g. the scores that decide a group of layers), which the host reads with one synchronization.

after_probe

after_probe(index: int, values: tuple[float, ...]) -> StepAction

The action at layer index given the values of :meth:probe.

step_op

step_op(index: int, action: StepAction, hidden: Tensor, ops: StepOps) -> tuple[Tensor, Tensor | None]

The state after layer index under action (recorded in a graph, so without host synchronization) and the one-element signal of an action with emits_signal (else None). Default: run the layer, fill its K/V, or pass the state through.

after_op

after_op(index: int, action: StepAction, signal: float) -> None

Receive the signal of an action with emits_signal at layer index.

end_step

end_step(counts: Tensor) -> None

Receive the step's counts, a host [L + 1, 3] long tensor whose row l holds whether the token entered layer l, executed it, and had only its K/V filled.

device_plan

device_plan(index: int) -> StepPlan

The action or branch at layer index of the current device-decided step (default: :meth:planned, which must not need a probe or a signal).

device_probes

device_probes(index: int) -> bool

Whether :meth:device_decide runs before layer index in the current step (default: never).

device_flags

device_flags(device: device) -> Tensor

The policy's 1-D bool flag buffer on device that :class:StepBranch flags index. It must stay the same tensor across steps (recorded graphs read it); the engine first asks for it outside graph capture.

device_begin

device_begin(device: device) -> None

Recorded at the start of every device-decided step (reset per-step flags here).

device_decide

device_decide(index: int, hidden: Tensor) -> None

Recorded before layer index: write the flags that the following branches read, from the layer's input hidden [1, 1, d], without host synchronization.

device_signal

device_signal(index: int, action: StepAction, signal: Tensor) -> None

Recorded after an action with emits_signal: update the flags from the one-element signal.

end_device_step

end_device_step(counts: Tensor, flags: Tensor | None) -> None

Receive the counts of a device-decided step (as in :meth:end_step) and a host copy of its flags at the end of the step (None when the step read no flag). Default: :meth:end_step.

Route dataclass

Route(indices: Tensor, valid: Tensor)

The tokens of each row that run a layer; the others skip it with their K/V filled.

Attributes:

Name Type Description
indices Tensor

Token columns [B, K]. Within a row they must be distinct (padding entries included).

valid Tensor

Which entries are real [B, K]; rows routing fewer than K tokens pad with False.

from_mask classmethod

from_mask(mask: Tensor) -> Route

Route the tokens where mask [B, S] is true; K is the largest count of any row.

StepAction dataclass

StepAction(name: str, runs: bool, fills_kv: bool = False, emits_signal: bool = False)

What a one-token decode step does at one layer (see :meth:LayerPolicy.planned).

The step engine (:class:economize.decoding.DepthSteps) records one CUDA graph per sequence of (layer, action.name) pairs, so a name must determine the computation :meth:LayerPolicy.step_op records.

Attributes:

Name Type Description
name str

Identifies the computation (part of the graph key).

runs bool

Whether the layer is executed (counted as executed).

fills_kv bool

Whether only the layer's K/V are written (counted as filled).

emits_signal bool

Whether :meth:LayerPolicy.step_op returns a scalar that the host reads before it plans the next layer (CALM's confidence); the engine ends a graph after such a layer.

StepBranch dataclass

StepBranch(flag: int, then: StepAction, otherwise: StepAction)

A layer whose action a device-decided step chooses on the device (see :meth:LayerPolicy.device_plan).

The step runs then when the policy's flag flag (an entry of :meth:LayerPolicy.device_flags) is set at that layer and otherwise when it is not. Under CUDA graphs the two actions become conditional graph nodes, so the host neither reads the flag nor records a graph per outcome.

Attributes:

Name Type Description
flag int

Index into the policy's flag buffer.

then StepAction

The action when the flag is set.

otherwise StepAction

The action when it is not.

StepOps

Bases: Protocol

The layer operations the step engine hands to :meth:LayerPolicy.step_op (the state is on the layer's device).

run

run(index: int, hidden: Tensor) -> Tensor

Layer index applied to hidden (its K/V written).

fill

fill(index: int, hidden: Tensor) -> None

Write the K/V of layer index computed from hidden, without the rest of the layer.

ExactPass dataclass

ExactPass(final: Tensor, hidden: dict[int, Tensor] = dict(), context: LayerContext | None = None)

Result of one pass of the unmodified model.

Attributes:

Name Type Description
final Tensor

Output of the last layer, [B, S, d].

hidden dict[int, Tensor]

Captured hidden states {layer: [B, S, d]} (0 is the token embedding).

context LayerContext | None

The pass's :class:LayerContext (positions, slots, padding).

LayerRunner

LayerRunner(adapter: ArchAdapter)

Executes the decoder layers of the model behind adapter on a :class:~economize.runtime.KVCache.

Raises:

Type Description
UnsupportedModelError

No mask format is registered in :data:~economize.runtime.MASK_FORMATS for the model's attention implementation.

has_recurrent_layers property

has_recurrent_layers: bool

Whether some layer keeps a recurrent state (such models need :meth:replay after rejected drafts).

refresh

refresh() -> None

Forget what the runner derived from the model: layer devices and the set of recurrent layers.

Call it after the layers changed (layers removed, the model moved to other devices).

new_cache

new_cache(capacity: int, batch_size: int = 1, kind: str | None = None, ring: RingSpec | None = None) -> KVCache

An empty cache of the kind the model needs (adapter.cache_kind unless kind is given), with the window cache ring for the sliding layers if given.

context

context(cache: KVCache, positions: Tensor, valid: Tensor | None = None, *, trusted: bool = False, consecutive: bool = False, whole_sequences: bool = False) -> LayerContext

A chain-layout pass at positions (see :meth:LayerContext.chain).

context_from_layout

context_from_layout(cache: KVCache, layout: ContextLayout, token_inputs: Mapping[str, Tensor] | None = None) -> LayerContext

The context of a pass laid out as layout (see :meth:LayerContext.from_layout).

The CUDA graphs of the decoding loop rebuild the context of every replayed exact pass with it, from the layout of the context :meth:context built inside the graph, so graphed and eager passes share one construction.

tree_context

tree_context(cache: KVCache, tree: TreeLayout, valid: Tensor | None = None, *, trusted: bool = False) -> LayerContext

A pass over the nodes of tree (see :meth:LayerContext.for_tree).

Recurrent layers of a hybrid model run every node's root-to-node path as a chain from a branched copy of the row's state and leave the cache's states where they were, so the decoder replays the committed path.

Raises:

Type Description
IncompatibleTechniquesError

The model has recurrent layers and the cache cannot branch their states (it does not declare supports_state_edit).

embed

embed(tokens: Tensor, ctx: LayerContext) -> Tensor

Input of layer 1 for tokens [B, S] (also fills the per-token inputs of ctx).

run

run(hidden: Tensor, ctx: LayerContext, first: int, last: int, *, overrides: Mapping[int, LayerCall] | None = None, capture: Iterable[int] = (), policy: LayerPolicy | None = None) -> tuple[Tensor, dict[int, Tensor]]

Run layers first..last (1-indexed, inclusive) on hidden [B, S, d].

Every layer writes its K/V into ctx.cache at ctx.slots. Returns the output of layer last and the outputs of the layers listed in capture.

forward

forward(tokens: Tensor, ctx: LayerContext, *, capture: Iterable[int] = (), policy: LayerPolicy | None = None) -> ExactPass

The model's own pass over tokens [B, S] within ctx (layer 0 in capture is the input).

logits

logits(final: Tensor) -> Tensor

Next-token logits from last-layer states (final norm, LM head and any logit transform of the family).

replay

replay(cache: KVCache, snapshot: RecurrentSnapshot, tokens: Tensor, start: Tensor, lengths: Tensor) -> None

Bring recurrent states in line with the tokens actually committed after a speculative pass.

A pass over tokens [B, S] starting at positions start [B] advanced every recurrent state by S tokens, padding included. Rows that committed only their first lengths[b] < S tokens get the state of snapshot (taken before the pass) back and run those tokens again. K/V slots need no correction: the replay rewrites them with the same values.

additive_mask

additive_mask(visible: Tensor, dtype: dtype) -> Tensor

[B, 1, Q, K], 0 where attention is allowed and the most negative finite value elsewhere.

boolean_mask

boolean_mask(visible: Tensor, dtype: dtype) -> Tensor

[B, 1, Q, K], True where attention is allowed (scaled_dot_product_attention convention).

tree_ancestors

tree_ancestors(parents: Tensor) -> Tensor

reach[b, i, j]: node j is node i or one of its ancestors, [B, T, T] bool.

Repeated squaring of the parent relation takes ceil(log2 T) batched matrix products instead of a loop over tree depth. No host synchronization (CUDA graphs record it).

visibility

visibility(spec: AttentionSpec, query_positions: Tensor, key_positions: Tensor, tree: TreeLayout | None = None) -> Tensor

Which cache slots each query sees, [B, Q, num_slots] bool.

Parameters:

Name Type Description Default
spec AttentionSpec

The layer's attention pattern; its kind selects the rule in :data:MASKS.

required
query_positions Tensor

Positions of the queries, [B, Q].

required
key_positions Tensor

Position held by every slot in chain layout, [num_slots] (see :meth:economize.runtime.KVCache.key_positions), or per row, [B, num_slots] (a window cache, see :meth:economize.runtime.RingSpec.key_positions).

required
tree TreeLayout | None

Tree nodes among the keys, if the pass verifies or drafts a tree.

None

Raises:

Type Description
ConfigError

A tree over per-row key positions.

current_phase

current_phase() -> Phase | None

The phase of the model call in progress, or None outside decoding.

device_tensor

device_tensor(values: object, device: device | str, dtype: dtype = long) -> Tensor

torch.tensor(values, dtype=dtype, device=device) without a device synchronization on CUDA.

Parameters:

Name Type Description Default
values object

A (nested) list of Python numbers or bools.

required
device device | str

The target device. Other device types than CUDA get a plain :func:torch.tensor.

required
dtype dtype

The tensor's dtype.

long