Skip to content

economize.modules

Neural building blocks for the components that techniques add to a model.

Reusable neural building blocks for the components that techniques add to a model.

Float32Parameters

Bases: Module

A module whose float32 parameters and buffers stay float32 when the module is cast to another dtype.

Drafter parts are trained and run in float32 inside a model of any dtype and cast their inputs and outputs themselves. Casting the whole :class:~economize.EfficientModel (model.half(), model.to(torch.bfloat16), model.double()) casts the base model as asked; this module then follows device moves only, so its float32 tensors keep their precision and its forward keeps working. Tensors of other dtypes (copies stored in the model's dtype) follow the cast.

InModelDtype

InModelDtype(block: Module, dtype: dtype)

Runs a trainable copy of a decoder layer in the model's dtype and returns the model's dtype.

It has the calling convention of a decoder layer: hidden followed by the family's positional and keyword layer arguments (see ModelAdapter.layer_inputs; Gemma-4 passes its per-layer input positionally).

A copy stored in the model's dtype runs as it is. A float32 copy's floating-point weights are cast to the model's dtype once and the cast is reused until a weight changes (an optimizer step or a loaded state bumps its version), so the layer computes exactly what the model's own layer computes from the same weights. Casting on every call (as an autocast region per call does) would keep one cast of the weights per call alive for backward: a rollout of K steps through a 31B layer pair would then hold K bf16 copies of it.

cast_tensors

cast_tensors() -> dict[str, Tensor]

The block's floating-point parameters and buffers in the model's dtype, cast again only when one of them changed or gradient mode differs from the cached cast's.

DraftKVCache

DraftKVCache(num_layers: int, batch_size: int, num_heads: int, head_dim: int, capacity: int, *, device: device | str, dtype: dtype)

Bases: SlotLayout

Keys and values of one or more draft attention layers, laid out like the model's cache.

Every layer holds two buffers [B, heads, capacity + 1, head_dim]. Slot p holds position p, and the last slot (:attr:trash_slot) absorbs the writes of padding, of uncommitted tokens and of stopped rows. Reads (:meth:read) stop before the trash slot, so whatever lands there never reaches an attention: a NaN or an unbounded value in the trash slot would otherwise poison the attention output even under a zero weight.

Parameters:

Name Type Description Default
num_layers int

Number of draft attention layers.

required
batch_size int

Rows of the batch.

required
num_heads int

Key/value heads per layer.

required
head_dim int

Size of every head.

required
capacity int

Number of usable positions per row.

required
device device | str

Device of the buffers.

required
dtype dtype

Storage dtype of the buffers. Writes are cast to it.

required

slots

slots(positions: Tensor, keep: Tensor | None = None) -> Tensor

The slot of every position: the position itself where keep holds, else the trash slot.

scatter

scatter(layer: int, keys: Tensor, values: Tensor, slots: Tensor) -> None

Write the entries of several tokens per row: keys/values [B, heads, S, head_dim] go to the slots [B, S]. Entries sent to the same slot, other than the trash slot, must not collide.

write

write(layer: int, keys: Tensor, values: Tensor, slots: Tensor) -> None

Write one entry per row: keys/values [B, heads, head_dim] go to the slots [B].

read

read(layer: int, limit: int | None = None) -> tuple[Tensor, Tensor]

Keys and values of the first limit slots (default: all usable slots), [B, heads, limit, dim].

The trash slot is never part of the result.

visible

visible(positions: Tensor, limit: int | None = None, *, inclusive: bool = True) -> Tensor

Causal mask [B, Q, limit] of the slots that queries at positions [B, Q] may attend to.

A query sees the slots before its position, and its own slot when inclusive. Positions at or past limit (stopped rows, padding) are clamped to the last slot read, and slot 0 stays visible to every query, so no attention row is empty (an empty row would produce NaN).

reorder

reorder(rows: Tensor) -> None

Keep and reorder the batch rows rows (as :meth:~economize.decoding.Drafter.reorder).

LayerLoRA

LayerLoRA(targets: Mapping[int, Mapping[str, Module]], rank: int, alpha: float)

Bases: Module

LoRA updates for the linear maps of several decoder layers.

Parameters:

Name Type Description Default
targets Mapping[int, Mapping[str, Module]]

{layer index: {name: linear map}}, e.g. built from :meth:economize.arch.ArchAdapter.lora_targets. A map is any module with in_features and out_features whose output the update is added to (nn.Linear, a low-rank factorization).

required
rank int

Rank of every update.

required
alpha float

Scaling numerator; the update is multiplied by alpha / rank.

required

Parameters are stored as layers.<layer>.<name>.lora_A / lora_B. Construction leaves the adapted maps untouched; :meth:install adds the hooks and :meth:remove takes them off again.

installed property

installed: bool

Whether the hooks are on the adapted maps.

install

install(targets: Mapping[int, Mapping[str, Module]] | None = None) -> None

Hook the updates into the adapted linear maps (idempotent).

Parameters:

Name Type Description Default
targets Mapping[int, Mapping[str, Module]] | None

The maps to adapt, in the layout given at construction. Pass them when the base model's modules were replaced after construction (e.g. by a low-rank factorization); None keeps the maps given at construction.

None

Raises:

Type Description
ConfigError

targets lacks a map that has an update, or a map's shape differs from its update.

active

active() -> Iterator[None]

Apply the updates to every call of the adapted linear maps inside the block.

remove

remove() -> None

Remove the hooks from the adapted linear maps (the parameters stay).

LoRADelta

LoRADelta(in_features: int, out_features: int, rank: int, scale: float)

Bases: Module

The update scale * B A x of one linear map in_features -> out_features.

A gets the default nn.Linear (Kaiming uniform) init and B starts at zero, so the update starts at zero.

On a linear map split by tensor parallelism (see :meth:shard_like) the factor that shares the split dimension is sharded like the map's weight: B for a map split along its outputs (column-parallel), whose update is the local slice of the outputs, and A for a map split along its inputs (row-parallel), whose rank-r intermediate is summed over the processes before B maps it to the whole output.

shard_like

shard_like(weight: Tensor) -> None

Shard the factors like weight, the [out, in] weight of the adapted map, if it is a DTensor split along one dimension (a collective call: the first process's factors are scattered, so every process starts from the same update). Factors that are sharded already stay as they are.

forward

forward(x: Tensor) -> Tensor

The update for input x, in the dtype of the LoRA parameters (on a split map: this process's part of the update for its part of the input, see the class docstring).

RMSNorm

RMSNorm(size: int, eps: float = 1e-06)

Bases: Module

weight * x / sqrt(mean(x^2) + eps), the Llama/Qwen norm (Hugging Face LlamaRMSNorm): the statistic and the normalization in float32, cast back to the input dtype before the weight.

Parameters:

Name Type Description Default
size int

Width of the normalized dimension.

required
eps float

Added to the mean square.

1e-06

ReadoutAdapter

ReadoutAdapter(hidden_size: int, width: int | None = None)

Bases: Module

Maps the output of an intermediate layer toward the final residual stream before the model's norm and head.

h + linear(n) + mlp(n) with n = rms_normalize(h), computed in float32. Both branches start at zero, so an untrained adapter is the identity.

Parameters:

Name Type Description Default
hidden_size int

Width of the residual stream.

required
width int | None

Hidden width of the gated branch (default: hidden_size).

None

RotaryTable

RotaryTable(head_dim: int, theta: float = 10000.0, scaling: Mapping[str, object] | None = None, *, partial_rotary_factor: float = 1.0, max_position_embeddings: int | None = None)

Bases: Module

The rotary table of a rope configuration (see :func:rope_frequencies for the arguments).

forward(positions) returns float32 cos/sin [..., D'] (D' = int(head_dim * partial_rotary_factor)) for :func:apply_rotary. The frequencies are a non-persistent buffer: they follow .to(device), stay out of checkpoints and keep float32 when the module is cast to a lower precision (bfloat16 frequencies would shift the angles of late positions by whole radians).

GatedMLP

GatedMLP(hidden_size: int, intermediate_size: int)

Bases: Module

down_proj(silu(gate_proj(x)) * up_proj(x)) with bias-free linear maps and the parameter names of Hugging Face's LlamaMLP, so published draft-layer weights load as they are (PyTorch's default init).

Parameters:

Name Type Description Default
hidden_size int

Input and output width.

required
intermediate_size int

Width of the gated hidden layer.

required

SwiGLU

SwiGLU(in_features: int, hidden_features: int, out_features: int, *, init_std: float = 0.02, out_init_std: float = 0.001)

Bases: Module

out(silu(gate(x)) * value(x)) with bias-free linear maps.

Parameters:

Name Type Description Default
in_features int

Input width.

required
hidden_features int

Width of the gated hidden layer.

required
out_features int

Output width.

required
init_std float

Standard deviation of the normal init of gate and value.

0.02
out_init_std float

Standard deviation of the init of out; 0 gives a zero init, so the block starts as the zero function.

0.001

copy_dtype_of

copy_dtype_of(name: str, model_dtype: dtype) -> dtype

The storage dtype that the name in :data:COPY_DTYPES stands for in a model of model_dtype.

reusing_copies

reusing_copies(copies: Mapping[Module, Module]) -> Iterator[None]

Within the block, :func:trainable_copy of a layer in copies returns the copy given for it (once) instead of copying the layer again.

The recipe builds a technique a second time after a weight transform rewrote the base model (see :func:~economize.core.recipe.attach_techniques). The second build takes over the first build's copies, which were made from the untransformed layers: copies of quantized, sparse or low-rank layers would otherwise be dequantized, densified, or keep the factorization (or fail), while the trained state they load is that of a copy of the original layer. A transform that changes a layer's shapes changes the first build's copies the same way (:meth:~economize.core.technique.Technique.layer_copies). A copy taken over keeps its weights; its attention modules are renumbered like the layer's own (depth pruning renumbers the layers it keeps).

trainable_copy

trainable_copy(layer: Module, dtype: dtype | None = float32, layer_idx: int | None = None) -> Module

A copy of a decoder layer in dtype (None: the layer's own) with trainable dense weights (the layers of adaptation="full", the blocks of new drafter modules).

With layer_idx the copy's attention modules write the cache entries of layer layer_idx (0-based, the index Hugging Face attention modules pass to past_key_values.update) instead of the original's.

Weights held as quantized tensor subclasses (torchao, or any tensor with a working dequantize()) are copied in dequantized form, and quantized linear modules known to :data:DENSE_LINEARS (bitsandbytes 4-bit and 8-bit) become float32 nn.Linear modules; the quantized originals are never copied. Stand-in modules (e.g. low-rank factorizations) are copied as they are. Inside :func:reusing_copies a copy made earlier is returned instead.

Raises:

Type Description
ConfigError

A weight is neither a float tensor nor dequantizable.

rms_normalize

rms_normalize(x: Tensor, eps: float = 1e-06) -> Tensor

Scale x to unit root mean square over the last dimension (RMSNorm without a weight).

The statistic is computed in float32 and cast back to x.dtype before the product, which matches the reference implementation bit for bit.

apply_rotary

apply_rotary(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor

Rotate the last dimension of x by cos/sin (x * cos + rotate_half(x) * sin).

cos and sin must broadcast against x in every dimension but the last, which may be narrower than x's (partial rotary: only the leading cos.shape[-1] dimensions are rotated). The result has the promoted dtype of x and the table; cast the table first to stay in x's dtype.

rope_frequencies

rope_frequencies(head_dim: int, theta: float = 10000.0, scaling: Mapping[str, object] | None = None, *, partial_rotary_factor: float = 1.0, max_position_embeddings: int | None = None) -> tuple[Tensor, float]

Inverse frequencies [int(head_dim * partial_rotary_factor) / 2] and the attention scaling of a rope configuration, computed by transformers for scaled types.

Parameters:

Name Type Description Default
head_dim int

Width of one attention head.

required
theta float

The rope base (rope_theta).

10000.0
scaling Mapping[str, object] | None

rope_scaling (or rope_parameters) of a Hugging Face config: rope_type (or type) and the type's parameters; None or type "default" is unscaled.

None
partial_rotary_factor float

Fraction of the head that is rotated.

1.0
max_position_embeddings int | None

The model's max_position_embeddings; the default of original_max_position_embeddings for the types that need it.

None

Raises:

Type Description
ConfigError

The type is unknown, its parameters are invalid, or it is "dynamic" (its frequencies change with the sequence length, which a static table cannot follow).

rotary_tables

rotary_tables(positions: Tensor, inv_freq: Tensor, attention_scaling: float = 1.0) -> tuple[Tensor, Tensor]

Float32 cos and sin [..., 2 * F] of positions [...] for inverse frequencies [F] (each frequency twice, the layout of :func:rotate_half), times attention_scaling.

rotate_half

rotate_half(x: Tensor) -> Tensor

[-x2, x1] for the halves x1, x2 of the last dimension.