Skip to content

economize.attention

Decode-attention kernels and their registration with transformers.

Attention kernels for decoding (see :mod:.decode) and their registration with transformers.

Usage::

import economize.attention

economize.attention.install()  # registers "economize" with transformers
model = AutoModelForCausalLM.from_pretrained(name, attn_implementation="economize")

Every economize technique that works under sdpa works under "economize": the runtime treats a registered kernel as a member of its family (:func:.registry.attention_family). New kernels are added by registering an :class:.registry.AttentionKernel in :data:.registry.ATTENTION_KERNELS (or through the economize.attention_kernels entry-point group). A compressed KV cache can hand the kernel its packed bytes next to the dense buffers (:mod:.packed); "economize" reads KIVI codes (:mod:.kivi) and the query-selected pages of Quest (:mod:.quest) this way. It also reads the "gathered" format (:mod:.gathered, compact prompt entries next to dense buffers), which no built-in technique attaches since the eviction caches store only the kept entries themselves. A sparse-prefill pattern attached to an attention module (:mod:.prefill) makes "economize" attend long fresh prompts over MInference's indexed keys only (:mod:.minference). :mod:.sdpa_guard keeps sdpa exact where PyTorch 2.13's masked kernel errs (one K/V head, head dims above 128); adapters of sdpa models install it. A pass over whole sequences can hand the attention a band-shaped :class:.banded.BandMask instead of a dense mask (:mod:.banded), which sdpa and "economize" attend in blocks over the keys each block sees.

BandMask dataclass

BandMask(length: int, window: int | None = None, sinks: int = 0, block: int | None = None)

Bases: StructuredMask

Query q of a pass over positions 0 .. length - 1 sees key k <= q when q - k < window or k < sinks.

window=None is causal attention, BandMask(n, window=w) a sliding window of w positions (the query's own included) and BandMask(n, window=r, sinks=s) DuoAttention's streaming heads.

Attributes:

Name Type Description
length int

Tokens per row; queries and keys are positions 0 .. length - 1 in order.

window int | None

Most recent positions a query sees, its own included (None: all earlier ones).

sinks int

Positions from the start every query sees.

block int | None

Queries per attention call of a bounded band (default: the window, clipped to 128 .. 512). Smaller blocks compute fewer masked scores in more calls.

causal property

causal: bool

Whether every query sees all earlier positions (no window, or one at least as long as the pass).

block_size property

block_size: int

Queries per attention call of a bounded band.

StructuredMask

Bases: ABC

A mask passed to the attention function in place of a mask tensor, which then lets the mask attend.

Subclasses describe a pattern that is cheaper to attend by its structure than through a dense mask.

attend abstractmethod

attend(forward: AttentionForward, module: Module, query: Tensor, key: Tensor, value: Tensor, **kwargs: object) -> tuple[Tensor, None]

The attention output [B, Q, H, D] under this mask.

Parameters:

Name Type Description Default
forward AttentionForward

The attention function to run the pieces on; it takes a boolean mask tensor or None (causal) in the mask argument.

required
module Module

The attention module.

required
query Tensor

[B, H, Q, D].

required
key Tensor

[B, H_kv, K, D].

required
value Tensor

[B, H_kv, K, D_v].

required
kwargs object

The call's other keyword arguments (dropout, scaling, ...), passed on to forward.

{}

dense abstractmethod

dense(device: device) -> Tensor

The same mask as a [1, 1, Q, K] boolean tensor, True where attention is allowed.

GatheredKV dataclass

GatheredKV(key: Tensor, value: Tensor, index: Tensor, count: Tensor, start: Tensor, dropped: int, format: str = 'gathered')

Compacted prompt entries of one layer (a :class:~.packed.PackedKV of format "gathered").

Attributes:

Name Type Description
key Tensor

[B, Hkv, C, D] kept prompt keys of every row and KV head, in slot order (C >= count[b, h]).

value Tensor

[B, Hkv, C, Dv] the matching values.

index Tensor

int32 [B, Hkv, C] original slot of every compact entry (its mask column).

count Tensor

int32 [B, Hkv] compact entries of every row and KV head.

start Tensor

int32 [B] first dense slot read for row b (the prompt's end); slots below it are read only through the compact entries.

dropped int

min(start[b] - count[b, h]), on the host: the virtual key axis is keys - dropped long.

AttentionObserver

Bases: Protocol

A torch function mode that watches sdpa calls and can be told about an attention call that ran elsewhere.

A long query under such a mode runs on FlashAttention; :meth:observe_attention then receives the inputs sdpa would have seen ([B, H_q, Q, D] queries, [B, H_kv, S, D] keys, the boolean mask cut to S keys), so the mode records the same thing either way.

observe_attention

observe_attention(query: Tensor, key: Tensor, attn_mask: Tensor | None, scale: float) -> None

Record an attention call of query over key under attn_mask with softmax scale scale.

KIVIPacked dataclass

KIVIPacked(bits: int, key_group: int, value_group: int, key_codes: Tensor, key_scale: Tensor, key_zero: Tensor, value_codes: Tensor, value_scale: Tensor, value_zero: Tensor, keys_quantized: Tensor, values_quantized: Tensor, key_ring: Tensor | None = None, value_ring: Tensor | None = None, ring: int = 0, materialize: Callable[[], tuple[Tensor, Tensor]] | None = None, format: str = 'kivi')

Packed K/V of one layer (a :class:~.packed.PackedKV of format "kivi").

Attributes:

Name Type Description
bits int

Bits per code.

key_group int

Tokens per key scale (per channel).

value_group int

Channels per value scale (per token).

key_codes Tensor

uint8 [B, Hkv, S, D * bits / 8].

key_scale Tensor

fp16 [B, Hkv, ceil(S / key_group), D].

key_zero Tensor

Like key_scale.

value_codes Tensor

uint8 [B, Hkv, S, Dv * bits / 8].

value_scale Tensor

fp16 [B, Hkv, S, Dv / value_group].

value_zero Tensor

Like value_scale.

keys_quantized Tensor

int32 [B] on the device: keys < keys_quantized[b] of row b are packed.

values_quantized Tensor

int32 [B]: likewise for values.

key_ring Tensor | None

For a cache that holds no dense buffer (ring > 0), the full-precision keys [B, Hkv, W, D] (W >= ring; a cache may keep a trash slot past ring) in the query's dtype: slot s that is not packed lives at s % ring. None: the dense key buffer the cache returns holds every slot.

value_ring Tensor | None

Like key_ring, for values.

ring int

Slots of the rings, 0 without them.

materialize Callable[[], tuple[Tensor, Tensor]] | None

For a cache without dense buffers, a function that returns the layer's dense keys and values (the codes dequantized, the rings at their slots) for attention functions that do not read the format; None when the buffers the cache returns are dense.

MInferencePrefill dataclass

MInferencePrefill(heads: tuple[HeadPattern, ...], top_k: int = 100, min_queries: int = 65, name: str = 'minference')

The :class:~.prefill.SparsePrefill of one layer under MInference.

Attributes:

Name Type Description
heads tuple[HeadPattern, ...]

The pattern of every query head.

top_k int

Key blocks per query block of the block-sparse heads.

min_queries int

Shortest prompt the patterns apply to.

name str

The path name in :func:~.interface.kernel_usage.

SparseIndex dataclass

SparseIndex(range_start: Tensor, range_end: Tensor, range_count: Tensor, column_index: Tensor, column_count: Tensor, window: Tensor, sinks: Tensor, queries: int)

The keys every query of a prompt of queries tokens attends to, per row and query head.

Query i (in block row m = i // BLOCK) of row b and head h sees key j iff j <= i, j lies in one of the row's range_count[b, h, m] key ranges [range_start, range_end) or among its column_count[b, h, m] columns column_index, and, when window[h] > 0, i - j < window[h] or j < sinks[h].

Attributes:

Name Type Description
range_start Tensor

int32 [B, H, M, R].

range_end Tensor

int32 [B, H, M, R].

range_count Tensor

int32 [B, H, M].

column_index Tensor

int32 [B, H, M, C].

column_count Tensor

int32 [B, H, M].

window Tensor

int32 [H], 0 for no window.

sinks Tensor

int32 [H], the keys a windowed head also sees.

queries int

Prompt length Q.

blocks property

blocks: int

Block rows M = ceil(Q / BLOCK).

density

density() -> float

Fraction of the causal (query, key) pairs the index keeps, over all rows and heads (builds the mask).

PackedKV

Bases: Protocol

Packed K/V of one layer that a kernel can attend over directly.

attend

attend(query: Tensor, key: Tensor, value: Tensor, mask: Tensor | None, scale: float, softcap: float | None = None, sinks: Tensor | None = None) -> Tensor

Attention of query [B, Hq, Q, D] over the layer's cache, [B, Q, Hq, Dv] out.

key and value are the dense buffers the cache returned (the parts that are not packed are read from them); mask, scale, softcap and sinks are those of :func:~.decode.decode_attention.

SparsePrefill

Bases: Protocol

Chooses the keys every query of a fresh prompt attends to, in one layer.

name property

name: str

Name of the pattern family; the attention call is logged on path "kernel_<name>" (or as fallback reason "<name>_<reason>").

min_queries property

min_queries: int

Shortest prompt (tokens per row) the pattern applies to; shorter prompts attend densely.

index

index(query: Tensor, key: Tensor, scale: float) -> SparseIndex

The keys every query attends to.

Parameters:

Name Type Description Default
query Tensor

[B, Hq, Q, D], the prompt's queries at positions 0 .. Q - 1.

required
key Tensor

[B, Hkv, Q, D], the prompt's keys.

required
scale float

The layer's score multiplier.

required

QuestPages dataclass

QuestPages(kmin: Tensor, kmax: Tensor, done: Tensor, min_done: int, max_done: int, page: int, pages: int, max_queries: int = 1, on_use: Callable[[int], None] | None = None, layer: int = 0, format: str = 'quest')

Page bounds of one layer's committed cache (a :class:~.packed.PackedKV of format "quest").

Attributes:

Name Type Description
kmin Tensor

[B, Hkv, P, D] channel-wise smallest key of every committed page (rows below done[b] valid).

kmax Tensor

[B, Hkv, P, D] the largest keys.

done Tensor

int32 [B] committed pages of every row; slots from done[b] * page on are read densely.

min_done int

min(done), on the host.

max_done int

max(done), on the host.

page int

Slots per page (a power of two, at least 16).

pages int

Committed pages every row and KV head reads (the reference's page budget minus the running page).

max_queries int

Longest query (tokens per row) that is restricted to the pages; longer ones see every key.

on_use Callable[[int], None] | None

Called with layer when an attention function reads the pages (the cache checks that every attached layer was read).

layer int

The cache layer.

select

select(query: Tensor) -> Tensor

int32 [B, Hkv, pages] selected pages for query (see :func:select_pages).

keep

keep(query: Tensor, slots: int) -> Tensor

Boolean [B, Hkv, slots]: the slots query reads (selected pages and the dense tail).

restrict_mask

restrict_mask(query: Tensor, key: Tensor, mask: Tensor | None, is_causal: bool = False) -> Tensor | None

mask with the unselected pages hidden, for attention functions that read the dense buffers.

Parameters:

Name Type Description Default
query Tensor

[B, Hq, Q, D].

required
key Tensor

The dense key buffer [B, Hkv, S, D].

required
mask Tensor | None

Boolean (True = visible) or additive float mask broadcastable to [B, Hq, Q, S], or None.

required
is_causal bool

Whether a None mask stands for a causal one (aligned top-left, as in sdpa).

False

Returns:

Type Description
Tensor | None

A [B, Hq, Q, S] mask of mask's kind (boolean for None), or mask itself when the query is

Tensor | None

longer than :attr:max_queries.

AttentionKernel dataclass

AttentionKernel(family: str, forward: Callable[..., tuple[Tensor, Tensor | None]], mask_function: Callable[..., object] | None = None, description: str = '', fp8_kv: bool = False, packed_kv: frozenset[str] = frozenset(), sparse_prefill: bool = False, structured_masks: bool = False)

One attention implementation that economize can run a model with.

Attributes:

Name Type Description
family str

Built-in implementation ("sdpa" or "eager") whose mask format and semantics the kernel shares.

forward Callable[..., tuple[Tensor, Tensor | None]]

The transformers attention function (the signature of transformers.integrations.sdpa_attention.sdpa_attention_forward).

mask_function Callable[..., object] | None

Mask builder for transformers.masking_utils.AttentionMaskInterface; None reuses the family's.

description str

One line for listings.

fp8_kv bool

Whether forward takes K/V in float8_e4m3fn / float8_e5m2 with queries in a wider dtype (an fp8 KV cache can then hand its buffers over without upcasting them).

packed_kv frozenset[str]

Packed K/V formats forward reads from a :class:~.packed.PackedKV attached to the key tensor (see :mod:.packed), such as "kivi". A kernel that ignores the attachment still computes the same result from the dense buffers, only slower.

sparse_prefill bool

Whether forward honours a :class:~.prefill.SparsePrefill attached to the attention module (MInference's patterns): a kernel that ignores it attends prompts densely, so a sparse-prefill technique refuses it.

structured_masks bool

Whether forward takes a :class:~.banded.StructuredMask (such as a :class:~.banded.BandMask) in place of the mask tensor and lets it attend (see :func:~.banded.accepts_structured_masks).

accepts_structured_masks

accepts_structured_masks(implementation: str) -> bool

Whether attention implementation implementation takes a :class:StructuredMask in place of a mask tensor.

True for a registered kernel that declares structured_masks and for "sdpa" while economize's function (:mod:.sdpa_guard, which :meth:~economize.arch.ArchAdapter.validate installs for sdpa models) is the registered one.

decode_attention

decode_attention(query: Tensor, key: Tensor, value: Tensor, mask: Tensor | None, scale: float, softcap: float | None = None, out: Tensor | None = None, sinks: Tensor | None = None, launch: DecodePlan | None = None, window: int | None = None) -> Tensor

Attention of a few queries per row over a KV buffer (see the module docstring).

Parameters:

Name Type Description Default
query Tensor

[B, Hq, Q, D] (any strides), bf16, fp16 or fp32.

required
key Tensor

[B, Hkv, S, D] (any strides), the query's dtype or an fp8 dtype.

required
value Tensor

[B, Hkv, S, Dv], like key.

required
mask Tensor | None

Boolean [B, 1 or Hq, Q, S] (broadcast strides allowed, True = visible) or None.

required
scale float

Multiplier of the scores.

required
softcap float | None

Optional tanh soft cap of the scaled scores.

None
out Tensor | None

Optional [B, Q, Hq, Dv] output buffer.

None
sinks Tensor | None

Optional [Hq] attention-sink logits (see :func:reference_attention).

None
launch DecodePlan | None

Launch shape to use instead of :func:plan's (tuning and tests).

None
window int | None

The layer's sliding window, if the mask restricts every query to it. It only sizes the splits (see :func:plan); the mask alone decides what each query sees.

None

Returns:

Type Description
Tensor

[B, Q, Hq, Dv] in the query's dtype. fp32 inputs are computed in IEEE fp32 (no TF32).

reference_attention

reference_attention(query: Tensor, key: Tensor, value: Tensor, mask: Tensor | None, scale: float, softcap: float | None = None, sinks: Tensor | None = None) -> Tensor

The definition :func:decode_attention implements, in fp32.

Parameters:

Name Type Description Default
query Tensor

[B, Hq, Q, D].

required
key Tensor

[B, Hkv, S, D] (Hq a multiple of Hkv).

required
value Tensor

[B, Hkv, S, Dv].

required
mask Tensor | None

Boolean [B, 1 or Hq, Q, S] (True = visible) or None (every key visible).

required
scale float

Multiplier of the scores.

required
softcap float | None

Optional softcap * tanh(score / softcap) applied to the scaled scores.

None
sinks Tensor | None

Optional [Hq] attention-sink logits (gpt-oss): one extra logit per head in the softmax's denominator, with no value.

None

Returns:

Type Description
Tensor

[B, Q, Hq, Dv] in the query's dtype (zeros for a query that sees no key).

triton_available cached

triton_available() -> bool

Whether the Triton kernels can be compiled (triton importable). The kernels live in private modules that are imported on their first launch, so import economize never imports triton; this check imports it.

gathered_decode_attention

gathered_decode_attention(query: Tensor, key: Tensor, value: Tensor, mask: Tensor | None, scale: float, gathered: GatheredKV, softcap: float | None = None, sinks: Tensor | None = None, out: Tensor | None = None, launch: DecodePlan | None = None) -> Tensor

:func:~.decode.decode_attention over a cache whose prompt entries were compacted (see the module docstring).

Parameters:

Name Type Description Default
query Tensor

[B, Hq, Q, D], bf16, fp16 or fp32.

required
key Tensor

Dense [B, Hkv, S, D] in the query's dtype; read only at slots >= gathered.start[b].

required
value Tensor

Dense [B, Hkv, S, Dv]; likewise.

required
mask Tensor | None

Boolean [B, 1 or Hq, Q, S] over the original slots, or None.

required
scale float

Multiplier of the scores.

required
gathered GatheredKV

The compact entries (see :class:GatheredKV).

required
softcap float | None

Optional tanh soft cap of the scaled scores.

None
sinks Tensor | None

Optional [Hq] attention-sink logits.

None
out Tensor | None

Optional [B, Q, Hq, Dv] output buffer.

None
launch DecodePlan | None

Launch shape to use instead of :func:~.decode.plan's (tuning and tests).

None

Returns:

Type Description
Tensor

[B, Q, Hq, Dv] in the query's dtype.

economize_attention_forward

economize_attention_forward(module: Module, query: Tensor, key: Tensor, value: Tensor, attention_mask: Tensor | None, dropout: float = 0.0, scaling: float | None = None, is_causal: bool | None = None, **kwargs: object) -> tuple[Tensor, Tensor | None]

transformers attention function ([B, H, Q, D] in, [B, Q, H, D] out) on the decode kernel.

The choice between the kernel and the sdpa fallback is made for every call, so a prefill or a tapped exact pass falls back without moving the decoding steps of the same model off the kernel; :func:kernel_usage logs each choice by layer, query length and reason. A :class:~.banded.StructuredMask attends on sdpa (path "sdpa", reason "structured").

install

install(name: str | None = None) -> list[str]

Register attention kernels with transformers (all of :data:ATTENTION_KERNELS, or the one name).

Afterwards AutoModelForCausalLM.from_pretrained(..., attn_implementation="economize") or model.set_attn_implementation("economize") selects the kernel. Idempotent.

The registration is process-wide because transformers keeps its attention functions in one class-level registry that every model reads. It adds named functions and holds no economize state: which kernel a model runs stays a choice of that model (its attn_implementation), and models that do not name an economize kernel are unaffected.

Returns:

Type Description
list[str]

The names registered.

kernel_calls

kernel_calls() -> dict[str, int]

How many attention calls ran on the kernel, on FlashAttention (long queries) and on the fallback since import (for tests and benchmarks).

kernel_usage

kernel_usage(reset: bool = False) -> list[UsageRecord]

Which path each attention call took, grouped by layer, query length and fallback reason.

Every Python-level call is counted (eager steps and CUDA-graph captures; replays run the captured path). A benchmark stores this list next to its timings so that a row can show which layers and shapes ran on the kernel and which fell back to sdpa, and why.

Parameters:

Name Type Description Default
reset bool

Clear the log after reading it.

False

Returns:

Type Description
list[UsageRecord]

One record per (layer, queries, path, reason) with its call count, sorted by layer and query length.

usage_summary

usage_summary() -> UsageSummary

Compact form of :func:kernel_usage: calls per path, per fallback reason, and the query lengths per path.

kivi_decode_attention

kivi_decode_attention(query: Tensor, key: Tensor, value: Tensor, mask: Tensor | None, scale: float, packed: KIVIPacked, softcap: float | None = None, sinks: Tensor | None = None, out: Tensor | None = None) -> Tensor

:func:~.decode.decode_attention over a cache whose oldest entries are KIVI codes.

Parameters:

Name Type Description Default
query Tensor

[B, Hq, Q, D], bf16, fp16 or fp32.

required
key Tensor

Dense [B, Hkv, S, D] in the query's dtype; read only at slots >= packed.keys_quantized[b]. With packed.ring it is not read at all (only its shape is a stand-in); the full-precision keys come from packed.key_ring.

required
value Tensor

Dense [B, Hkv, S, Dv]; read only at slots >= packed.values_quantized[b] (or not at all with packed.ring).

required
mask Tensor | None

Boolean [B, 1 or Hq, Q, S] or None.

required
scale float

Multiplier of the scores.

required
packed KIVIPacked

The codes, scales and zero points (see :class:KIVIPacked).

required
softcap float | None

Optional tanh soft cap of the scaled scores.

None
sinks Tensor | None

Optional [Hq] attention-sink logits.

None
out Tensor | None

Optional [B, Q, Hq, Dv] output buffer.

None

Returns:

Type Description
Tensor

[B, Q, Hq, Dv] in the query's dtype.

sparse_prefill_attention

sparse_prefill_attention(query: Tensor, key: Tensor, value: Tensor, index: SparseIndex, scale: float, softcap: float | None = None, out: Tensor | None = None, tiles: tuple[int, int] | None = None) -> Tensor

Causal attention of a prompt over the keys of index with the Triton kernel.

Parameters:

Name Type Description Default
query Tensor

[B, Hq, Q, D], bf16, fp16 or fp32.

required
key Tensor

[B, Hkv, S >= Q, D] in the query's dtype or an fp8 dtype; slots from Q on are ignored.

required
value Tensor

[B, Hkv, S, Dv], like key.

required
index SparseIndex

The keys each query sees (index.queries == Q).

required
scale float

Score multiplier.

required
softcap float | None

Optional tanh soft cap of the scaled scores.

None
out Tensor | None

Optional [B, Q, Hq, Dv] output buffer.

None
tiles tuple[int, int] | None

(rows, keys) per program instead of the default for the head dim (powers of two of at least 16; the rows divide 64).

None

Returns:

Type Description
Tensor

[B, Q, Hq, Dv] in the query's dtype.

attach_packed

attach_packed(key: Tensor, packed: PackedKV) -> Tensor

A view of key that carries packed (the buffer itself is left untouched).

packed_of

packed_of(key: Tensor) -> PackedKV | None

The :class:PackedKV attached to key, or None.

attach_prefill

attach_prefill(module: Module, prefill: SparsePrefill) -> None

Make module's fresh prompts attend through prefill (replaces an earlier attachment).

detach_prefill

detach_prefill(module: Module) -> None

Remove module's attachment, if any.

prefill_of

prefill_of(module: Module) -> SparsePrefill | None

The :class:SparsePrefill attached to module, or None.

quest_decode_attention

quest_decode_attention(query: Tensor, key: Tensor, value: Tensor, mask: Tensor | None, scale: float, pages: QuestPages, softcap: float | None = None, sinks: Tensor | None = None, out: Tensor | None = None, launch: DecodePlan | None = None, index: Tensor | None = None) -> Tensor

:func:~.decode.decode_attention over the selected pages and the dense tail (see the module docstring).

Parameters:

Name Type Description Default
query Tensor

[B, Hq, Q, D], bf16, fp16 or fp32.

required
key Tensor

Dense [B, Hkv, S, D] in the query's dtype or an fp8 dtype.

required
value Tensor

Dense [B, Hkv, S, Dv], like key.

required
mask Tensor | None

Boolean [B, 1 or Hq, Q, S] over the slots, or None.

required
scale float

Multiplier of the scores.

required
pages QuestPages

The page bounds (see :class:QuestPages).

required
softcap float | None

Optional tanh soft cap of the scaled scores.

None
sinks Tensor | None

Optional [Hq] attention-sink logits.

None
out Tensor | None

Optional [B, Q, Hq, Dv] output buffer.

None
launch DecodePlan | None

Launch shape to use instead of :func:~.decode.plan's (tuning and tests); its key tile must divide the page and its split length.

None
index Tensor | None

Selected pages (int32 [B, Hkv, pages]) to use instead of :meth:QuestPages.select's.

None

Returns:

Type Description
Tensor

[B, Q, Hq, Dv] in the query's dtype.

accepts_fp8_kv

accepts_fp8_kv(implementation: str) -> bool

Whether the registered kernel implementation takes fp8 K/V directly (False for built-ins).

accepts_packed_kv

accepts_packed_kv(implementation: str, fmt: str) -> bool

Whether the registered kernel implementation reads packed K/V of format fmt (False for built-ins).

accepts_sparse_prefill

accepts_sparse_prefill(implementation: str) -> bool

Whether the registered kernel implementation attends prompts through an attached sparse prefill.

attention_family

attention_family(implementation: str) -> str

The built-in implementation whose masks and semantics implementation shares (itself if unregistered).