scvi.train.PyroTrainingPlan#

class scvi.train.PyroTrainingPlan(pyro_module, loss_fn=None, optim=None, optim_kwargs=None, n_steps_kl_warmup=None, n_epochs_kl_warmup=400, scale_elbo=1.0)[source]#

Bases: LightningModule

Lightning module task to train Pyro scvi-tools modules.

Parameters:
pyro_module : PyroBaseModuleClass

An instance of PyroBaseModuleClass. This object should have callable model and guide attributes or methods.

loss_fn : ELBO | NoneOptional[ELBO] (default: None)

A Pyro loss. Should be a subclass of ELBO. If None, defaults to Trace_ELBO.

optim : PyroOptim | NoneOptional[PyroOptim] (default: None)

A Pyro optimizer instance, e.g., Adam. If None, defaults to pyro.optim.Adam optimizer with a learning rate of 1e-3.

optim_kwargs : dict | NoneOptional[dict] (default: None)

Keyword arguments for default optimiser pyro.optim.Adam.

n_steps_kl_warmup : int | NoneOptional[int] (default: None)

Number of training steps (minibatches) to scale weight on KL divergences from 0 to 1. Only activated when n_epochs_kl_warmup is set to None.

n_epochs_kl_warmup : int | NoneOptional[int] (default: 400)

Number of epochs to scale weight on KL divergences from 0 to 1. Overrides n_steps_kl_warmup when both are not None.

scale_elbo : float (default: 1.0)

Scale ELBO using scale. Potentially useful for avoiding numerical inaccuracy when working with very large ELBO.

Attributes table#

kl_weight

Scaling factor on KL divergence during training.

n_obs_training

Number of training examples.

Methods table#

backward(*args, **kwargs)

Called to perform backward on the loss returned in training_step().

configure_optimizers()

PyTorch Lightning shim optimizer.

forward(*args, **kwargs)

Passthrough to model.forward().

optimizer_step(*args, **kwargs)

Override this method to adjust the default way the Trainer calls each optimizer.

training_epoch_end(outputs)

Called at the end of the training epoch with the outputs of all training steps.

training_step(batch, batch_idx)

Here you compute and return the training loss and some additional metrics for e.g.

Attributes#

CHECKPOINT_HYPER_PARAMS_KEY#

PyroTrainingPlan.CHECKPOINT_HYPER_PARAMS_KEY = 'hyper_parameters'#

CHECKPOINT_HYPER_PARAMS_NAME#

PyroTrainingPlan.CHECKPOINT_HYPER_PARAMS_NAME = 'hparams_name'#

CHECKPOINT_HYPER_PARAMS_TYPE#

PyroTrainingPlan.CHECKPOINT_HYPER_PARAMS_TYPE = 'hparams_type'#

T_destination#

PyroTrainingPlan.T_destination#

alias of TypeVar(‘T_destination’, bound=Dict[str, Any])

alias of TypeVar(‘T_destination’, bound=Dict[str, Any]) .. autoattribute:: PyroTrainingPlan.T_destination automatic_optimization ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

PyroTrainingPlan.automatic_optimization[source]#

If set to False you are responsible for calling .backward(), .step(), .zero_grad().

Return type:

bool

current_epoch#

PyroTrainingPlan.current_epoch[source]#

The current epoch in the Trainer, or 0 if not attached.

Return type:

int

device#

PyroTrainingPlan.device[source]#
Return type:

str | deviceUnion[str, device]

dtype#

PyroTrainingPlan.dtype[source]#
Return type:

str | dtypeUnion[str, dtype]

dump_patches#

PyroTrainingPlan.dump_patches: bool = False#

example_input_array#

PyroTrainingPlan.example_input_array[source]#

The example input array is a specification of what the module can consume in the forward() method. The return type is interpreted as follows:

  • Single tensor: It is assumed the model takes a single argument, i.e., model.forward(model.example_input_array)

  • Tuple: The input array should be interpreted as a sequence of positional arguments, i.e., model.forward(*model.example_input_array)

  • Dict: The input array represents named keyword arguments, i.e., model.forward(**model.example_input_array)

Return type:

Any

global_rank#

PyroTrainingPlan.global_rank[source]#

The index of the current process across all nodes and devices.

Return type:

int

global_step#

PyroTrainingPlan.global_step[source]#

Total training batches seen across all epochs.

If no Trainer is attached, this propery is 0.

Return type:

int

hparams#

PyroTrainingPlan.hparams[source]#

The collection of hyperparameters saved with save_hyperparameters(). It is mutable by the user. For the frozen set of initial hyperparameters, use hparams_initial.

Return type:

AttributeDict | MutableMappingUnion[AttributeDict, MutableMapping]

Returns:

Mutable hyperparameters dictionary

hparams_initial#

PyroTrainingPlan.hparams_initial[source]#

The collection of hyperparameters saved with save_hyperparameters(). These contents are read-only. Manual updates to the saved hyperparameters can instead be performed through hparams.

Returns:

immutable initial hyperparameters

Return type:

AttributeDict

kl_weight#

PyroTrainingPlan.kl_weight[source]#

Scaling factor on KL divergence during training.

local_rank#

PyroTrainingPlan.local_rank[source]#

The index of the current process within a single node.

Return type:

int

logger#

PyroTrainingPlan.logger[source]#

Reference to the logger object in the Trainer.

Return type:

Logger | NoneOptional[Logger]

loggers#

PyroTrainingPlan.loggers[source]#

Reference to the list of loggers in the Trainer.

Return type:

List[Logger]

n_obs_training#

PyroTrainingPlan.n_obs_training[source]#

Number of training examples.

If not None, updates the n_obs attr of the Pyro module’s model and guide, if they exist.

on_gpu#

PyroTrainingPlan.on_gpu[source]#

Returns True if this model is currently located on a GPU.

Useful to set flags around the LightningModule for different CPU vs GPU behavior.

trainer#

PyroTrainingPlan.trainer[source]#
Return type:

Trainer

truncated_bptt_steps#

PyroTrainingPlan.truncated_bptt_steps[source]#

Enables Truncated Backpropagation Through Time in the Trainer when set to a positive integer.

It represents the number of times training_step() gets called before backpropagation. If this is > 0, the training_step() receives an additional argument hiddens and is expected to return a hidden state.

Return type:

int

use_amp#

PyroTrainingPlan.use_amp[source]#

Deprecated since version v1.6..

This property was deprecated in v1.6 and will be removed in v1.8.

Return type:

bool

training#

PyroTrainingPlan.training: bool#

Methods#

backward#

PyroTrainingPlan.backward(*args, **kwargs)[source]#

Called to perform backward on the loss returned in training_step(). Override this hook with your own implementation if you need to.

Parameters:
loss

The loss tensor returned by training_step(). If gradient accumulation is used, the loss here holds the normalized value (scaled by 1 / accumulation steps).

optimizer

Current optimizer being used. None if using manual optimization.

optimizer_idx

Index of the current optimizer being used. None if using manual optimization.

Example:

def backward(self, loss, optimizer, optimizer_idx):
    loss.backward()

configure_optimizers#

PyroTrainingPlan.configure_optimizers()[source]#

PyTorch Lightning shim optimizer.

PyTorch Lightning wants to take steps on an optimizer returned by this function in order to increment the global step count. See PyTorch Lighinting optimizer manual loop.

Here we provide a shim optimizer that we can take steps on at minimal computational cost in order to keep Lightning happy :).

forward#

PyroTrainingPlan.forward(*args, **kwargs)[source]#

Passthrough to model.forward().

optimizer_step#

PyroTrainingPlan.optimizer_step(*args, **kwargs)[source]#

Override this method to adjust the default way the Trainer calls each optimizer.

By default, Lightning calls step() and zero_grad() as shown in the example once per optimizer. This method (and zero_grad()) won’t be called during the accumulation phase when Trainer(accumulate_grad_batches != 1). Overriding this hook has no benefit with manual optimization.

Parameters:
epoch

Current epoch

batch_idx

Index of current batch

optimizer

A PyTorch optimizer

optimizer_idx

If you used multiple optimizers, this indexes into that list.

optimizer_closure

The optimizer closure. This closure must be executed as it includes the calls to training_step(), optimizer.zero_grad(), and backward().

on_tpu

True if TPU backward is required

using_native_amp

True if using native amp

using_lbfgs

True if the matching optimizer is torch.optim.LBFGS

Examples:

# DEFAULT
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_idx,
                   optimizer_closure, on_tpu, using_native_amp, using_lbfgs):
    optimizer.step(closure=optimizer_closure)

# Alternating schedule for optimizer steps (i.e.: GANs)
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_idx,
                   optimizer_closure, on_tpu, using_native_amp, using_lbfgs):
    # update generator opt every step
    if optimizer_idx == 0:
        optimizer.step(closure=optimizer_closure)

    # update discriminator opt every 2 steps
    if optimizer_idx == 1:
        if (batch_idx + 1) % 2 == 0 :
            optimizer.step(closure=optimizer_closure)
        else:
            # call the closure by itself to run `training_step` + `backward` without an optimizer step
            optimizer_closure()

    # ...
    # add as many optimizers as you want

Here’s another example showing how to use this for more advanced things such as learning rate warm-up:

# learning rate warm-up
def optimizer_step(
    self,
    epoch,
    batch_idx,
    optimizer,
    optimizer_idx,
    optimizer_closure,
    on_tpu,
    using_native_amp,
    using_lbfgs,
):
    # update params
    optimizer.step(closure=optimizer_closure)

    # manually warm up lr without a scheduler
    if self.trainer.global_step < 500:
        lr_scale = min(1.0, float(self.trainer.global_step + 1) / 500.0)
        for pg in optimizer.param_groups:
            pg["lr"] = lr_scale * self.learning_rate

training_epoch_end#

PyroTrainingPlan.training_epoch_end(outputs)[source]#

Called at the end of the training epoch with the outputs of all training steps. Use this in case you need to do something with all the outputs returned by training_step().

# the pseudocode for these calls
train_outs = []
for train_batch in train_data:
    out = training_step(train_batch)
    train_outs.append(out)
training_epoch_end(train_outs)
Parameters:
outputs

List of outputs you defined in training_step(). If there are multiple optimizers or when using truncated_bptt_steps > 0, the lists have the dimensions (n_batches, tbptt_steps, n_optimizers). Dimensions of length 1 are squeezed.

Returns:

None

Note

If this method is not overridden, this won’t be called.

def training_epoch_end(self, training_step_outputs):
    # do something with all training_step outputs
    for out in training_step_outputs:
        ...

training_step#

PyroTrainingPlan.training_step(batch, batch_idx)[source]#

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters:
batch : Tensor | (Tensor, …) | [Tensor, …]

The output of your DataLoader. A tensor, tuple or list.

batch_idx : int

Integer displaying index of this batch

optimizer_idx : int

When using multiple optimizers, this argument will also be present.

hiddens : Any

Passed in if :paramref:`~pytorch_lightning.core.module.LightningModule.truncated_bptt_steps` > 0.

Returns:

Any of.

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'

  • None - Training will skip to the next batch. This is only for automatic optimization.

    This is not supported for multi-GPU, TPU, IPU, or DeepSpeed.

In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.

Example:

def training_step(self, batch, batch_idx):
    x, y, z = batch
    out = self.encoder(x)
    loss = self.loss(out, x)
    return loss

If you define multiple optimizers, this step will be called with an additional optimizer_idx parameter.

# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx, optimizer_idx):
    if optimizer_idx == 0:
        # do training_step with encoder
        ...
    if optimizer_idx == 1:
        # do training_step with decoder
        ...

If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step.

# Truncated back-propagation through time
def training_step(self, batch, batch_idx, hiddens):
    # hiddens are the hidden states from the previous truncated backprop step
    out, hiddens = self.lstm(data, hiddens)
    loss = ...
    return {"loss": loss, "hiddens": hiddens}

Note

The loss value shown in the progress bar is smoothed (averaged) over the last values, so it differs from the actual loss returned in train/validation step.