BaseTrainer#
- class core.trainer.BaseTrainer(cfg, rank, world_size)[source]#
Bases:
objectThe epoch loop, and everything around it that depends on neither task nor model.
Logging, checkpointing, DDP, early stopping and best-model selection live here; a subclass supplies
setup()and the epoch internals.- train()[source]#
Run the full training loop.
Iterates over epochs, calling
train_epoch()each epoch andval_epoch()everyval.every_n_epochsepochs and at the final epoch. Checkpoints are saved after each epoch. Supports early stopping via the return value ofval_epoch().
- abstract val_epoch()[source]#
Perform a validation epoch.
Called every val.every_n_epochs epochs, and at the end of training.
- Returns:
bool, True if early stopping should be triggered, False (or falsey) otherwise.
- Return type:
early_stop
- abstract setup(ckpt)[source]#
Set up the trainer.
This method is called after setting up distributed, loading the checkpoint, and setting up logging.
- add_checkpoint_items(**kwargs)[source]#
Add items to the checkpoint dictionary, saved and restored by state_dict.
Registering is what makes an object survive a resume, so every rank does it; writing the file stays rank zero’s job.
- Parameters:
kwargs – The items to add to the checkpoint dictionary.
- make_ddp(module, find_unused_parameters=False)[source]#
Wrap a module in DistributedDataParallel if running in distributed mode.
- Parameters:
- Returns:
The DDP-wrapped module, or the original module if not distributed.
- Return type:
- reduce_mean(total, count)[source]#
Mean over the whole split rather than over this rank’s shard of it.
A distributed sampler hands every rank a different slice, so a locally divided sum leaves the ranks disagreeing on the score they select on. Every rank must call this the same number of times, in the same order.
- reset_best_tracking(minimize=None)[source]#
Initialize the best-score bookkeeping used by
save_if_best().save_if_best()calls this itself on first use, so a trainer only needs it to pin a direction that config does not carry: passminimizewhen the trainer fixes it in code, or call it fromsetupafter decidingval.minimizethere. Direction otherwise comes fromval.minimize, defaulting to maximizing.A trainer that never tracks a best never gets these attributes, so it stays free to use those names itself. Only
best_modelandbest_metricsare always defined, since code outside this method reads them.
- save_if_best(score, metrics=None)[source]#
Keep this epoch’s weights if its score is the best seen so far.
On an improvement: records the score and epoch, snapshots the weights into
best_model, and writesbest.pt. The two have different readers:best_modelis whattestreloads in this same process, and it survivesckpt.enable=false;best.ptis what a later run loads. Passmetricsto also record thebest/val/*dict for logging. Feed the result tostep_patience()to early-stop as well; a trainer that only wants best-model selection can call this alone.Call it on every rank, since every rank’s
testreloads its ownbest_model; thebest.ptwrite self-gates to rank 0 on its own. A trainer whose score only exists on rank 0 may call it under a rank guard, but then owesstep_patience()a verdict broadcast to the other ranks.
- step_patience(improved)[source]#
Advance the early-stopping counter with this epoch’s outcome.
An improvement refills the counter; otherwise it ticks down, but only once the epoch reaches
val.start_patience.Every rank has to reach the same verdict, or one leaves the epoch loop while the others block in the next collective. That holds on its own when the score is rank-invariant, i.e. a torchmetrics
compute()or areduce_mean()result; a rank-0-only score has to be broadcast by the caller instead.- Parameters:
improved (
bool) – Whatsave_if_best()returned for this epoch.- Return type:
- Returns:
True once patience is exhausted, i.e. training should stop.
- get_param_groups(*modules)[source]#
Split parameters into a weight-decayed and an undecayed optimizer group.
A parameter skips weight decay if it is 1-D (biases, norm and other scale vectors) or if its name contains one of
cfg.no_weight_decay. The default list covers biases, norms and every*_emblookup table; a model overrides it only when a name lies about what it is.
- clip_and_log_grad_norm(*modules)[source]#
Clip gradients in place and log the pre-clip norm as
train/grad_norm.The norm is measured even when
grad_clipis unset so the metric does not vanish on unclipped runs. Call once per optimizer step, afterbackward().- Parameters:
modules (
Module) – Modules to clip over,self.modelby default. Pass the same ones asget_param_groups(), so the norm spans every parameter stepped.- Return type:
- log_epoch_grad_norm()[source]#
Log the epoch-mean grad norm, the counterpart to the epoch-mean train loss.