Training#
The Trainer#
The Trainer class is responsible for running
the whole training loop:
from xnn.common.train import Trainer
trainer = Trainer(cfg, train_set, val_set, test_set) # Validation and test sets are optional
metrics = trainer.fit() # {"train": ..., "val": ..., "test": ...}
Cascading a fit() function call on a
Trainer instance object, does the following:
Builds the model from
cfg.modeland adds force and stress heads for the nonzero loss weights,Holds out
data.val_fractionanddata.test_fractionof the training set when no validation or test set is given,Validates every epoch and writes
best.ptandlast.pttocfg.output_dir, andEvaluates the test set once after the last epoch.
A checkpoint loads back with from_pretrained(path), and
trainer.save_pretrained("my-model") writes a portable model directory (see
the Load a Pre-trained Model guide for mode details).
The loss#
The loss is a weighted sum of the per-property errors:
The defaults are \(w_E = 1\), \(w_F = 10\) and \(w_\sigma = 0\), can
be set by energy_weight, force_weight and stress_weight in optim
section of the config file. A property contributes to the loss only when the
data provides it and its weight is nonzero. Train on forces whenever you have
them, since they are often far more informative to the training than energies
alone.
You can shape the loss further:
Per-structure weights. A
weightin a structure’s dictionary scales its share of every term, for instance to balance a sparse set against a dense scan.Per-label weights.
energy_weight,force_weightandstress_weightin a structure scale one of its terms, andatom_force_weightthe force error of each atom. A weight of 0 drops the label (see Weight Energy and Force Labels).Huber loss.
optim.huber_deltakeeps the error quadratic up to \(\delta\) and linear beyond, which limits the pull of a few large outliers. Below \(\delta\) it equals the squared error, so the loss weights keep their meaning when you switch it on (MACE’s Huber loss is half as large).Several heads. A multi-head model sums each head’s terms, and
optim.head_weightsgives a head its own weights (see Fine-tune a Pretrained Model).
Metrics, checkpoints and stopping#
Each epoch prints the loss terms for the training and validation sets, then
the MAE and RMSE of every labelled property (energy_mae per atom,
forces_rmse, …). Every value is averaged over the whole set, so batch
sizes do not skew it. The trainer section decides what drives the run:
trainer:
monitor: val/forces_mae # Picks best.pt and drives early stopping
mode: min
val_every_n_epochs: 1
save_every_n_epochs: 0 # > 0 also keeps epoch_<n>.pt
early_stopping_patience: 20 # Validations without improvement; 0 turns it off
early_stopping_threshold: 0.02 # Stop once forces_mae drops below 0.02
Any logged key can be monitored. In Python the same features are callbacks, and you can add your own:
from xnn.common.train import Callback, EarlyStopping, ModelCheckpoint
class Snapshot(Callback):
def on_epoch_end(self, trainer, epoch, metrics):
if epoch % 50 == 0:
trainer.save(f"runs/exp/epoch_{epoch}.pt")
trainer = Trainer(cfg, train_set, val_set, callbacks=[
ModelCheckpoint(monitor="val/energy_rmse", filename="best_energy.pt"),
EarlyStopping(monitor="val/forces_mae", patience=30),
Snapshot()])
Logging#
Metrics go to the console and to metrics.csv in output_dir by
default. TensorBoard needs the tensorboard extra:
trainer:
loggers: [console, csv, tensorboard]
log_every_n_steps: 0 # > 0 also logs training values every n steps
The console prints every error with its unit and every loss term with the
square of it, for example forces 4.5e-02 eV/A. The units come from the
data section and default to eV and Angstrom. They only label the numbers, so
set them to the units your data are in:
data:
energy_unit: kcal/mol
length_unit: A
In Python, pass logger=[...] to the trainer, or subclass
Logger to send the metrics anywhere.
Optimizer and fine-tuning#
The optim section holds the optimizer settings:
optim:
optimizer: adamw # adam, amsgrad or adamw
lr: 1.0e-3
scheduler: plateau # none, cosine or plateau
clip_grad: 1.0 # Max gradient norm; 0 turns it off
ema_decay: 0.999 # Validate and save an average of the weights
freeze: ["model.node_embedding*"] # Parameter-name patterns to keep fixed
prior_weight: 0.0 # > 0 pulls the parameters toward their starting values
prior_weights: {"*charge": 10.0} # The same per parameter-name pattern
prior_weight adds prior_weight * sum((p - p0)^2) over the trainable
parameters to the training loss (logged as prior), in the parameters’ own
units; it is the regularization of a force-field refit whose data leave some
parameter directions free. model.pretrained, model.lora and
model.heads turn the same trainer into a fine-tuning run (see
Fine-tune a Pretrained Model).
loss_weighting: uncertainty learns the balance between the loss terms
instead of fixing it, as QRNN does for its energy and charge terms. Each term
L (times its weight) is trained as L / (2 sigma^2) + log sigma with a
learned sigma per term (Kendall et al., Proc. IEEE CVPR, 7482 (2018)).
The logged
lossstays the fixed-weight sum, so validation and early stopping compare epochs the same way.sigma_<term>logs each learned scale, and checkpoints keep them asloss_sigmas.It needs a single head and does not combine with
trainer.cuda_graph.
Reaction energies#
A reaction energy is a difference of the energies of several structures. Give
the reactions to the trainer as a ReactionSet and
set a weight:
from xnn.common.data.hub import load_dataset
from xnn.common.train import ReactionSet, Trainer
data = load_dataset("gmtkn55", subsets=["W4-11", "S22"], closed_shell=True)
reactions = ReactionSet.from_gmtkn55(data, wtmad2=True)
cfg.optim.reaction_weight = 1.0
trainer = Trainer(cfg, train_set, val_set, reactions=reactions, val_reactions=reactions)
Each training step adds the loss of
optim.reaction_batch_sizereactions (16 by default), drawn in turn from a shuffled order.The term is the mean squared error of the reaction energies in eV. With
wtmad2=Trueeach set’s errors are scaled as in WTMAD-2.Validation reports
val/reaction_maeandval/reaction_rmsein eV.ReactionSet(structures, records)takes reactions of your own: each record lists thespeciesnames, theirstoichiometryand thereferenceenergy.The term runs in ordinary single-process steps, not with
trainer.cuda_graphor several GPUs.
Captured steps and fast paths#
Models with a fast path train through it when use_fast takes it (see
Run Models on Fused GPU Kernels). trainer.cuda_graph: true replays each training
step as one CUDA graph for DimeNet, DimeNet++, GemNet, PhysNet, SpookyNet, MACE, TensorNet, QET
and QRNN.
It needs one GPU and a single head, pads every batch to fixed sizes and drops
the last, smaller batch of each epoch.
Several GPUs or nodes#
Distributed training uses PyTorch DDP and needs no code or config changes, only
a launcher such as torchrun:
torchrun --nproc-per-node 2 -m xnn train --config train.yaml
torchrun --nnodes 2 --nproc-per-node 4 \
--rdzv-backend c10d --rdzv-endpoint "$HEAD_NODE":29500 \
-m xnn train --config train.yaml
Note that:
the
data.batch_sizeis a per GPU micro-batch size. The effective batch isbatch_sizetimes the total number of GPUs (over a single node or multiple nodes).Only the first rank prints and writes checkpoints, and checkpoints are interchangeable with single-GPU runs.
The FSDP and DeepSpeed ZeRo methods are not currently supported, because force and stress losses need a double backward pass that only DDP provides.
Custom batching#
The training loader reshuffles the data at every epoch. To batch differently,
for instance molecules and periodic cells in separate batches, pass a
train_batch_sampler that yields lists of dataset indices:
trainer = Trainer(cfg, train_set, val_set, train_batch_sampler=my_sampler)
If the sampler has a set_epoch(epoch) method, the trainer calls it before
every epoch.
Reproducibility#
The cfg.seed sets the seed for the run. PyTorch itself does not guarantee
bit-identical results across devices or CUDA versions.