calpit.nn.lightning
PyTorch Lightning training of Cal-PIT networks.
CalPIT.fit uses fit_lightning. Use CalPITModule and BestWeightsEarlyStopping directly to train with your own Trainer, loggers or callbacks, then wrap the trained network with CalPIT.from_fitted.
Attributes
Classes
Running sum of per-batch summed losses and of the rows they cover. |
|
LightningModule that trains a Cal-PIT network on (alpha, x, target) batches. |
|
Stops training when the validation loss stops improving and restores the best weights. |
Functions
|
|
|
Trains a Cal-PIT network with a Lightning Trainer. |
|
Silences Lightning's messages and warnings while enabled. |
Module Contents
- class CalPITModule(model: torch.nn.Module, lr: float = 0.001, weight_decay: float = 1e-05, lr_decay: float = 0.99)[source]
Bases:
lightning.LightningModuleLightningModule that trains a Cal-PIT network on (alpha, x, target) batches.
The loss is the binary cross entropy summed over each batch (calpit.nn.coverage_loss). The optimizer is AdamW, with the learning rate lr * lr_decay**epoch. Override configure_optimizers to change either.
- Parameters:
model – The network, which follows the contract in calpit.nn.models.
lr – The initial learning rate.
weight_decay – The AdamW weight decay.
lr_decay – The factor the learning rate shrinks by every epoch.
- Variables:
model – The network.
lr – The initial learning rate.
weight_decay – The AdamW weight decay.
lr_decay – The learning-rate decay per epoch.
train_loss_history – The mean training loss per row of every epoch.
val_bce_history – The mean validation binary cross entropy per row of every epoch.
- forward(alpha: torch.Tensor, x: torch.Tensor) torch.Tensor[source]
Evaluates the network.
- Parameters:
alpha – The coverage levels, shape (batch,).
x – The features, shape (batch, n_features).
- Returns:
The network’s output, shape (batch,).
- training_step(batch: tuple[torch.Tensor, torch.Tensor, torch.Tensor], batch_idx: int) torch.Tensor[source]
Returns the summed loss of a batch.
- validation_step(batch: tuple[torch.Tensor, torch.Tensor, torch.Tensor], batch_idx: int) None[source]
Adds the summed binary cross entropy of a batch.
- class BestWeightsEarlyStopping(patience: int = 20)[source]
Bases:
lightning.CallbackStops training when the validation loss stops improving and restores the best weights.
It monitors the val_bce_history of a CalPITModule, in float64 and summed over all processes when training on several devices. An epoch counts as an improvement when its validation loss is at most the best so far. Training stops after patience epochs in a row without one. The best weights are kept in memory, not written to disk, and loaded back when training ends.
- Parameters:
patience – The number of epochs without improvement to stop after.
- Variables:
patience – The number of epochs without improvement to stop after.
best_score – The lowest validation loss so far, or None before the first validation.
wait_count – The number of epochs since the last improvement.
best_state – A copy of the state dict at the best epoch, or None.
- on_validation_end(trainer: lightning.Trainer, pl_module: lightning.LightningModule) None[source]
Compares the epoch’s validation loss with the best and stops if it is time.
- fit_lightning(model: torch.nn.Module, x_train: numpy.typing.ArrayLike, pit_train: numpy.typing.ArrayLike, x_val: numpy.typing.ArrayLike | None = None, pit_val: numpy.typing.ArrayLike | None = None, *, alpha_val: numpy.typing.ArrayLike | None = None, oversample: float = 1, batch_size: int = 2048, max_epochs: int = 1000, lr: float = 0.001, weight_decay: float = 1e-05, lr_decay: float = 0.99, patience: int = 20, num_workers: int = 0, verbose: bool = False, trainer_kwargs: collections.abc.Mapping[str, Any] | None = None) tuple[CalPITModule, lightning.Trainer][source]
Trains a Cal-PIT network with a Lightning Trainer.
The training set draws a fresh alpha for every item each epoch (CoverageDataset). With a validation set, every validation object is scored at every alpha_val (CoverageGridDataset), training stops early and the best weights are restored (BestWeightsEarlyStopping).
- Parameters:
model – The network, trained in place.
x_train – The training features, shape (n_train, n_features).
pit_train – The training PIT values, shape (n_train,).
x_val – The validation features, shape (n_val, n_features), or None to train for max_epochs without validation.
pit_val – The validation PIT values, shape (n_val,).
alpha_val – The validation coverage levels, shape (n_alpha,). None uses 201 levels from 0.001 to 0.999.
oversample – How many training items each object yields per epoch.
batch_size – The number of rows per batch.
max_epochs – The maximum number of epochs.
lr – The initial learning rate.
weight_decay – The AdamW weight decay.
lr_decay – The factor the learning rate shrinks by every epoch.
patience – The number of epochs without improvement to stop after.
num_workers – The number of DataLoader worker processes.
verbose – Whether to show Lightning’s progress bar, model summary and messages.
trainer_kwargs – Arguments for lightning.Trainer that override the defaults: accelerator “auto”, one device, no logger, no checkpoint files. Callbacks given here are added to calpit’s own.
- Returns:
The trained module and the trainer, as a tuple (module, trainer).