Skip to content

economize.train

Training of the components that techniques add, and of adapted base models.

Training of the components that techniques add (drafters, routers, adapters) and of adapted base models.

The contract is :class:Objective (:mod:economize.train.objective): registered objectives declare their trainable parameters, what they need from the teacher pass and their recommended optimizer settings, and both loops, :func:fit (a plain loop, optionally on accelerate) and :class:EffTrainer (transformers.Trainer), drive any registered objective. Importing this package registers the technique-agnostic objectives distill_kl, step_distill and ce. Technique-specific objectives (layerskip, early_exit_kl, eagle3_ttt, medusa_ce, ...) live with their technique under :mod:economize.techniques and register when economize is imported. Objective classes that earlier releases exported from this package stay importable here as deprecated aliases that resolve to the registered classes through :data:OBJECTIVES and warn (economize.train.LayerSkip moved to :mod:economize.techniques.early_exit, for example), so this package never imports a concrete technique. :class:EffTrainer imports transformers.Trainer (and thereby accelerate) only when first accessed. :mod:economize.train.rl holds the pieces of on-policy RL with a drafter inside the policy (exact and hybrid log-probabilities with gradients, acceptance on the policy's samples).

RunCheckpointer

RunCheckpointer(output_dir: str | Path | None, *, rank: int = 0, world: int = 1, keep: int = 2, barrier: Callable[[], None] | None = None)

The checkpoints of one :func:~economize.train.fit run in output_dir (see the module docstring).

Every process of a multi-process run holds one; process 0 writes the weights and the shared state, every process its own random and data state.

Parameters:

Name Type Description Default
output_dir str | Path | None

The run directory (None: nothing is written or read).

required
rank int

Index of this process.

0
world int

Number of processes.

1
keep int

Number of intermediate checkpoints kept (older ones are deleted).

2
barrier Callable[[], None] | None

Waits for every process (None: a single process, nothing to wait for).

None

main property

main: bool

Whether this process writes the weights and the shared state.

save

save(step: int, *, save_weights: Callable[[Path], None], shared_state: Callable[[], Mapping[str, object]], own_state: Mapping[str, object]) -> Path | None

Write checkpoint-<step>: the weights and the shared state (process 0, the state file last, so that its presence marks a complete checkpoint) and, in a multi-process run, every process's own_state; then delete the checkpoints beyond the newest keep. Every process must call this.

Parameters:

Name Type Description Default
step int

Optimizer steps completed.

required
save_weights Callable[[Path], None]

Writes the weights into the directory it is given (called on process 0).

required
shared_state Callable[[], Mapping[str, object]]

The trainer state, e.g. the optimizer, history and process 0's random and data state (called on process 0).

required
own_state Mapping[str, object]

This process's random and data state.

required

Returns:

Type Description
Path | None

The checkpoint directory (None without an output_dir).

prune

prune() -> None

Delete every checkpoint-<step> directory but the newest keep.

save_result

save_result(result: Mapping[str, object]) -> None

Write the result of the finished run (process 0), after the final weights.

resume_path

resume_path(resume: bool | str | Path | None) -> Path | None

The checkpoint a run with resume continues from: the latest in output_dir for True, the given path, or None (start from scratch).

Raises:

Type Description
ValueError

resume=True without an output_dir.

load_state

load_state(path: str | Path) -> dict[str, object]

The trainer state of checkpoint path, with this process's own random and data state where the checkpoint has one.

finished

finished(steps: int) -> bool

Whether the final weights of a run of at least steps steps exist.

load_result

load_result() -> dict[str, object]

The result of the finished run (empty for a run finished by an economize version that wrote none).

BatchSource

Bases: Protocol

An endless supply of training batches with a resumable position.

A source may also define shard(rank: int, world: int) -> None, which :func:~economize.train.fit calls once, before the first batch, on every process of a run of world > 1 processes so that each process reads its own part of the data (see :func:shard_source). The method is optional and not part of the protocol checked by isinstance; the built-in sources all define it.

next_batch

next_batch() -> Batch

The next batch (on the CPU; the loop moves it).

state_dict

state_dict() -> Mapping[str, object]

The source's position, picklable.

load_state_dict

load_state_dict(state: Mapping[str, object]) -> None

Continue from a position saved by :meth:state_dict.

Example dataclass

Example(input_ids: Tensor, loss_mask: Tensor | None = None)

One token sequence and, optionally, which of its positions count in the loss.

Attributes:

Name Type Description
input_ids Tensor

[T] token ids.

loss_mask Tensor | None

[T], 1 where the next token is a target (None: every position).

LoaderSource

LoaderSource(loader: Iterable[BatchLike], *, rank: int = 0, world: int = 1, seed: int | None = None)

Batches from any re-iterable (a DataLoader, a list, a Hugging Face dataset of token lists, ...).

Items may be :class:Batch es, [B, T] tensors, or mappings with input_ids (and optionally attention_mask / loss_mask or labels, where -100 labels mark positions that do not count). The source cycles over epochs; resuming skips the batches already consumed in the current epoch.

Resuming re-creates the iterator of the current epoch, so its order must be a function of the epoch. With a seed the source makes it one before every epoch: it calls set_epoch(epoch) on the loader and on its sampler where they have one (Hugging Face iterable datasets, DistributedSampler), and reseeds the generator of a DataLoader and of its RandomSampler with spawn_seed(seed, epoch). A shuffling DataLoader then yields the same batches in an uninterrupted and in a resumed run, and the same order on every process. :func:~economize.train.fit passes its data seed. Without a seed the loader is iterated as given.

In a run of several processes (see :meth:shard) process rank reads items rank, rank + world, ... of every epoch, so that the processes train on disjoint batches. The loader must then yield the same items in the same order on every process (no shuffling, or a DataLoader whose generator has the same seed everywhere).

Parameters:

Name Type Description Default
loader Iterable[BatchLike]

The re-iterable.

required
rank int

Index of this process.

0
world int

Number of processes.

1
seed int | None

Seed of the order of every epoch (None: leave the loader's own order).

None

shard

shard(rank: int, world: int) -> None

Read the items of process rank of world: one item of every round of world items, in lockstep with the other processes; the incomplete last round of an epoch is dropped (call before the first batch).

PasskeyRetrieval

PasskeyRetrieval(encode: Callable[[str], Sequence[int]], haystack: Sequence[int] | Tensor, *, prompt_tokens: Sequence[int] | None = None, batch_size: int = 1, context_length_min: int = 1000, context_length_max: int = 32000, context_lengths_num_intervals: int = 50, min_depth_ratio: float = 0.05, max_depth_ratio: float = 0.95, depth_ratio_num_intervals: int = 1000, num_passkeys: int = 10, passkey_length: int = 32, buffer_size: int = 300, pad_to_multiple_of: int = 16, pad_token_id: int = 0, seed: int = 42, needle: str = NEEDLE, question: str = QUESTION, prompt_before: str = PROMPT_BEFORE, prompt_after: str = PROMPT_AFTER, separator: str = SEPARATOR)

Batches of multi-passkey retrieval examples (DuoAttention's gate-training data).

Parameters:

Name Type Description Default
encode Callable[[str], Sequence[int]]

Text to token ids, without special tokens.

required
haystack Sequence[int] | Tensor

Token ids of the filler text; the first context_length_max are used, and they are shortened further by buffer_size plus the length of the needles, questions and prompts, as in the reference.

required
prompt_tokens Sequence[int] | None

Token ids of prompt_before (default encode(prompt_before); the reference encodes it with the tokenizer's special tokens, see :meth:from_tokenizer).

None
batch_size int

Examples per batch (reference batch_size 1). Longer examples are right-padded with pad_token_id and the batch carries an attention mask.

1
context_length_min int

Shortest haystack length in tokens (reference 1000, scripts/train.sh).

1000
context_length_max int

Longest haystack length (32000).

32000
context_lengths_num_intervals int

Number of evenly spaced haystack lengths (50); one epoch visits each once.

50
min_depth_ratio float

Smallest relative needle depth (0.05).

0.05
max_depth_ratio float

Largest relative needle depth (0.95).

0.95
depth_ratio_num_intervals int

Number of evenly spaced depths the needles are drawn from without replacement (1000).

1000
num_passkeys int

Needles per example (10, at most 20).

10
passkey_length int

Words per passkey (32, the reference's passkey_length default).

32
buffer_size int

Tokens kept free below context_length_max (300).

300
pad_to_multiple_of int

Every example's length is a multiple of this (16). As in the reference, the padding is taken from the end of the haystack and inserted before prompt_after, and a full block is added when the length is already a multiple.

16
pad_token_id int

Id of the right padding between examples of one batch.

0
seed int

Seed of the order of the lengths and of each example's depths and passkeys (reference 42).

42
needle str

Needle template with an {ordinal_number} field (the reference's text, typo included).

NEEDLE
question str

Retrieval question template.

QUESTION
prompt_before str

Text before the haystack.

PROMPT_BEFORE
prompt_after str

Text between the haystack and the questions.

PROMPT_AFTER
separator str

Text around each needle and after each answer.

SEPARATOR

from_tokenizer classmethod

from_tokenizer(tokenizer: PreTrainedTokenizerBase, texts: Iterable[str], **options: Unpack[PasskeyOptions]) -> PasskeyRetrieval

Build the source from a Hugging Face tokenizer and haystack texts (e.g. the reference's BookSum chapters).

As in the reference, texts are concatenated until the concatenation has at least context_length_max tokens; the haystack is its first context_length_max tokens (the reference decodes and re-encodes them, which can change a token at the cut). prompt_before is encoded with the tokenizer's special tokens and the padding id is the tokenizer's (0 without one); options go to the constructor.

shard

shard(rank: int, world: int) -> None

Process rank of world draws with its own seed (independent examples on every process).

example

example(interval: int, generator: Generator) -> Example

The example of haystack length self.lengths[interval] with depths and passkeys drawn from generator (__getitem__ of the reference).

SequenceSource

SequenceSource(examples: Sequence[Example], batch_size: int, *, pad_token_id: int = 0, seed: int = 0, shuffle: bool = True)

Bases: _ShuffledSource

Shuffled, right-padded batches of :class:Example s of any length.

TensorSource

TensorSource(data: Tensor | Batch, batch_size: int, *, seed: int = 0, shuffle: bool = True)

Bases: _ShuffledSource

Shuffled batches of the rows of a [N, T] token tensor (or of a :class:Batch with masks).

TokenStream

TokenStream(path: str | Path, seq_len: int, batch_size: int, seed: int = 0, *, aligned: bool = False, dtype: DTypeLike = uint32)

Random windows of seq_len tokens from a flat uint32 token file.

Draws the windows of the reference implementation in tests/train/test_data_sources.py for the same file, length and seed: start offsets come from numpy.random.default_rng(seed).integers, anywhere in the file, or at multiples of seq_len with aligned (files of whole records).

Parameters:

Name Type Description Default
path str | Path

The token file (numpy.memmap with dtype dtype).

required
seq_len int

Tokens per row T.

required
batch_size int

Rows per batch B.

required
seed int

Seed of the window positions.

0
aligned bool

Start windows at multiples of seq_len only.

False
dtype DTypeLike

Token dtype of the file.

uint32

shard

shard(rank: int, world: int) -> None

Draw the windows of process rank of world: positions seeded with spawn_seed(seed, rank), independent of the other processes' (call before the first batch).

MetricMeans

MetricMeans()

Running means of metric dictionaries: every :meth:add counts once for each metric it reports.

Values may be scalars or vectors (one value per draft step, averaged elementwise). The sums stay tensors until :meth:means, so adding does not synchronize with the device.

all_reduce

all_reduce(reduce: AllReduce, device: device | str) -> None

Sum the sums and counts over the processes of a data-parallel run (every process must hold the same metric names with the same shapes).

means

means() -> dict[str, float | list[float]]

The mean of every metric (floats, or lists for vector metrics).

TrainConfig dataclass

TrainConfig(steps: int = 1000, batch_size: int = 8, seq_len: int = 1024, grad_accum: int = 1, lr: float | None = None, lr_backbone: float | None = None, weight_decay: float | None = None, betas: tuple[float, float] | None = None, warmup_steps: int | None = None, schedule: str | None = None, min_lr_ratio: float | None = None, grad_clip: float | None = None, autocast: str | dtype | None = None, nonfinite: NonFinitePolicy = 'raise', log_every: int = 50, eval_every: int | None = None, eval_batch_size: int = 8, save_every: int | None = None, keep_checkpoints: int = 2, output_dir: str | Path | None = None, resume: bool | str | Path = False, seed: int | None = None, accelerate: bool = False, offload_optimizer: bool = False, find_unused_parameters: bool = True)

Settings of a :func:fit run. Optimizer fields left at None take the objective's :class:~economize.train.OptimDefaults.

Attributes:

Name Type Description
steps int

Optimizer steps.

batch_size int

Rows per micro-batch (for data that :func:fit turns into a source itself).

seq_len int

Tokens per row of a token file passed as data.

grad_accum int

Micro-batches per optimizer step.

lr float | None

Learning rate of "head" groups.

lr_backbone float | None

Learning rate of every "backbone" group (None: each group's own rate).

weight_decay float | None

Weight decay of groups that set none.

betas tuple[float, float] | None

AdamW betas.

warmup_steps int | None

Linear warmup steps.

schedule str | None

Name in :data:~economize.train.SCHEDULES ("cosine", "linear", "constant").

min_lr_ratio float | None

Final learning rate as a fraction of the peak.

grad_clip float | None

Maximum gradient norm (0: no clipping).

autocast str | dtype | None

Autocast dtype for the objective's forward ("bfloat16", torch.float16, ...; None: none, the model's own dtypes). Teacher passes always run without autocast. float16 scales the loss with a GradScaler (when the trained parameters are float32), so small gradients do not underflow and steps with overflowing gradients are skipped.

nonfinite NonFinitePolicy

What a step whose loss is NaN or infinite does: "raise" stops the run with a :class:~economize.errors.TrainingError before the optimizer applies the step, "skip" drops the step's gradients (the step still counts, the learning rate still advances) and "warn" logs a warning and applies the step.

log_every int

Log every this many steps (and the last step).

eval_every int | None

Evaluate on eval_data every this many steps (None: only after the last step).

eval_batch_size int

Rows per evaluation batch for tensor evaluation data.

save_every int | None

Write a checkpoint every this many steps (None: only the final weights).

keep_checkpoints int

Number of intermediate checkpoints kept (older ones are deleted).

output_dir str | Path | None

Directory of checkpoints, logs and the final weights (None: nothing is written).

resume bool | str | Path

True continues from the latest checkpoint in output_dir (if any), a path continues from that checkpoint. True on a finished run (output_dir/final holds the weights after steps or more steps) loads the final weights and returns the stored result without training.

seed int | None

Seeds torch, numpy and random at the start, and the data order of data that :func:fit turns into a source (None: no seeding, the current random state is used, and data seed 0).

accelerate bool

Run on accelerate (accelerate launch for several processes): data-parallel gradient averaging, one log and checkpoint writer. Each process reads its own batches through :func:~economize.train.data.shard_source: random sources draw with spawn_seed(seed, rank), a :class:~economize.train.LoaderSource gives every process disjoint items, and a user-defined source needs a shard(rank, world) method (otherwise every process reads the same batches, with a warning).

offload_optimizer bool

Keep the AdamW moments in CPU memory (:class:~economize.train.OffloadedAdamW), for trained parameters that leave no room for them on the device.

find_unused_parameters bool

Passed to DistributedDataParallel with several processes. True (the safe default) allows objectives that leave some trained parameters without gradient in a step (e.g. layerskip with layer dropout); False saves a graph traversal per step when every trained parameter gets a gradient.

Logged training records hold the loss and metrics averaged over the step's micro-batches and, with several processes, over the processes; evaluation splits the batches over the processes and averages over all of them.

optimizer_settings

optimizer_settings(defaults: OptimDefaults) -> OptimDefaults

The objective's defaults with this run's settings applied.

TrainResult dataclass

TrainResult(steps: int, losses: list[float] = list(), history: list[LogRecord] = list(), eval: EvalMetrics | None = None, output_dir: Path | None = None, final_path: Path | None = None)

What :func:fit returns.

Attributes:

Name Type Description
steps int

Optimizer steps completed (including those of a resumed run).

losses list[float]

Loss of every step of this call.

history list[LogRecord]

The logged records (training and evaluation).

eval EvalMetrics | None

Metrics of the last evaluation (None without eval_data).

output_dir Path | None

The run directory.

final_path Path | None

Directory of the final weights (economize.load reads it).

ObjectiveModule

ObjectiveModule(model: EfficientModel, objective: Objective, teacher_head: TeacherHead | None = None)

Bases: Module

Wraps an :class:~economize.EfficientModel and an :class:~economize.train.Objective.

forward(input_ids, attention_mask=None, loss_mask=None) runs the teacher pass the objective requests (without gradients, and outside any autocast region the caller opened) and returns {"loss": ..., "metrics": {...}}. Because the loss is computed inside forward, a DistributedDataParallel wrapper around this module synchronizes the gradients of the trained parameters.

Construction calls :meth:Objective.setup, collects the objective's parameter groups and freezes every other parameter of the model; :meth:close undoes both. train(mode) switches the techniques, and the base model only when the objective put it in training mode during setup (objectives that train the base model); a drafter's teacher always runs in eval mode.

Parameters:

Name Type Description Default
model EfficientModel

The model.

required
objective Objective

The objective.

required
teacher_head TeacherHead | None

Replaces the teacher's final states and head after each teacher pass (a larger teacher).

None

trains_base property

trains_base: bool

Whether some trained parameter belongs to the base model.

hf_device_map property

hf_device_map: dict[str, int | str | device]

The base model's hf_device_map (transformers.Trainer leaves models spread over devices in place). Absent, as on the base model, when the model was loaded without a device map: accelerate tests it with hasattr.

forward

forward(input_ids: Tensor, attention_mask: Tensor | None = None, loss_mask: Tensor | None = None, labels: Tensor | None = None, return_loss: bool = True) -> ObjectiveModuleOutput

Teacher pass and loss of one batch. labels (-100 = ignored, Hugging Face convention) stand in for loss_mask when it is not given; their values are otherwise unused (the targets are the inputs).

gradient_checkpointing_enable

gradient_checkpointing_enable(**kwargs: Unpack[_CheckpointingOptions]) -> None

Enable gradient checkpointing in the base model (TrainingArguments(gradient_checkpointing=True)).

close

close() -> None

Call :meth:Objective.teardown, restore the parameters' requires_grad flags and the model's modes.

Batch dataclass

Batch(input_ids: Tensor, attention_mask: Tensor | None = None, loss_mask: Tensor | None = None)

Token sequences of one training step.

Attributes:

Name Type Description
input_ids Tensor

[B, T] token ids.

attention_mask Tensor | None

[B, T], 1 for real tokens and 0 for right padding (None: no padding).

loss_mask Tensor | None

[B, T], 1 where a position's next-token prediction counts in the loss (None: every position with a next token; chat data masks the prompt here).

to

to(device: device | str) -> Batch

The batch on device.

has_targets

has_targets() -> bool

Whether any next-token prediction of the batch counts: a position with a real next token (attention_mask) that loss_mask marks. A batch without one gives no training signal (a masked loss of such a batch is 0 or NaN).

Objective

Bases: ABC

A training objective. Subclasses are dataclasses whose fields are the objective's hyperparameters.

Class attributes

name: Registry name (set by :func:register_objective). defaults: Optimizer and schedule settings the objective recommends.

setup

setup(model: EfficientModel) -> None

Prepare model once before the first step (check that the needed technique is attached, install training-only hooks). The default does nothing.

teardown

teardown(model: EfficientModel) -> None

Undo :meth:setup after training. The default does nothing.

begin_step

begin_step(step: int, total_steps: int) -> None

Called by the loops before each optimizer step (0-based step of total_steps), for objectives with curricula or schedules of their own. The default does nothing.

parameter_groups abstractmethod

parameter_groups(model: EfficientModel) -> list[ParamGroup]

The parameters to train, in optimizer groups. Everything else in model stays frozen.

modules

modules(model: EfficientModel) -> Sequence[Module]

Modules the objective trains that live outside model (gates or probes whose result is exported as a file, not attached as a technique). The loops register them with the trained module, so that data parallel wrappers synchronize their gradients, and checkpoints save and restore their states. Called once, after :meth:setup. The default is none.

teacher_request

teacher_request(model: EfficientModel) -> TeacherRequest | None

What the teacher pass must provide, or None when the objective needs no teacher (plain cross-entropy). The default requests the last block's output (teacher logits through :meth:TeacherOutputs.log_probs).

loss abstractmethod

loss(model: EfficientModel, batch: Batch, teacher: TeacherOutputs | None) -> ObjectiveOutput

The loss of batch (called with gradients enabled, inside the loop's autocast).

evaluate

evaluate(model: EfficientModel, batch: Batch, teacher: TeacherOutputs | None) -> Mapping[str, Tensor | float]

Evaluation metrics of batch (called under torch.no_grad()). Tensors may be vectors, e.g. one value per draft step for a teacher-forced curve. The default returns the training metrics and loss.

hyperparameters

hyperparameters() -> dict[str, object]

The dataclass fields of the objective (its constructor arguments) and their values.

with_options

with_options(**changes: object) -> _O

A copy with some hyperparameters changed.

ObjectiveOutput dataclass

ObjectiveOutput(loss: Tensor, metrics: Mapping[str, Tensor | float] = dict())

The loss of one batch and the metrics to log.

Attributes:

Name Type Description
loss Tensor

Scalar tensor to minimize.

metrics Mapping[str, Tensor | float]

Detached scalar tensors (or floats) by name; loops average them over accumulation steps.

OptimDefaults dataclass

OptimDefaults(lr: float = 0.0005, lr_backbone: float | None = None, weight_decay: float = 0.01, betas: tuple[float, float] = (0.9, 0.95), warmup_steps: int = 100, schedule: str = 'cosine', min_lr_ratio: float = 0.1, grad_clip: float | None = 1.0)

Optimizer and schedule settings an objective recommends; the run's arguments override each of them.

Attributes:

Name Type Description
lr float

Learning rate of "head" groups.

lr_backbone float | None

Learning rate of "backbone" groups (None: each group's own lr, else lr).

weight_decay float

Weight decay of groups that set none.

betas tuple[float, float]

AdamW betas.

warmup_steps int

Linear warmup from 0.

schedule str

Decay after warmup, a name in :data:~economize.train.SCHEDULES ("cosine", "linear", "constant" or a registered one).

min_lr_ratio float

Final learning rate as a fraction of the peak (cosine and linear).

grad_clip float | None

Maximum global gradient norm (None: no clipping).

ParamGroup dataclass

ParamGroup(name: str, params: list[Parameter], kind: GroupKind = 'head', lr: float | None = None, weight_decay: float | None = None)

Parameters an objective trains, with their optimizer settings.

Attributes:

Name Type Description
name str

Label used in logs and checkpoints.

params list[Parameter]

The parameters (all of them get requires_grad=True).

kind GroupKind

"head" for newly added modules (learning rate lr of the run), "backbone" for adapted or copied pretrained layers (learning rate lr_backbone of the run).

lr float | None

Default learning rate of the group, used when the run sets no rate for its kind.

weight_decay float | None

Weight decay of the group (None: the objective's default).

TeacherOutputs dataclass

TeacherOutputs(hidden: Mapping[int, Tensor], final: Tensor, head: Callable[[Tensor], Tensor], cache: KVCache | None = None, logits: Tensor | None = None)

Results of the teacher pass, computed without gradients.

Attributes:

Name Type Description
hidden Mapping[int, Tensor]

Residual-stream states [B, T, D] by layer index, as listed in the request.

final Tensor

Last block's output [B, T, D] (before the final norm).

head Callable[[Tensor], Tensor]

Maps last-block outputs to logits (final norm and LM head of the teacher).

cache KVCache | None

The pass's keys and values, slot t holding position t (when requested).

logits Tensor | None

Full [B, T, V] logits (when requested).

log_probs

log_probs(*index: Tensor | slice) -> Tensor

Float32 log-probabilities of the teacher at final[index] (e.g. (slice(None), positions)). The head runs in the model's own dtypes, also when an objective calls this inside the loop's autocast region.

TeacherRequest dataclass

TeacherRequest(hidden_layers: tuple[int, ...] = (), cache: bool = False, logits: bool = False, own_pass: bool = True)

What an objective needs from the teacher pass over a batch.

Attributes:

Name Type Description
hidden_layers tuple[int, ...]

Residual-stream states to keep: 0 is the embedding output, l the output of block l (1-based), num_layers the last block's output before the final norm.

cache bool

Keep every layer's keys and values of the pass in a :class:~economize.runtime.KVCache (rollouts that attend to the teacher's prefix need them).

logits bool

Materialize the full [B, T, V] teacher logits. Most objectives leave this off and call :meth:TeacherOutputs.log_probs on the positions they score, which is far cheaper for large vocabularies.

own_pass bool

Whether the objective reads the trained model's own pass (its hidden states or cache) when a larger teacher replaces the distributions. Objectives that read only final, head and logits set it to False: with a teacher head that can run alone (:func:larger_teacher) the loops then skip the trained model's exact pass, whose outputs would all be replaced. Without a teacher head the pass always runs.

merge

merge(other: TeacherRequest) -> TeacherRequest

The union of two requests (for objectives that combine others).

TechniqueObjective

Bases: Objective, Generic[_TT]

An objective that trains one attached technique of a known type (the drafters' and dynamic-depth techniques' own objectives).

Subclasses are dataclasses with a field technique (the attachment name, defaulting to the technique's registry name :attr:Technique.name <economize.core.Technique.name>, which is its config's technique). The type argument names the class they train (:meth:technique_type), and they get the lookup (:meth:trained), a :meth:setup that fails early when the technique is missing, the technique's own teacher request (:meth:teacher_request) and one "head" optimizer group with all of the technique's parameters (:meth:parameter_groups, named :attr:group)::

@register_objective("my_drafter_kl", default_for=(MyDrafter.name,))
@dataclass
class MyDrafterKL(TechniqueObjective[MyDrafter]):
    technique: str = MyDrafter.name

    def loss(self, model, batch, teacher):
        drafter = self.trained(model)
        ...

Attributes:

Name Type Description
technique str

Name under which the trained technique is attached.

Class attributes

group: Name of the optimizer group of :meth:parameter_groups ("": the attachment name).

technique_type classmethod

technique_type() -> type[_TT]

The class (or a base class) of the techniques this objective trains: by default the type argument of the class (MyDrafterKL(TechniqueObjective[MyDrafter]) trains a MyDrafter).

Raises:

Type Description
NotImplementedError

The class gives no concrete type argument and does not override this method.

trained

trained(model: EfficientModel) -> _TT

The trained technique.

Raises:

Type Description
IncompatibleTechniquesError

Nothing is attached as :attr:technique, or it is no :meth:technique_type.

setup

setup(model: EfficientModel) -> None

Check that the trained technique is attached.

teacher_request

teacher_request(model: EfficientModel) -> TeacherRequest | None

The trained technique's own request when it is a :class:TrainRequestProvider, else the default of :meth:Objective.teacher_request (the last block's output).

parameter_groups

parameter_groups(model: EfficientModel) -> list[ParamGroup]

All parameters of the trained technique, as one "head" group named :attr:group.

Raises:

Type Description
IncompatibleTechniquesError

The technique has no parameters.

TrainRequestProvider

Bases: Protocol

Implemented by a technique that states what its training needs from the teacher pass (drafters do). :class:TechniqueObjective uses it as its default :meth:~Objective.teacher_request.

train_request

train_request(model: EfficientModel) -> TeacherRequest

What training this technique needs from the teacher pass over a batch.

CrossEntropy dataclass

CrossEntropy(parameters: BaseParameters = 'trainable')

Bases: Objective

Next-token cross-entropy of the model's forward pass (with every attached technique active).

Attributes:

Name Type Description
parameters BaseParameters

Which base parameters are trained (see :data:~economize.train.objectives.base.BaseParameters); the techniques' own trainable parameters are trained as well.

DistillKL dataclass

DistillKL(technique: str | None = None, divergence: str = 'kl', ce_weight: float = 0.0, step_decay: float = 1.0)

Bases: Objective

KL distillation of a :class:TrainableDrafter, averaged over positions and weighted over draft steps.

Attributes:

Name Type Description
technique str | None

Name of the drafting technique (None: the attached technique that implements :class:TrainableDrafter).

divergence str

A name in :data:~economize.train.objectives.DIVERGENCES.

ce_weight float

Weight of the cross-entropy on the true token t + k.

step_decay float

Draft step k has weight step_decay ** (k - 1).

drafter

drafter(model: EfficientModel) -> Technique

The trained technique.

LogitDistill dataclass

LogitDistill(divergence: str = 'kl', ce_weight: float = 0.0, parameters: BaseParameters = 'trainable')

Bases: Objective

Divergence between the teacher's and the model's next-token distributions at every position.

The teacher pass of the trained model alone would distill the model into itself, so a teacher_model is required: :meth:loss raises when the teacher's distributions are those of the trained model.

Attributes:

Name Type Description
divergence str

A name in :data:~economize.train.objectives.DIVERGENCES (Minitron: "kl", the forward KL).

ce_weight float

Weight of the next-token cross-entropy on the data (Minitron: 0).

parameters BaseParameters

Which base parameters are trained (see :data:~economize.train.objectives.base.BaseParameters); the techniques' own trainable parameters are trained as well.

StepDistill dataclass

StepDistill(technique: str | None = None, steps: int = 8, stride: int = 1, divergence: str = 'kl', ce_weight: float = 0.0, step_decay: float = 1.0, head_chunk: int = 0, eval_horizon: int = 16, eval_stride: int = 32, eval_first: int = 64)

Bases: Objective

Divergence distillation of a :class:StepDrafter over steps decode-faithful draft steps.

Attributes:

Name Type Description
technique str | None

Name of the trained technique (None: the one attached technique that implements :class:StepDrafter).

steps int

Draft steps per rollout (capped at the drafter's :meth:~StepDrafter.step_limit).

stride int

Distance between rollout starts in training (1: every position, the first start drawn uniformly from [0, stride) otherwise).

divergence str

A name in :data:~economize.train.objectives.DIVERGENCES ("kl" = KL(teacher || drafter)).

ce_weight float

Weight of the cross-entropy on the true token (positions whose token lies outside a restricted draft vocabulary are left out of it).

step_decay float

Step k has weight step_decay ** (k - 1).

head_chunk int

Compute each step's logits and divergence in chunks of at most this many tokens, each under activation checkpointing (0: the whole step at once, still checkpointed).

eval_horizon int

Draft steps of the evaluation curve (steps beyond the drafter's limit score agree = run = 0 and NaN divergences).

eval_stride int

Distance between rollout starts in evaluation.

eval_first int

First rollout start in evaluation.

drafter

drafter(model: EfficientModel) -> Technique

The trained technique.

step_divergence

step_divergence() -> Callable[[Tensor, Tensor], Tensor]

Per-position divergence (teacher log-probs, drafter log-probs) -> [B, S] of the training loss.

rollout_states

rollout_states(drafter: StepDrafter, model: EfficientModel, batch: Batch, teacher: TeacherOutputs, starts: Tensor, steps: int) -> Sequence[Tensor]

The draft-step states the training loss scores (default: :meth:StepDrafter.step_states).

evaluate

evaluate(model: EfficientModel, batch: Batch, teacher: TeacherOutputs | None) -> Mapping[str, Tensor | float]

The teacher-forced curve of one batch: per draft step k = 1..eval_horizon (vectors) the metrics of :data:STEP_CURVE_METRICS, defined as for the other drafter objectives. With a restricted draft vocabulary agree compares the drafter's argmax (a model token) with the teacher's over the whole vocabulary, kl is taken against the teacher restricted to the draft vocabulary, and excess_nll counts only true tokens inside it.

StepDrafter

Bases: Protocol

Implemented by drafting techniques that can be rolled out step by step on teacher-forced sequences.

step_request

step_request(model: EfficientModel) -> TeacherRequest

What :meth:step_states needs from the teacher pass.

step_states

step_states(model: EfficientModel, batch: Batch, teacher: TeacherOutputs, starts: Tensor, steps: int) -> Sequence[Tensor]

The inputs of the drafter's head for draft steps k = 1..steps after exact passes that ended at starts [S]: entry k - 1 is [B, S, ...], its column i drafts token starts[i] + k + 1 from the exact states up to starts[i] and the true tokens up to starts[i] + k, exactly as in decoding. starts + steps + 1 is below the sequence length. Gradients must reach the trained parameters.

step_logits

step_logits(states: Tensor, step: int) -> Tensor

Float logits [B, S, V'] of draft step step from (a slice along S of) its entry of :meth:step_states; V' is the size of :meth:step_vocab.

step_vocab

step_vocab() -> Tensor | None

The model token ids of the columns of :meth:step_logits (sorted), or None for the model's whole vocabulary.

step_limit

step_limit() -> int | None

The most draft steps the drafter makes after an exact pass (None: no limit), e.g. Medusa's heads.

step_parameter_groups

step_parameter_groups() -> list[ParamGroup]

The trainable parameters in optimizer groups: new modules as "head", adapted or copied pretrained layers as "backbone".

TrainableDrafter

Bases: TrainRequestProvider, Protocol

Implemented by techniques whose drafts can be scored against the teacher in one teacher-forced pass; their train_request states what :meth:train_logits needs from the teacher pass (e.g. the states its heads read).

train_logits

train_logits(model: EfficientModel, batch: Batch, teacher: TeacherOutputs) -> Mapping[int, Tensor]

Logits [B, T, V] by draft step k >= 1: position t is the drafter's distribution of token t + k (positions t > T - 1 - k are ignored). Gradients must reach the drafter's parameters.

OffloadedAdamW

OffloadedAdamW(params: ParamsT, *, betas: tuple[float, float] = (0.9, 0.999), **defaults: float)

Bases: Optimizer

AdamW that keeps a float32 master copy of every parameter and both moments in CPU memory.

step copies the gradients to the CPU (upcast to float32), runs torch.optim.AdamW on the masters and copies the updated weights back, rounded to the parameters' dtypes. For float32 parameters the update is the one torch.optim.AdamW computes on the device (up to kernel rounding). For bfloat16 parameters it is standard mixed-precision training: small updates accumulate in the masters instead of vanishing in the rounding. The device holds the parameters and their gradients only. For a trainable copy of two Gemma-4-31B layers this frees the 7.6 GB of moments, and storing the copy in bfloat16 (copy_dtype="model") halves the rest.

Learning rates and the other hyperparameters are read from this optimizer's param_groups at every step, so schedulers work on it as on any optimizer. state_dict holds the CPU optimizer's state and the masters; load_state_dict restores both (a state without masters refreshes them from the parameters, so load those first).

LargerTeacher

LargerTeacher(teacher_model: Module, vocab_size: int | None = None)

Distill from another model with the same tokenizer (DistillSpec-style); see :func:larger_teacher.

Called with the outputs of the trained model's teacher pass, it runs teacher_model over the batch and replaces the last-block states and the head, so that :meth:TeacherOutputs.log_probs gives the other model's distributions; the intermediate states and the cache stay those of the trained model (rollouts start from its own states). Only final, head and logits change. Every entry of hidden, including hidden[num_layers] (the trained model's own last-block output, which now differs from final), stays the trained model's, so state losses always target the states of the model the drafter runs on.

:meth:standalone runs the other model alone, for objectives that read only its distributions (requests with own_pass=False, such as logit_distill).

The other model runs in eval mode (no dropout), also after a caller's .train() on a module that holds it.

Parameters:

Name Type Description Default
teacher_model Module

An :class:~economize.EfficientModel or a transformers causal LM, on any device.

required
vocab_size int | None

Truncate the teacher's logits to this many entries (models of one family often pad their embedding matrices to different sizes). None: no truncation.

None

StandaloneTeacherHead

Bases: Protocol

A :data:TeacherHead that can also produce its outputs without the trained model's pass, for requests with own_pass=False (:class:LargerTeacher is one).

standalone

standalone(batch: Batch, request: TeacherRequest) -> TeacherOutputs

The teacher's outputs for batch with empty hidden states and no cache.

EffCollator

EffCollator(pad_token_id: int = 0, max_length: int | None = None)

Right-pads examples into the tensors :class:~economize.train.ObjectiveModule takes.

Each feature is a mapping with input_ids and optionally loss_mask (1 where the next-token prediction counts) or labels (Hugging Face convention, -100 = ignored; turned into a loss_mask), or an :class:~economize.train.Example. The output has input_ids, plus attention_mask when rows were padded and loss_mask when some example masks positions.

Parameters:

Name Type Description Default
pad_token_id int

Id written into padding positions (they are masked, so any id works).

0
max_length int | None

Truncate longer examples to this many tokens.

None

EffTrainer

EffTrainer(model: EfficientModel, objective: str | Objective | None = None, args: TrainingArguments | None = None, *, lr_backbone: float | None = None, teacher_model: Module | TeacherHead | None = None, schedule: str | None = None, min_lr_ratio: float | None = None, offload_optimizer: bool | None = None, nonfinite: NonFinitePolicy | None = None, eval_with_objective: bool = False, data_collator: DataCollator | None = None, callbacks: list[TrainerCallback] | None = None, **trainer_kwargs: Unpack[_TrainerOptions])

Bases: Trainer

A transformers.Trainer that trains economize techniques with a registered objective.

Parameters:

Name Type Description Default
model EfficientModel

The model with the techniques to train attached (economize.apply; the base model may be a PEFT model).

required
objective str | Objective | None

An objective or a registered name (None: the default objective of the attached drafter).

None
args TrainingArguments | None

Training arguments (None: :func:economize_training_args of the objective, in ./economize_trainer). learning_rate is the rate of "head" groups. With :class:EffTrainingArguments its economize fields apply (the keyword arguments below win over them).

None
lr_backbone float | None

Learning rate of every "backbone" group (None: args.lr_backbone, else each group's own rate, else learning_rate).

None
teacher_model Module | TeacherHead | None

A larger model with the same tokenizer to distill from, or a ready teacher head (see :func:~economize.train.larger_teacher).

None
schedule str | None

A name in :data:~economize.train.SCHEDULES used with min_lr_ratio and args.warmup_steps instead of args.lr_scheduler_type (None: args.economize_schedule, else the transformers schedule of args).

None
min_lr_ratio float | None

Floor of the economize schedule (None: args.min_lr_ratio, else the objective's).

None
offload_optimizer bool | None

Keep the AdamW moments in CPU memory (None: args.offload_optimizer).

None
nonfinite NonFinitePolicy | None

What an optimizer step whose loss is NaN or infinite does (None: args.nonfinite, else "raise"): "raise" stops training with :class:~economize.errors.NonFiniteLossError before the optimizer applies the step, "skip" drops the step's gradients with a warning (the step still counts and the learning rate still advances) and "warn" logs a warning and applies the step.

None
eval_with_objective bool

Also report the objective's evaluation protocol (:meth:Objective.evaluate, e.g. the teacher-forced curve of a drafter) on the evaluation batches. Scalar metrics are logged as eval_<name>, per-step curves as eval_<name>1 and eval_<name>K (first and last step), and the full averaged result is kept in :attr:last_eval. Where a name coincides with a training metric (kl1, nmse1, ...), the protocol's value is reported. The batches must be long enough for the protocol (e.g. eval_first + eval_horizon + 2 tokens for step_distill).

False
data_collator DataCollator | None

Defaults to :class:EffCollator with the tokenizer's pad id.

None
**trainer_kwargs Unpack[_TrainerOptions]

Further Trainer arguments (train_dataset, eval_dataset, processing_class, callbacks, ...).

{}

Training metrics of the objective (e.g. kl1, nmse1) are averaged over the steps since the last log and logged next to the loss (averaged over processes); evaluation metrics appear with the eval_ prefix. :meth:Objective.begin_step runs once per optimizer step (a callback at on_step_begin), as in :func:~economize.train.fit. A training micro-batch in which no next-token prediction counts (every position masked by attention_mask or loss_mask, e.g. chat rows whose answer was cut off) adds no gradient: it is counted, logged as skipped_batches with a warning on the first one, and an optimizer step made only of such batches leaves the parameters unchanged. Trainer cannot draw past a batch as :func:~economize.train.fit does, and MAX_EMPTY_DRAWS such batches in a row raise :class:~economize.errors.ConfigError. Checkpoints are written in economize's format and resume_from_checkpoint restores techniques, trained base parameters, optimizer and scheduler. Several GPUs need a distributed launch (accelerate launch / torchrun): DataParallel replicas would not share the techniques' state, so a single process always uses one device.

optimizer_settings

optimizer_settings(num_training_steps: int | None = None) -> OptimDefaults

The objective's :class:~economize.train.OptimDefaults with the settings of args and of this trainer applied (the counterpart of :meth:TrainConfig.optimizer_settings <economize.train.TrainConfig>).

create_optimizer

create_optimizer(model: Module | None = None) -> Optimizer

AdamW with one group per objective parameter group (see :func:~economize.train.build_optimizer).

create_scheduler

create_scheduler(num_training_steps: int, optimizer: Optimizer | None = None) -> LRScheduler

economize's schedule (:func:~economize.train.build_scheduler) when one is set, else the transformers schedule of args.

training_step

training_step(model: Module, inputs: dict[str, Any], num_items_in_batch: Any = None) -> Tensor

Trainer.training_step with the checks of the class docstring: batches without a counted prediction are counted and add no gradient, and a non-finite loss is handled under :attr:nonfinite.

prediction_step

prediction_step(model: Module, inputs: dict[str, Tensor], prediction_loss_only: bool, ignore_keys: list[str] | None = None) -> tuple[Tensor | None, None, None]

The training loss of the objective on one evaluation batch, with its metrics logged under the eval_ prefix, and with eval_with_objective the metrics of :meth:Objective.evaluate on the batch.

The loss is what model(**inputs) returns, i.e. the objective's training loss (:meth:Objective.loss through :class:~economize.train.ObjectiveModule) without gradients, including any random choices the objective makes during training (e.g. randomly drawn rollout offsets). The fixed evaluation protocol that :func:~economize.train.fit and :func:~economize.train.evaluate report (e.g. teacher-forced accuracy at every horizon step) is :meth:Objective.evaluate, which eval_with_objective adds. No logits or labels are returned, so compute_metrics receives none.

close

close() -> None

Undo the objective's setup and restore the model's requires_grad flags and modes.

EffTrainingArguments dataclass

EffTrainingArguments(economize_schedule: str | None = None, min_lr_ratio: float | None = None, lr_backbone: float | None = None, offload_optimizer: bool = False, nonfinite: str = 'raise')

Bases: TrainingArguments

TrainingArguments with the optimizer settings of economize that transformers has no field for.

Attributes:

Name Type Description
economize_schedule str | None

A name in :data:~economize.train.SCHEDULES. When set, :class:EffTrainer builds the schedule with :func:~economize.train.build_scheduler (warmup from warmup_steps, floor min_lr_ratio) and ignores lr_scheduler_type.

min_lr_ratio float | None

Floor of the economize schedule as a fraction of the peak (None: the objective's).

lr_backbone float | None

Learning rate of every "backbone" parameter group (None: each group's own rate).

offload_optimizer bool

Keep the AdamW moments in CPU memory (:class:~economize.train.OffloadedAdamW).

nonfinite str

What an optimizer step with a NaN or infinite loss does ("raise", "skip" or "warn"), as TrainConfig.nonfinite of :func:~economize.train.fit (see :class:EffTrainer).

latest_checkpoint

latest_checkpoint(output_dir: str | Path) -> Path | None

The checkpoint-<step> directory with the highest step in output_dir (None: there is none).

load_trained

load_trained(model: EfficientModel, path: str | Path, *, owned: Module | None = None) -> None

Load weights written by :func:save_trained into the techniques and base parameters of model (and into owned, the modules the objective trains outside the model), then compare model's frozen base weights with the checkpoint's teacher fingerprint.

Raises:

Type Description
ValueError

The checkpoint holds weights of a technique that is not attached, or of a base parameter that model lacks.

Warns:

Type Description
TeacherMismatchWarning

The base weights that were not trained differ from those the run started from.

save_trained

save_trained(model: EfficientModel, params: Iterable[Parameter], path: str | Path, *, meta: Mapping[str, object] | None = None, save_base: bool = False, owned: Module | None = None) -> Path

Write the techniques of model and the trained base parameters among params to path.

Parameters:

Name Type Description Default
model EfficientModel

The trained model.

required
params Iterable[Parameter]

The parameters the objective trained.

required
path str | Path

Output directory (created if missing).

required
meta Mapping[str, object] | None

Stored under "train" in economize_config.json.

None
save_base bool

Also write base_model.save_pretrained(path / "base") when base parameters were trained (a PEFT model writes its adapters only), for use outside economize.

False
owned Module | None

Modules the objective trains outside the model; their state goes to OBJECTIVE_FILE.

None

as_batch

as_batch(item: BatchLike | None) -> Batch

A :class:Batch from a batch, a [B, T] tensor or a mapping of tensors or lists (labels = -100 masked). A single sequence [T] (e.g. one row of a Hugging Face dataset) becomes a batch of one row.

as_source

as_source(data: TrainData, batch_size: int = 8, *, seq_len: int = 1024, seed: int = 0) -> BatchSource

A :class:BatchSource from a source, a token file path, a [N, T] tensor, a list of :class:Example s or an iterable of batches.

collate

collate(examples: Sequence[Example], pad_token_id: int = 0) -> Batch

Right-pad examples into one :class:Batch (padding is masked in attention_mask).

fixed_windows

fixed_windows(path: str | Path, n: int, seq_len: int, *, dtype: DTypeLike = uint32) -> Tensor

n evenly spaced windows [n, seq_len] of a token file (as the reference implementation in tests/train/test_data_sources.py).

generate_self_distillation

generate_self_distillation(model: Module, tokenizer: PreTrainedTokenizerBase, prompts: Sequence[str | Conversation], *, max_new_tokens: int = 256, batch_size: int = 8, chat: bool | None = None, progress: Callable[[int, int], None] | None = None, **generate_kwargs: object) -> list[Example]

Examples made of prompts and the target's own continuations (HF generate), with the loss on the continuation only. Training a drafter on them matches its training data to what it will draft at test time.

Parameters:

Name Type Description Default
model Module

The target, a transformers causal LM (pass efficient_model.base_model for an economize model).

required
tokenizer PreTrainedTokenizerBase

Its tokenizer.

required
prompts Sequence[str | Conversation]

Strings, or chat conversations (rendered with the chat template and a generation prompt).

required
max_new_tokens int

Continuation length.

256
batch_size int

Prompts per generate call.

8
chat bool | None

Whether prompts are conversations (default: inferred from the first prompt).

None
progress Callable[[int, int], None] | None

Called with (done, total) after each batch.

None
generate_kwargs object

Further generate options (default greedy: do_sample=False).

{}

shard_source

shard_source(source: BatchSource, rank: int, world: int) -> BatchSource

Prepare source for process rank of a run of world processes, through its shard(rank, world) method (see :class:BatchSource). A source without one is read as given on every process: unless it splits the data by itself, all processes then train on the same batches, and a warning says so.

tokenize_chats

tokenize_chats(tokenizer: PreTrainedTokenizerBase, conversations: Iterable[Conversation], max_length: int, *, assistant_only: bool = True) -> list[Example]

Examples from chat conversations (lists of {"role", "content"} messages) with the tokenizer's chat template.

With assistant_only the loss counts only the tokens of assistant turns: turn i's tokens are those the template adds between the conversation up to turn i - 1 with a generation prompt and the conversation up to turn i (templates whose rendering of a prefix is a prefix of the full rendering, which holds for the common chat templates). Conversations longer than max_length tokens are truncated.

Raises:

Type Description
ConfigError

With assistant_only, when the template's rendering of a prefix with a generation prompt is no prefix of the full rendering (Gemma 4's generation prompt opens an empty thought channel that a rendered assistant turn lacks, for example), so the turn boundaries, and the mask, cannot be read off.

tokenize_texts

tokenize_texts(tokenizer: PreTrainedTokenizerBase, texts: Iterable[str], max_length: int, *, add_eos: bool = True) -> list[Example]

Plain-text examples (every next token counts), truncated to max_length tokens.

evaluate_batch

evaluate_batch(model: EfficientModel, objective: Objective, batch: Batch, *, request: TeacherRequest | None = None, teacher_head: TeacherHead | None = None, autocast: dtype | None = None) -> Mapping[str, Tensor | float]

:meth:Objective.evaluate of one batch: the teacher pass request asks for (default: the objective's; without autocast, in the model's own dtypes), then the objective's metrics under autocast.

fit

fit(model: EfficientModel, data: TrainData, objective: str | Objective | None = None, *, config: TrainConfig | None = None, eval_data: EvalData | None = None, teacher_model: Module | TeacherHead | None = None, callbacks: Iterable[Callable[[LogRecord], None]] = (), **overrides: Unpack[TrainOverrides]) -> TrainResult

Train model with objective on data.

Parameters:

Name Type Description Default
model EfficientModel

The model with the techniques to train attached (economize.apply).

required
data TrainData

A :class:~economize.train.BatchSource, a token file path, a [N, T] tensor, a list of :class:~economize.train.Example s or an iterable of batches (see :func:~economize.train.as_source).

required
objective str | Objective | None

An objective or a registered name (None: the default objective of the attached drafter, e.g. eagle3_ttt for eagle3).

None
config TrainConfig | None

Run settings; keyword overrides replace single fields (fit(..., steps=200, lr=1e-3)).

None
eval_data EvalData | None

Held-out rows [N, T] or batches, evaluated with the objective's evaluate.

None
teacher_model Module | TeacherHead | None

A larger model with the same tokenizer to distill from (see :func:~economize.train.larger_teacher), or a ready teacher head.

None
callbacks Iterable[Callable[[LogRecord], None]]

Called with every logged record.

()

Returns:

Type Description
TrainResult

The losses, the logged records, the last evaluation and the output paths.

attached_technique

attached_technique(model: EfficientModel, name: str, kind: type[_T], error: str) -> _T

The technique attached to model as name, checked to be a kind (a class, or a runtime-checkable protocol such as :class:~economize.train.objectives.StepDrafter). Objectives look their technique up with it.

Raises:

Type Description
IncompatibleTechniquesError

With message error, when nothing is attached as name or the attached technique is no kind.

build_objective

build_objective(objective: str | Objective, **options: object) -> Objective

An objective instance from a registered name and hyperparameters, or objective itself.

default_objective

default_objective(model: EfficientModel) -> Objective

The default objective of the first attached technique that has one (e.g. eagle3_ttt for eagle3).

The lookup follows the technique's type: a subclass attached under its own name (class MyEagle3(Eagle3Technique): name = "my_eagle3") trains with the default objective of the nearest base class that has one, and the objective is pointed at the attachment name.

Raises:

Type Description
ConfigError

No attached technique has a default objective.

register_default_objective

register_default_objective(technique: str, objective: str) -> None

Train technique (a technique name) with the registered objective objective when none is named.

register_objective

register_objective(name: str, *, default_for: Sequence[str] = ()) -> Callable[[type[_O]], type[_O]]

Class decorator registering an :class:Objective subclass in :data:OBJECTIVES under name.

Parameters:

Name Type Description Default
name str

Registry name.

required
default_for Sequence[str]

Technique names this objective trains when :func:default_objective is asked for one.

()

trainable

trainable(groups: Sequence[ParamGroup]) -> list[Parameter]

The distinct parameters of groups, in order.

unique_parameters

unique_parameters(params: Iterable[Parameter]) -> list[Parameter]

params without repeats (e.g. tied embeddings), in order of first appearance.

build_optimizer

build_optimizer(groups: Sequence[ParamGroup], settings: OptimDefaults, *, offload: bool = False) -> Optimizer

AdamW over groups: head groups at settings.lr; backbone groups at settings.lr_backbone, else their own lr, else settings.lr; each group's weight_decay unless None. The peak rate of every group is stored as "initial_lr". offload keeps the optimizer state in CPU memory with float32 master weights (:class:~economize.train.OffloadedAdamW), which parameters stored in a low precision (copy_dtype="model") need.

build_scheduler

build_scheduler(optimizer: Optimizer, settings: OptimDefaults, total_steps: int, *, start_step: int = 0) -> LambdaLR

The learning-rate schedule of settings (warmup, decay shape, floor) over total_steps optimizer steps.

The rate of every group is its "initial_lr" (see :func:build_optimizer) times :func:~economize.train.lr_factor of the step. Call step() after every optimizer step.

Parameters:

Name Type Description Default
optimizer Optimizer

An optimizer from :func:build_optimizer (every group has "initial_lr").

required
settings OptimDefaults

Warmup steps, schedule name and min_lr_ratio.

required
total_steps int

Optimizer steps of the run.

required
start_step int

The step of the next optimizer update (a resumed run's step count).

0

lr_factor

lr_factor(step: int, total_steps: int, warmup_steps: int, schedule: str, min_lr_ratio: float) -> float

Multiplier of the peak learning rate at step (0-based) of total_steps.

larger_teacher

larger_teacher(teacher_model: Module, vocab_size: int | None = None) -> LargerTeacher

Distill from another model with the same tokenizer (DistillSpec-style): the :class:LargerTeacher of teacher_model, a :data:TeacherHead that replaces the distributions of the trained model's teacher pass with those of teacher_model (truncated to vocab_size entries when given).

policy_pass

policy_pass(model: EfficientModel, batch: Batch, request: TeacherRequest) -> TeacherOutputs

:func:run_teacher with gradients: the same exact pass, but its states, cache and logits depend on the base weights, so that a loss on them (a policy gradient, or a drafter rollout that starts from them) trains the model. Used by on-policy RL (:mod:economize.train.rl); :func:economize.train.rl.detach_outputs turns the result into a teacher for drafter objectives.

run_teacher

run_teacher(model: EfficientModel, batch: Batch, request: TeacherRequest) -> TeacherOutputs

Run the unmodified model over batch and keep the states, cache and logits listed in request.

The pass goes through :class:~economize.runtime.LayerRunner with the model's own layers (no technique is active), so its states are the reference that drafters are trained to reproduce. It runs in the model's own dtypes, also inside a caller's autocast region. Rows may be right-padded (batch.attention_mask); padding tokens write to the cache's trash slot and no real token attends to them.

Parameters:

Name Type Description Default
model EfficientModel

The model; its base weights are the teacher.

required
batch Batch

Token ids [B, T].

required
request TeacherRequest

What to keep (see :class:TeacherRequest).

required

teacher_pass

teacher_pass(model: EfficientModel, batch: Batch, request: TeacherRequest, teacher_head: TeacherHead | None = None) -> TeacherOutputs

The teacher outputs an objective trains or evaluates against: :func:run_teacher of model, followed by teacher_head when one is given. A request with own_pass=False and a :class:StandaloneTeacherHead skip the trained model's pass, whose outputs the head would replace anyway.

economize_training_args

economize_training_args(objective: str | Objective, output_dir: str, **overrides: object) -> EffTrainingArguments

:class:EffTrainingArguments with the optimizer and schedule settings the objective recommends.

Learning rate, backbone rate, weight decay, AdamW betas, warmup steps and gradient clipping come from the objective's :class:~economize.train.OptimDefaults, and the schedule is the objective's schedule with its min_lr_ratio floor (economize_schedule), so :class:EffTrainer follows the same learning rates as :func:~economize.train.fit. overrides are further fields and win over the defaults; passing lr_scheduler_type without economize_schedule selects that transformers schedule instead.