Training strategy API#

Core training-loop classes and helpers.

See also

Strategies#

TrainingStrategy

Pydantic-driven supervised training loop for MLIP models.

default_training_fn

Run a forward pass and prefix output keys with predicted_.

Field

Type

Description

hooks

list[Hook | TrainingUpdateHook | TrainingUpdateOrchestrator]

Hooks to run at training stages. Accepts Hook Protocol instances, bare TrainingUpdateHook instances (auto-wrapped into a single TrainingUpdateOrchestrator), or an explicit TrainingUpdateOrchestrator. Example: hooks=[CheckpointHook(...), MyClipGradHook()].

step_count

int

Runtime optimizer-step counter, excluded from specs. Batches whose optimizer step is skipped by update hooks do not advance this counter.

models

dict[str, BaseModelMixin]

Named models visible to training_fn and hooks. Single-model inputs are stored under "main"; torch.nn.ModuleDict inputs are accepted and normalized to a plain dict.

optimizer_configs

dict[str, list[OptimizerConfig]]

Optimizer/scheduler configs keyed by model name. Keys may target a subset of models; omitted models are frozen/eval during run.

num_epochs

int | None

Epoch count; mutually exclusive with num_steps. At runtime, epochs are converted into a target step count from the dataloader length and epoch_step_modifier.

num_steps

int | None

Target step count; mutually exclusive with num_epochs.

epoch_step_modifier

float

Positive multiplier applied when converting num_epochs to a target step count. Hooks may inspect this value through ctx.workflow.

training_fn

Callable[..., Mapping[str, Tensor]] | None

Explicit forward-pass callable. Single-model strategies call (model, batch); named-model strategies call (models, batch).

loss_fn

ComposedLossFunction

Composed loss whose components drive target collection. Leaf losses are accepted and normalized to one-component composed losses.

loss_target_assembler

LossTargetAssemblyProtocol

Callable that assembles loss targets from the loss function, training predictions, current batch, and optional workflow.

devices

list[device]

One device shared by all models, or one entry per model naming that same device; named-model run stages its batch on the first, so two distinct devices are refused at run time. An index-less ‘cuda’ is resolved to the process’s current device before the entries are compared.

distributed_manager

DistributedManager | None

Optional external distributed manager. The strategy passes this through hook contexts for distributed-aware hooks.

global_step_count

int

Runtime optimizer-step counter across all data-parallel workers, excluded from specs. This advances by the distributed world size when an optimizer step runs, so checkpoint restarts can recover sampler progress without assuming the same world size.

batch_count

int

Runtime batch counter, excluded from specs. This advances for every completed batch, including batches whose optimizer step is skipped.

epoch_count

int

Runtime epoch counter, excluded from specs.

epoch_step_count

int

Runtime counter for batches consumed within the current epoch, excluded from specs.

single_model_input

bool

Runtime flag recording whether a single model was supplied (stored under "main") rather than a named mapping. Set automatically during validation and used to pick the training_fn call convention.

last_validation

dict[str, Any] | None

Most recent validation summary dict, or None before the first validation pass. Exposed to hooks via ctx.validation.

inference_model

Module | ModuleDict | None

Optional inference-time model (e.g. EMA weights) used in place of the live training model for validation when ValidationConfig.use_ema is set.

validation_config

ValidationConfig | None

Validation configuration controlling when and how validation runs. None disables validation.

devices has length 1 or len(models). A named-model run stages one batch on devices[0] and hands it to every model. A per-model list must therefore name the same device in every entry, and a list naming more than one distinct device is refused at run time. The per-model form lets a caller list a device for each model it places; it is not a way to span devices. Entries are compared after resolve_device() fills in the index of an index-less cuda, which means whichever device the process has made current, so cuda and cuda:0 count as one device on the rank whose current device is 0 and as two on every other rank. A single-model run is unaffected. A DDPHook on the NCCL backend collapses devices to this rank’s own device before the check runs.

Optimizer helpers#

OptimizerConfig

Declarative optimizer and optional LR-scheduler bundle.

setup_optimizers

Build optimizers and schedulers for configured model names.

zero_gradients

Call zero_grad(set_to_none=True) on each optimizer.

step_optimizers

Call step() on each optimizer.

step_lr_schedulers

Call step() on each non-None time-based scheduler.

Field

Type

Description

optimizer_cls

type

Optimizer class; optimizer_kwargs must match its signature.

optimizer_kwargs

dict[str, Any]

Keyword arguments forwarded to the optimizer constructor; validated against its __init__ signature at construction time.

scheduler_cls

type | None

Optional LR scheduler. Time-based schedulers (StepLR, CosineAnnealingLR, etc.) step every optimizer step. Metric-driven schedulers (ReduceLROnPlateau and subclasses) step only at validation checkpoints via step_metric_schedulers().

scheduler_kwargs

dict[str, Any]

Must be empty unless scheduler_cls is set.

scheduler_metric_adapter

Callable[[dict[str, Any]], float] | str | None

How a metric-driven scheduler (ReduceLROnPlateau) extracts its scalar metric from the validation summary dict. A str is treated as a key lookup into the summary; a callable receives the whole summary dict and returns a float; None uses the default extractor (see _extract_scheduler_metric()).

Serialization and checkpoints#

load_checkpoint() and load_checkpoint() rebuild a saved strategy from its metadata and restore the weights into models built from the saved specs. models= hands the loader live models to restore into instead, one per saved name, for a caller whose other objects already hold them. Extra keyword arguments are runtime overrides forwarded to the strategy class’s from_spec_dict. Both are refused on the loads that rebuild no strategy.

BaseSpec

Base class for JSON-serializable, no-pickle hyperparameter specs.

create_model_spec

Build a BaseSpec instance for target with the given kwargs.

create_model_spec_from_json

Rebuild a BaseSpec from its JSON-dict form.

register_type_serializer

Register JSON (de)serializers for a custom type.

CheckpointManifest

Unified checkpoint manifest and runtime container.

save_checkpoint

Save a checkpoint with a manifest.

load_checkpoint

Load a multi-component checkpoint written by save_checkpoint().

Runtime helpers#

configure_dataloader

Thin wrapper around DataLoader.

configure_parallelism

Configure model parallelism, preserving input shape.

move_to_devices

Move one model or named models to device(s), preserving input shape.

rehome_optimizer_state

Move an optimizer's per-parameter state onto its parameters' devices.

freeze_unconfigured_models

Temporarily eval/freeze models omitted from optimizer configs.

eval_configured_models

Temporarily put optimizer-configured models in evaluation mode.

evaluating

Temporarily put a module tree in evaluation mode.

Parallelism helpers#

A parallelism wrapper takes the place of the model a strategy holds. Code that needs the model’s own surface, such as its model_config, a BaseModelMixin method, or an unwrapped state_dict, has to reach through the wrapper first. unwrap_model() returns the module behind the wrapper, or the model itself when nothing wraps it. It recognizes a wrapper by the module attribute the wrapper publishes, not by its class, so a hand-rolled wrapper unwraps exactly as DistributedDataParallel does.

unwrap_model

Return the module a parallelism wrapper owns, or the model itself.

Distributed helpers#

all_reduce_flags() collects one flag per rank into a world-sized vector that reads the same everywhere: each rank raises its own entry and a MAX all-reduce merges them, on the device collective_device() picks for the backend. A strategy uses it to turn a verdict only one rank can see, such as an empty data shard, into a refusal every rank raises together, before any rank reaches a collective its peers would block on. all_gather_rows() stacks every rank’s rows of a tensor in rank order, padding unequal shards and trimming them back, and returns the slice this rank contributed; by default the gather is differentiable, so a loss over the world tensor sends gradients back to each rank’s rows. all_gather_objects() collects one picklable object per rank. All three return without a collective on a single process.

all_reduce_flags

Return every rank's flag as one tensor, this rank's at its own index.

all_gather_rows

Return every rank's tensor stacked along the leading dim, and this rank's rows.

all_gather_objects

Return every rank's obj, in rank order.