TrainingLoop
- class TrainingLoop(model: Model, triples_factory: CoreTriplesFactory, optimizer: str | Optimizer | type[Optimizer] | None = None, optimizer_kwargs: Mapping[str, Any] | None = None, lr_scheduler: str | LRScheduler | type[LRScheduler] | None = None, lr_scheduler_kwargs: Mapping[str, Any] | None = None, automatic_memory_optimization: bool = True, mode: Literal['training', 'validation', 'testing'] | None = None, result_tracker: str | ResultTracker | type[ResultTracker] | None = None, result_tracker_kwargs: Mapping[str, Any] | None = None)[source]
Bases:
Generic
[SampleType
,BatchType
],ABC
A training loop.
Initialize the training loop.
- Parameters:
model (Model) – The model to train
triples_factory (CoreTriplesFactory) – The training triples factory
optimizer (Optimizer) – The optimizer to use while training the model
optimizer_kwargs (Mapping[str, Any] | None) – additional keyword-based parameters to instantiate the optimizer (if necessary). params will be added automatically based on the model.
lr_scheduler (LRScheduler | None) – The learning rate scheduler you want to use while training the model
lr_scheduler_kwargs (Mapping[str, Any] | None) – additional keyword-based parameters to instantiate the LR scheduler (if necessary). optimizer will be added automatically.
automatic_memory_optimization (bool) – bool Whether to automatically optimize the sub-batch size during training and batch size during evaluation with regards to the hardware at hand.
mode (Literal['training', 'validation', 'testing'] | None) – The inductive training mode. None if transductive.
result_tracker (str | ResultTracker | type[ResultTracker] | None) – the result tracker
result_tracker_kwargs (Mapping[str, Any] | None) – additional keyword-based parameters to instantiate the result tracker
Attributes Summary
The checksum of the model and optimizer the training loop was configured with.
The device used by the model.
The loss used by the model.
Methods Summary
batch_size_search
(*, triples_factory[, ...])Find the maximum batch size for training with the current setting.
Get the normalized name of the training loop.
sub_batch_and_slice
(*, batch_size, sampler, ...)Check if sub-batching and/or slicing is necessary to train the model on the hardware at hand.
train
(triples_factory[, num_epochs, ...])Train the KGE model.
Attributes Documentation
- checksum
The checksum of the model and optimizer the training loop was configured with.
- device
The device used by the model.
- hpo_default = {'batch_size': {'high': 12, 'low': 4, 'scale': 'power_two', 'type': <class 'int'>}, 'num_epochs': {'high': 1000, 'low': 100, 'q': 100, 'type': <class 'int'>}}
- loss
The loss used by the model.
Methods Documentation
- batch_size_search(*, triples_factory: CoreTriplesFactory, batch_size: int | None = None) tuple[int, bool] [source]
Find the maximum batch size for training with the current setting.
This method checks how big the batch size can be for the current model with the given training data and the hardware at hand. If possible, the method will output the determined batch size and a boolean value indicating that this batch size was successfully evaluated. Otherwise, the output will be batch size 1 and the boolean value will be False.
- Parameters:
triples_factory (CoreTriplesFactory) – The triples factory over which search is run
batch_size (int | None) – The batch size to start the search with. If None, set batch_size=num_triples (i.e. full batch training).
- Returns:
Tuple containing the maximum possible batch size as well as an indicator if the evaluation with that size was successful.
- Raises:
RuntimeError – If a runtime error is raised during training
- Return type:
- classmethod get_normalized_name() str [source]
Get the normalized name of the training loop.
- Return type:
- sub_batch_and_slice(*, batch_size: int, sampler: str | None, triples_factory: CoreTriplesFactory) tuple[int, int | None] [source]
Check if sub-batching and/or slicing is necessary to train the model on the hardware at hand.
- train(triples_factory: CoreTriplesFactory, num_epochs: int = 1, batch_size: int | None = None, slice_size: int | None = None, label_smoothing: float = 0.0, sampler: str | None = None, continue_training: bool = False, only_size_probing: bool = False, use_tqdm: bool = True, use_tqdm_batch: bool = True, tqdm_kwargs: Mapping[str, Any] | None = None, stopper: Stopper | None = None, sub_batch_size: int | None = None, num_workers: int | None = None, clear_optimizer: bool = False, checkpoint_directory: None | str | Path = None, checkpoint_name: str | None = None, checkpoint_frequency: int | None = None, checkpoint_on_failure: bool = False, drop_last: bool | None = None, callbacks: str | TrainingCallback | type[TrainingCallback] | None | Sequence[str | TrainingCallback | type[TrainingCallback] | None] = None, callbacks_kwargs: Mapping[str, Any] | None | Sequence[Mapping[str, Any] | None] = None, gradient_clipping_max_norm: float | None = None, gradient_clipping_norm_type: float | None = None, gradient_clipping_max_abs_value: float | None = None, pin_memory: bool = True) list[float] | None [source]
Train the KGE model.
Note
Gradient clipping is a technique to avoid the exploding gradient problem. Clip by norm and clip by value are two alternative implementations.
- Parameters:
triples_factory (CoreTriplesFactory) – The training triples.
num_epochs (int) – The number of epochs to train the model.
batch_size (int | None) – If set the batch size to use for mini-batch training. Otherwise find the largest possible batch_size automatically.
slice_size (int | None) – >0 The divisor for the scoring function when using slicing. This is only possible for LCWA training loops in general and only for models that have the slicing capability implemented.
label_smoothing (float) – (0 <= label_smoothing < 1) If larger than zero, use label smoothing.
sampler (str | None) – (None or ‘schlichtkrull’) The type of sampler to use. At the moment sLCWA in R-GCN is the only user of schlichtkrull sampling.
continue_training (bool) – If set to False, (re-)initialize the model’s weights. Otherwise continue training.
only_size_probing (bool) – The evaluation is only performed for two batches to test the memory footprint, especially on GPUs.
use_tqdm (bool) – Should a progress bar be shown for epochs?
use_tqdm_batch (bool) – Should a progress bar be shown for batching (inside the epoch progress bar)?
tqdm_kwargs (Mapping[str, Any] | None) – Keyword arguments passed to
tqdm
managing the progress bar.stopper (Stopper | None) – An instance of
pykeen.stopper.EarlyStopper
with settings for checking if training should stop earlysub_batch_size (int | None) – If provided split each batch into sub-batches to avoid memory issues for large models / small GPUs.
num_workers (int | None) – The number of child CPU workers used for loading data. If None, data are loaded in the main process.
clear_optimizer (bool) – Whether to delete the optimizer instance after training (as the optimizer might have additional memory consumption due to e.g. moments in Adam).
checkpoint_directory (None | str | Path) – An optional directory to store the checkpoint files. If None, a subdirectory named
checkpoints
in the directory defined bypykeen.constants.PYKEEN_HOME
is used. Unless the environment variablePYKEEN_HOME
is overridden, this will be~/.pykeen/checkpoints
.checkpoint_name (str | None) – The filename for saving checkpoints. If the given filename exists already, that file will be loaded and used to continue training.
checkpoint_frequency (int | None) – The frequency of saving checkpoints in minutes. Setting it to 0 will save a checkpoint after every epoch.
checkpoint_on_failure (bool) – Whether to save a checkpoint in cases of a RuntimeError or MemoryError. This option differs from ordinary checkpoints, since ordinary checkpoints are only saved after a successful epoch. When saving checkpoints due to failure of the training loop there is no guarantee that all random states can be recovered correctly, which might cause problems with regards to the reproducibility of that specific training loop. Therefore, these checkpoints are saved with a distinct checkpoint name, which will be
PyKEEN_just_saved_my_day_{datetime}.pt
in the given checkpoint_root.drop_last (bool | None) – Whether to drop the last batch in each epoch to prevent smaller batches. Defaults to False, except if the model contains batch normalization layers. Can be provided explicitly to override.
callbacks (str | TrainingCallback | type[TrainingCallback] | None | Sequence[str | TrainingCallback | type[TrainingCallback] | None]) – An optional
pykeen.training.TrainingCallback
or collection of callback instances that define one of several functionalities. Their interface was inspired by Keras.callbacks_kwargs (Mapping[str, Any] | None | Sequence[Mapping[str, Any] | None]) – additional keyword-based parameter to instantiate the training callback.
gradient_clipping_max_norm (float | None) – The maximum gradient norm for use with gradient clipping. If None, no gradient norm clipping is used.
gradient_clipping_norm_type (float | None) – The gradient norm type to use for maximum gradient norm, cf.
torch.nn.utils.clip_grad_norm_()
gradient_clipping_max_abs_value (float | None) – The maximum absolute value in gradients, cf.
torch.nn.utils.clip_grad_value_()
. If None, no gradient clipping will be used.pin_memory (bool) – whether to use memory pinning in the data loader, cf. https://pytorch.org/docs/stable/notes/cuda.html#cuda-memory-pinning
- Returns:
The losses per epoch.
- Return type: