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

_LIGHTNING_LOGGERS

Classes

_LossSums

Running sum of per-batch summed losses and of the rows they cover.

CalPITModule

LightningModule that trains a Cal-PIT network on (alpha, x, target) batches.

BestWeightsEarlyStopping

Stops training when the validation loss stops improving and restores the best weights.

Functions

_exponential_decay(→ float)

fit_lightning(→ tuple[CalPITModule, lightning.Trainer])

Trains a Cal-PIT network with a Lightning Trainer.

_quiet(→ collections.abc.Iterator[None])

Silences Lightning's messages and warnings while enabled.

Module Contents

_LIGHTNING_LOGGERS = ('lightning.pytorch', 'lightning.fabric')[source]
_exponential_decay(lr_decay: float, epoch: int) → float[source]
class _LossSums[source]

Running sum of per-batch summed losses and of the rows they cover.

losses: list[torch.Tensor] = [][source]
n_rows = 0[source]
add(loss: torch.Tensor, n_rows: int) → None[source]
mean(trainer: lightning.Trainer) → float[source]

Returns the mean loss per row, over all processes when training on several.

class CalPITModule(model: torch.nn.Module, lr: float = 0.001, weight_decay: float = 1e-05, lr_decay: float = 0.99)[source]

Bases: lightning.LightningModule

LightningModule 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.

model[source]
lr = 0.001[source]
weight_decay = 1e-05[source]
lr_decay = 0.99[source]
output_type[source]
train_loss_history: list[float] = [][source]
val_bce_history: list[float] = [][source]
_train_sums[source]
_val_sums[source]
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,).

_summed_loss(batch: tuple[torch.Tensor, torch.Tensor, torch.Tensor]) → torch.Tensor[source]
on_train_epoch_start() → None[source]

Starts the sum of the training loss.

training_step(batch: tuple[torch.Tensor, torch.Tensor, torch.Tensor], batch_idx: int) → torch.Tensor[source]

Returns the summed loss of a batch.

on_train_epoch_end() → None[source]

Records and logs the mean training loss per row as train_loss.

on_validation_epoch_start() → None[source]

Starts the sum of the validation loss.

validation_step(batch: tuple[torch.Tensor, torch.Tensor, torch.Tensor], batch_idx: int) → None[source]

Adds the summed binary cross entropy of a batch.

on_validation_epoch_end() → None[source]

Records and logs the mean validation binary cross entropy per row as val_bce.

configure_optimizers() → lightning.pytorch.utilities.types.OptimizerLRSchedulerConfig[source]

Returns AdamW with the learning rate decaying every epoch.

class BestWeightsEarlyStopping(patience: int = 20)[source]

Bases: lightning.Callback

Stops 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.

patience = 20[source]
best_score: float | None = None[source]
wait_count = 0[source]
best_state: dict[str, torch.Tensor] | None = None[source]
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.

on_fit_end(trainer: lightning.Trainer, pl_module: lightning.LightningModule) → None[source]

Loads the best weights back into the module.

state_dict() → dict[str, Any][source]

Returns the callback’s state for Lightning checkpoints.

load_state_dict(state_dict: collections.abc.Mapping[str, Any]) → None[source]

Restores the callback’s state from a Lightning checkpoint.

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).

_quiet(enabled: bool) → collections.abc.Iterator[None][source]

Silences Lightning’s messages and warnings while enabled.