economize.arch¶
Architecture adapters, one per model family, looked up by config.model_type.
Architecture adapters (one per model family, looked up by config.model_type).
ArchAdapter
¶
ArchAdapter(model: Module)
Bases: ABC
Uniform view of a decoder-only causal LM.
Layers are 1-indexed, and index 0 denotes the token embedding, so hidden[l] is the output of layer l.
The adapter implements every facet protocol of :mod:economize.arch.protocols, one section each below.
Subclasses provide the modules (the four abstract properties of :class:~economize.arch.protocols.DecoderModules);
every other member has a default that follows the Hugging Face conventions shared by most families and is
overridden only in the facets where a family differs. Code that needs one aspect of a model should accept the
facet protocol instead of the whole adapter.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
The wrapped Hugging Face model (a |
|
config |
The text decoder's config ( |
|
attention_implementations |
tuple[str, ...]
|
Attention implementations the family's layers support with an explicit mask, by name or by the family a registered kernel reports. |
layers
abstractmethod
property
¶
layers: ModuleList
The decoder layers, 0-indexed as stored in the model.
final_norm
abstractmethod
property
¶
final_norm: Module
The norm applied after the last decoder layer.
model_layers
property
¶
model_layers: ModuleList
The decoder layers the wrapped model runs in its own forward. They are :attr:layers, except on an
adapter from :meth:with_layers, whose :attr:layers are other modules.
base_adapter
property
¶
base_adapter: ArchAdapter
The adapter of the wrapped model: this adapter, or the one :meth:with_layers was called on.
model_type
property
¶
model_type: str
model_type of the wrapped model (of the wrapper for multimodal models).
rotary_device
property
¶
rotary_device: device
Device of the rotary embedding, where its tables are computed (differs from a layer's under
device_map); the embedding's device without a rotary embedding.
tensor_parallel_size
property
¶
tensor_parallel_size: int
Processes the model is split over by transformers' tensor parallelism (tp_plan); 1 when unsplit.
A split model holds 1 / size of the attention heads and of the MLP width of every layer in each process.
:attr:num_kv_heads stays the model's total; the caches of the layer runner take their shapes from the
key/value states they store and therefore hold the local heads.
attn_implementation
property
¶
attn_implementation: str
The attention implementation the decoder was loaded with, as its family.
A kernel registered in :data:economize.attention.ATTENTION_KERNELS reports the built-in implementation
whose masks and semantics it shares ("economize" reports "sdpa").
takes_structured_masks
property
¶
takes_structured_masks: bool
Whether the decoder's attention function takes a :class:~economize.attention.StructuredMask in place
of a mask tensor (see :func:~economize.attention.accepts_structured_masks).
layer_types
property
¶
layer_types: list[str]
config.layer_types, or the Mistral convention (sliding everywhere if sliding_window is set).
cache_kind
property
¶
cache_kind: str
Key of :data:economize.runtime.CACHES this model needs ("hybrid" when some layer is recurrent).
rotary_emb
property
¶
rotary_emb: Module | None
The model's rotary embedding module; None (the default) for a family without one, whose layers then
receive position_embeddings=None.
uses_per_layer_inputs
property
¶
uses_per_layer_inputs: bool
Whether every layer receives a per-token input of its own besides the hidden state (Gemma-4's per-layer embeddings), so that layers of one type cannot share their call arguments.
with_layers
¶
with_layers(layers: Sequence[Module]) -> ArchAdapter
A view of this adapter whose :attr:layers are layers (one module per decoder layer, such as copies
of the base layers that a draft path runs) and whose other members are this adapter's.
The view's :attr:model_layers and :attr:base_adapter still name the base model's layers and this adapter,
so code that must reach the model's own forward (input capture for calibration) uses them. The view is a
shallow copy of the adapter under a subclass of its class; building it changes nothing on the model.
Raises:
| Type | Description |
|---|---|
ConfigError
|
|
module_path
¶
module_path(module: Module) -> str
The dotted name of module inside :attr:model ("model.layers.3", "lm_head"), as a state dict
or a serving engine names it. Raise :class:UnsupportedModelError if module is not part of the model.
layer_config
¶
layer_config(index: int) -> HFConfig
The config of layer index (1-indexed): its entry of per_layer_config on a heterogeneous config
(transformers >= 5.17), the model's text config otherwise.
head_geometry
¶
head_geometry(index: int) -> HeadGeometry
Head counts and head width of attention layer index (1-indexed); the standard sizes unless the
layer's own config (heterogeneous configs) or the family gives some layer types other ones.
shape_fields
classmethod
¶
shape_fields(config: HFConfig, fields: Mapping[str, object]) -> Mapping[str, object]
Corrections to the generic reading fields of :meth:economize.bench.ModelShape.from_config for this
family's text config (for example {"gated": False}). None by default.
layer_device
¶
layer_device(index: int) -> device
Device of layer index (differs between layers when the model is split with device_map).
attention_spec
¶
attention_spec(index: int) -> AttentionSpec
Mask kind, window and rotary key of layer index (1-indexed).
state_kind
¶
state_kind(index: int) -> StateKind
Whether layer index keeps per-position K/V or a recurrent state.
kv_source
¶
kv_source(index: int) -> int
The layer whose cache entries layer index attends over (itself, except for KV-sharing layers).
rope_key
¶
rope_key(layer_type: str) -> str
Rotary table of layers of type layer_type ("default": one table for every layer).
position_embeddings
¶
position_embeddings(like: Tensor, positions: Tensor, rope: str = 'default') -> object
Rotary table (usually (cos, sin)) for positions [B, S] in the dtype and on the device of
like; None without a rotary embedding.
embed
¶
embed(input_ids: Tensor, ctx: PassContext | None = None) -> Tensor
Input of the first decoder layer for input_ids [..., S].
Families that feed extra per-token inputs to every layer store them in ctx.token_inputs.
layer_inputs
¶
layer_inputs(index: int, hidden: Tensor, ctx: PassContext, cache: object, mask: Tensor | StructuredMask | None) -> LayerInputs
Positional arguments after hidden and keyword arguments for calling decoder layer index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache
|
object
|
What the layer receives as |
required |
mask
|
Tensor | StructuredMask | None
|
The attention mask ( |
required |
call_layer
¶
call_layer(index: int, layer: DecoderLayer, hidden: Tensor, ctx: PassContext) -> Tensor
Run layer (decoder layer index or a stand-in callable) on hidden [B, S, d] within ctx.
The layer writes its K/V through ctx.cache at ctx.slots.
layer_call_key
¶
layer_call_key(index: int) -> Hashable
Key under which layer-wise calibration shares the call arguments of layer index (1-indexed).
Layers with equal keys receive the same arguments besides the hidden state (mask, rotary embeddings), so
:func:economize.core.calibration.capture_inputs records them once per key. The default is the layer type
(:attr:layer_types); layers that also take an input of their own (:attr:uses_per_layer_inputs) get a key
each, (type, index).
kv_projection
¶
kv_projection(index: int, layer: DecoderLayer, hidden: Tensor, ctx: PassContext) -> tuple[Tensor, Tensor]
The K/V layer would write for hidden [B, S, d], without running its attention or MLP.
The default calls the layer with a stand-in cache that records K/V and aborts the layer, which reproduces
the family's norms, projections and rotary embedding exactly. The query projection is skipped where it is a
plain linear layer (:meth:_query_skipped).
fill_kv
¶
fill_kv(index: int, layer: DecoderLayer, hidden: Tensor, ctx: PassContext) -> None
Write the K/V layer index would produce for hidden at ctx.slots, without running the layer.
Layers that attend over another layer's cache entries, and token-wise layers, write nothing.
Raises:
| Type | Description |
|---|---|
IncompatibleTechniquesError
|
Layer |
logits
¶
logits(hidden: Tensor) -> Tensor
Final norm, LM head and :meth:transform_logits applied to last-layer hidden states.
transform_logits
¶
transform_logits(logits: Tensor) -> Tensor
The family's transform of the LM head's output (identity; Gemma's softcap and Granite's
logits_scaling override it).
It must act on every logit on its own, so that a head restricted to some token ids (a draft vocabulary,
:func:~economize.techniques._drafting.adapter_head_slice) can apply it to its columns only. A family whose
transform mixes the logits of different tokens overrides :meth:logits instead.
mixer
¶
mixer(layer: Module) -> Module | None
The token mixer of one decoder layer (its attention or recurrent block), found under the Hugging Face
names in _MIXERS; None when the layer has none. Families with another layout override this.
attention_module
¶
attention_module(index: int) -> Module | None
The softmax-attention module of layer index: the module that receives the attention mask and, under
eager attention, returns the attention weights. None for a recurrent layer or a layer without one.
linear_modules
¶
linear_modules(layer: Module) -> dict[str, Linear]
Every nn.Linear of one decoder layer, keyed by its dotted path inside the layer.
Fused MoE expert weights are 3-D parameters, not nn.Linear modules; see :meth:expert_parameters.
lora_targets
¶
lora_targets(layer: Module) -> dict[str, Module]
The linear maps LoRA may adapt, keyed by attribute name: the token mixer's projections and the dense MLP
projections (*_proj children of mlp; routers, experts and shared-expert gates excluded).
A map is an nn.Linear or a module standing in for one (in_features and out_features set, such as
a low-rank factorization or a PEFT LoRA layer). An economize LoRA on a PEFT LoRA layer adds its update to the
layer's output, which already holds PEFT's own update (merged or not).
expert_parameters
¶
expert_parameters(layer: Module) -> dict[str, Parameter]
The fused weights of every MoE expert block of one layer (experts.gate_up_proj etc.), else {}.
remove_layers
¶
remove_layers(indices: Iterable[int]) -> None
Delete decoder layers indices (1-indexed) from the model, in place.
The remaining layers are renumbered (their layer_idx attributes), config.num_hidden_layers is
updated and :meth:renumber_config rewrites every config field that addresses layers by index, so the
shallower model also survives save_pretrained and from_pretrained. Families whose config derives the
layer count from a per-layer field (Nemotron-H) need nothing more.
Raises:
| Type | Description |
|---|---|
ConfigError
|
An index lies outside |
UnsupportedModelError
|
Some layer attends over another layer's cache entries (KV sharing), which a removal would break. |
renumber_config
¶
renumber_config(kept: Sequence[int]) -> None
Rewrite the config fields that address decoder layers by index, for a removal that keeps kept.
:meth:remove_layers calls it before deleting any layer (self.num_layers is still the old count). The
default sets num_hidden_layers (unless the config derives it from a per-layer field), filters the
per-layer lists (:attr:per_layer_config_fields), recounts the split indices
(:attr:layer_threshold_config_fields) and renumbers the index lists (:attr:layer_index_config_fields).
Families whose fields need more (a periodic pattern such as Qwen-MoE's decoder_sparse_step) override it and
call super(). The per-layer overrides of a heterogeneous config follow their layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kept
|
Sequence[int]
|
0-indexed old indices of the layers that stay, ascending. |
required |
validate
¶
validate() -> None
Raise :class:UnsupportedModelError if the loaded model cannot be run by economize.
AttentionLayout
¶
Bases: Protocol
What each layer attends over and what it keeps in the cache.
attention_spec
¶
attention_spec(index: int) -> AttentionSpec
Mask kind, window and rotary key of layer index.
kv_source
¶
kv_source(index: int) -> int
The layer whose cache entries layer index attends over (itself unless it shares K/V).
DecoderModules
¶
Bases: Protocol
The modules of a decoder-only LM. Layers are 1-indexed; index 0 denotes the token embedding.
DepthEditing
¶
Bases: Protocol
Removing decoder layers in place, config included.
DevicePlacement
¶
Bases: Protocol
Where each part of the model computes.
KVProjection
¶
Bases: Protocol
The K/V a layer writes, computed without running its attention or MLP.
LayerExecution
¶
Bases: Protocol
How the token embedding and one decoder layer are run inside a pass.
layer_inputs
¶
layer_inputs(index: int, hidden: Tensor, ctx: PassContext, cache: object, mask: Tensor | StructuredMask | None) -> LayerInputs
Positional and keyword arguments after hidden for calling layer index.
LogitHead
¶
Bases: Protocol
Last-layer hidden states to logits.
transform_logits
¶
transform_logits(logits: Tensor) -> Tensor
The family's per-logit transform of the LM head's output.
ModelSizes
¶
Bases: Protocol
Widths and head geometry of the model and of each layer.
layer_config
¶
layer_config(index: int) -> HFConfig
The config of layer index (its own entry of a heterogeneous config, else the model's).
RotaryPositions
¶
Bases: Protocol
Rotary position tables, one per rotary key.
WeightLayout
¶
Bases: Protocol
The weights of one decoder layer, as weight rewrites (LoRA, quantization, pruning) address them.
expert_parameters
¶
expert_parameters(layer: Module) -> dict[str, Parameter]
The fused weights of every MoE expert block of layer ({} for a dense layer).
AttentionSpec
dataclass
¶
AttentionSpec(kind: str = 'full', window: int | None = None, rope: str = 'default')
Which cached positions one decoder layer attends to, and which rotary table it uses.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
Layer kind, a key of :data: |
window |
int | None
|
Sliding-window length (a query at position |
rope |
str
|
Key of the rotary table passed to :meth: |
HeadGeometry
dataclass
¶
HeadGeometry(heads: int, kv_heads: int, head_dim: int)
Head counts and head width of one attention layer (Gemma-4's full-attention layers differ from its sliding layers).
Attributes:
| Name | Type | Description |
|---|---|---|
heads |
int
|
Query heads. |
kv_heads |
int
|
Key/value heads. |
head_dim |
int
|
Width of one head. |
LayerCache
¶
Bases: Protocol
The part of a KV cache an adapter uses: one layer's keys and values, read whole and written at the pass's slots.
:class:economize.runtime.KVCache implements it.
LayerKind
dataclass
¶
LayerKind(name: str, state: StateKind, window_field: str | None = None, layer_types: tuple[str, ...] = ())
One kind of decoder layer.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The kind, :attr: |
state |
StateKind
|
What layers of this kind remember about earlier tokens. |
window_field |
str | None
|
Config field holding :attr: |
layer_types |
tuple[str, ...]
|
|
PassContext
¶
Bases: Protocol
What an adapter reads from the context of a pass through some decoder layers.
:class:economize.runtime.LayerContext implements it; the protocol keeps :mod:economize.arch free of runtime
imports.
Attributes:
| Name | Type | Description |
|---|---|---|
cache |
LayerCache
|
The cache every layer reads ( |
slots |
Tensor
|
Cache slot every token writes, |
token_inputs |
dict[str, Tensor]
|
Extra per-token inputs that some families feed to every layer. |
mask
¶
mask(spec: AttentionSpec, device: device) -> Tensor | StructuredMask | None
The attention mask of a layer with pattern spec on device.
rotary
¶
rotary(rope: str, like: Tensor) -> object
Rotary table rope for the pass's positions, in the dtype and on the device of like.
StateKind
¶
Bases: Enum
What a decoder layer remembers about earlier tokens.
SoftcappedLogitsMixin
¶
SoftcappedLogitsMixin(model: Module)
Bases: ArchAdapter
Logits squashed to (-c, c) by c * tanh(z / c) with c = config.final_logit_softcapping (Gemma).
final_logit_softcap
property
¶
final_logit_softcap: float | None
The cap c (None: logits are not capped).
SparseStepMoeMixin
¶
SparseStepMoeMixin(model: Module)
Bases: ArchAdapter
MoE layouts chosen by decoder_sparse_step and mlp_only_layers (Qwen1.5/2/3-MoE, Qwen3-Next).
Layer i (0-indexed) has a sparse MoE block iff i not in mlp_only_layers, num_experts > 0 and
(i + 1) % decoder_sparse_step == 0. A periodic pattern does not survive a removal, so
:meth:renumber_config writes the kept layers' layout out explicitly: decoder_sparse_step = 1 and
mlp_only_layers = the new indices of the kept dense layers.
StandardDecoderAdapter
¶
StandardDecoderAdapter(model: Module)
Bases: ArchAdapter
decoder.{embed_tokens, layers, norm, rotary_emb} and model.lm_head.
The decoder is model.model for a *ForCausalLM and model.model.language_model for a multimodal
*ForConditionalGeneration. Layers are called as layer(hidden, attention_mask=..., position_ids=...,
past_key_values=..., use_cache=True, position_embeddings=...) and write K/V through
past_key_values.update. Rotary modules whose forward takes a layer_type (Gemma-3, OLMo-3) get one
table per layer type. Family modules under :mod:economize.arch.families subclass it for what differs.
decoder
property
¶
decoder: Module
The text decoder module (holds the embedding, the layers and the final norm).
rotary_per_layer_type
cached
property
¶
rotary_per_layer_type: bool
Whether the rotary module keeps one table per layer type (its forward takes layer_type).
matches
staticmethod
¶
matches(model: Module) -> bool
Whether model has the standard layout (used for unregistered model types).
adapter_for
¶
adapter_for(model: Module) -> ArchAdapter
Build the adapter registered for the model's model_type (the wrapper's, else its text config's).
A PEFT wrapper (PeftModel) is unwrapped: the adapter works on its base model, with the LoRA layers in place.
Unknown model types fall back to the standard Llama-like layout when the model has it, with a warning.
Raises:
| Type | Description |
|---|---|
UnsupportedModelError
|
No adapter fits, or the model's layers or attention implementation are unsupported. |
module_device
¶
module_device(module: Module, default: device | None = None) -> device
Where module computes: the execution device of an accelerate hook, else its first parameter's device.
register_adapter
¶
register_adapter(*model_types: str) -> Callable[[_A], _A]
Class decorator registering an adapter for one or more model_type values.
A multimodal wrapper needs no entry of its own when its text config's model_type is registered.
config_value
¶
config_value(config: HFConfig, name: str, default: object = None) -> Any
config.<name> or default, also for a per-layer attribute of a heterogeneous config.
There it is the global value, the one of every layer without an override. Adapters that give some layers other
sizes say so in :meth:ArchAdapter.head_geometry.
is_heterogeneous
¶
is_heterogeneous(config: HFConfig) -> bool
Whether config gives some layers attribute values of their own (per_layer_config).
kept_below
¶
kept_below(kept: Sequence[int], threshold: int) -> int
How many of the kept layers (0-indexed old indices) lie below threshold: the new value of a field that
splits the layers at an index (first_k_dense_replace, max_window_layers) after a removal.
layer_overrides
¶
layer_overrides(config: HFConfig) -> dict[int, dict[str, JSONValue]]
The attributes each layer overrides, by 0-indexed layer ({} for a homogeneous config).
Read from the config's serialized form (to_dict()["per_layer_config"]), the public view of the overrides.
renumbered
¶
renumbered(indices: Iterable[int], kept: Sequence[int]) -> list[int]
The new 0-indexed positions of the kept layers among indices (old 0-indexed); removed layers drop out.
set_layer_overrides
¶
set_layer_overrides(config: HFConfig, overrides: Mapping[int, Mapping[str, object]]) -> None
Replace the per-layer overrides of a heterogeneous config (0-indexed layers of the current
num_hidden_layers). transformers validates the indices and drops values equal to the global ones.
text_config
¶
text_config(config: object) -> HFConfig
The config of the text decoder (config itself for a plain causal LM, the text sub-config of a wrapper).
config is typed object because callers pass model.config of an nn.Module, which torch types as
Tensor | Module.