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 |
window |
int | None
|
Most recent positions a query sees, its own included ( |
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. |
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 |
required |
module
|
Module
|
The attention module. |
required |
query
|
Tensor
|
|
required |
key
|
Tensor
|
|
required |
value
|
Tensor
|
|
required |
kwargs
|
object
|
The call's other keyword arguments ( |
{}
|
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
|
|
value |
Tensor
|
|
index |
Tensor
|
|
count |
Tensor
|
|
start |
Tensor
|
|
dropped |
int
|
|
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
|
|
key_scale |
Tensor
|
fp16 |
key_zero |
Tensor
|
Like |
value_codes |
Tensor
|
|
value_scale |
Tensor
|
fp16 |
value_zero |
Tensor
|
Like |
keys_quantized |
Tensor
|
|
values_quantized |
Tensor
|
|
key_ring |
Tensor | None
|
For a cache that holds no dense buffer ( |
value_ring |
Tensor | None
|
Like |
ring |
int
|
Slots of the rings, |
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;
|
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: |
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
|
|
range_end |
Tensor
|
|
range_count |
Tensor
|
|
column_index |
Tensor
|
|
column_count |
Tensor
|
|
window |
Tensor
|
|
sinks |
Tensor
|
|
queries |
int
|
Prompt length |
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
|
|
required |
key
|
Tensor
|
|
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
|
|
kmax |
Tensor
|
|
done |
Tensor
|
|
min_done |
int
|
|
max_done |
int
|
|
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 |
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
|
|
required |
key
|
Tensor
|
The dense key buffer |
required |
mask
|
Tensor | None
|
Boolean ( |
required |
is_causal
|
bool
|
Whether a |
False
|
Returns:
| Type | Description |
|---|---|
Tensor | None
|
A |
Tensor | None
|
longer than :attr: |
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 ( |
forward |
Callable[..., tuple[Tensor, Tensor | None]]
|
The |
mask_function |
Callable[..., object] | None
|
Mask builder for |
description |
str
|
One line for listings. |
fp8_kv |
bool
|
Whether |
packed_kv |
frozenset[str]
|
Packed K/V formats |
sparse_prefill |
bool
|
Whether |
structured_masks |
bool
|
Whether |
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
|
|
required |
key
|
Tensor
|
|
required |
value
|
Tensor
|
|
required |
mask
|
Tensor | None
|
Boolean |
required |
scale
|
float
|
Multiplier of the scores. |
required |
softcap
|
float | None
|
Optional tanh soft cap of the scaled scores. |
None
|
out
|
Tensor | None
|
Optional |
None
|
sinks
|
Tensor | None
|
Optional |
None
|
launch
|
DecodePlan | None
|
Launch shape to use instead of :func: |
None
|
window
|
int | None
|
The layer's sliding window, if the mask restricts every query to it. It only sizes the splits
(see :func: |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
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
|
|
required |
key
|
Tensor
|
|
required |
value
|
Tensor
|
|
required |
mask
|
Tensor | None
|
Boolean |
required |
scale
|
float
|
Multiplier of the scores. |
required |
softcap
|
float | None
|
Optional |
None
|
sinks
|
Tensor | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
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
|
|
required |
key
|
Tensor
|
Dense |
required |
value
|
Tensor
|
Dense |
required |
mask
|
Tensor | None
|
Boolean |
required |
scale
|
float
|
Multiplier of the scores. |
required |
gathered
|
GatheredKV
|
The compact entries (see :class: |
required |
softcap
|
float | None
|
Optional tanh soft cap of the scaled scores. |
None
|
sinks
|
Tensor | None
|
Optional |
None
|
out
|
Tensor | None
|
Optional |
None
|
launch
|
DecodePlan | None
|
Launch shape to use instead of :func: |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
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 |
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
|
|
required |
key
|
Tensor
|
Dense |
required |
value
|
Tensor
|
Dense |
required |
mask
|
Tensor | None
|
Boolean |
required |
scale
|
float
|
Multiplier of the scores. |
required |
packed
|
KIVIPacked
|
The codes, scales and zero points (see :class: |
required |
softcap
|
float | None
|
Optional tanh soft cap of the scaled scores. |
None
|
sinks
|
Tensor | None
|
Optional |
None
|
out
|
Tensor | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
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
|
|
required |
key
|
Tensor
|
|
required |
value
|
Tensor
|
|
required |
index
|
SparseIndex
|
The keys each query sees ( |
required |
scale
|
float
|
Score multiplier. |
required |
softcap
|
float | None
|
Optional tanh soft cap of the scaled scores. |
None
|
out
|
Tensor | None
|
Optional |
None
|
tiles
|
tuple[int, int] | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
attach_packed
¶
attach_packed(key: Tensor, packed: PackedKV) -> Tensor
A view of key that carries packed (the buffer itself is left untouched).
attach_prefill
¶
attach_prefill(module: Module, prefill: SparsePrefill) -> None
Make module's fresh prompts attend through prefill (replaces an earlier attachment).
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
|
|
required |
key
|
Tensor
|
Dense |
required |
value
|
Tensor
|
Dense |
required |
mask
|
Tensor | None
|
Boolean |
required |
scale
|
float
|
Multiplier of the scores. |
required |
pages
|
QuestPages
|
The page bounds (see :class: |
required |
softcap
|
float | None
|
Optional tanh soft cap of the scaled scores. |
None
|
sinks
|
Tensor | None
|
Optional |
None
|
out
|
Tensor | None
|
Optional |
None
|
launch
|
DecodePlan | None
|
Launch shape to use instead of :func: |
None
|
index
|
Tensor | None
|
Selected pages ( |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
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).