This file contains abstract classes for deterministic and probabilistic PyTorch Lightning Modules
- class darts.models.forecasting.pl_forecasting_module.PLDualCovariatesModule(input_chunk_length, output_chunk_length, output_chunk_shift=0, train_sample_shape=None, loss_fn=MSELoss(), torch_metrics=None, likelihood=None, optimizer_cls=<class 'torch.optim.adam.Adam'>, optimizer_kwargs=None, lr_scheduler_cls=None, lr_scheduler_kwargs=None, use_reversible_instance_norm=False)[source]¶
Bases:
PLForecastingModule
,ABC
PyTorch Lightning-based Forecasting Module.
This class is meant to be inherited to create a new PyTorch Lightning-based forecasting module. When subclassing this class, please make sure to add the following methods with the given signatures:
PLForecastingModule.__init__()
PLForecastingModule._produce_train_output()
PLForecastingModule._get_batch_prediction()
In subclass MyModel’s
__init__()
function callsuper(MyModel, self).__init__(**kwargs)
wherekwargs
are the parameters ofPLForecastingModule
.- Parameters
input_chunk_length (
int
) – Number of time steps in the past to take as a model input (per chunk). Applies to the target series, and past and/or future covariates (if the model supports it).output_chunk_length (
int
) – Number of time steps predicted at once (per chunk) by the internal model. Also, the number of future values from future covariates to use as a model input (if the model supports future covariates). It is not the same as forecast horizon n used in predict(), which is the desired number of prediction points generated using either a one-shot- or autoregressive forecast. Setting n <= output_chunk_length prevents auto-regression. This is useful when the covariates don’t extend far enough into the future, or to prohibit the model from using future values of past and / or future covariates for prediction (depending on the model’s covariate support).train_sample_shape (
Optional
[Tuple
]) – Shape of the model’s input, used to instantiate model without callingfit_from_dataset
and perform sanity check on new training/inference datasets used for re-training or prediction.loss_fn (
_Loss
) – PyTorch loss function used for training. This parameter will be ignored for probabilistic models if thelikelihood
parameter is specified. Default:torch.nn.MSELoss()
.torch_metrics (
Union
[Metric
,MetricCollection
,None
]) – A torch metric or aMetricCollection
used for evaluation. A full list of available metrics can be found at https://torchmetrics.readthedocs.io/en/latest/. Default:None
.likelihood (
Optional
[Likelihood
]) – One of Darts’Likelihood
models to be used for probabilistic forecasts. Default:None
.optimizer_cls (
Optimizer
) – The PyTorch optimizer class to be used. Default:torch.optim.Adam
.optimizer_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch optimizer (e.g.,{'lr': 1e-3}
for specifying a learning rate). Otherwise the default values of the selectedoptimizer_cls
will be used. Default:None
.lr_scheduler_cls (
Optional
[_LRScheduler
]) – Optionally, the PyTorch learning rate scheduler class to be used. SpecifyingNone
corresponds to using a constant learning rate. Default:None
.lr_scheduler_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch learning rate scheduler. Default:None
.use_reversible_instance_norm (
bool
) – Whether to use reversible instance normalization RINorm against distribution shift as shown in [1]. It is only applied to the features of the target series and not the covariates.
References
- 1
T. Kim et al. “Reversible Instance Normalization for Accurate Time-Series Forecasting against Distribution Shift”, https://openreview.net/forum?id=cGDAkQo1C0p
Attributes
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.The current epoch in the
Trainer
, or 0 if not attached.Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.The example input array is a specification of what the module can consume in the
forward()
method.The index of the current process across all nodes and devices.
Total training batches seen across all epochs.
The collection of hyperparameters saved with
save_hyperparameters()
.The collection of hyperparameters saved with
save_hyperparameters()
.The index of the current process within a single node.
Reference to the logger object in the Trainer.
Reference to the list of loggers in the Trainer.
Returns
True
if this model is currently located on a GPU.Number of time steps predicted at once by the model.
Determines how Lightning loads this model using .load_state_dict(..., strict=model.strict_loading).
device
dtype
epochs_trained
fabric
supports_probabilistic_prediction
trainer
Methods
add_module
(name, module)Add a child module to the current module.
all_gather
(data[, group, sync_grads])Gather tensors or collections of tensors from multiple processes.
apply
(fn)Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.backward
(loss, *args, **kwargs)Called to perform backward on the loss returned in
training_step()
.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Return an iterator over module buffers.
children
()Return an iterator over immediate children modules.
clip_gradients
(optimizer[, ...])Handles gradient clipping internally.
compile
(*args, **kwargs)Compile this Module's forward using
torch.compile()
.Configure model-specific callbacks.
configure_gradient_clipping
(optimizer[, ...])Perform gradient clipping for the optimizer parameters.
Hook to create modules in a strategy and precision aware context.
configures optimizers and learning rate schedulers for model optimization.
Deprecated.
configure_torch_metrics
(torch_metrics)process the torch_metrics parameter.
cpu
()See
torch.nn.Module.cpu()
.cuda
([device])Moves all model parameters and buffers to the GPU.
double
()See
torch.nn.Module.double()
.eval
()Set the module in evaluation mode.
Set the extra representation of the module.
float
()See
torch.nn.Module.float()
.forward
(*args, **kwargs)Same as
torch.nn.Module.forward()
.freeze
()Freeze all params for inference.
get_buffer
(target)Return the buffer given by
target
if it exists, otherwise throw an error.Return any extra state to include in the module's state_dict.
get_parameter
(target)Return the parameter given by
target
if it exists, otherwise throw an error.get_submodule
(target)Return the submodule given by
target
if it exists, otherwise throw an error.half
()See
torch.nn.Module.half()
.ipu
([device])Move all model parameters and buffers to the IPU.
load_from_checkpoint
(checkpoint_path[, ...])Primary way of loading a model from a checkpoint.
load_state_dict
(state_dict[, strict, assign])Copy parameters and buffers from
state_dict
into this module and its descendants.log
(name, value[, prog_bar, logger, ...])Log a key, value pair.
log_dict
(dictionary[, prog_bar, logger, ...])Log a dictionary of values at once.
lr_scheduler_step
(scheduler, metric)Override this method to adjust the default way the
Trainer
calls each scheduler.Returns the learning rate scheduler(s) that are being used during training.
manual_backward
(loss, *args, **kwargs)Call this directly from your
training_step()
when doing optimizations manually.modules
()Return an iterator over all modules in the network.
named_buffers
([prefix, recurse, ...])Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse, ...])Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
Called after
loss.backward()
and before optimizers are stepped.on_after_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch after it is transferred to the device.
on_before_backward
(loss)Called before
loss.backward()
.on_before_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch before it is transferred to the device.
on_before_optimizer_step
(optimizer)Called before
optimizer.step()
.on_before_zero_grad
(optimizer)Called after
training_step()
and beforeoptimizer.zero_grad()
.Called at the very end of fit.
Called at the very beginning of fit.
on_load_checkpoint
(checkpoint)Called by Lightning to restore your model.
on_predict_batch_end
(outputs, batch, batch_idx)Called in the predict loop after the batch.
on_predict_batch_start
(batch, batch_idx[, ...])Called in the predict loop before anything happens for that batch.
Called at the end of predicting.
Called at the end of predicting.
Called at the beginning of predicting.
Called when the predict loop starts.
Called at the beginning of predicting.
on_save_checkpoint
(checkpoint)Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
on_test_batch_end
(outputs, batch, batch_idx)Called in the test loop after the batch.
on_test_batch_start
(batch, batch_idx[, ...])Called in the test loop before anything happens for that batch.
Called at the end of testing.
Called in the test loop at the very end of the epoch.
Called in the test loop at the very beginning of the epoch.
Called when the test loop starts.
Called when the test loop ends.
Called at the beginning of testing.
on_train_batch_end
(outputs, batch, batch_idx)Called in the training loop after the batch.
on_train_batch_start
(batch, batch_idx)Called in the training loop before anything happens for that batch.
Called at the end of training before logger experiment is closed.
Called in the training loop at the very end of the epoch.
Called in the training loop at the very beginning of the epoch.
Called at the beginning of training after sanity check.
on_validation_batch_end
(outputs, batch, ...)Called in the validation loop after the batch.
on_validation_batch_start
(batch, batch_idx)Called in the validation loop before anything happens for that batch.
Called at the end of validation.
Called in the validation loop at the very end of the epoch.
Called in the validation loop at the very beginning of the epoch.
Called when the validation loop starts.
Called when the validation loop ends.
Called by the training loop to release gradients before entering the validation loop.
Called at the beginning of validation.
optimizer_step
(epoch, batch_idx, optimizer)Override this method to adjust the default way the
Trainer
calls the optimizer.optimizer_zero_grad
(epoch, batch_idx, optimizer)Override this method to change the default behaviour of
optimizer.zero_grad()
.optimizers
([use_pl_optimizer])Returns the optimizer(s) that are being used during training.
parameters
([recurse])Return an iterator over module parameters.
An iterable or collection of iterables specifying prediction samples.
predict_step
(batch, batch_idx[, dataloader_idx])performs the prediction step
Use this to download and prepare data.
print
(*args, **kwargs)Prints only from process 0.
register_backward_hook
(hook)Register a backward hook on the module.
register_buffer
(name, tensor[, persistent])Add a buffer to the module.
register_forward_hook
(hook, *[, prepend, ...])Register a forward hook on the module.
register_forward_pre_hook
(hook, *[, ...])Register a forward pre-hook on the module.
register_full_backward_hook
(hook[, prepend])Register a backward hook on the module.
register_full_backward_pre_hook
(hook[, prepend])Register a backward pre-hook on the module.
Register a post hook to be run after module's
load_state_dict
is called.register_module
(name, module)Alias for
add_module()
.register_parameter
(name, param)Add a parameter to the module.
Register a pre-hook for the
state_dict()
method.requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
save_hyperparameters
(*args[, ignore, frame, ...])Save arguments to
hparams
attribute.set_extra_state
(state)Set extra state contained in the loaded state_dict.
set_predict_parameters
(n, num_samples, ...)to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
setup
(stage)Called at the beginning of fit (train + validate), validate, test, or predict.
See
torch.Tensor.share_memory_()
.state_dict
(*args[, destination, prefix, ...])Return a dictionary containing references to the whole state of the module.
teardown
(stage)Called at the end of fit (train + validate), validate, test, or predict.
An iterable or collection of iterables specifying test samples.
test_step
(*args, **kwargs)Operates on a single batch of data from the test set.
to
(*args, **kwargs)See
torch.nn.Module.to()
.to_dtype
(dtype)Cast module precision (float32 by default) to another precision.
to_empty
(*, device[, recurse])Move the parameters and buffers to the specified device without copying storage.
to_onnx
(file_path[, input_sample])Saves the model in ONNX format.
to_torchscript
([file_path, method, ...])By default compiles the whole model to a
ScriptModule
.toggle_optimizer
(optimizer)Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
train
([mode])Set the module in training mode.
An iterable or collection of iterables specifying training samples.
training_step
(train_batch, batch_idx)performs the training step
transfer_batch_to_device
(batch, device, ...)Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.type
(dst_type)See
torch.nn.Module.type()
.unfreeze
()Unfreeze all parameters for training.
untoggle_optimizer
(optimizer)Resets the state of required gradients that were toggled with
toggle_optimizer()
.An iterable or collection of iterables specifying validation samples.
validation_step
(val_batch, batch_idx)performs the validation step
xpu
([device])Move all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Reset gradients of all model parameters.
__call__
set_mc_dropout
- CHECKPOINT_HYPER_PARAMS_KEY = 'hyper_parameters'¶
- CHECKPOINT_HYPER_PARAMS_NAME = 'hparams_name'¶
- CHECKPOINT_HYPER_PARAMS_TYPE = 'hparams_type'¶
- T_destination¶
alias of TypeVar(‘T_destination’, bound=
Dict
[str
,Any
])
- add_module(name, module)¶
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- Return type
None
- all_gather(data, group=None, sync_grads=False)¶
Gather tensors or collections of tensors from multiple processes.
This method needs to be called on all processes and the tensors need to have the same shape across all processes, otherwise your program will stall forever.
- Parameters
data (
Union
[Tensor
,Dict
,List
,Tuple
]) – int, float, tensor of shape (batch, …), or a (possibly nested) collection thereof.group (
Optional
[Any
]) – the process group to gather results from. Defaults to all processes (world)sync_grads (
bool
) – flag that allows users to synchronize gradients for the all_gather operation
- Return type
Union
[Tensor
,Dict
,List
,Tuple
]- Returns
A tensor of shape (world_size, batch, …), or if the input was a collection the output will also be a collection with tensors of this shape. For the special case where world_size is 1, no additional dimension is added to the tensor(s).
- apply(fn)¶
Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters
fn (
Module
-> None) – function to be applied to each submodule- Returns
self
- Return type
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- property automatic_optimization: bool¶
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.- Return type
bool
- backward(loss, *args, **kwargs)¶
Called to perform backward on the loss returned in
training_step()
. Override this hook with your own implementation if you need to.- Parameters
loss (
Tensor
) – The loss tensor returned bytraining_step()
. If gradient accumulation is used, the loss here holds the normalized value (scaled by 1 / accumulation steps).
Example:
def backward(self, loss): loss.backward()
- Return type
None
- bfloat16()¶
Casts all floating point parameters and buffers to
bfloat16
datatype.Note
This method modifies the module in-place.
- Returns
self
- Return type
Module
- buffers(recurse=True)¶
Return an iterator over module buffers.
- Parameters
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Tensor
]
- call_super_init: bool = False¶
- children()¶
Return an iterator over immediate children modules.
- Yields
Module – a child module
- Return type
Iterator
[Module
]
- clip_gradients(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Handles gradient clipping internally.
Note
Do not override this method. If you want to customize gradient clipping, consider using
configure_gradient_clipping()
method.For manual optimization (
self.automatic_optimization = False
), if you want to use gradient clipping, consider callingself.clip_gradients(opt, gradient_clip_val=0.5, gradient_clip_algorithm="norm")
manually in the training step.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. Passgradient_clip_algorithm="value"
to clip by value, andgradient_clip_algorithm="norm"
to clip by norm.
- Return type
None
- compile(*args, **kwargs)¶
Compile this Module’s forward using
torch.compile()
.This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile()
.See
torch.compile()
for details on the arguments for this function.
- configure_callbacks()¶
Configure model-specific callbacks. When the model gets attached, e.g., when
.fit()
or.test()
gets called, the list or a callback returned here will be merged with the list of callbacks passed to the Trainer’scallbacks
argument. If a callback returned here has the same type as one or several callbacks already present in the Trainer’s callbacks list, it will take priority and replace them. In addition, Lightning will make sureModelCheckpoint
callbacks run last.- Return type
Union
[Sequence
[Callback
],Callback
]- Returns
A callback or a list of callbacks which will extend the list of callbacks in the Trainer.
Example:
def configure_callbacks(self): early_stop = EarlyStopping(monitor="val_acc", mode="max") checkpoint = ModelCheckpoint(monitor="val_loss") return [early_stop, checkpoint]
- configure_gradient_clipping(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Perform gradient clipping for the optimizer parameters. Called before
optimizer_step()
.- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients. By default, value passed in Trainer will be available here.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. By default, value passed in Trainer will be available here.
Example:
def configure_gradient_clipping(self, optimizer, gradient_clip_val, gradient_clip_algorithm): # Implement your own custom logic to clip gradients # You can call `self.clip_gradients` with your settings: self.clip_gradients( optimizer, gradient_clip_val=gradient_clip_val, gradient_clip_algorithm=gradient_clip_algorithm )
- Return type
None
- configure_model()¶
Hook to create modules in a strategy and precision aware context.
This is particularly useful for when using sharded strategies (FSDP and DeepSpeed), where we’d like to shard the model instantly to save memory and initialization time. For non-sharded strategies, you can choose to override this hook or to initialize your model under the
init_module()
context manager.This hook is called during each of fit/val/test/predict stages in the same process, so ensure that implementation of this hook is idempotent, i.e., after the first time the hook is called, subsequent calls to it should be a no-op.
- Return type
None
- configure_optimizers()¶
configures optimizers and learning rate schedulers for model optimization.
- configure_sharded_model()¶
Deprecated.
Use
configure_model()
instead.- Return type
None
- static configure_torch_metrics(torch_metrics)¶
process the torch_metrics parameter.
- Return type
MetricCollection
- cpu()¶
See
torch.nn.Module.cpu()
.- Return type
Self
- cuda(device=None)¶
Moves all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
- Parameters
device (
Union
[int
,device
,None
]) – If specified, all parameters will be copied to that device. If None, the current CUDA device index will be used.- Returns
self
- Return type
Module
- property current_epoch: int¶
The current epoch in the
Trainer
, or 0 if not attached.- Return type
int
- property device: device¶
- Return type
device
- property device_mesh: Optional[DeviceMesh]¶
Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.- Return type
Optional
[ForwardRef
]
- double()¶
See
torch.nn.Module.double()
.- Return type
Self
- property dtype: Union[str, dtype]¶
- Return type
Union
[str
,dtype
]
- dump_patches: bool = False¶
- property epochs_trained¶
- eval()¶
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.This is equivalent with
self.train(False)
.See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns
self
- Return type
Module
- property example_input_array: Optional[Union[Tensor, Tuple, Dict]]¶
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
Union
[Tensor
,Tuple
,Dict
,None
]
- extra_repr()¶
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type
str
- property fabric: Optional[Fabric]¶
- Return type
Optional
[Fabric
]
- float()¶
See
torch.nn.Module.float()
.- Return type
Self
- abstract forward(*args, **kwargs)¶
Same as
torch.nn.Module.forward()
.- Parameters
*args – Whatever you decide to pass into the forward method.
**kwargs – Keyword arguments are also possible.
- Return type
Any
- Returns
Your model’s output
- freeze()¶
Freeze all params for inference.
Example:
model = MyLightningModule(...) model.freeze()
- Return type
None
- get_buffer(target)¶
Return the buffer given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the buffer to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The buffer referenced by
target
- Return type
torch.Tensor
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()¶
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()
for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns
Any extra state to store in the module’s state_dict
- Return type
object
- get_parameter(target)¶
Return the parameter given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the Parameter to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The Parameter referenced by
target
- Return type
torch.nn.Parameter
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)¶
Return the submodule given by
target
if it exists, otherwise throw an error.For example, let’s say you have an
nn.Module
A
that looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )
(The diagram shows an
nn.Module
A
.A
has a nested submodulenet_b
, which itself has two submodulesnet_c
andlinear
.net_c
then has a submoduleconv
.)To check whether or not we have the
linear
submodule, we would callget_submodule("net_b.linear")
. To check whether we have theconv
submodule, we would callget_submodule("net_b.net_c.conv")
.The runtime of
get_submodule
is bounded by the degree of module nesting intarget
. A query againstnamed_modules
achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submodule
should always be used.- Parameters
target (
str
) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns
The submodule referenced by
target
- Return type
torch.nn.Module
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- property global_rank: int¶
The index of the current process across all nodes and devices.
- Return type
int
- property global_step: int¶
Total training batches seen across all epochs.
If no Trainer is attached, this propery is 0.
- Return type
int
- half()¶
See
torch.nn.Module.half()
.- Return type
Self
- property hparams: Union[AttributeDict, MutableMapping]¶
The collection of hyperparameters saved with
save_hyperparameters()
. It is mutable by the user. For the frozen set of initial hyperparameters, usehparams_initial
.- Return type
Union
[AttributeDict
,MutableMapping
]- Returns
Mutable hyperparameters dictionary
- property hparams_initial: AttributeDict¶
The collection of hyperparameters saved with
save_hyperparameters()
. These contents are read-only. Manual updates to the saved hyperparameters can instead be performed throughhparams
.- Returns
immutable initial hyperparameters
- Return type
AttributeDict
- ipu(device=None)¶
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- load_from_checkpoint(checkpoint_path, map_location=None, hparams_file=None, strict=None, **kwargs)¶
Primary way of loading a model from a checkpoint. When Lightning saves a checkpoint it stores the arguments passed to
__init__
in the checkpoint under"hyper_parameters"
.Any arguments specified through **kwargs will override args stored in
"hyper_parameters"
.- Parameters
checkpoint_path (
Union
[str
,Path
,IO
]) – Path to checkpoint. This can also be a URL, or file-like objectmap_location (
Union
[device
,str
,int
,Callable
[[UntypedStorage
,str
],Optional
[UntypedStorage
]],Dict
[Union
[device
,str
,int
],Union
[device
,str
,int
]],None
]) – If your checkpoint saved a GPU model and you now load on CPUs or a different number of GPUs, use this to map to the new setup. The behaviour is the same as intorch.load()
.hparams_file (
Union
[str
,Path
,None
]) –Optional path to a
.yaml
or.csv
file with hierarchical structure as in this example:drop_prob: 0.2 dataloader: batch_size: 32
You most likely won’t need this since Lightning will always save the hyperparameters to the checkpoint. However, if your checkpoint weights don’t have the hyperparameters saved, use this method to pass in a
.yaml
file with the hparams you’d like to use. These will be converted into adict
and passed into yourLightningModule
for use.If your model’s
hparams
argument isNamespace
and.yaml
file has hierarchical structure, you need to refactor your model to treathparams
asdict
.strict (
Optional
[bool
]) – Whether to strictly enforce that the keys incheckpoint_path
match the keys returned by this module’s state dict. Defaults toTrue
unlessLightningModule.strict_loading
is set, in which case it defaults to the value ofLightningModule.strict_loading
.**kwargs – Any extra keyword args needed to init the model. Can also be used to override saved hyperparameter values.
- Return type
Self
- Returns
LightningModule
instance with loaded weights and hyperparameters (if available).
Note
load_from_checkpoint
is a class method. You should use yourLightningModule
class to call it instead of theLightningModule
instance, or aTypeError
will be raised.Note
To ensure all layers can be loaded from the checkpoint, this function will call
configure_model()
directly after instantiating the model if this hook is overridden in your LightningModule. However, note thatload_from_checkpoint
does not support loading sharded checkpoints, and you may run out of memory if the model is too large. In this case, consider loading through the Trainer via.fit(ckpt_path=...)
.Example:
# load weights without mapping ... model = MyLightningModule.load_from_checkpoint('path/to/checkpoint.ckpt') # or load weights mapping all weights from GPU 1 to GPU 0 ... map_location = {'cuda:1':'cuda:0'} model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', map_location=map_location ) # or load weights and hyperparameters from separate files. model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', hparams_file='/path/to/hparams_file.yaml' ) # override some of the params with new values model = MyLightningModule.load_from_checkpoint( PATH, num_layers=128, pretrained_ckpt_path=NEW_PATH, ) # predict pretrained_model.eval() pretrained_model.freeze() y_hat = pretrained_model(x)
- load_state_dict(state_dict, strict=True, assign=False)¶
Copy parameters and buffers from
state_dict
into this module and its descendants.If
strict
isTrue
, then the keys ofstate_dict
must exactly match the keys returned by this module’sstate_dict()
function.Warning
If
assign
isTrue
the optimizer must be created after the call toload_state_dict
unlessget_swap_module_params_on_conversion()
isTrue
.- Parameters
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dict
match the keys returned by this module’sstate_dict()
function. Default:True
assign (bool, optional) – When
False
, the properties of the tensors in the current module are preserved while whenTrue
, the properties of the Tensors in the state dict are preserved. The only exception is therequires_grad
field ofDefault: ``False`
- Returns
- missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided
state_dict
.
- unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided
state_dict
.
- Return type
NamedTuple
withmissing_keys
andunexpected_keys
fields
Note
If a parameter or buffer is registered as
None
and its corresponding key exists instate_dict
,load_state_dict()
will raise aRuntimeError
.
- property local_rank: int¶
The index of the current process within a single node.
- Return type
int
- log(name, value, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, metric_attribute=None, rank_zero_only=False)¶
Log a key, value pair.
Example:
self.log('train_loss', loss)
The default behavior per hook is documented here: extensions/logging:Automatic Logging.
- Parameters
name (
str
) – key to log. Must be identical across all processes if using DDP or any other distributed strategy.value (
Union
[Metric
,Tensor
,int
,float
]) – value to log. Can be afloat
,Tensor
, or aMetric
.prog_bar (
bool
) – ifTrue
logs to the progress bar.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto detach the graph.sync_dist (
bool
) – ifTrue
, reduces the metric across devices. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the DDP group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple dataloaders). If False, user needs to give unique names for each dataloader to not mix the values.batch_size (
Optional
[int
]) – Current batch_size. This will be directly inferred from the loaded batch, but for some data structures you might need to explicitly provide it.metric_attribute (
Optional
[str
]) – To restore the metric state, Lightning requires the reference of thetorchmetrics.Metric
in your model. This is found automatically if it is a model attribute.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- log_dict(dictionary, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, rank_zero_only=False)¶
Log a dictionary of values at once.
Example:
values = {'loss': loss, 'acc': acc, ..., 'metric_n': metric_n} self.log_dict(values)
- Parameters
dictionary (
Union
[Mapping
[str
,Union
[Metric
,Tensor
,int
,float
]],MetricCollection
]) – key value pairs. Keys must be identical across all processes if using DDP or any other distributed strategy. The values can be afloat
,Tensor
,Metric
, orMetricCollection
.prog_bar (
bool
) – ifTrue
logs to the progress base.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step.None
auto-logs for training_step but not validation/test_step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics.None
auto-logs for val/test step but nottraining_step
. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto-detach the graphsync_dist (
bool
) – ifTrue
, reduces the metric across GPUs/TPUs. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the ddp group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple). IfFalse
, user needs to give unique names for each dataloader to not mix values.batch_size (
Optional
[int
]) – Current batch size. This will be directly inferred from the loaded batch, but some data structures might need to explicitly provide it.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- property logger: Optional[Union[Logger, Logger]]¶
Reference to the logger object in the Trainer.
- Return type
Union
[Logger
,Logger
,None
]
- property loggers: Union[List[Logger], List[Logger]]¶
Reference to the list of loggers in the Trainer.
- Return type
Union
[List
[Logger
],List
[Logger
]]
- lr_scheduler_step(scheduler, metric)¶
Override this method to adjust the default way the
Trainer
calls each scheduler. By default, Lightning callsstep()
and as shown in the example for each scheduler based on itsinterval
.- Parameters
scheduler (
Union
[LRScheduler
,ReduceLROnPlateau
]) – Learning rate scheduler.metric (
Optional
[Any
]) – Value of the monitor used for schedulers likeReduceLROnPlateau
.
Examples:
# DEFAULT def lr_scheduler_step(self, scheduler, metric): if metric is None: scheduler.step() else: scheduler.step(metric) # Alternative way to update schedulers if it requires an epoch value def lr_scheduler_step(self, scheduler, metric): scheduler.step(epoch=self.current_epoch)
- Return type
None
- lr_schedulers()¶
Returns the learning rate scheduler(s) that are being used during training. Useful for manual optimization.
- Return type
Union
[None
,List
[Union
[LRScheduler
,ReduceLROnPlateau
]],LRScheduler
,ReduceLROnPlateau
]- Returns
A single scheduler, or a list of schedulers in case multiple ones are present, or
None
if no schedulers were returned inconfigure_optimizers()
.
- manual_backward(loss, *args, **kwargs)¶
Call this directly from your
training_step()
when doing optimizations manually. By using this, Lightning can ensure that all the proper scaling gets applied when using mixed precision.See manual optimization for more examples.
Example:
def training_step(...): opt = self.optimizers() loss = ... opt.zero_grad() # automatically applies scaling, etc... self.manual_backward(loss) opt.step()
- Parameters
loss (
Tensor
) – The tensor on which to compute gradients. Must have a graph attached.*args – Additional positional arguments to be forwarded to
backward()
**kwargs – Additional keyword arguments to be forwarded to
backward()
- Return type
None
- modules()¶
Return an iterator over all modules in the network.
- Yields
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- Return type
Iterator
[Module
]
- named_buffers(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- Return type
Iterator
[Tuple
[str
,Tensor
]]
- named_children()¶
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- Return type
Iterator
[Tuple
[str
,Module
]]
- named_modules(memo=None, prefix='', remove_duplicate=True)¶
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters
memo (
Optional
[Set
[Module
]]) – a memo to store the set of modules already added to the resultprefix (
str
) – a prefix that will be added to the name of the moduleremove_duplicate (
bool
) – whether to remove the duplicated module instances in the result or not
- Yields
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- Return type
Iterator
[Tuple
[str
,Parameter
]]
- on_after_backward()¶
Called after
loss.backward()
and before optimizers are stepped.Note
If using native AMP, the gradients will not be unscaled at this point. Use the
on_before_optimizer_step
if you need the unscaled gradients.- Return type
None
- on_after_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch after it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_after_batch_transfer(self, batch, dataloader_idx): batch['x'] = gpu_transforms(batch['x']) return batch
- on_before_backward(loss)¶
Called before
loss.backward()
.- Parameters
loss (
Tensor
) – Loss divided by number of batches for gradient accumulation and scaled if using AMP.- Return type
None
- on_before_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch before it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_before_batch_transfer(self, batch, dataloader_idx): batch['x'] = transforms(batch['x']) return batch
- on_before_optimizer_step(optimizer)¶
Called before
optimizer.step()
.If using gradient accumulation, the hook is called once the gradients have been accumulated. See: :paramref:`~pytorch_lightning.trainer.trainer.Trainer.accumulate_grad_batches`.
If using AMP, the loss will be unscaled before calling this hook. See these docs for more information on the scaling of gradients.
If clipping gradients, the gradients will not have been clipped yet.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.
Example:
def on_before_optimizer_step(self, optimizer): # example to inspect gradient information in tensorboard if self.trainer.global_step % 25 == 0: # don't make the tf file huge for k, v in self.named_parameters(): self.logger.experiment.add_histogram( tag=k, values=v.grad, global_step=self.trainer.global_step )
- Return type
None
- on_before_zero_grad(optimizer)¶
Called after
training_step()
and beforeoptimizer.zero_grad()
.Called in the training loop after taking an optimizer step and before zeroing grads. Good place to inspect weight information with weights updated.
This is where it is called:
for optimizer in optimizers: out = training_step(...) model.on_before_zero_grad(optimizer) # < ---- called here optimizer.zero_grad() backward()
- Parameters
optimizer (
Optimizer
) – The optimizer for which grads should be zeroed.- Return type
None
- on_fit_end()¶
Called at the very end of fit.
If on DDP it is called on every process
- Return type
None
- on_fit_start()¶
Called at the very beginning of fit.
If on DDP it is called on every process
- Return type
None
- property on_gpu: bool¶
Returns
True
if this model is currently located on a GPU.Useful to set flags around the LightningModule for different CPU vs GPU behavior.
- Return type
bool
- on_load_checkpoint(checkpoint)¶
Called by Lightning to restore your model. If you saved something with
on_save_checkpoint()
this is your chance to restore this.- Parameters
checkpoint (
Dict
[str
,Any
]) – Loaded checkpoint
Example:
def on_load_checkpoint(self, checkpoint): # 99% of the time you don't need to implement this method self.something_cool_i_want_to_save = checkpoint['something_cool_i_want_to_save']
Note
Lightning auto-restores global step, epoch, and train state including amp scaling. There is no need for you to restore anything regarding training.
- Return type
None
- on_predict_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop after the batch.
- Parameters
outputs (
Optional
[Any
]) – The outputs of predict_step(x)batch (
Any
) – The batched data as it is returned by the prediction DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_start()¶
Called at the beginning of predicting.
- Return type
None
- on_predict_model_eval()¶
Called when the predict loop starts.
The predict loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior.- Return type
None
- on_predict_start()¶
Called at the beginning of predicting.
- Return type
None
- on_save_checkpoint(checkpoint)¶
Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
- Parameters
checkpoint (
Dict
[str
,Any
]) – The full checkpoint dictionary before it gets dumped to a file. Implementations of this hook can insert additional data into this dictionary.
Example:
def on_save_checkpoint(self, checkpoint): # 99% of use cases you don't need to implement this method checkpoint['something_cool_i_want_to_save'] = my_cool_pickable_object
Note
Lightning saves all aspects of training (epoch, global step, etc…) including amp scaling. There is no need for you to store anything about training.
- Return type
None
- on_test_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the test loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of test_step(x)batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the test loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_end()¶
Called at the end of testing.
- Return type
None
- on_test_epoch_end()¶
Called in the test loop at the very end of the epoch.
- Return type
None
- on_test_epoch_start()¶
Called in the test loop at the very beginning of the epoch.
- Return type
None
- on_test_model_eval()¶
Called when the test loop starts.
The test loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_test_model_train()
.- Return type
None
- on_test_model_train()¶
Called when the test loop ends.
The test loop by default restores the training mode of the LightningModule to what it was before starting testing. Override this hook to change the behavior. See also
on_test_model_eval()
.- Return type
None
- on_test_start()¶
Called at the beginning of testing.
- Return type
None
- on_train_batch_end(outputs, batch, batch_idx)¶
Called in the training loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of training_step(x)batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
Note
The value
outputs["loss"]
here will be the normalized value w.r.taccumulate_grad_batches
of the loss returned fromtraining_step
.- Return type
None
- on_train_batch_start(batch, batch_idx)¶
Called in the training loop before anything happens for that batch.
If you return -1 here, you will skip training for the rest of the current epoch.
- Parameters
batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
- Return type
Optional
[int
]
- on_train_end()¶
Called at the end of training before logger experiment is closed.
- Return type
None
- on_train_epoch_end()¶
Called in the training loop at the very end of the epoch.
To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the
LightningModule
and access them in this hook:class MyLightningModule(L.LightningModule): def __init__(self): super().__init__() self.training_step_outputs = [] def training_step(self): loss = ... self.training_step_outputs.append(loss) return loss def on_train_epoch_end(self): # do something with all training_step outputs, for example: epoch_mean = torch.stack(self.training_step_outputs).mean() self.log("training_epoch_mean", epoch_mean) # free up the memory self.training_step_outputs.clear()
- on_train_epoch_start()¶
Called in the training loop at the very beginning of the epoch.
- Return type
None
- on_train_start()¶
Called at the beginning of training after sanity check.
- Return type
None
- on_validation_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of validation_step(x)batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_end()¶
Called at the end of validation.
- Return type
None
- on_validation_epoch_end()¶
Called in the validation loop at the very end of the epoch.
- on_validation_epoch_start()¶
Called in the validation loop at the very beginning of the epoch.
- Return type
None
- on_validation_model_eval()¶
Called when the validation loop starts.
The validation loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_validation_model_train()
.- Return type
None
- on_validation_model_train()¶
Called when the validation loop ends.
The validation loop by default restores the training mode of the LightningModule to what it was before starting validation. Override this hook to change the behavior. See also
on_validation_model_eval()
.- Return type
None
- on_validation_model_zero_grad()¶
Called by the training loop to release gradients before entering the validation loop.
- Return type
None
- on_validation_start()¶
Called at the beginning of validation.
- Return type
None
- optimizer_step(epoch, batch_idx, optimizer, optimizer_closure=None)¶
Override this method to adjust the default way the
Trainer
calls the optimizer.By default, Lightning calls
step()
andzero_grad()
as shown in the example. This method (andzero_grad()
) won’t be called during the accumulation phase whenTrainer(accumulate_grad_batches != 1)
. Overriding this hook has no benefit with manual optimization.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Union
[Optimizer
,LightningOptimizer
]) – A PyTorch optimizeroptimizer_closure (
Optional
[Callable
[[],Any
]]) – The optimizer closure. This closure must be executed as it includes the calls totraining_step()
,optimizer.zero_grad()
, andbackward()
.
Examples:
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_closure): # Add your custom logic to run directly before `optimizer.step()` optimizer.step(closure=optimizer_closure) # Add your custom logic to run directly after `optimizer.step()`
- Return type
None
- optimizer_zero_grad(epoch, batch_idx, optimizer)¶
Override this method to change the default behaviour of
optimizer.zero_grad()
.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Optimizer
) – A PyTorch optimizer
Examples:
# DEFAULT def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad() # Set gradients to `None` instead of zero to improve performance (not required on `torch>=2.0.0`). def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad(set_to_none=True)
See
torch.optim.Optimizer.zero_grad()
for the explanation of the above example.- Return type
None
- optimizers(use_pl_optimizer=True)¶
Returns the optimizer(s) that are being used during training. Useful for manual optimization.
- Parameters
use_pl_optimizer (
bool
) – IfTrue
, will wrap the optimizer(s) in aLightningOptimizer
for automatic handling of precision, profiling, and counting of step calls for proper logging and checkpointing. It specifically wraps thestep
method and custom optimizers that don’t have this method are not supported.- Return type
Union
[Optimizer
,LightningOptimizer
,_FabricOptimizer
,List
[Optimizer
],List
[LightningOptimizer
],List
[_FabricOptimizer
]]- Returns
A single optimizer, or a list of optimizers in case multiple ones are present.
- property output_chunk_length: Optional[int]¶
Number of time steps predicted at once by the model.
- Return type
Optional
[int
]
- parameters(recurse=True)¶
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Parameter
]
- predict_dataloader()¶
An iterable or collection of iterables specifying prediction samples.
For more information about multiple dataloaders, see this section.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.predict()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
- Return type
Any
- Returns
A
torch.utils.data.DataLoader
or a sequence of them specifying prediction samples.
- predict_step(batch, batch_idx, dataloader_idx=None)¶
performs the prediction step
- batch
output of Darts’
InferenceDataset
- tuple of(past_target, past_covariates, historic_future_covariates, future_covariates, future_past_covariates, input time series, prediction start time step)
- batch_idx
the batch index of the current batch
- dataloader_idx
the dataloader index
- Return type
Sequence
[TimeSeries
]
- prepare_data()¶
Use this to download and prepare data. Downloading and saving data with multiple processes (distributed settings) will result in corrupted data. Lightning ensures this method is called only within a single process, so you can safely add your downloading logic within.
Warning
DO NOT set state to the model (use
setup
instead) since this is NOT called on every deviceExample:
def prepare_data(self): # good download_data() tokenize() etc() # bad self.split = data_split self.some_state = some_other_state()
In a distributed environment,
prepare_data
can be called in two ways (using prepare_data_per_node)Once per node. This is the default and is only called on LOCAL_RANK=0.
Once in total. Only called on GLOBAL_RANK=0.
Example:
# DEFAULT # called once per node on LOCAL_RANK=0 of that node class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = True # call on GLOBAL_RANK=0 (great for shared file systems) class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = False
This is called before requesting the dataloaders:
model.prepare_data() initialize_distributed() model.setup(stage) model.train_dataloader() model.val_dataloader() model.test_dataloader() model.predict_dataloader()
- Return type
None
- print(*args, **kwargs)¶
Prints only from process 0. Use this in any distributed mode to log only once.
- Parameters
*args – The thing to print. The same as for Python’s built-in print function.
**kwargs – The same as for Python’s built-in print function.
Example:
def forward(self, x): self.print(x, 'in forward')
- Return type
None
- register_backward_hook(hook)¶
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()
and the behavior of this function will change in future versions.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_buffer(name, tensor, persistent=True)¶
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_mean
is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistent
toFalse
. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict
.Buffers can be accessed as attributes using given names.
- Parameters
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None
, then operations that run on buffers, such ascuda
, are ignored. IfNone
, the buffer is not included in the module’sstate_dict
.persistent (bool) – whether the buffer is part of this module’s
state_dict
.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- Return type
None
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)¶
Register a forward hook on the module.
The hook will be called every time after
forward()
has computed an output.If
with_kwargs
isFalse
or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()
is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargs
isTrue
, the forward hook will be passed thekwargs
given to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True
, the providedhook
will be fired before all existingforward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward
hooks on thistorch.nn.modules.Module
. Note that globalforward
hooks registered withregister_module_forward_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If
True
, thehook
will be passed the kwargs given to the forward function. Default:False
always_call (bool) – If
True
thehook
will be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)¶
Register a forward pre-hook on the module.
The hook will be called every time before
forward()
is invoked.If
with_kwargs
is false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargs
is true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingforward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward_pre
hooks on thistorch.nn.modules.Module
. Note that globalforward_pre
hooks registered withregister_module_forward_pre_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If true, the
hook
will be passed the kwargs given to the forward function. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)¶
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_input
andgrad_output
are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_input
in subsequent computations.grad_input
will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_input
andgrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward
hooks on thistorch.nn.modules.Module
. Note that globalbackward
hooks registered withregister_module_full_backward_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)¶
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_output
is a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_output
in subsequent computations. Entries ingrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Note that globalbackward_pre
hooks registered withregister_module_full_backward_pre_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)¶
Register a post hook to be run after module’s
load_state_dict
is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
module
argument is the current module that this hook is registered on, and theincompatible_keys
argument is aNamedTuple
consisting of attributesmissing_keys
andunexpected_keys
.missing_keys
is alist
ofstr
containing the missing keys andunexpected_keys
is alist
ofstr
containing the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()
withstrict=True
are affected by modifications the hook makes tomissing_keys
orunexpected_keys
, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True
, and clearing out both missing and unexpected keys will avoid an error.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_module(name, module)¶
Alias for
add_module()
.- Return type
None
- register_parameter(name, param)¶
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None
, then operations that run on parameters, such ascuda
, are ignored. IfNone
, the parameter is not included in the module’sstate_dict
.
- Return type
None
- register_state_dict_pre_hook(hook)¶
Register a pre-hook for the
state_dict()
method.These hooks will be called with arguments:
self
,prefix
, andkeep_vars
before callingstate_dict
onself
. The registered hooks can be used to perform pre-processing before thestate_dict
call is made.
- requires_grad_(requires_grad=True)¶
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_grad
attributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True
.- Returns
self
- Return type
Module
- save_hyperparameters(*args, ignore=None, frame=None, logger=True)¶
Save arguments to
hparams
attribute.- Parameters
args (
Any
) – single object of dict, NameSpace or OmegaConf or string names or arguments from class__init__
ignore (
Union
[str
,Sequence
[str
],None
]) – an argument name or a list of argument names from class__init__
to be ignoredframe (
Optional
[frame
]) – a frame object. Default is Nonelogger (
bool
) – Whether to send the hyperparameters to the logger. Default: True
- Example::
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # manually assign arguments ... self.save_hyperparameters('arg1', 'arg3') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class AutomaticArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # equivalent automatic ... self.save_hyperparameters() ... def forward(self, *args, **kwargs): ... ... >>> model = AutomaticArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg2": abc "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class SingleArgModel(HyperparametersMixin): ... def __init__(self, params): ... super().__init__() ... # manually assign single argument ... self.save_hyperparameters(params) ... def forward(self, *args, **kwargs): ... ... >>> model = SingleArgModel(Namespace(p1=1, p2='abc', p3=3.14)) >>> model.hparams "p1": 1 "p2": abc "p3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # pass argument(s) to ignore as a string or in a list ... self.save_hyperparameters(ignore='arg2') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
- Return type
None
- set_extra_state(state)¶
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()
to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()
for your module if you need to store extra state within its state_dict.- Parameters
state (dict) – Extra state from the state_dict
- Return type
None
- set_mc_dropout(active)¶
- set_predict_parameters(n, num_samples, roll_size, batch_size, n_jobs, predict_likelihood_parameters, mc_dropout)¶
to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
- Return type
None
- setup(stage)¶
Called at the beginning of fit (train + validate), validate, test, or predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
Example:
class LitModel(...): def __init__(self): self.l1 = None def prepare_data(self): download_data() tokenize() # don't do this self.something = else def setup(self, stage): data = load_data(...) self.l1 = nn.Linear(28, data.num_classes)
- Return type
None
See
torch.Tensor.share_memory_()
.- Return type
~T
- state_dict(*args, destination=None, prefix='', keep_vars=False)¶
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
None
are not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()
also accepts positional arguments fordestination
,prefix
andkeep_vars
in order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destination
as it is not designed for end-users.- Parameters
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDict
will be created and returned. Default:None
.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''
.keep_vars (bool, optional) – by default the
Tensor
s returned in the state dict are detached from autograd. If it’s set toTrue
, detaching will not be performed. Default:False
.
- Returns
a dictionary containing a whole state of the module
- Return type
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- property strict_loading: bool¶
Determines how Lightning loads this model using .load_state_dict(…, strict=model.strict_loading).
- Return type
bool
- property supports_probabilistic_prediction: bool¶
- Return type
bool
- teardown(stage)¶
Called at the end of fit (train + validate), validate, test, or predict.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
- Return type
None
- test_dataloader()¶
An iterable or collection of iterables specifying test samples.
For more information about multiple dataloaders, see this section.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
test()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
Note
If you don’t need a test dataset and a
test_step()
, you don’t need to implement this method.- Return type
Any
- test_step(*args, **kwargs)¶
Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.
- Parameters
batch – The output of your data iterable, normally a
DataLoader
.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- Return type
Union
[Tensor
,Mapping
[str
,Any
],None
]- Returns
Tensor
- The loss tensordict
- A dictionary. Can include any keys, but must include the key'loss'
.None
- Skip to the next batch.
# if you have one test dataloader: def test_step(self, batch, batch_idx): ... # if you have multiple test dataloaders: def test_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single test dataset def test_step(self, batch, batch_idx): x, y = batch # implement your own out = self(x) loss = self.loss(out, y) # log 6 example images # or generated text... or whatever sample_imgs = x[:6] grid = torchvision.utils.make_grid(sample_imgs) self.logger.experiment.add_image('example_images', grid, 0) # calculate acc labels_hat = torch.argmax(out, dim=1) test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'test_loss': loss, 'test_acc': test_acc})
If you pass in multiple test dataloaders,
test_step()
will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.# CASE 2: multiple test dataloaders def test_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. ...
Note
If you don’t need to test you don’t need to implement this method.
Note
When the
test_step()
is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.
- to(*args, **kwargs)¶
See
torch.nn.Module.to()
.- Return type
Self
- to_dtype(dtype)¶
Cast module precision (float32 by default) to another precision.
- to_empty(*, device, recurse=True)¶
Move the parameters and buffers to the specified device without copying storage.
- Parameters
device (
torch.device
) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns
self
- Return type
Module
- to_onnx(file_path, input_sample=None, **kwargs)¶
Saves the model in ONNX format.
- Parameters
file_path (
Union
[str
,Path
]) – The path of the file the onnx model should be saved to.input_sample (
Optional
[Any
]) – An input for tracing. Default: None (Use self.example_input_array)**kwargs – Will be passed to torch.onnx.export function.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1) model = SimpleModel() input_sample = torch.randn(1, 64) model.to_onnx("export.onnx", input_sample, export_params=True)
- Return type
None
- to_torchscript(file_path=None, method='script', example_inputs=None, **kwargs)¶
By default compiles the whole model to a
ScriptModule
. If you want to use tracing, please provided the argumentmethod='trace'
and make sure that either the example_inputs argument is provided, or the model hasexample_input_array
set. If you would like to customize the modules that are scripted you should override this method. In case you want to return multiple modules, we recommend using a dictionary.- Parameters
file_path (
Union
[str
,Path
,None
]) – Path where to save the torchscript. Default: None (no file saved).method (
Optional
[str
]) – Whether to use TorchScript’s script or trace method. Default: ‘script’example_inputs (
Optional
[Any
]) – An input to be used to do tracing when method is set to ‘trace’. Default: None (usesexample_input_array
)**kwargs – Additional arguments that will be passed to the
torch.jit.script()
ortorch.jit.trace()
function.
Note
Requires the implementation of the
forward()
method.The exported script will be set to evaluation mode.
It is recommended that you install the latest supported version of PyTorch to use this feature without limitations. See also the
torch.jit
documentation for supported features.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1))) model = SimpleModel() model.to_torchscript(file_path="model.pt") torch.jit.save(model.to_torchscript( file_path="model_trace.pt", method='trace', example_inputs=torch.randn(1, 64)) )
- Return type
Union
[ScriptModule
,Dict
[str
,ScriptModule
]]- Returns
This LightningModule as a torchscript, regardless of whether file_path is defined or not.
- toggle_optimizer(optimizer)¶
Makes sure only the gradients of the current optimizer’s parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
It works with
untoggle_optimizer()
to make sureparam_requires_grad_state
is properly reset.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to toggle.- Return type
None
- train(mode=True)¶
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.- Parameters
mode (bool) – whether to set training mode (
True
) or evaluation mode (False
). Default:True
.- Returns
self
- Return type
Module
- train_dataloader()¶
An iterable or collection of iterables specifying training samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
fit()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
- Return type
Any
- property trainer: Trainer¶
- Return type
Trainer
- training: bool¶
- training_step(train_batch, batch_idx)¶
performs the training step
- Return type
Tensor
- transfer_batch_to_device(batch, device, dataloader_idx)¶
Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.The data types listed below (and any arbitrary nesting of them) are supported out of the box:
torch.Tensor
or anything that implements .to(…)list
dict
tuple
For anything else, you need to define how the data is moved to the target device (CPU, GPU, TPU, …).
Note
This hook should only transfer the data and not modify it, nor should it move the data to any other device than the one passed in as argument (unless you know what you are doing). To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be transferred to a new device.device (
device
) – The target device as defined in PyTorch.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A reference to the data on the new device.
Example:
def transfer_batch_to_device(self, batch, device, dataloader_idx): if isinstance(batch, CustomBatch): # move all tensors in your custom data structure to the device batch.samples = batch.samples.to(device) batch.targets = batch.targets.to(device) elif dataloader_idx == 0: # skip device transfer for the first dataloader or anything you wish pass else: batch = super().transfer_batch_to_device(batch, device, dataloader_idx) return batch
See also
move_data_to_device()
apply_to_collection()
- type(dst_type)¶
See
torch.nn.Module.type()
.- Return type
Self
- unfreeze()¶
Unfreeze all parameters for training.
model = MyLightningModule(...) model.unfreeze()
- Return type
None
- untoggle_optimizer(optimizer)¶
Resets the state of required gradients that were toggled with
toggle_optimizer()
.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to untoggle.- Return type
None
- val_dataloader()¶
An iterable or collection of iterables specifying validation samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.fit()
validate()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
Note
If you don’t need a validation dataset and a
validation_step()
, you don’t need to implement this method.- Return type
Any
- validation_step(val_batch, batch_idx)¶
performs the validation step
- Return type
Tensor
- xpu(device=None)¶
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- zero_grad(set_to_none=True)¶
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizer
for more context.- Parameters
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()
for details.- Return type
None
- class darts.models.forecasting.pl_forecasting_module.PLForecastingModule(input_chunk_length, output_chunk_length, output_chunk_shift=0, train_sample_shape=None, loss_fn=MSELoss(), torch_metrics=None, likelihood=None, optimizer_cls=<class 'torch.optim.adam.Adam'>, optimizer_kwargs=None, lr_scheduler_cls=None, lr_scheduler_kwargs=None, use_reversible_instance_norm=False)[source]¶
Bases:
LightningModule
,ABC
PyTorch Lightning-based Forecasting Module.
This class is meant to be inherited to create a new PyTorch Lightning-based forecasting module. When subclassing this class, please make sure to add the following methods with the given signatures:
PLForecastingModule.__init__()
PLForecastingModule._produce_train_output()
PLForecastingModule._get_batch_prediction()
In subclass MyModel’s
__init__()
function callsuper(MyModel, self).__init__(**kwargs)
wherekwargs
are the parameters ofPLForecastingModule
.- Parameters
input_chunk_length (
int
) – Number of time steps in the past to take as a model input (per chunk). Applies to the target series, and past and/or future covariates (if the model supports it).output_chunk_length (
int
) – Number of time steps predicted at once (per chunk) by the internal model. Also, the number of future values from future covariates to use as a model input (if the model supports future covariates). It is not the same as forecast horizon n used in predict(), which is the desired number of prediction points generated using either a one-shot- or autoregressive forecast. Setting n <= output_chunk_length prevents auto-regression. This is useful when the covariates don’t extend far enough into the future, or to prohibit the model from using future values of past and / or future covariates for prediction (depending on the model’s covariate support).train_sample_shape (
Optional
[Tuple
]) – Shape of the model’s input, used to instantiate model without callingfit_from_dataset
and perform sanity check on new training/inference datasets used for re-training or prediction.loss_fn (
_Loss
) – PyTorch loss function used for training. This parameter will be ignored for probabilistic models if thelikelihood
parameter is specified. Default:torch.nn.MSELoss()
.torch_metrics (
Union
[Metric
,MetricCollection
,None
]) – A torch metric or aMetricCollection
used for evaluation. A full list of available metrics can be found at https://torchmetrics.readthedocs.io/en/latest/. Default:None
.likelihood (
Optional
[Likelihood
]) – One of Darts’Likelihood
models to be used for probabilistic forecasts. Default:None
.optimizer_cls (
Optimizer
) – The PyTorch optimizer class to be used. Default:torch.optim.Adam
.optimizer_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch optimizer (e.g.,{'lr': 1e-3}
for specifying a learning rate). Otherwise the default values of the selectedoptimizer_cls
will be used. Default:None
.lr_scheduler_cls (
Optional
[_LRScheduler
]) – Optionally, the PyTorch learning rate scheduler class to be used. SpecifyingNone
corresponds to using a constant learning rate. Default:None
.lr_scheduler_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch learning rate scheduler. Default:None
.use_reversible_instance_norm (
bool
) – Whether to use reversible instance normalization RINorm against distribution shift as shown in [1]. It is only applied to the features of the target series and not the covariates.
References
- 1
T. Kim et al. “Reversible Instance Normalization for Accurate Time-Series Forecasting against Distribution Shift”, https://openreview.net/forum?id=cGDAkQo1C0p
Attributes
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.The current epoch in the
Trainer
, or 0 if not attached.Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.The example input array is a specification of what the module can consume in the
forward()
method.The index of the current process across all nodes and devices.
Total training batches seen across all epochs.
The collection of hyperparameters saved with
save_hyperparameters()
.The collection of hyperparameters saved with
save_hyperparameters()
.The index of the current process within a single node.
Reference to the logger object in the Trainer.
Reference to the list of loggers in the Trainer.
Returns
True
if this model is currently located on a GPU.Number of time steps predicted at once by the model.
Determines how Lightning loads this model using .load_state_dict(..., strict=model.strict_loading).
device
dtype
epochs_trained
fabric
supports_probabilistic_prediction
trainer
Methods
add_module
(name, module)Add a child module to the current module.
all_gather
(data[, group, sync_grads])Gather tensors or collections of tensors from multiple processes.
apply
(fn)Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.backward
(loss, *args, **kwargs)Called to perform backward on the loss returned in
training_step()
.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Return an iterator over module buffers.
children
()Return an iterator over immediate children modules.
clip_gradients
(optimizer[, ...])Handles gradient clipping internally.
compile
(*args, **kwargs)Compile this Module's forward using
torch.compile()
.Configure model-specific callbacks.
configure_gradient_clipping
(optimizer[, ...])Perform gradient clipping for the optimizer parameters.
Hook to create modules in a strategy and precision aware context.
configures optimizers and learning rate schedulers for model optimization.
Deprecated.
configure_torch_metrics
(torch_metrics)process the torch_metrics parameter.
cpu
()See
torch.nn.Module.cpu()
.cuda
([device])Moves all model parameters and buffers to the GPU.
double
()See
torch.nn.Module.double()
.eval
()Set the module in evaluation mode.
Set the extra representation of the module.
float
()See
torch.nn.Module.float()
.forward
(*args, **kwargs)Same as
torch.nn.Module.forward()
.freeze
()Freeze all params for inference.
get_buffer
(target)Return the buffer given by
target
if it exists, otherwise throw an error.Return any extra state to include in the module's state_dict.
get_parameter
(target)Return the parameter given by
target
if it exists, otherwise throw an error.get_submodule
(target)Return the submodule given by
target
if it exists, otherwise throw an error.half
()See
torch.nn.Module.half()
.ipu
([device])Move all model parameters and buffers to the IPU.
load_from_checkpoint
(checkpoint_path[, ...])Primary way of loading a model from a checkpoint.
load_state_dict
(state_dict[, strict, assign])Copy parameters and buffers from
state_dict
into this module and its descendants.log
(name, value[, prog_bar, logger, ...])Log a key, value pair.
log_dict
(dictionary[, prog_bar, logger, ...])Log a dictionary of values at once.
lr_scheduler_step
(scheduler, metric)Override this method to adjust the default way the
Trainer
calls each scheduler.Returns the learning rate scheduler(s) that are being used during training.
manual_backward
(loss, *args, **kwargs)Call this directly from your
training_step()
when doing optimizations manually.modules
()Return an iterator over all modules in the network.
named_buffers
([prefix, recurse, ...])Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse, ...])Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
Called after
loss.backward()
and before optimizers are stepped.on_after_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch after it is transferred to the device.
on_before_backward
(loss)Called before
loss.backward()
.on_before_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch before it is transferred to the device.
on_before_optimizer_step
(optimizer)Called before
optimizer.step()
.on_before_zero_grad
(optimizer)Called after
training_step()
and beforeoptimizer.zero_grad()
.Called at the very end of fit.
Called at the very beginning of fit.
on_load_checkpoint
(checkpoint)Called by Lightning to restore your model.
on_predict_batch_end
(outputs, batch, batch_idx)Called in the predict loop after the batch.
on_predict_batch_start
(batch, batch_idx[, ...])Called in the predict loop before anything happens for that batch.
Called at the end of predicting.
Called at the end of predicting.
Called at the beginning of predicting.
Called when the predict loop starts.
Called at the beginning of predicting.
on_save_checkpoint
(checkpoint)Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
on_test_batch_end
(outputs, batch, batch_idx)Called in the test loop after the batch.
on_test_batch_start
(batch, batch_idx[, ...])Called in the test loop before anything happens for that batch.
Called at the end of testing.
Called in the test loop at the very end of the epoch.
Called in the test loop at the very beginning of the epoch.
Called when the test loop starts.
Called when the test loop ends.
Called at the beginning of testing.
on_train_batch_end
(outputs, batch, batch_idx)Called in the training loop after the batch.
on_train_batch_start
(batch, batch_idx)Called in the training loop before anything happens for that batch.
Called at the end of training before logger experiment is closed.
Called in the training loop at the very end of the epoch.
Called in the training loop at the very beginning of the epoch.
Called at the beginning of training after sanity check.
on_validation_batch_end
(outputs, batch, ...)Called in the validation loop after the batch.
on_validation_batch_start
(batch, batch_idx)Called in the validation loop before anything happens for that batch.
Called at the end of validation.
Called in the validation loop at the very end of the epoch.
Called in the validation loop at the very beginning of the epoch.
Called when the validation loop starts.
Called when the validation loop ends.
Called by the training loop to release gradients before entering the validation loop.
Called at the beginning of validation.
optimizer_step
(epoch, batch_idx, optimizer)Override this method to adjust the default way the
Trainer
calls the optimizer.optimizer_zero_grad
(epoch, batch_idx, optimizer)Override this method to change the default behaviour of
optimizer.zero_grad()
.optimizers
([use_pl_optimizer])Returns the optimizer(s) that are being used during training.
parameters
([recurse])Return an iterator over module parameters.
An iterable or collection of iterables specifying prediction samples.
predict_step
(batch, batch_idx[, dataloader_idx])performs the prediction step
Use this to download and prepare data.
print
(*args, **kwargs)Prints only from process 0.
register_backward_hook
(hook)Register a backward hook on the module.
register_buffer
(name, tensor[, persistent])Add a buffer to the module.
register_forward_hook
(hook, *[, prepend, ...])Register a forward hook on the module.
register_forward_pre_hook
(hook, *[, ...])Register a forward pre-hook on the module.
register_full_backward_hook
(hook[, prepend])Register a backward hook on the module.
register_full_backward_pre_hook
(hook[, prepend])Register a backward pre-hook on the module.
Register a post hook to be run after module's
load_state_dict
is called.register_module
(name, module)Alias for
add_module()
.register_parameter
(name, param)Add a parameter to the module.
Register a pre-hook for the
state_dict()
method.requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
save_hyperparameters
(*args[, ignore, frame, ...])Save arguments to
hparams
attribute.set_extra_state
(state)Set extra state contained in the loaded state_dict.
set_predict_parameters
(n, num_samples, ...)to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
setup
(stage)Called at the beginning of fit (train + validate), validate, test, or predict.
See
torch.Tensor.share_memory_()
.state_dict
(*args[, destination, prefix, ...])Return a dictionary containing references to the whole state of the module.
teardown
(stage)Called at the end of fit (train + validate), validate, test, or predict.
An iterable or collection of iterables specifying test samples.
test_step
(*args, **kwargs)Operates on a single batch of data from the test set.
to
(*args, **kwargs)See
torch.nn.Module.to()
.to_dtype
(dtype)Cast module precision (float32 by default) to another precision.
to_empty
(*, device[, recurse])Move the parameters and buffers to the specified device without copying storage.
to_onnx
(file_path[, input_sample])Saves the model in ONNX format.
to_torchscript
([file_path, method, ...])By default compiles the whole model to a
ScriptModule
.toggle_optimizer
(optimizer)Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
train
([mode])Set the module in training mode.
An iterable or collection of iterables specifying training samples.
training_step
(train_batch, batch_idx)performs the training step
transfer_batch_to_device
(batch, device, ...)Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.type
(dst_type)See
torch.nn.Module.type()
.unfreeze
()Unfreeze all parameters for training.
untoggle_optimizer
(optimizer)Resets the state of required gradients that were toggled with
toggle_optimizer()
.An iterable or collection of iterables specifying validation samples.
validation_step
(val_batch, batch_idx)performs the validation step
xpu
([device])Move all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Reset gradients of all model parameters.
__call__
set_mc_dropout
- CHECKPOINT_HYPER_PARAMS_KEY = 'hyper_parameters'¶
- CHECKPOINT_HYPER_PARAMS_NAME = 'hparams_name'¶
- CHECKPOINT_HYPER_PARAMS_TYPE = 'hparams_type'¶
- T_destination¶
alias of TypeVar(‘T_destination’, bound=
Dict
[str
,Any
])
- add_module(name, module)¶
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- Return type
None
- all_gather(data, group=None, sync_grads=False)¶
Gather tensors or collections of tensors from multiple processes.
This method needs to be called on all processes and the tensors need to have the same shape across all processes, otherwise your program will stall forever.
- Parameters
data (
Union
[Tensor
,Dict
,List
,Tuple
]) – int, float, tensor of shape (batch, …), or a (possibly nested) collection thereof.group (
Optional
[Any
]) – the process group to gather results from. Defaults to all processes (world)sync_grads (
bool
) – flag that allows users to synchronize gradients for the all_gather operation
- Return type
Union
[Tensor
,Dict
,List
,Tuple
]- Returns
A tensor of shape (world_size, batch, …), or if the input was a collection the output will also be a collection with tensors of this shape. For the special case where world_size is 1, no additional dimension is added to the tensor(s).
- apply(fn)¶
Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters
fn (
Module
-> None) – function to be applied to each submodule- Returns
self
- Return type
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- property automatic_optimization: bool¶
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.- Return type
bool
- backward(loss, *args, **kwargs)¶
Called to perform backward on the loss returned in
training_step()
. Override this hook with your own implementation if you need to.- Parameters
loss (
Tensor
) – The loss tensor returned bytraining_step()
. If gradient accumulation is used, the loss here holds the normalized value (scaled by 1 / accumulation steps).
Example:
def backward(self, loss): loss.backward()
- Return type
None
- bfloat16()¶
Casts all floating point parameters and buffers to
bfloat16
datatype.Note
This method modifies the module in-place.
- Returns
self
- Return type
Module
- buffers(recurse=True)¶
Return an iterator over module buffers.
- Parameters
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Tensor
]
- call_super_init: bool = False¶
- children()¶
Return an iterator over immediate children modules.
- Yields
Module – a child module
- Return type
Iterator
[Module
]
- clip_gradients(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Handles gradient clipping internally.
Note
Do not override this method. If you want to customize gradient clipping, consider using
configure_gradient_clipping()
method.For manual optimization (
self.automatic_optimization = False
), if you want to use gradient clipping, consider callingself.clip_gradients(opt, gradient_clip_val=0.5, gradient_clip_algorithm="norm")
manually in the training step.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. Passgradient_clip_algorithm="value"
to clip by value, andgradient_clip_algorithm="norm"
to clip by norm.
- Return type
None
- compile(*args, **kwargs)¶
Compile this Module’s forward using
torch.compile()
.This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile()
.See
torch.compile()
for details on the arguments for this function.
- configure_callbacks()¶
Configure model-specific callbacks. When the model gets attached, e.g., when
.fit()
or.test()
gets called, the list or a callback returned here will be merged with the list of callbacks passed to the Trainer’scallbacks
argument. If a callback returned here has the same type as one or several callbacks already present in the Trainer’s callbacks list, it will take priority and replace them. In addition, Lightning will make sureModelCheckpoint
callbacks run last.- Return type
Union
[Sequence
[Callback
],Callback
]- Returns
A callback or a list of callbacks which will extend the list of callbacks in the Trainer.
Example:
def configure_callbacks(self): early_stop = EarlyStopping(monitor="val_acc", mode="max") checkpoint = ModelCheckpoint(monitor="val_loss") return [early_stop, checkpoint]
- configure_gradient_clipping(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Perform gradient clipping for the optimizer parameters. Called before
optimizer_step()
.- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients. By default, value passed in Trainer will be available here.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. By default, value passed in Trainer will be available here.
Example:
def configure_gradient_clipping(self, optimizer, gradient_clip_val, gradient_clip_algorithm): # Implement your own custom logic to clip gradients # You can call `self.clip_gradients` with your settings: self.clip_gradients( optimizer, gradient_clip_val=gradient_clip_val, gradient_clip_algorithm=gradient_clip_algorithm )
- Return type
None
- configure_model()¶
Hook to create modules in a strategy and precision aware context.
This is particularly useful for when using sharded strategies (FSDP and DeepSpeed), where we’d like to shard the model instantly to save memory and initialization time. For non-sharded strategies, you can choose to override this hook or to initialize your model under the
init_module()
context manager.This hook is called during each of fit/val/test/predict stages in the same process, so ensure that implementation of this hook is idempotent, i.e., after the first time the hook is called, subsequent calls to it should be a no-op.
- Return type
None
- configure_optimizers()[source]¶
configures optimizers and learning rate schedulers for model optimization.
- configure_sharded_model()¶
Deprecated.
Use
configure_model()
instead.- Return type
None
- static configure_torch_metrics(torch_metrics)[source]¶
process the torch_metrics parameter.
- Return type
MetricCollection
- cpu()¶
See
torch.nn.Module.cpu()
.- Return type
Self
- cuda(device=None)¶
Moves all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
- Parameters
device (
Union
[int
,device
,None
]) – If specified, all parameters will be copied to that device. If None, the current CUDA device index will be used.- Returns
self
- Return type
Module
- property current_epoch: int¶
The current epoch in the
Trainer
, or 0 if not attached.- Return type
int
- property device: device¶
- Return type
device
- property device_mesh: Optional[DeviceMesh]¶
Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.- Return type
Optional
[ForwardRef
]
- double()¶
See
torch.nn.Module.double()
.- Return type
Self
- property dtype: Union[str, dtype]¶
- Return type
Union
[str
,dtype
]
- dump_patches: bool = False¶
- property epochs_trained¶
- eval()¶
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.This is equivalent with
self.train(False)
.See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns
self
- Return type
Module
- property example_input_array: Optional[Union[Tensor, Tuple, Dict]]¶
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
Union
[Tensor
,Tuple
,Dict
,None
]
- extra_repr()¶
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type
str
- property fabric: Optional[Fabric]¶
- Return type
Optional
[Fabric
]
- float()¶
See
torch.nn.Module.float()
.- Return type
Self
- abstract forward(*args, **kwargs)[source]¶
Same as
torch.nn.Module.forward()
.- Parameters
*args – Whatever you decide to pass into the forward method.
**kwargs – Keyword arguments are also possible.
- Return type
Any
- Returns
Your model’s output
- freeze()¶
Freeze all params for inference.
Example:
model = MyLightningModule(...) model.freeze()
- Return type
None
- get_buffer(target)¶
Return the buffer given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the buffer to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The buffer referenced by
target
- Return type
torch.Tensor
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()¶
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()
for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns
Any extra state to store in the module’s state_dict
- Return type
object
- get_parameter(target)¶
Return the parameter given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the Parameter to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The Parameter referenced by
target
- Return type
torch.nn.Parameter
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)¶
Return the submodule given by
target
if it exists, otherwise throw an error.For example, let’s say you have an
nn.Module
A
that looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )
(The diagram shows an
nn.Module
A
.A
has a nested submodulenet_b
, which itself has two submodulesnet_c
andlinear
.net_c
then has a submoduleconv
.)To check whether or not we have the
linear
submodule, we would callget_submodule("net_b.linear")
. To check whether we have theconv
submodule, we would callget_submodule("net_b.net_c.conv")
.The runtime of
get_submodule
is bounded by the degree of module nesting intarget
. A query againstnamed_modules
achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submodule
should always be used.- Parameters
target (
str
) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns
The submodule referenced by
target
- Return type
torch.nn.Module
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- property global_rank: int¶
The index of the current process across all nodes and devices.
- Return type
int
- property global_step: int¶
Total training batches seen across all epochs.
If no Trainer is attached, this propery is 0.
- Return type
int
- half()¶
See
torch.nn.Module.half()
.- Return type
Self
- property hparams: Union[AttributeDict, MutableMapping]¶
The collection of hyperparameters saved with
save_hyperparameters()
. It is mutable by the user. For the frozen set of initial hyperparameters, usehparams_initial
.- Return type
Union
[AttributeDict
,MutableMapping
]- Returns
Mutable hyperparameters dictionary
- property hparams_initial: AttributeDict¶
The collection of hyperparameters saved with
save_hyperparameters()
. These contents are read-only. Manual updates to the saved hyperparameters can instead be performed throughhparams
.- Returns
immutable initial hyperparameters
- Return type
AttributeDict
- ipu(device=None)¶
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- load_from_checkpoint(checkpoint_path, map_location=None, hparams_file=None, strict=None, **kwargs)¶
Primary way of loading a model from a checkpoint. When Lightning saves a checkpoint it stores the arguments passed to
__init__
in the checkpoint under"hyper_parameters"
.Any arguments specified through **kwargs will override args stored in
"hyper_parameters"
.- Parameters
checkpoint_path (
Union
[str
,Path
,IO
]) – Path to checkpoint. This can also be a URL, or file-like objectmap_location (
Union
[device
,str
,int
,Callable
[[UntypedStorage
,str
],Optional
[UntypedStorage
]],Dict
[Union
[device
,str
,int
],Union
[device
,str
,int
]],None
]) – If your checkpoint saved a GPU model and you now load on CPUs or a different number of GPUs, use this to map to the new setup. The behaviour is the same as intorch.load()
.hparams_file (
Union
[str
,Path
,None
]) –Optional path to a
.yaml
or.csv
file with hierarchical structure as in this example:drop_prob: 0.2 dataloader: batch_size: 32
You most likely won’t need this since Lightning will always save the hyperparameters to the checkpoint. However, if your checkpoint weights don’t have the hyperparameters saved, use this method to pass in a
.yaml
file with the hparams you’d like to use. These will be converted into adict
and passed into yourLightningModule
for use.If your model’s
hparams
argument isNamespace
and.yaml
file has hierarchical structure, you need to refactor your model to treathparams
asdict
.strict (
Optional
[bool
]) – Whether to strictly enforce that the keys incheckpoint_path
match the keys returned by this module’s state dict. Defaults toTrue
unlessLightningModule.strict_loading
is set, in which case it defaults to the value ofLightningModule.strict_loading
.**kwargs – Any extra keyword args needed to init the model. Can also be used to override saved hyperparameter values.
- Return type
Self
- Returns
LightningModule
instance with loaded weights and hyperparameters (if available).
Note
load_from_checkpoint
is a class method. You should use yourLightningModule
class to call it instead of theLightningModule
instance, or aTypeError
will be raised.Note
To ensure all layers can be loaded from the checkpoint, this function will call
configure_model()
directly after instantiating the model if this hook is overridden in your LightningModule. However, note thatload_from_checkpoint
does not support loading sharded checkpoints, and you may run out of memory if the model is too large. In this case, consider loading through the Trainer via.fit(ckpt_path=...)
.Example:
# load weights without mapping ... model = MyLightningModule.load_from_checkpoint('path/to/checkpoint.ckpt') # or load weights mapping all weights from GPU 1 to GPU 0 ... map_location = {'cuda:1':'cuda:0'} model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', map_location=map_location ) # or load weights and hyperparameters from separate files. model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', hparams_file='/path/to/hparams_file.yaml' ) # override some of the params with new values model = MyLightningModule.load_from_checkpoint( PATH, num_layers=128, pretrained_ckpt_path=NEW_PATH, ) # predict pretrained_model.eval() pretrained_model.freeze() y_hat = pretrained_model(x)
- load_state_dict(state_dict, strict=True, assign=False)¶
Copy parameters and buffers from
state_dict
into this module and its descendants.If
strict
isTrue
, then the keys ofstate_dict
must exactly match the keys returned by this module’sstate_dict()
function.Warning
If
assign
isTrue
the optimizer must be created after the call toload_state_dict
unlessget_swap_module_params_on_conversion()
isTrue
.- Parameters
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dict
match the keys returned by this module’sstate_dict()
function. Default:True
assign (bool, optional) – When
False
, the properties of the tensors in the current module are preserved while whenTrue
, the properties of the Tensors in the state dict are preserved. The only exception is therequires_grad
field ofDefault: ``False`
- Returns
- missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided
state_dict
.
- unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided
state_dict
.
- Return type
NamedTuple
withmissing_keys
andunexpected_keys
fields
Note
If a parameter or buffer is registered as
None
and its corresponding key exists instate_dict
,load_state_dict()
will raise aRuntimeError
.
- property local_rank: int¶
The index of the current process within a single node.
- Return type
int
- log(name, value, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, metric_attribute=None, rank_zero_only=False)¶
Log a key, value pair.
Example:
self.log('train_loss', loss)
The default behavior per hook is documented here: extensions/logging:Automatic Logging.
- Parameters
name (
str
) – key to log. Must be identical across all processes if using DDP or any other distributed strategy.value (
Union
[Metric
,Tensor
,int
,float
]) – value to log. Can be afloat
,Tensor
, or aMetric
.prog_bar (
bool
) – ifTrue
logs to the progress bar.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto detach the graph.sync_dist (
bool
) – ifTrue
, reduces the metric across devices. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the DDP group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple dataloaders). If False, user needs to give unique names for each dataloader to not mix the values.batch_size (
Optional
[int
]) – Current batch_size. This will be directly inferred from the loaded batch, but for some data structures you might need to explicitly provide it.metric_attribute (
Optional
[str
]) – To restore the metric state, Lightning requires the reference of thetorchmetrics.Metric
in your model. This is found automatically if it is a model attribute.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- log_dict(dictionary, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, rank_zero_only=False)¶
Log a dictionary of values at once.
Example:
values = {'loss': loss, 'acc': acc, ..., 'metric_n': metric_n} self.log_dict(values)
- Parameters
dictionary (
Union
[Mapping
[str
,Union
[Metric
,Tensor
,int
,float
]],MetricCollection
]) – key value pairs. Keys must be identical across all processes if using DDP or any other distributed strategy. The values can be afloat
,Tensor
,Metric
, orMetricCollection
.prog_bar (
bool
) – ifTrue
logs to the progress base.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step.None
auto-logs for training_step but not validation/test_step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics.None
auto-logs for val/test step but nottraining_step
. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto-detach the graphsync_dist (
bool
) – ifTrue
, reduces the metric across GPUs/TPUs. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the ddp group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple). IfFalse
, user needs to give unique names for each dataloader to not mix values.batch_size (
Optional
[int
]) – Current batch size. This will be directly inferred from the loaded batch, but some data structures might need to explicitly provide it.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- property logger: Optional[Union[Logger, Logger]]¶
Reference to the logger object in the Trainer.
- Return type
Union
[Logger
,Logger
,None
]
- property loggers: Union[List[Logger], List[Logger]]¶
Reference to the list of loggers in the Trainer.
- Return type
Union
[List
[Logger
],List
[Logger
]]
- lr_scheduler_step(scheduler, metric)¶
Override this method to adjust the default way the
Trainer
calls each scheduler. By default, Lightning callsstep()
and as shown in the example for each scheduler based on itsinterval
.- Parameters
scheduler (
Union
[LRScheduler
,ReduceLROnPlateau
]) – Learning rate scheduler.metric (
Optional
[Any
]) – Value of the monitor used for schedulers likeReduceLROnPlateau
.
Examples:
# DEFAULT def lr_scheduler_step(self, scheduler, metric): if metric is None: scheduler.step() else: scheduler.step(metric) # Alternative way to update schedulers if it requires an epoch value def lr_scheduler_step(self, scheduler, metric): scheduler.step(epoch=self.current_epoch)
- Return type
None
- lr_schedulers()¶
Returns the learning rate scheduler(s) that are being used during training. Useful for manual optimization.
- Return type
Union
[None
,List
[Union
[LRScheduler
,ReduceLROnPlateau
]],LRScheduler
,ReduceLROnPlateau
]- Returns
A single scheduler, or a list of schedulers in case multiple ones are present, or
None
if no schedulers were returned inconfigure_optimizers()
.
- manual_backward(loss, *args, **kwargs)¶
Call this directly from your
training_step()
when doing optimizations manually. By using this, Lightning can ensure that all the proper scaling gets applied when using mixed precision.See manual optimization for more examples.
Example:
def training_step(...): opt = self.optimizers() loss = ... opt.zero_grad() # automatically applies scaling, etc... self.manual_backward(loss) opt.step()
- Parameters
loss (
Tensor
) – The tensor on which to compute gradients. Must have a graph attached.*args – Additional positional arguments to be forwarded to
backward()
**kwargs – Additional keyword arguments to be forwarded to
backward()
- Return type
None
- modules()¶
Return an iterator over all modules in the network.
- Yields
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- Return type
Iterator
[Module
]
- named_buffers(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- Return type
Iterator
[Tuple
[str
,Tensor
]]
- named_children()¶
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- Return type
Iterator
[Tuple
[str
,Module
]]
- named_modules(memo=None, prefix='', remove_duplicate=True)¶
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters
memo (
Optional
[Set
[Module
]]) – a memo to store the set of modules already added to the resultprefix (
str
) – a prefix that will be added to the name of the moduleremove_duplicate (
bool
) – whether to remove the duplicated module instances in the result or not
- Yields
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- Return type
Iterator
[Tuple
[str
,Parameter
]]
- on_after_backward()¶
Called after
loss.backward()
and before optimizers are stepped.Note
If using native AMP, the gradients will not be unscaled at this point. Use the
on_before_optimizer_step
if you need the unscaled gradients.- Return type
None
- on_after_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch after it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_after_batch_transfer(self, batch, dataloader_idx): batch['x'] = gpu_transforms(batch['x']) return batch
- on_before_backward(loss)¶
Called before
loss.backward()
.- Parameters
loss (
Tensor
) – Loss divided by number of batches for gradient accumulation and scaled if using AMP.- Return type
None
- on_before_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch before it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_before_batch_transfer(self, batch, dataloader_idx): batch['x'] = transforms(batch['x']) return batch
- on_before_optimizer_step(optimizer)¶
Called before
optimizer.step()
.If using gradient accumulation, the hook is called once the gradients have been accumulated. See: :paramref:`~pytorch_lightning.trainer.trainer.Trainer.accumulate_grad_batches`.
If using AMP, the loss will be unscaled before calling this hook. See these docs for more information on the scaling of gradients.
If clipping gradients, the gradients will not have been clipped yet.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.
Example:
def on_before_optimizer_step(self, optimizer): # example to inspect gradient information in tensorboard if self.trainer.global_step % 25 == 0: # don't make the tf file huge for k, v in self.named_parameters(): self.logger.experiment.add_histogram( tag=k, values=v.grad, global_step=self.trainer.global_step )
- Return type
None
- on_before_zero_grad(optimizer)¶
Called after
training_step()
and beforeoptimizer.zero_grad()
.Called in the training loop after taking an optimizer step and before zeroing grads. Good place to inspect weight information with weights updated.
This is where it is called:
for optimizer in optimizers: out = training_step(...) model.on_before_zero_grad(optimizer) # < ---- called here optimizer.zero_grad() backward()
- Parameters
optimizer (
Optimizer
) – The optimizer for which grads should be zeroed.- Return type
None
- on_fit_end()[source]¶
Called at the very end of fit.
If on DDP it is called on every process
- Return type
None
- on_fit_start()¶
Called at the very beginning of fit.
If on DDP it is called on every process
- Return type
None
- property on_gpu: bool¶
Returns
True
if this model is currently located on a GPU.Useful to set flags around the LightningModule for different CPU vs GPU behavior.
- Return type
bool
- on_load_checkpoint(checkpoint)[source]¶
Called by Lightning to restore your model. If you saved something with
on_save_checkpoint()
this is your chance to restore this.- Parameters
checkpoint (
Dict
[str
,Any
]) – Loaded checkpoint
Example:
def on_load_checkpoint(self, checkpoint): # 99% of the time you don't need to implement this method self.something_cool_i_want_to_save = checkpoint['something_cool_i_want_to_save']
Note
Lightning auto-restores global step, epoch, and train state including amp scaling. There is no need for you to restore anything regarding training.
- Return type
None
- on_predict_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop after the batch.
- Parameters
outputs (
Optional
[Any
]) – The outputs of predict_step(x)batch (
Any
) – The batched data as it is returned by the prediction DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_epoch_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_start()¶
Called at the beginning of predicting.
- Return type
None
- on_predict_model_eval()¶
Called when the predict loop starts.
The predict loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior.- Return type
None
- on_save_checkpoint(checkpoint)[source]¶
Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
- Parameters
checkpoint (
Dict
[str
,Any
]) – The full checkpoint dictionary before it gets dumped to a file. Implementations of this hook can insert additional data into this dictionary.
Example:
def on_save_checkpoint(self, checkpoint): # 99% of use cases you don't need to implement this method checkpoint['something_cool_i_want_to_save'] = my_cool_pickable_object
Note
Lightning saves all aspects of training (epoch, global step, etc…) including amp scaling. There is no need for you to store anything about training.
- Return type
None
- on_test_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the test loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of test_step(x)batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the test loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_end()¶
Called at the end of testing.
- Return type
None
- on_test_epoch_end()¶
Called in the test loop at the very end of the epoch.
- Return type
None
- on_test_epoch_start()¶
Called in the test loop at the very beginning of the epoch.
- Return type
None
- on_test_model_eval()¶
Called when the test loop starts.
The test loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_test_model_train()
.- Return type
None
- on_test_model_train()¶
Called when the test loop ends.
The test loop by default restores the training mode of the LightningModule to what it was before starting testing. Override this hook to change the behavior. See also
on_test_model_eval()
.- Return type
None
- on_test_start()¶
Called at the beginning of testing.
- Return type
None
- on_train_batch_end(outputs, batch, batch_idx)¶
Called in the training loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of training_step(x)batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
Note
The value
outputs["loss"]
here will be the normalized value w.r.taccumulate_grad_batches
of the loss returned fromtraining_step
.- Return type
None
- on_train_batch_start(batch, batch_idx)¶
Called in the training loop before anything happens for that batch.
If you return -1 here, you will skip training for the rest of the current epoch.
- Parameters
batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
- Return type
Optional
[int
]
- on_train_end()¶
Called at the end of training before logger experiment is closed.
- Return type
None
- on_train_epoch_end()[source]¶
Called in the training loop at the very end of the epoch.
To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the
LightningModule
and access them in this hook:class MyLightningModule(L.LightningModule): def __init__(self): super().__init__() self.training_step_outputs = [] def training_step(self): loss = ... self.training_step_outputs.append(loss) return loss def on_train_epoch_end(self): # do something with all training_step outputs, for example: epoch_mean = torch.stack(self.training_step_outputs).mean() self.log("training_epoch_mean", epoch_mean) # free up the memory self.training_step_outputs.clear()
- on_train_epoch_start()¶
Called in the training loop at the very beginning of the epoch.
- Return type
None
- on_train_start()¶
Called at the beginning of training after sanity check.
- Return type
None
- on_validation_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of validation_step(x)batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_end()¶
Called at the end of validation.
- Return type
None
- on_validation_epoch_start()¶
Called in the validation loop at the very beginning of the epoch.
- Return type
None
- on_validation_model_eval()¶
Called when the validation loop starts.
The validation loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_validation_model_train()
.- Return type
None
- on_validation_model_train()¶
Called when the validation loop ends.
The validation loop by default restores the training mode of the LightningModule to what it was before starting validation. Override this hook to change the behavior. See also
on_validation_model_eval()
.- Return type
None
- on_validation_model_zero_grad()¶
Called by the training loop to release gradients before entering the validation loop.
- Return type
None
- on_validation_start()¶
Called at the beginning of validation.
- Return type
None
- optimizer_step(epoch, batch_idx, optimizer, optimizer_closure=None)¶
Override this method to adjust the default way the
Trainer
calls the optimizer.By default, Lightning calls
step()
andzero_grad()
as shown in the example. This method (andzero_grad()
) won’t be called during the accumulation phase whenTrainer(accumulate_grad_batches != 1)
. Overriding this hook has no benefit with manual optimization.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Union
[Optimizer
,LightningOptimizer
]) – A PyTorch optimizeroptimizer_closure (
Optional
[Callable
[[],Any
]]) – The optimizer closure. This closure must be executed as it includes the calls totraining_step()
,optimizer.zero_grad()
, andbackward()
.
Examples:
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_closure): # Add your custom logic to run directly before `optimizer.step()` optimizer.step(closure=optimizer_closure) # Add your custom logic to run directly after `optimizer.step()`
- Return type
None
- optimizer_zero_grad(epoch, batch_idx, optimizer)¶
Override this method to change the default behaviour of
optimizer.zero_grad()
.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Optimizer
) – A PyTorch optimizer
Examples:
# DEFAULT def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad() # Set gradients to `None` instead of zero to improve performance (not required on `torch>=2.0.0`). def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad(set_to_none=True)
See
torch.optim.Optimizer.zero_grad()
for the explanation of the above example.- Return type
None
- optimizers(use_pl_optimizer=True)¶
Returns the optimizer(s) that are being used during training. Useful for manual optimization.
- Parameters
use_pl_optimizer (
bool
) – IfTrue
, will wrap the optimizer(s) in aLightningOptimizer
for automatic handling of precision, profiling, and counting of step calls for proper logging and checkpointing. It specifically wraps thestep
method and custom optimizers that don’t have this method are not supported.- Return type
Union
[Optimizer
,LightningOptimizer
,_FabricOptimizer
,List
[Optimizer
],List
[LightningOptimizer
],List
[_FabricOptimizer
]]- Returns
A single optimizer, or a list of optimizers in case multiple ones are present.
- property output_chunk_length: Optional[int]¶
Number of time steps predicted at once by the model.
- Return type
Optional
[int
]
- parameters(recurse=True)¶
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Parameter
]
- predict_dataloader()¶
An iterable or collection of iterables specifying prediction samples.
For more information about multiple dataloaders, see this section.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.predict()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
- Return type
Any
- Returns
A
torch.utils.data.DataLoader
or a sequence of them specifying prediction samples.
- predict_step(batch, batch_idx, dataloader_idx=None)[source]¶
performs the prediction step
- batch
output of Darts’
InferenceDataset
- tuple of(past_target, past_covariates, historic_future_covariates, future_covariates, future_past_covariates, input time series, prediction start time step)
- batch_idx
the batch index of the current batch
- dataloader_idx
the dataloader index
- Return type
Sequence
[TimeSeries
]
- prepare_data()¶
Use this to download and prepare data. Downloading and saving data with multiple processes (distributed settings) will result in corrupted data. Lightning ensures this method is called only within a single process, so you can safely add your downloading logic within.
Warning
DO NOT set state to the model (use
setup
instead) since this is NOT called on every deviceExample:
def prepare_data(self): # good download_data() tokenize() etc() # bad self.split = data_split self.some_state = some_other_state()
In a distributed environment,
prepare_data
can be called in two ways (using prepare_data_per_node)Once per node. This is the default and is only called on LOCAL_RANK=0.
Once in total. Only called on GLOBAL_RANK=0.
Example:
# DEFAULT # called once per node on LOCAL_RANK=0 of that node class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = True # call on GLOBAL_RANK=0 (great for shared file systems) class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = False
This is called before requesting the dataloaders:
model.prepare_data() initialize_distributed() model.setup(stage) model.train_dataloader() model.val_dataloader() model.test_dataloader() model.predict_dataloader()
- Return type
None
- print(*args, **kwargs)¶
Prints only from process 0. Use this in any distributed mode to log only once.
- Parameters
*args – The thing to print. The same as for Python’s built-in print function.
**kwargs – The same as for Python’s built-in print function.
Example:
def forward(self, x): self.print(x, 'in forward')
- Return type
None
- register_backward_hook(hook)¶
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()
and the behavior of this function will change in future versions.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_buffer(name, tensor, persistent=True)¶
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_mean
is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistent
toFalse
. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict
.Buffers can be accessed as attributes using given names.
- Parameters
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None
, then operations that run on buffers, such ascuda
, are ignored. IfNone
, the buffer is not included in the module’sstate_dict
.persistent (bool) – whether the buffer is part of this module’s
state_dict
.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- Return type
None
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)¶
Register a forward hook on the module.
The hook will be called every time after
forward()
has computed an output.If
with_kwargs
isFalse
or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()
is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargs
isTrue
, the forward hook will be passed thekwargs
given to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True
, the providedhook
will be fired before all existingforward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward
hooks on thistorch.nn.modules.Module
. Note that globalforward
hooks registered withregister_module_forward_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If
True
, thehook
will be passed the kwargs given to the forward function. Default:False
always_call (bool) – If
True
thehook
will be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)¶
Register a forward pre-hook on the module.
The hook will be called every time before
forward()
is invoked.If
with_kwargs
is false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargs
is true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingforward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward_pre
hooks on thistorch.nn.modules.Module
. Note that globalforward_pre
hooks registered withregister_module_forward_pre_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If true, the
hook
will be passed the kwargs given to the forward function. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)¶
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_input
andgrad_output
are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_input
in subsequent computations.grad_input
will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_input
andgrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward
hooks on thistorch.nn.modules.Module
. Note that globalbackward
hooks registered withregister_module_full_backward_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)¶
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_output
is a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_output
in subsequent computations. Entries ingrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Note that globalbackward_pre
hooks registered withregister_module_full_backward_pre_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)¶
Register a post hook to be run after module’s
load_state_dict
is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
module
argument is the current module that this hook is registered on, and theincompatible_keys
argument is aNamedTuple
consisting of attributesmissing_keys
andunexpected_keys
.missing_keys
is alist
ofstr
containing the missing keys andunexpected_keys
is alist
ofstr
containing the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()
withstrict=True
are affected by modifications the hook makes tomissing_keys
orunexpected_keys
, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True
, and clearing out both missing and unexpected keys will avoid an error.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_module(name, module)¶
Alias for
add_module()
.- Return type
None
- register_parameter(name, param)¶
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None
, then operations that run on parameters, such ascuda
, are ignored. IfNone
, the parameter is not included in the module’sstate_dict
.
- Return type
None
- register_state_dict_pre_hook(hook)¶
Register a pre-hook for the
state_dict()
method.These hooks will be called with arguments:
self
,prefix
, andkeep_vars
before callingstate_dict
onself
. The registered hooks can be used to perform pre-processing before thestate_dict
call is made.
- requires_grad_(requires_grad=True)¶
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_grad
attributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True
.- Returns
self
- Return type
Module
- save_hyperparameters(*args, ignore=None, frame=None, logger=True)¶
Save arguments to
hparams
attribute.- Parameters
args (
Any
) – single object of dict, NameSpace or OmegaConf or string names or arguments from class__init__
ignore (
Union
[str
,Sequence
[str
],None
]) – an argument name or a list of argument names from class__init__
to be ignoredframe (
Optional
[frame
]) – a frame object. Default is Nonelogger (
bool
) – Whether to send the hyperparameters to the logger. Default: True
- Example::
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # manually assign arguments ... self.save_hyperparameters('arg1', 'arg3') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class AutomaticArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # equivalent automatic ... self.save_hyperparameters() ... def forward(self, *args, **kwargs): ... ... >>> model = AutomaticArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg2": abc "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class SingleArgModel(HyperparametersMixin): ... def __init__(self, params): ... super().__init__() ... # manually assign single argument ... self.save_hyperparameters(params) ... def forward(self, *args, **kwargs): ... ... >>> model = SingleArgModel(Namespace(p1=1, p2='abc', p3=3.14)) >>> model.hparams "p1": 1 "p2": abc "p3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # pass argument(s) to ignore as a string or in a list ... self.save_hyperparameters(ignore='arg2') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
- Return type
None
- set_extra_state(state)¶
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()
to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()
for your module if you need to store extra state within its state_dict.- Parameters
state (dict) – Extra state from the state_dict
- Return type
None
- set_predict_parameters(n, num_samples, roll_size, batch_size, n_jobs, predict_likelihood_parameters, mc_dropout)[source]¶
to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
- Return type
None
- setup(stage)¶
Called at the beginning of fit (train + validate), validate, test, or predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
Example:
class LitModel(...): def __init__(self): self.l1 = None def prepare_data(self): download_data() tokenize() # don't do this self.something = else def setup(self, stage): data = load_data(...) self.l1 = nn.Linear(28, data.num_classes)
- Return type
None
See
torch.Tensor.share_memory_()
.- Return type
~T
- state_dict(*args, destination=None, prefix='', keep_vars=False)¶
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
None
are not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()
also accepts positional arguments fordestination
,prefix
andkeep_vars
in order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destination
as it is not designed for end-users.- Parameters
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDict
will be created and returned. Default:None
.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''
.keep_vars (bool, optional) – by default the
Tensor
s returned in the state dict are detached from autograd. If it’s set toTrue
, detaching will not be performed. Default:False
.
- Returns
a dictionary containing a whole state of the module
- Return type
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- property strict_loading: bool¶
Determines how Lightning loads this model using .load_state_dict(…, strict=model.strict_loading).
- Return type
bool
- property supports_probabilistic_prediction: bool¶
- Return type
bool
- teardown(stage)¶
Called at the end of fit (train + validate), validate, test, or predict.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
- Return type
None
- test_dataloader()¶
An iterable or collection of iterables specifying test samples.
For more information about multiple dataloaders, see this section.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
test()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
Note
If you don’t need a test dataset and a
test_step()
, you don’t need to implement this method.- Return type
Any
- test_step(*args, **kwargs)¶
Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.
- Parameters
batch – The output of your data iterable, normally a
DataLoader
.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- Return type
Union
[Tensor
,Mapping
[str
,Any
],None
]- Returns
Tensor
- The loss tensordict
- A dictionary. Can include any keys, but must include the key'loss'
.None
- Skip to the next batch.
# if you have one test dataloader: def test_step(self, batch, batch_idx): ... # if you have multiple test dataloaders: def test_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single test dataset def test_step(self, batch, batch_idx): x, y = batch # implement your own out = self(x) loss = self.loss(out, y) # log 6 example images # or generated text... or whatever sample_imgs = x[:6] grid = torchvision.utils.make_grid(sample_imgs) self.logger.experiment.add_image('example_images', grid, 0) # calculate acc labels_hat = torch.argmax(out, dim=1) test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'test_loss': loss, 'test_acc': test_acc})
If you pass in multiple test dataloaders,
test_step()
will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.# CASE 2: multiple test dataloaders def test_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. ...
Note
If you don’t need to test you don’t need to implement this method.
Note
When the
test_step()
is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.
- to(*args, **kwargs)¶
See
torch.nn.Module.to()
.- Return type
Self
- to_empty(*, device, recurse=True)¶
Move the parameters and buffers to the specified device without copying storage.
- Parameters
device (
torch.device
) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns
self
- Return type
Module
- to_onnx(file_path, input_sample=None, **kwargs)¶
Saves the model in ONNX format.
- Parameters
file_path (
Union
[str
,Path
]) – The path of the file the onnx model should be saved to.input_sample (
Optional
[Any
]) – An input for tracing. Default: None (Use self.example_input_array)**kwargs – Will be passed to torch.onnx.export function.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1) model = SimpleModel() input_sample = torch.randn(1, 64) model.to_onnx("export.onnx", input_sample, export_params=True)
- Return type
None
- to_torchscript(file_path=None, method='script', example_inputs=None, **kwargs)¶
By default compiles the whole model to a
ScriptModule
. If you want to use tracing, please provided the argumentmethod='trace'
and make sure that either the example_inputs argument is provided, or the model hasexample_input_array
set. If you would like to customize the modules that are scripted you should override this method. In case you want to return multiple modules, we recommend using a dictionary.- Parameters
file_path (
Union
[str
,Path
,None
]) – Path where to save the torchscript. Default: None (no file saved).method (
Optional
[str
]) – Whether to use TorchScript’s script or trace method. Default: ‘script’example_inputs (
Optional
[Any
]) – An input to be used to do tracing when method is set to ‘trace’. Default: None (usesexample_input_array
)**kwargs – Additional arguments that will be passed to the
torch.jit.script()
ortorch.jit.trace()
function.
Note
Requires the implementation of the
forward()
method.The exported script will be set to evaluation mode.
It is recommended that you install the latest supported version of PyTorch to use this feature without limitations. See also the
torch.jit
documentation for supported features.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1))) model = SimpleModel() model.to_torchscript(file_path="model.pt") torch.jit.save(model.to_torchscript( file_path="model_trace.pt", method='trace', example_inputs=torch.randn(1, 64)) )
- Return type
Union
[ScriptModule
,Dict
[str
,ScriptModule
]]- Returns
This LightningModule as a torchscript, regardless of whether file_path is defined or not.
- toggle_optimizer(optimizer)¶
Makes sure only the gradients of the current optimizer’s parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
It works with
untoggle_optimizer()
to make sureparam_requires_grad_state
is properly reset.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to toggle.- Return type
None
- train(mode=True)¶
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.- Parameters
mode (bool) – whether to set training mode (
True
) or evaluation mode (False
). Default:True
.- Returns
self
- Return type
Module
- train_dataloader()¶
An iterable or collection of iterables specifying training samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
fit()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
- Return type
Any
- property trainer: Trainer¶
- Return type
Trainer
- training: bool¶
- transfer_batch_to_device(batch, device, dataloader_idx)¶
Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.The data types listed below (and any arbitrary nesting of them) are supported out of the box:
torch.Tensor
or anything that implements .to(…)list
dict
tuple
For anything else, you need to define how the data is moved to the target device (CPU, GPU, TPU, …).
Note
This hook should only transfer the data and not modify it, nor should it move the data to any other device than the one passed in as argument (unless you know what you are doing). To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be transferred to a new device.device (
device
) – The target device as defined in PyTorch.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A reference to the data on the new device.
Example:
def transfer_batch_to_device(self, batch, device, dataloader_idx): if isinstance(batch, CustomBatch): # move all tensors in your custom data structure to the device batch.samples = batch.samples.to(device) batch.targets = batch.targets.to(device) elif dataloader_idx == 0: # skip device transfer for the first dataloader or anything you wish pass else: batch = super().transfer_batch_to_device(batch, device, dataloader_idx) return batch
See also
move_data_to_device()
apply_to_collection()
- type(dst_type)¶
See
torch.nn.Module.type()
.- Return type
Self
- unfreeze()¶
Unfreeze all parameters for training.
model = MyLightningModule(...) model.unfreeze()
- Return type
None
- untoggle_optimizer(optimizer)¶
Resets the state of required gradients that were toggled with
toggle_optimizer()
.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to untoggle.- Return type
None
- val_dataloader()¶
An iterable or collection of iterables specifying validation samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.fit()
validate()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
Note
If you don’t need a validation dataset and a
validation_step()
, you don’t need to implement this method.- Return type
Any
- xpu(device=None)¶
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- zero_grad(set_to_none=True)¶
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizer
for more context.- Parameters
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()
for details.- Return type
None
- class darts.models.forecasting.pl_forecasting_module.PLFutureCovariatesModule(input_chunk_length, output_chunk_length, output_chunk_shift=0, train_sample_shape=None, loss_fn=MSELoss(), torch_metrics=None, likelihood=None, optimizer_cls=<class 'torch.optim.adam.Adam'>, optimizer_kwargs=None, lr_scheduler_cls=None, lr_scheduler_kwargs=None, use_reversible_instance_norm=False)[source]¶
Bases:
PLForecastingModule
,ABC
PyTorch Lightning-based Forecasting Module.
This class is meant to be inherited to create a new PyTorch Lightning-based forecasting module. When subclassing this class, please make sure to add the following methods with the given signatures:
PLForecastingModule.__init__()
PLForecastingModule._produce_train_output()
PLForecastingModule._get_batch_prediction()
In subclass MyModel’s
__init__()
function callsuper(MyModel, self).__init__(**kwargs)
wherekwargs
are the parameters ofPLForecastingModule
.- Parameters
input_chunk_length (
int
) – Number of time steps in the past to take as a model input (per chunk). Applies to the target series, and past and/or future covariates (if the model supports it).output_chunk_length (
int
) – Number of time steps predicted at once (per chunk) by the internal model. Also, the number of future values from future covariates to use as a model input (if the model supports future covariates). It is not the same as forecast horizon n used in predict(), which is the desired number of prediction points generated using either a one-shot- or autoregressive forecast. Setting n <= output_chunk_length prevents auto-regression. This is useful when the covariates don’t extend far enough into the future, or to prohibit the model from using future values of past and / or future covariates for prediction (depending on the model’s covariate support).train_sample_shape (
Optional
[Tuple
]) – Shape of the model’s input, used to instantiate model without callingfit_from_dataset
and perform sanity check on new training/inference datasets used for re-training or prediction.loss_fn (
_Loss
) – PyTorch loss function used for training. This parameter will be ignored for probabilistic models if thelikelihood
parameter is specified. Default:torch.nn.MSELoss()
.torch_metrics (
Union
[Metric
,MetricCollection
,None
]) – A torch metric or aMetricCollection
used for evaluation. A full list of available metrics can be found at https://torchmetrics.readthedocs.io/en/latest/. Default:None
.likelihood (
Optional
[Likelihood
]) – One of Darts’Likelihood
models to be used for probabilistic forecasts. Default:None
.optimizer_cls (
Optimizer
) – The PyTorch optimizer class to be used. Default:torch.optim.Adam
.optimizer_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch optimizer (e.g.,{'lr': 1e-3}
for specifying a learning rate). Otherwise the default values of the selectedoptimizer_cls
will be used. Default:None
.lr_scheduler_cls (
Optional
[_LRScheduler
]) – Optionally, the PyTorch learning rate scheduler class to be used. SpecifyingNone
corresponds to using a constant learning rate. Default:None
.lr_scheduler_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch learning rate scheduler. Default:None
.use_reversible_instance_norm (
bool
) – Whether to use reversible instance normalization RINorm against distribution shift as shown in [1]. It is only applied to the features of the target series and not the covariates.
References
- 1
T. Kim et al. “Reversible Instance Normalization for Accurate Time-Series Forecasting against Distribution Shift”, https://openreview.net/forum?id=cGDAkQo1C0p
Attributes
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.The current epoch in the
Trainer
, or 0 if not attached.Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.The example input array is a specification of what the module can consume in the
forward()
method.The index of the current process across all nodes and devices.
Total training batches seen across all epochs.
The collection of hyperparameters saved with
save_hyperparameters()
.The collection of hyperparameters saved with
save_hyperparameters()
.The index of the current process within a single node.
Reference to the logger object in the Trainer.
Reference to the list of loggers in the Trainer.
Returns
True
if this model is currently located on a GPU.Number of time steps predicted at once by the model.
Determines how Lightning loads this model using .load_state_dict(..., strict=model.strict_loading).
device
dtype
epochs_trained
fabric
supports_probabilistic_prediction
trainer
Methods
add_module
(name, module)Add a child module to the current module.
all_gather
(data[, group, sync_grads])Gather tensors or collections of tensors from multiple processes.
apply
(fn)Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.backward
(loss, *args, **kwargs)Called to perform backward on the loss returned in
training_step()
.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Return an iterator over module buffers.
children
()Return an iterator over immediate children modules.
clip_gradients
(optimizer[, ...])Handles gradient clipping internally.
compile
(*args, **kwargs)Compile this Module's forward using
torch.compile()
.Configure model-specific callbacks.
configure_gradient_clipping
(optimizer[, ...])Perform gradient clipping for the optimizer parameters.
Hook to create modules in a strategy and precision aware context.
configures optimizers and learning rate schedulers for model optimization.
Deprecated.
configure_torch_metrics
(torch_metrics)process the torch_metrics parameter.
cpu
()See
torch.nn.Module.cpu()
.cuda
([device])Moves all model parameters and buffers to the GPU.
double
()See
torch.nn.Module.double()
.eval
()Set the module in evaluation mode.
Set the extra representation of the module.
float
()See
torch.nn.Module.float()
.forward
(*args, **kwargs)Same as
torch.nn.Module.forward()
.freeze
()Freeze all params for inference.
get_buffer
(target)Return the buffer given by
target
if it exists, otherwise throw an error.Return any extra state to include in the module's state_dict.
get_parameter
(target)Return the parameter given by
target
if it exists, otherwise throw an error.get_submodule
(target)Return the submodule given by
target
if it exists, otherwise throw an error.half
()See
torch.nn.Module.half()
.ipu
([device])Move all model parameters and buffers to the IPU.
load_from_checkpoint
(checkpoint_path[, ...])Primary way of loading a model from a checkpoint.
load_state_dict
(state_dict[, strict, assign])Copy parameters and buffers from
state_dict
into this module and its descendants.log
(name, value[, prog_bar, logger, ...])Log a key, value pair.
log_dict
(dictionary[, prog_bar, logger, ...])Log a dictionary of values at once.
lr_scheduler_step
(scheduler, metric)Override this method to adjust the default way the
Trainer
calls each scheduler.Returns the learning rate scheduler(s) that are being used during training.
manual_backward
(loss, *args, **kwargs)Call this directly from your
training_step()
when doing optimizations manually.modules
()Return an iterator over all modules in the network.
named_buffers
([prefix, recurse, ...])Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse, ...])Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
Called after
loss.backward()
and before optimizers are stepped.on_after_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch after it is transferred to the device.
on_before_backward
(loss)Called before
loss.backward()
.on_before_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch before it is transferred to the device.
on_before_optimizer_step
(optimizer)Called before
optimizer.step()
.on_before_zero_grad
(optimizer)Called after
training_step()
and beforeoptimizer.zero_grad()
.Called at the very end of fit.
Called at the very beginning of fit.
on_load_checkpoint
(checkpoint)Called by Lightning to restore your model.
on_predict_batch_end
(outputs, batch, batch_idx)Called in the predict loop after the batch.
on_predict_batch_start
(batch, batch_idx[, ...])Called in the predict loop before anything happens for that batch.
Called at the end of predicting.
Called at the end of predicting.
Called at the beginning of predicting.
Called when the predict loop starts.
Called at the beginning of predicting.
on_save_checkpoint
(checkpoint)Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
on_test_batch_end
(outputs, batch, batch_idx)Called in the test loop after the batch.
on_test_batch_start
(batch, batch_idx[, ...])Called in the test loop before anything happens for that batch.
Called at the end of testing.
Called in the test loop at the very end of the epoch.
Called in the test loop at the very beginning of the epoch.
Called when the test loop starts.
Called when the test loop ends.
Called at the beginning of testing.
on_train_batch_end
(outputs, batch, batch_idx)Called in the training loop after the batch.
on_train_batch_start
(batch, batch_idx)Called in the training loop before anything happens for that batch.
Called at the end of training before logger experiment is closed.
Called in the training loop at the very end of the epoch.
Called in the training loop at the very beginning of the epoch.
Called at the beginning of training after sanity check.
on_validation_batch_end
(outputs, batch, ...)Called in the validation loop after the batch.
on_validation_batch_start
(batch, batch_idx)Called in the validation loop before anything happens for that batch.
Called at the end of validation.
Called in the validation loop at the very end of the epoch.
Called in the validation loop at the very beginning of the epoch.
Called when the validation loop starts.
Called when the validation loop ends.
Called by the training loop to release gradients before entering the validation loop.
Called at the beginning of validation.
optimizer_step
(epoch, batch_idx, optimizer)Override this method to adjust the default way the
Trainer
calls the optimizer.optimizer_zero_grad
(epoch, batch_idx, optimizer)Override this method to change the default behaviour of
optimizer.zero_grad()
.optimizers
([use_pl_optimizer])Returns the optimizer(s) that are being used during training.
parameters
([recurse])Return an iterator over module parameters.
An iterable or collection of iterables specifying prediction samples.
predict_step
(batch, batch_idx[, dataloader_idx])performs the prediction step
Use this to download and prepare data.
print
(*args, **kwargs)Prints only from process 0.
register_backward_hook
(hook)Register a backward hook on the module.
register_buffer
(name, tensor[, persistent])Add a buffer to the module.
register_forward_hook
(hook, *[, prepend, ...])Register a forward hook on the module.
register_forward_pre_hook
(hook, *[, ...])Register a forward pre-hook on the module.
register_full_backward_hook
(hook[, prepend])Register a backward hook on the module.
register_full_backward_pre_hook
(hook[, prepend])Register a backward pre-hook on the module.
Register a post hook to be run after module's
load_state_dict
is called.register_module
(name, module)Alias for
add_module()
.register_parameter
(name, param)Add a parameter to the module.
Register a pre-hook for the
state_dict()
method.requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
save_hyperparameters
(*args[, ignore, frame, ...])Save arguments to
hparams
attribute.set_extra_state
(state)Set extra state contained in the loaded state_dict.
set_predict_parameters
(n, num_samples, ...)to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
setup
(stage)Called at the beginning of fit (train + validate), validate, test, or predict.
See
torch.Tensor.share_memory_()
.state_dict
(*args[, destination, prefix, ...])Return a dictionary containing references to the whole state of the module.
teardown
(stage)Called at the end of fit (train + validate), validate, test, or predict.
An iterable or collection of iterables specifying test samples.
test_step
(*args, **kwargs)Operates on a single batch of data from the test set.
to
(*args, **kwargs)See
torch.nn.Module.to()
.to_dtype
(dtype)Cast module precision (float32 by default) to another precision.
to_empty
(*, device[, recurse])Move the parameters and buffers to the specified device without copying storage.
to_onnx
(file_path[, input_sample])Saves the model in ONNX format.
to_torchscript
([file_path, method, ...])By default compiles the whole model to a
ScriptModule
.toggle_optimizer
(optimizer)Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
train
([mode])Set the module in training mode.
An iterable or collection of iterables specifying training samples.
training_step
(train_batch, batch_idx)performs the training step
transfer_batch_to_device
(batch, device, ...)Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.type
(dst_type)See
torch.nn.Module.type()
.unfreeze
()Unfreeze all parameters for training.
untoggle_optimizer
(optimizer)Resets the state of required gradients that were toggled with
toggle_optimizer()
.An iterable or collection of iterables specifying validation samples.
validation_step
(val_batch, batch_idx)performs the validation step
xpu
([device])Move all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Reset gradients of all model parameters.
__call__
set_mc_dropout
- CHECKPOINT_HYPER_PARAMS_KEY = 'hyper_parameters'¶
- CHECKPOINT_HYPER_PARAMS_NAME = 'hparams_name'¶
- CHECKPOINT_HYPER_PARAMS_TYPE = 'hparams_type'¶
- T_destination¶
alias of TypeVar(‘T_destination’, bound=
Dict
[str
,Any
])
- add_module(name, module)¶
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- Return type
None
- all_gather(data, group=None, sync_grads=False)¶
Gather tensors or collections of tensors from multiple processes.
This method needs to be called on all processes and the tensors need to have the same shape across all processes, otherwise your program will stall forever.
- Parameters
data (
Union
[Tensor
,Dict
,List
,Tuple
]) – int, float, tensor of shape (batch, …), or a (possibly nested) collection thereof.group (
Optional
[Any
]) – the process group to gather results from. Defaults to all processes (world)sync_grads (
bool
) – flag that allows users to synchronize gradients for the all_gather operation
- Return type
Union
[Tensor
,Dict
,List
,Tuple
]- Returns
A tensor of shape (world_size, batch, …), or if the input was a collection the output will also be a collection with tensors of this shape. For the special case where world_size is 1, no additional dimension is added to the tensor(s).
- allow_zero_length_dataloader_with_multiple_devices: bool¶
- apply(fn)¶
Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters
fn (
Module
-> None) – function to be applied to each submodule- Returns
self
- Return type
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- property automatic_optimization: bool¶
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.- Return type
bool
- backward(loss, *args, **kwargs)¶
Called to perform backward on the loss returned in
training_step()
. Override this hook with your own implementation if you need to.- Parameters
loss (
Tensor
) – The loss tensor returned bytraining_step()
. If gradient accumulation is used, the loss here holds the normalized value (scaled by 1 / accumulation steps).
Example:
def backward(self, loss): loss.backward()
- Return type
None
- bfloat16()¶
Casts all floating point parameters and buffers to
bfloat16
datatype.Note
This method modifies the module in-place.
- Returns
self
- Return type
Module
- buffers(recurse=True)¶
Return an iterator over module buffers.
- Parameters
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Tensor
]
- call_super_init: bool = False¶
- children()¶
Return an iterator over immediate children modules.
- Yields
Module – a child module
- Return type
Iterator
[Module
]
- clip_gradients(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Handles gradient clipping internally.
Note
Do not override this method. If you want to customize gradient clipping, consider using
configure_gradient_clipping()
method.For manual optimization (
self.automatic_optimization = False
), if you want to use gradient clipping, consider callingself.clip_gradients(opt, gradient_clip_val=0.5, gradient_clip_algorithm="norm")
manually in the training step.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. Passgradient_clip_algorithm="value"
to clip by value, andgradient_clip_algorithm="norm"
to clip by norm.
- Return type
None
- compile(*args, **kwargs)¶
Compile this Module’s forward using
torch.compile()
.This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile()
.See
torch.compile()
for details on the arguments for this function.
- configure_callbacks()¶
Configure model-specific callbacks. When the model gets attached, e.g., when
.fit()
or.test()
gets called, the list or a callback returned here will be merged with the list of callbacks passed to the Trainer’scallbacks
argument. If a callback returned here has the same type as one or several callbacks already present in the Trainer’s callbacks list, it will take priority and replace them. In addition, Lightning will make sureModelCheckpoint
callbacks run last.- Return type
Union
[Sequence
[Callback
],Callback
]- Returns
A callback or a list of callbacks which will extend the list of callbacks in the Trainer.
Example:
def configure_callbacks(self): early_stop = EarlyStopping(monitor="val_acc", mode="max") checkpoint = ModelCheckpoint(monitor="val_loss") return [early_stop, checkpoint]
- configure_gradient_clipping(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Perform gradient clipping for the optimizer parameters. Called before
optimizer_step()
.- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients. By default, value passed in Trainer will be available here.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. By default, value passed in Trainer will be available here.
Example:
def configure_gradient_clipping(self, optimizer, gradient_clip_val, gradient_clip_algorithm): # Implement your own custom logic to clip gradients # You can call `self.clip_gradients` with your settings: self.clip_gradients( optimizer, gradient_clip_val=gradient_clip_val, gradient_clip_algorithm=gradient_clip_algorithm )
- Return type
None
- configure_model()¶
Hook to create modules in a strategy and precision aware context.
This is particularly useful for when using sharded strategies (FSDP and DeepSpeed), where we’d like to shard the model instantly to save memory and initialization time. For non-sharded strategies, you can choose to override this hook or to initialize your model under the
init_module()
context manager.This hook is called during each of fit/val/test/predict stages in the same process, so ensure that implementation of this hook is idempotent, i.e., after the first time the hook is called, subsequent calls to it should be a no-op.
- Return type
None
- configure_optimizers()¶
configures optimizers and learning rate schedulers for model optimization.
- configure_sharded_model()¶
Deprecated.
Use
configure_model()
instead.- Return type
None
- static configure_torch_metrics(torch_metrics)¶
process the torch_metrics parameter.
- Return type
MetricCollection
- cpu()¶
See
torch.nn.Module.cpu()
.- Return type
Self
- cuda(device=None)¶
Moves all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
- Parameters
device (
Union
[int
,device
,None
]) – If specified, all parameters will be copied to that device. If None, the current CUDA device index will be used.- Returns
self
- Return type
Module
- property current_epoch: int¶
The current epoch in the
Trainer
, or 0 if not attached.- Return type
int
- property device: device¶
- Return type
device
- property device_mesh: Optional[DeviceMesh]¶
Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.- Return type
Optional
[ForwardRef
]
- double()¶
See
torch.nn.Module.double()
.- Return type
Self
- property dtype: Union[str, dtype]¶
- Return type
Union
[str
,dtype
]
- dump_patches: bool = False¶
- property epochs_trained¶
- eval()¶
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.This is equivalent with
self.train(False)
.See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns
self
- Return type
Module
- property example_input_array: Optional[Union[Tensor, Tuple, Dict]]¶
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
Union
[Tensor
,Tuple
,Dict
,None
]
- extra_repr()¶
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type
str
- property fabric: Optional[Fabric]¶
- Return type
Optional
[Fabric
]
- float()¶
See
torch.nn.Module.float()
.- Return type
Self
- abstract forward(*args, **kwargs)¶
Same as
torch.nn.Module.forward()
.- Parameters
*args – Whatever you decide to pass into the forward method.
**kwargs – Keyword arguments are also possible.
- Return type
Any
- Returns
Your model’s output
- freeze()¶
Freeze all params for inference.
Example:
model = MyLightningModule(...) model.freeze()
- Return type
None
- get_buffer(target)¶
Return the buffer given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the buffer to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The buffer referenced by
target
- Return type
torch.Tensor
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()¶
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()
for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns
Any extra state to store in the module’s state_dict
- Return type
object
- get_parameter(target)¶
Return the parameter given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the Parameter to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The Parameter referenced by
target
- Return type
torch.nn.Parameter
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)¶
Return the submodule given by
target
if it exists, otherwise throw an error.For example, let’s say you have an
nn.Module
A
that looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )
(The diagram shows an
nn.Module
A
.A
has a nested submodulenet_b
, which itself has two submodulesnet_c
andlinear
.net_c
then has a submoduleconv
.)To check whether or not we have the
linear
submodule, we would callget_submodule("net_b.linear")
. To check whether we have theconv
submodule, we would callget_submodule("net_b.net_c.conv")
.The runtime of
get_submodule
is bounded by the degree of module nesting intarget
. A query againstnamed_modules
achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submodule
should always be used.- Parameters
target (
str
) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns
The submodule referenced by
target
- Return type
torch.nn.Module
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- property global_rank: int¶
The index of the current process across all nodes and devices.
- Return type
int
- property global_step: int¶
Total training batches seen across all epochs.
If no Trainer is attached, this propery is 0.
- Return type
int
- half()¶
See
torch.nn.Module.half()
.- Return type
Self
- property hparams: Union[AttributeDict, MutableMapping]¶
The collection of hyperparameters saved with
save_hyperparameters()
. It is mutable by the user. For the frozen set of initial hyperparameters, usehparams_initial
.- Return type
Union
[AttributeDict
,MutableMapping
]- Returns
Mutable hyperparameters dictionary
- property hparams_initial: AttributeDict¶
The collection of hyperparameters saved with
save_hyperparameters()
. These contents are read-only. Manual updates to the saved hyperparameters can instead be performed throughhparams
.- Returns
immutable initial hyperparameters
- Return type
AttributeDict
- ipu(device=None)¶
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- load_from_checkpoint(checkpoint_path, map_location=None, hparams_file=None, strict=None, **kwargs)¶
Primary way of loading a model from a checkpoint. When Lightning saves a checkpoint it stores the arguments passed to
__init__
in the checkpoint under"hyper_parameters"
.Any arguments specified through **kwargs will override args stored in
"hyper_parameters"
.- Parameters
checkpoint_path (
Union
[str
,Path
,IO
]) – Path to checkpoint. This can also be a URL, or file-like objectmap_location (
Union
[device
,str
,int
,Callable
[[UntypedStorage
,str
],Optional
[UntypedStorage
]],Dict
[Union
[device
,str
,int
],Union
[device
,str
,int
]],None
]) – If your checkpoint saved a GPU model and you now load on CPUs or a different number of GPUs, use this to map to the new setup. The behaviour is the same as intorch.load()
.hparams_file (
Union
[str
,Path
,None
]) –Optional path to a
.yaml
or.csv
file with hierarchical structure as in this example:drop_prob: 0.2 dataloader: batch_size: 32
You most likely won’t need this since Lightning will always save the hyperparameters to the checkpoint. However, if your checkpoint weights don’t have the hyperparameters saved, use this method to pass in a
.yaml
file with the hparams you’d like to use. These will be converted into adict
and passed into yourLightningModule
for use.If your model’s
hparams
argument isNamespace
and.yaml
file has hierarchical structure, you need to refactor your model to treathparams
asdict
.strict (
Optional
[bool
]) – Whether to strictly enforce that the keys incheckpoint_path
match the keys returned by this module’s state dict. Defaults toTrue
unlessLightningModule.strict_loading
is set, in which case it defaults to the value ofLightningModule.strict_loading
.**kwargs – Any extra keyword args needed to init the model. Can also be used to override saved hyperparameter values.
- Return type
Self
- Returns
LightningModule
instance with loaded weights and hyperparameters (if available).
Note
load_from_checkpoint
is a class method. You should use yourLightningModule
class to call it instead of theLightningModule
instance, or aTypeError
will be raised.Note
To ensure all layers can be loaded from the checkpoint, this function will call
configure_model()
directly after instantiating the model if this hook is overridden in your LightningModule. However, note thatload_from_checkpoint
does not support loading sharded checkpoints, and you may run out of memory if the model is too large. In this case, consider loading through the Trainer via.fit(ckpt_path=...)
.Example:
# load weights without mapping ... model = MyLightningModule.load_from_checkpoint('path/to/checkpoint.ckpt') # or load weights mapping all weights from GPU 1 to GPU 0 ... map_location = {'cuda:1':'cuda:0'} model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', map_location=map_location ) # or load weights and hyperparameters from separate files. model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', hparams_file='/path/to/hparams_file.yaml' ) # override some of the params with new values model = MyLightningModule.load_from_checkpoint( PATH, num_layers=128, pretrained_ckpt_path=NEW_PATH, ) # predict pretrained_model.eval() pretrained_model.freeze() y_hat = pretrained_model(x)
- load_state_dict(state_dict, strict=True, assign=False)¶
Copy parameters and buffers from
state_dict
into this module and its descendants.If
strict
isTrue
, then the keys ofstate_dict
must exactly match the keys returned by this module’sstate_dict()
function.Warning
If
assign
isTrue
the optimizer must be created after the call toload_state_dict
unlessget_swap_module_params_on_conversion()
isTrue
.- Parameters
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dict
match the keys returned by this module’sstate_dict()
function. Default:True
assign (bool, optional) – When
False
, the properties of the tensors in the current module are preserved while whenTrue
, the properties of the Tensors in the state dict are preserved. The only exception is therequires_grad
field ofDefault: ``False`
- Returns
- missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided
state_dict
.
- unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided
state_dict
.
- Return type
NamedTuple
withmissing_keys
andunexpected_keys
fields
Note
If a parameter or buffer is registered as
None
and its corresponding key exists instate_dict
,load_state_dict()
will raise aRuntimeError
.
- property local_rank: int¶
The index of the current process within a single node.
- Return type
int
- log(name, value, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, metric_attribute=None, rank_zero_only=False)¶
Log a key, value pair.
Example:
self.log('train_loss', loss)
The default behavior per hook is documented here: extensions/logging:Automatic Logging.
- Parameters
name (
str
) – key to log. Must be identical across all processes if using DDP or any other distributed strategy.value (
Union
[Metric
,Tensor
,int
,float
]) – value to log. Can be afloat
,Tensor
, or aMetric
.prog_bar (
bool
) – ifTrue
logs to the progress bar.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto detach the graph.sync_dist (
bool
) – ifTrue
, reduces the metric across devices. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the DDP group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple dataloaders). If False, user needs to give unique names for each dataloader to not mix the values.batch_size (
Optional
[int
]) – Current batch_size. This will be directly inferred from the loaded batch, but for some data structures you might need to explicitly provide it.metric_attribute (
Optional
[str
]) – To restore the metric state, Lightning requires the reference of thetorchmetrics.Metric
in your model. This is found automatically if it is a model attribute.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- log_dict(dictionary, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, rank_zero_only=False)¶
Log a dictionary of values at once.
Example:
values = {'loss': loss, 'acc': acc, ..., 'metric_n': metric_n} self.log_dict(values)
- Parameters
dictionary (
Union
[Mapping
[str
,Union
[Metric
,Tensor
,int
,float
]],MetricCollection
]) – key value pairs. Keys must be identical across all processes if using DDP or any other distributed strategy. The values can be afloat
,Tensor
,Metric
, orMetricCollection
.prog_bar (
bool
) – ifTrue
logs to the progress base.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step.None
auto-logs for training_step but not validation/test_step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics.None
auto-logs for val/test step but nottraining_step
. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto-detach the graphsync_dist (
bool
) – ifTrue
, reduces the metric across GPUs/TPUs. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the ddp group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple). IfFalse
, user needs to give unique names for each dataloader to not mix values.batch_size (
Optional
[int
]) – Current batch size. This will be directly inferred from the loaded batch, but some data structures might need to explicitly provide it.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- property logger: Optional[Union[Logger, Logger]]¶
Reference to the logger object in the Trainer.
- Return type
Union
[Logger
,Logger
,None
]
- property loggers: Union[List[Logger], List[Logger]]¶
Reference to the list of loggers in the Trainer.
- Return type
Union
[List
[Logger
],List
[Logger
]]
- lr_scheduler_step(scheduler, metric)¶
Override this method to adjust the default way the
Trainer
calls each scheduler. By default, Lightning callsstep()
and as shown in the example for each scheduler based on itsinterval
.- Parameters
scheduler (
Union
[LRScheduler
,ReduceLROnPlateau
]) – Learning rate scheduler.metric (
Optional
[Any
]) – Value of the monitor used for schedulers likeReduceLROnPlateau
.
Examples:
# DEFAULT def lr_scheduler_step(self, scheduler, metric): if metric is None: scheduler.step() else: scheduler.step(metric) # Alternative way to update schedulers if it requires an epoch value def lr_scheduler_step(self, scheduler, metric): scheduler.step(epoch=self.current_epoch)
- Return type
None
- lr_schedulers()¶
Returns the learning rate scheduler(s) that are being used during training. Useful for manual optimization.
- Return type
Union
[None
,List
[Union
[LRScheduler
,ReduceLROnPlateau
]],LRScheduler
,ReduceLROnPlateau
]- Returns
A single scheduler, or a list of schedulers in case multiple ones are present, or
None
if no schedulers were returned inconfigure_optimizers()
.
- manual_backward(loss, *args, **kwargs)¶
Call this directly from your
training_step()
when doing optimizations manually. By using this, Lightning can ensure that all the proper scaling gets applied when using mixed precision.See manual optimization for more examples.
Example:
def training_step(...): opt = self.optimizers() loss = ... opt.zero_grad() # automatically applies scaling, etc... self.manual_backward(loss) opt.step()
- Parameters
loss (
Tensor
) – The tensor on which to compute gradients. Must have a graph attached.*args – Additional positional arguments to be forwarded to
backward()
**kwargs – Additional keyword arguments to be forwarded to
backward()
- Return type
None
- modules()¶
Return an iterator over all modules in the network.
- Yields
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- Return type
Iterator
[Module
]
- named_buffers(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- Return type
Iterator
[Tuple
[str
,Tensor
]]
- named_children()¶
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- Return type
Iterator
[Tuple
[str
,Module
]]
- named_modules(memo=None, prefix='', remove_duplicate=True)¶
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters
memo (
Optional
[Set
[Module
]]) – a memo to store the set of modules already added to the resultprefix (
str
) – a prefix that will be added to the name of the moduleremove_duplicate (
bool
) – whether to remove the duplicated module instances in the result or not
- Yields
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- Return type
Iterator
[Tuple
[str
,Parameter
]]
- on_after_backward()¶
Called after
loss.backward()
and before optimizers are stepped.Note
If using native AMP, the gradients will not be unscaled at this point. Use the
on_before_optimizer_step
if you need the unscaled gradients.- Return type
None
- on_after_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch after it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_after_batch_transfer(self, batch, dataloader_idx): batch['x'] = gpu_transforms(batch['x']) return batch
- on_before_backward(loss)¶
Called before
loss.backward()
.- Parameters
loss (
Tensor
) – Loss divided by number of batches for gradient accumulation and scaled if using AMP.- Return type
None
- on_before_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch before it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_before_batch_transfer(self, batch, dataloader_idx): batch['x'] = transforms(batch['x']) return batch
- on_before_optimizer_step(optimizer)¶
Called before
optimizer.step()
.If using gradient accumulation, the hook is called once the gradients have been accumulated. See: :paramref:`~pytorch_lightning.trainer.trainer.Trainer.accumulate_grad_batches`.
If using AMP, the loss will be unscaled before calling this hook. See these docs for more information on the scaling of gradients.
If clipping gradients, the gradients will not have been clipped yet.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.
Example:
def on_before_optimizer_step(self, optimizer): # example to inspect gradient information in tensorboard if self.trainer.global_step % 25 == 0: # don't make the tf file huge for k, v in self.named_parameters(): self.logger.experiment.add_histogram( tag=k, values=v.grad, global_step=self.trainer.global_step )
- Return type
None
- on_before_zero_grad(optimizer)¶
Called after
training_step()
and beforeoptimizer.zero_grad()
.Called in the training loop after taking an optimizer step and before zeroing grads. Good place to inspect weight information with weights updated.
This is where it is called:
for optimizer in optimizers: out = training_step(...) model.on_before_zero_grad(optimizer) # < ---- called here optimizer.zero_grad() backward()
- Parameters
optimizer (
Optimizer
) – The optimizer for which grads should be zeroed.- Return type
None
- on_fit_end()¶
Called at the very end of fit.
If on DDP it is called on every process
- Return type
None
- on_fit_start()¶
Called at the very beginning of fit.
If on DDP it is called on every process
- Return type
None
- property on_gpu: bool¶
Returns
True
if this model is currently located on a GPU.Useful to set flags around the LightningModule for different CPU vs GPU behavior.
- Return type
bool
- on_load_checkpoint(checkpoint)¶
Called by Lightning to restore your model. If you saved something with
on_save_checkpoint()
this is your chance to restore this.- Parameters
checkpoint (
Dict
[str
,Any
]) – Loaded checkpoint
Example:
def on_load_checkpoint(self, checkpoint): # 99% of the time you don't need to implement this method self.something_cool_i_want_to_save = checkpoint['something_cool_i_want_to_save']
Note
Lightning auto-restores global step, epoch, and train state including amp scaling. There is no need for you to restore anything regarding training.
- Return type
None
- on_predict_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop after the batch.
- Parameters
outputs (
Optional
[Any
]) – The outputs of predict_step(x)batch (
Any
) – The batched data as it is returned by the prediction DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_start()¶
Called at the beginning of predicting.
- Return type
None
- on_predict_model_eval()¶
Called when the predict loop starts.
The predict loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior.- Return type
None
- on_predict_start()¶
Called at the beginning of predicting.
- Return type
None
- on_save_checkpoint(checkpoint)¶
Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
- Parameters
checkpoint (
Dict
[str
,Any
]) – The full checkpoint dictionary before it gets dumped to a file. Implementations of this hook can insert additional data into this dictionary.
Example:
def on_save_checkpoint(self, checkpoint): # 99% of use cases you don't need to implement this method checkpoint['something_cool_i_want_to_save'] = my_cool_pickable_object
Note
Lightning saves all aspects of training (epoch, global step, etc…) including amp scaling. There is no need for you to store anything about training.
- Return type
None
- on_test_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the test loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of test_step(x)batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the test loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_end()¶
Called at the end of testing.
- Return type
None
- on_test_epoch_end()¶
Called in the test loop at the very end of the epoch.
- Return type
None
- on_test_epoch_start()¶
Called in the test loop at the very beginning of the epoch.
- Return type
None
- on_test_model_eval()¶
Called when the test loop starts.
The test loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_test_model_train()
.- Return type
None
- on_test_model_train()¶
Called when the test loop ends.
The test loop by default restores the training mode of the LightningModule to what it was before starting testing. Override this hook to change the behavior. See also
on_test_model_eval()
.- Return type
None
- on_test_start()¶
Called at the beginning of testing.
- Return type
None
- on_train_batch_end(outputs, batch, batch_idx)¶
Called in the training loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of training_step(x)batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
Note
The value
outputs["loss"]
here will be the normalized value w.r.taccumulate_grad_batches
of the loss returned fromtraining_step
.- Return type
None
- on_train_batch_start(batch, batch_idx)¶
Called in the training loop before anything happens for that batch.
If you return -1 here, you will skip training for the rest of the current epoch.
- Parameters
batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
- Return type
Optional
[int
]
- on_train_end()¶
Called at the end of training before logger experiment is closed.
- Return type
None
- on_train_epoch_end()¶
Called in the training loop at the very end of the epoch.
To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the
LightningModule
and access them in this hook:class MyLightningModule(L.LightningModule): def __init__(self): super().__init__() self.training_step_outputs = [] def training_step(self): loss = ... self.training_step_outputs.append(loss) return loss def on_train_epoch_end(self): # do something with all training_step outputs, for example: epoch_mean = torch.stack(self.training_step_outputs).mean() self.log("training_epoch_mean", epoch_mean) # free up the memory self.training_step_outputs.clear()
- on_train_epoch_start()¶
Called in the training loop at the very beginning of the epoch.
- Return type
None
- on_train_start()¶
Called at the beginning of training after sanity check.
- Return type
None
- on_validation_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of validation_step(x)batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_end()¶
Called at the end of validation.
- Return type
None
- on_validation_epoch_end()¶
Called in the validation loop at the very end of the epoch.
- on_validation_epoch_start()¶
Called in the validation loop at the very beginning of the epoch.
- Return type
None
- on_validation_model_eval()¶
Called when the validation loop starts.
The validation loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_validation_model_train()
.- Return type
None
- on_validation_model_train()¶
Called when the validation loop ends.
The validation loop by default restores the training mode of the LightningModule to what it was before starting validation. Override this hook to change the behavior. See also
on_validation_model_eval()
.- Return type
None
- on_validation_model_zero_grad()¶
Called by the training loop to release gradients before entering the validation loop.
- Return type
None
- on_validation_start()¶
Called at the beginning of validation.
- Return type
None
- optimizer_step(epoch, batch_idx, optimizer, optimizer_closure=None)¶
Override this method to adjust the default way the
Trainer
calls the optimizer.By default, Lightning calls
step()
andzero_grad()
as shown in the example. This method (andzero_grad()
) won’t be called during the accumulation phase whenTrainer(accumulate_grad_batches != 1)
. Overriding this hook has no benefit with manual optimization.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Union
[Optimizer
,LightningOptimizer
]) – A PyTorch optimizeroptimizer_closure (
Optional
[Callable
[[],Any
]]) – The optimizer closure. This closure must be executed as it includes the calls totraining_step()
,optimizer.zero_grad()
, andbackward()
.
Examples:
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_closure): # Add your custom logic to run directly before `optimizer.step()` optimizer.step(closure=optimizer_closure) # Add your custom logic to run directly after `optimizer.step()`
- Return type
None
- optimizer_zero_grad(epoch, batch_idx, optimizer)¶
Override this method to change the default behaviour of
optimizer.zero_grad()
.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Optimizer
) – A PyTorch optimizer
Examples:
# DEFAULT def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad() # Set gradients to `None` instead of zero to improve performance (not required on `torch>=2.0.0`). def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad(set_to_none=True)
See
torch.optim.Optimizer.zero_grad()
for the explanation of the above example.- Return type
None
- optimizers(use_pl_optimizer=True)¶
Returns the optimizer(s) that are being used during training. Useful for manual optimization.
- Parameters
use_pl_optimizer (
bool
) – IfTrue
, will wrap the optimizer(s) in aLightningOptimizer
for automatic handling of precision, profiling, and counting of step calls for proper logging and checkpointing. It specifically wraps thestep
method and custom optimizers that don’t have this method are not supported.- Return type
Union
[Optimizer
,LightningOptimizer
,_FabricOptimizer
,List
[Optimizer
],List
[LightningOptimizer
],List
[_FabricOptimizer
]]- Returns
A single optimizer, or a list of optimizers in case multiple ones are present.
- property output_chunk_length: Optional[int]¶
Number of time steps predicted at once by the model.
- Return type
Optional
[int
]
- parameters(recurse=True)¶
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Parameter
]
- pred_batch_size: Optional[int]¶
- pred_mc_dropout: Optional[bool]¶
- pred_n: Optional[int]¶
- pred_n_jobs: Optional[int]¶
- pred_num_samples: Optional[int]¶
- pred_roll_size: Optional[int]¶
- predict_dataloader()¶
An iterable or collection of iterables specifying prediction samples.
For more information about multiple dataloaders, see this section.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.predict()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
- Return type
Any
- Returns
A
torch.utils.data.DataLoader
or a sequence of them specifying prediction samples.
- predict_likelihood_parameters: Optional[bool]¶
- predict_step(batch, batch_idx, dataloader_idx=None)¶
performs the prediction step
- batch
output of Darts’
InferenceDataset
- tuple of(past_target, past_covariates, historic_future_covariates, future_covariates, future_past_covariates, input time series, prediction start time step)
- batch_idx
the batch index of the current batch
- dataloader_idx
the dataloader index
- Return type
Sequence
[TimeSeries
]
- prepare_data()¶
Use this to download and prepare data. Downloading and saving data with multiple processes (distributed settings) will result in corrupted data. Lightning ensures this method is called only within a single process, so you can safely add your downloading logic within.
Warning
DO NOT set state to the model (use
setup
instead) since this is NOT called on every deviceExample:
def prepare_data(self): # good download_data() tokenize() etc() # bad self.split = data_split self.some_state = some_other_state()
In a distributed environment,
prepare_data
can be called in two ways (using prepare_data_per_node)Once per node. This is the default and is only called on LOCAL_RANK=0.
Once in total. Only called on GLOBAL_RANK=0.
Example:
# DEFAULT # called once per node on LOCAL_RANK=0 of that node class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = True # call on GLOBAL_RANK=0 (great for shared file systems) class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = False
This is called before requesting the dataloaders:
model.prepare_data() initialize_distributed() model.setup(stage) model.train_dataloader() model.val_dataloader() model.test_dataloader() model.predict_dataloader()
- Return type
None
- prepare_data_per_node: bool¶
- print(*args, **kwargs)¶
Prints only from process 0. Use this in any distributed mode to log only once.
- Parameters
*args – The thing to print. The same as for Python’s built-in print function.
**kwargs – The same as for Python’s built-in print function.
Example:
def forward(self, x): self.print(x, 'in forward')
- Return type
None
- register_backward_hook(hook)¶
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()
and the behavior of this function will change in future versions.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_buffer(name, tensor, persistent=True)¶
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_mean
is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistent
toFalse
. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict
.Buffers can be accessed as attributes using given names.
- Parameters
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None
, then operations that run on buffers, such ascuda
, are ignored. IfNone
, the buffer is not included in the module’sstate_dict
.persistent (bool) – whether the buffer is part of this module’s
state_dict
.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- Return type
None
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)¶
Register a forward hook on the module.
The hook will be called every time after
forward()
has computed an output.If
with_kwargs
isFalse
or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()
is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargs
isTrue
, the forward hook will be passed thekwargs
given to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True
, the providedhook
will be fired before all existingforward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward
hooks on thistorch.nn.modules.Module
. Note that globalforward
hooks registered withregister_module_forward_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If
True
, thehook
will be passed the kwargs given to the forward function. Default:False
always_call (bool) – If
True
thehook
will be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)¶
Register a forward pre-hook on the module.
The hook will be called every time before
forward()
is invoked.If
with_kwargs
is false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargs
is true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingforward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward_pre
hooks on thistorch.nn.modules.Module
. Note that globalforward_pre
hooks registered withregister_module_forward_pre_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If true, the
hook
will be passed the kwargs given to the forward function. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)¶
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_input
andgrad_output
are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_input
in subsequent computations.grad_input
will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_input
andgrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward
hooks on thistorch.nn.modules.Module
. Note that globalbackward
hooks registered withregister_module_full_backward_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)¶
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_output
is a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_output
in subsequent computations. Entries ingrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Note that globalbackward_pre
hooks registered withregister_module_full_backward_pre_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)¶
Register a post hook to be run after module’s
load_state_dict
is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
module
argument is the current module that this hook is registered on, and theincompatible_keys
argument is aNamedTuple
consisting of attributesmissing_keys
andunexpected_keys
.missing_keys
is alist
ofstr
containing the missing keys andunexpected_keys
is alist
ofstr
containing the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()
withstrict=True
are affected by modifications the hook makes tomissing_keys
orunexpected_keys
, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True
, and clearing out both missing and unexpected keys will avoid an error.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_module(name, module)¶
Alias for
add_module()
.- Return type
None
- register_parameter(name, param)¶
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None
, then operations that run on parameters, such ascuda
, are ignored. IfNone
, the parameter is not included in the module’sstate_dict
.
- Return type
None
- register_state_dict_pre_hook(hook)¶
Register a pre-hook for the
state_dict()
method.These hooks will be called with arguments:
self
,prefix
, andkeep_vars
before callingstate_dict
onself
. The registered hooks can be used to perform pre-processing before thestate_dict
call is made.
- requires_grad_(requires_grad=True)¶
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_grad
attributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True
.- Returns
self
- Return type
Module
- save_hyperparameters(*args, ignore=None, frame=None, logger=True)¶
Save arguments to
hparams
attribute.- Parameters
args (
Any
) – single object of dict, NameSpace or OmegaConf or string names or arguments from class__init__
ignore (
Union
[str
,Sequence
[str
],None
]) – an argument name or a list of argument names from class__init__
to be ignoredframe (
Optional
[frame
]) – a frame object. Default is Nonelogger (
bool
) – Whether to send the hyperparameters to the logger. Default: True
- Example::
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # manually assign arguments ... self.save_hyperparameters('arg1', 'arg3') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class AutomaticArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # equivalent automatic ... self.save_hyperparameters() ... def forward(self, *args, **kwargs): ... ... >>> model = AutomaticArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg2": abc "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class SingleArgModel(HyperparametersMixin): ... def __init__(self, params): ... super().__init__() ... # manually assign single argument ... self.save_hyperparameters(params) ... def forward(self, *args, **kwargs): ... ... >>> model = SingleArgModel(Namespace(p1=1, p2='abc', p3=3.14)) >>> model.hparams "p1": 1 "p2": abc "p3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # pass argument(s) to ignore as a string or in a list ... self.save_hyperparameters(ignore='arg2') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
- Return type
None
- set_extra_state(state)¶
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()
to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()
for your module if you need to store extra state within its state_dict.- Parameters
state (dict) – Extra state from the state_dict
- Return type
None
- set_mc_dropout(active)¶
- set_predict_parameters(n, num_samples, roll_size, batch_size, n_jobs, predict_likelihood_parameters, mc_dropout)¶
to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
- Return type
None
- setup(stage)¶
Called at the beginning of fit (train + validate), validate, test, or predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
Example:
class LitModel(...): def __init__(self): self.l1 = None def prepare_data(self): download_data() tokenize() # don't do this self.something = else def setup(self, stage): data = load_data(...) self.l1 = nn.Linear(28, data.num_classes)
- Return type
None
See
torch.Tensor.share_memory_()
.- Return type
~T
- state_dict(*args, destination=None, prefix='', keep_vars=False)¶
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
None
are not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()
also accepts positional arguments fordestination
,prefix
andkeep_vars
in order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destination
as it is not designed for end-users.- Parameters
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDict
will be created and returned. Default:None
.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''
.keep_vars (bool, optional) – by default the
Tensor
s returned in the state dict are detached from autograd. If it’s set toTrue
, detaching will not be performed. Default:False
.
- Returns
a dictionary containing a whole state of the module
- Return type
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- property strict_loading: bool¶
Determines how Lightning loads this model using .load_state_dict(…, strict=model.strict_loading).
- Return type
bool
- property supports_probabilistic_prediction: bool¶
- Return type
bool
- teardown(stage)¶
Called at the end of fit (train + validate), validate, test, or predict.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
- Return type
None
- test_dataloader()¶
An iterable or collection of iterables specifying test samples.
For more information about multiple dataloaders, see this section.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
test()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
Note
If you don’t need a test dataset and a
test_step()
, you don’t need to implement this method.- Return type
Any
- test_step(*args, **kwargs)¶
Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.
- Parameters
batch – The output of your data iterable, normally a
DataLoader
.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- Return type
Union
[Tensor
,Mapping
[str
,Any
],None
]- Returns
Tensor
- The loss tensordict
- A dictionary. Can include any keys, but must include the key'loss'
.None
- Skip to the next batch.
# if you have one test dataloader: def test_step(self, batch, batch_idx): ... # if you have multiple test dataloaders: def test_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single test dataset def test_step(self, batch, batch_idx): x, y = batch # implement your own out = self(x) loss = self.loss(out, y) # log 6 example images # or generated text... or whatever sample_imgs = x[:6] grid = torchvision.utils.make_grid(sample_imgs) self.logger.experiment.add_image('example_images', grid, 0) # calculate acc labels_hat = torch.argmax(out, dim=1) test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'test_loss': loss, 'test_acc': test_acc})
If you pass in multiple test dataloaders,
test_step()
will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.# CASE 2: multiple test dataloaders def test_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. ...
Note
If you don’t need to test you don’t need to implement this method.
Note
When the
test_step()
is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.
- to(*args, **kwargs)¶
See
torch.nn.Module.to()
.- Return type
Self
- to_dtype(dtype)¶
Cast module precision (float32 by default) to another precision.
- to_empty(*, device, recurse=True)¶
Move the parameters and buffers to the specified device without copying storage.
- Parameters
device (
torch.device
) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns
self
- Return type
Module
- to_onnx(file_path, input_sample=None, **kwargs)¶
Saves the model in ONNX format.
- Parameters
file_path (
Union
[str
,Path
]) – The path of the file the onnx model should be saved to.input_sample (
Optional
[Any
]) – An input for tracing. Default: None (Use self.example_input_array)**kwargs – Will be passed to torch.onnx.export function.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1) model = SimpleModel() input_sample = torch.randn(1, 64) model.to_onnx("export.onnx", input_sample, export_params=True)
- Return type
None
- to_torchscript(file_path=None, method='script', example_inputs=None, **kwargs)¶
By default compiles the whole model to a
ScriptModule
. If you want to use tracing, please provided the argumentmethod='trace'
and make sure that either the example_inputs argument is provided, or the model hasexample_input_array
set. If you would like to customize the modules that are scripted you should override this method. In case you want to return multiple modules, we recommend using a dictionary.- Parameters
file_path (
Union
[str
,Path
,None
]) – Path where to save the torchscript. Default: None (no file saved).method (
Optional
[str
]) – Whether to use TorchScript’s script or trace method. Default: ‘script’example_inputs (
Optional
[Any
]) – An input to be used to do tracing when method is set to ‘trace’. Default: None (usesexample_input_array
)**kwargs – Additional arguments that will be passed to the
torch.jit.script()
ortorch.jit.trace()
function.
Note
Requires the implementation of the
forward()
method.The exported script will be set to evaluation mode.
It is recommended that you install the latest supported version of PyTorch to use this feature without limitations. See also the
torch.jit
documentation for supported features.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1))) model = SimpleModel() model.to_torchscript(file_path="model.pt") torch.jit.save(model.to_torchscript( file_path="model_trace.pt", method='trace', example_inputs=torch.randn(1, 64)) )
- Return type
Union
[ScriptModule
,Dict
[str
,ScriptModule
]]- Returns
This LightningModule as a torchscript, regardless of whether file_path is defined or not.
- toggle_optimizer(optimizer)¶
Makes sure only the gradients of the current optimizer’s parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
It works with
untoggle_optimizer()
to make sureparam_requires_grad_state
is properly reset.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to toggle.- Return type
None
- train(mode=True)¶
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.- Parameters
mode (bool) – whether to set training mode (
True
) or evaluation mode (False
). Default:True
.- Returns
self
- Return type
Module
- train_criterion_reduction: Optional[str]¶
- train_dataloader()¶
An iterable or collection of iterables specifying training samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
fit()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
- Return type
Any
- property trainer: Trainer¶
- Return type
Trainer
- training: bool¶
- training_step(train_batch, batch_idx)¶
performs the training step
- Return type
Tensor
- transfer_batch_to_device(batch, device, dataloader_idx)¶
Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.The data types listed below (and any arbitrary nesting of them) are supported out of the box:
torch.Tensor
or anything that implements .to(…)list
dict
tuple
For anything else, you need to define how the data is moved to the target device (CPU, GPU, TPU, …).
Note
This hook should only transfer the data and not modify it, nor should it move the data to any other device than the one passed in as argument (unless you know what you are doing). To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be transferred to a new device.device (
device
) – The target device as defined in PyTorch.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A reference to the data on the new device.
Example:
def transfer_batch_to_device(self, batch, device, dataloader_idx): if isinstance(batch, CustomBatch): # move all tensors in your custom data structure to the device batch.samples = batch.samples.to(device) batch.targets = batch.targets.to(device) elif dataloader_idx == 0: # skip device transfer for the first dataloader or anything you wish pass else: batch = super().transfer_batch_to_device(batch, device, dataloader_idx) return batch
See also
move_data_to_device()
apply_to_collection()
- type(dst_type)¶
See
torch.nn.Module.type()
.- Return type
Self
- unfreeze()¶
Unfreeze all parameters for training.
model = MyLightningModule(...) model.unfreeze()
- Return type
None
- untoggle_optimizer(optimizer)¶
Resets the state of required gradients that were toggled with
toggle_optimizer()
.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to untoggle.- Return type
None
- val_criterion_reduction: Optional[str]¶
- val_dataloader()¶
An iterable or collection of iterables specifying validation samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.fit()
validate()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
Note
If you don’t need a validation dataset and a
validation_step()
, you don’t need to implement this method.- Return type
Any
- validation_step(val_batch, batch_idx)¶
performs the validation step
- Return type
Tensor
- xpu(device=None)¶
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- zero_grad(set_to_none=True)¶
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizer
for more context.- Parameters
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()
for details.- Return type
None
- class darts.models.forecasting.pl_forecasting_module.PLMixedCovariatesModule(input_chunk_length, output_chunk_length, output_chunk_shift=0, train_sample_shape=None, loss_fn=MSELoss(), torch_metrics=None, likelihood=None, optimizer_cls=<class 'torch.optim.adam.Adam'>, optimizer_kwargs=None, lr_scheduler_cls=None, lr_scheduler_kwargs=None, use_reversible_instance_norm=False)[source]¶
Bases:
PLForecastingModule
,ABC
PyTorch Lightning-based Forecasting Module.
This class is meant to be inherited to create a new PyTorch Lightning-based forecasting module. When subclassing this class, please make sure to add the following methods with the given signatures:
PLForecastingModule.__init__()
PLForecastingModule._produce_train_output()
PLForecastingModule._get_batch_prediction()
In subclass MyModel’s
__init__()
function callsuper(MyModel, self).__init__(**kwargs)
wherekwargs
are the parameters ofPLForecastingModule
.- Parameters
input_chunk_length (
int
) – Number of time steps in the past to take as a model input (per chunk). Applies to the target series, and past and/or future covariates (if the model supports it).output_chunk_length (
int
) – Number of time steps predicted at once (per chunk) by the internal model. Also, the number of future values from future covariates to use as a model input (if the model supports future covariates). It is not the same as forecast horizon n used in predict(), which is the desired number of prediction points generated using either a one-shot- or autoregressive forecast. Setting n <= output_chunk_length prevents auto-regression. This is useful when the covariates don’t extend far enough into the future, or to prohibit the model from using future values of past and / or future covariates for prediction (depending on the model’s covariate support).train_sample_shape (
Optional
[Tuple
]) – Shape of the model’s input, used to instantiate model without callingfit_from_dataset
and perform sanity check on new training/inference datasets used for re-training or prediction.loss_fn (
_Loss
) – PyTorch loss function used for training. This parameter will be ignored for probabilistic models if thelikelihood
parameter is specified. Default:torch.nn.MSELoss()
.torch_metrics (
Union
[Metric
,MetricCollection
,None
]) – A torch metric or aMetricCollection
used for evaluation. A full list of available metrics can be found at https://torchmetrics.readthedocs.io/en/latest/. Default:None
.likelihood (
Optional
[Likelihood
]) – One of Darts’Likelihood
models to be used for probabilistic forecasts. Default:None
.optimizer_cls (
Optimizer
) – The PyTorch optimizer class to be used. Default:torch.optim.Adam
.optimizer_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch optimizer (e.g.,{'lr': 1e-3}
for specifying a learning rate). Otherwise the default values of the selectedoptimizer_cls
will be used. Default:None
.lr_scheduler_cls (
Optional
[_LRScheduler
]) – Optionally, the PyTorch learning rate scheduler class to be used. SpecifyingNone
corresponds to using a constant learning rate. Default:None
.lr_scheduler_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch learning rate scheduler. Default:None
.use_reversible_instance_norm (
bool
) – Whether to use reversible instance normalization RINorm against distribution shift as shown in [1]. It is only applied to the features of the target series and not the covariates.
References
- 1
T. Kim et al. “Reversible Instance Normalization for Accurate Time-Series Forecasting against Distribution Shift”, https://openreview.net/forum?id=cGDAkQo1C0p
Attributes
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.The current epoch in the
Trainer
, or 0 if not attached.Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.The example input array is a specification of what the module can consume in the
forward()
method.The index of the current process across all nodes and devices.
Total training batches seen across all epochs.
The collection of hyperparameters saved with
save_hyperparameters()
.The collection of hyperparameters saved with
save_hyperparameters()
.The index of the current process within a single node.
Reference to the logger object in the Trainer.
Reference to the list of loggers in the Trainer.
Returns
True
if this model is currently located on a GPU.Number of time steps predicted at once by the model.
Determines how Lightning loads this model using .load_state_dict(..., strict=model.strict_loading).
device
dtype
epochs_trained
fabric
supports_probabilistic_prediction
trainer
Methods
add_module
(name, module)Add a child module to the current module.
all_gather
(data[, group, sync_grads])Gather tensors or collections of tensors from multiple processes.
apply
(fn)Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.backward
(loss, *args, **kwargs)Called to perform backward on the loss returned in
training_step()
.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Return an iterator over module buffers.
children
()Return an iterator over immediate children modules.
clip_gradients
(optimizer[, ...])Handles gradient clipping internally.
compile
(*args, **kwargs)Compile this Module's forward using
torch.compile()
.Configure model-specific callbacks.
configure_gradient_clipping
(optimizer[, ...])Perform gradient clipping for the optimizer parameters.
Hook to create modules in a strategy and precision aware context.
configures optimizers and learning rate schedulers for model optimization.
Deprecated.
configure_torch_metrics
(torch_metrics)process the torch_metrics parameter.
cpu
()See
torch.nn.Module.cpu()
.cuda
([device])Moves all model parameters and buffers to the GPU.
double
()See
torch.nn.Module.double()
.eval
()Set the module in evaluation mode.
Set the extra representation of the module.
float
()See
torch.nn.Module.float()
.forward
(*args, **kwargs)Same as
torch.nn.Module.forward()
.freeze
()Freeze all params for inference.
get_buffer
(target)Return the buffer given by
target
if it exists, otherwise throw an error.Return any extra state to include in the module's state_dict.
get_parameter
(target)Return the parameter given by
target
if it exists, otherwise throw an error.get_submodule
(target)Return the submodule given by
target
if it exists, otherwise throw an error.half
()See
torch.nn.Module.half()
.ipu
([device])Move all model parameters and buffers to the IPU.
load_from_checkpoint
(checkpoint_path[, ...])Primary way of loading a model from a checkpoint.
load_state_dict
(state_dict[, strict, assign])Copy parameters and buffers from
state_dict
into this module and its descendants.log
(name, value[, prog_bar, logger, ...])Log a key, value pair.
log_dict
(dictionary[, prog_bar, logger, ...])Log a dictionary of values at once.
lr_scheduler_step
(scheduler, metric)Override this method to adjust the default way the
Trainer
calls each scheduler.Returns the learning rate scheduler(s) that are being used during training.
manual_backward
(loss, *args, **kwargs)Call this directly from your
training_step()
when doing optimizations manually.modules
()Return an iterator over all modules in the network.
named_buffers
([prefix, recurse, ...])Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse, ...])Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
Called after
loss.backward()
and before optimizers are stepped.on_after_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch after it is transferred to the device.
on_before_backward
(loss)Called before
loss.backward()
.on_before_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch before it is transferred to the device.
on_before_optimizer_step
(optimizer)Called before
optimizer.step()
.on_before_zero_grad
(optimizer)Called after
training_step()
and beforeoptimizer.zero_grad()
.Called at the very end of fit.
Called at the very beginning of fit.
on_load_checkpoint
(checkpoint)Called by Lightning to restore your model.
on_predict_batch_end
(outputs, batch, batch_idx)Called in the predict loop after the batch.
on_predict_batch_start
(batch, batch_idx[, ...])Called in the predict loop before anything happens for that batch.
Called at the end of predicting.
Called at the end of predicting.
Called at the beginning of predicting.
Called when the predict loop starts.
Called at the beginning of predicting.
on_save_checkpoint
(checkpoint)Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
on_test_batch_end
(outputs, batch, batch_idx)Called in the test loop after the batch.
on_test_batch_start
(batch, batch_idx[, ...])Called in the test loop before anything happens for that batch.
Called at the end of testing.
Called in the test loop at the very end of the epoch.
Called in the test loop at the very beginning of the epoch.
Called when the test loop starts.
Called when the test loop ends.
Called at the beginning of testing.
on_train_batch_end
(outputs, batch, batch_idx)Called in the training loop after the batch.
on_train_batch_start
(batch, batch_idx)Called in the training loop before anything happens for that batch.
Called at the end of training before logger experiment is closed.
Called in the training loop at the very end of the epoch.
Called in the training loop at the very beginning of the epoch.
Called at the beginning of training after sanity check.
on_validation_batch_end
(outputs, batch, ...)Called in the validation loop after the batch.
on_validation_batch_start
(batch, batch_idx)Called in the validation loop before anything happens for that batch.
Called at the end of validation.
Called in the validation loop at the very end of the epoch.
Called in the validation loop at the very beginning of the epoch.
Called when the validation loop starts.
Called when the validation loop ends.
Called by the training loop to release gradients before entering the validation loop.
Called at the beginning of validation.
optimizer_step
(epoch, batch_idx, optimizer)Override this method to adjust the default way the
Trainer
calls the optimizer.optimizer_zero_grad
(epoch, batch_idx, optimizer)Override this method to change the default behaviour of
optimizer.zero_grad()
.optimizers
([use_pl_optimizer])Returns the optimizer(s) that are being used during training.
parameters
([recurse])Return an iterator over module parameters.
An iterable or collection of iterables specifying prediction samples.
predict_step
(batch, batch_idx[, dataloader_idx])performs the prediction step
Use this to download and prepare data.
print
(*args, **kwargs)Prints only from process 0.
register_backward_hook
(hook)Register a backward hook on the module.
register_buffer
(name, tensor[, persistent])Add a buffer to the module.
register_forward_hook
(hook, *[, prepend, ...])Register a forward hook on the module.
register_forward_pre_hook
(hook, *[, ...])Register a forward pre-hook on the module.
register_full_backward_hook
(hook[, prepend])Register a backward hook on the module.
register_full_backward_pre_hook
(hook[, prepend])Register a backward pre-hook on the module.
Register a post hook to be run after module's
load_state_dict
is called.register_module
(name, module)Alias for
add_module()
.register_parameter
(name, param)Add a parameter to the module.
Register a pre-hook for the
state_dict()
method.requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
save_hyperparameters
(*args[, ignore, frame, ...])Save arguments to
hparams
attribute.set_extra_state
(state)Set extra state contained in the loaded state_dict.
set_predict_parameters
(n, num_samples, ...)to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
setup
(stage)Called at the beginning of fit (train + validate), validate, test, or predict.
See
torch.Tensor.share_memory_()
.state_dict
(*args[, destination, prefix, ...])Return a dictionary containing references to the whole state of the module.
teardown
(stage)Called at the end of fit (train + validate), validate, test, or predict.
An iterable or collection of iterables specifying test samples.
test_step
(*args, **kwargs)Operates on a single batch of data from the test set.
to
(*args, **kwargs)See
torch.nn.Module.to()
.to_dtype
(dtype)Cast module precision (float32 by default) to another precision.
to_empty
(*, device[, recurse])Move the parameters and buffers to the specified device without copying storage.
to_onnx
(file_path[, input_sample])Saves the model in ONNX format.
to_torchscript
([file_path, method, ...])By default compiles the whole model to a
ScriptModule
.toggle_optimizer
(optimizer)Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
train
([mode])Set the module in training mode.
An iterable or collection of iterables specifying training samples.
training_step
(train_batch, batch_idx)performs the training step
transfer_batch_to_device
(batch, device, ...)Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.type
(dst_type)See
torch.nn.Module.type()
.unfreeze
()Unfreeze all parameters for training.
untoggle_optimizer
(optimizer)Resets the state of required gradients that were toggled with
toggle_optimizer()
.An iterable or collection of iterables specifying validation samples.
validation_step
(val_batch, batch_idx)performs the validation step
xpu
([device])Move all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Reset gradients of all model parameters.
__call__
set_mc_dropout
- CHECKPOINT_HYPER_PARAMS_KEY = 'hyper_parameters'¶
- CHECKPOINT_HYPER_PARAMS_NAME = 'hparams_name'¶
- CHECKPOINT_HYPER_PARAMS_TYPE = 'hparams_type'¶
- T_destination¶
alias of TypeVar(‘T_destination’, bound=
Dict
[str
,Any
])
- add_module(name, module)¶
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- Return type
None
- all_gather(data, group=None, sync_grads=False)¶
Gather tensors or collections of tensors from multiple processes.
This method needs to be called on all processes and the tensors need to have the same shape across all processes, otherwise your program will stall forever.
- Parameters
data (
Union
[Tensor
,Dict
,List
,Tuple
]) – int, float, tensor of shape (batch, …), or a (possibly nested) collection thereof.group (
Optional
[Any
]) – the process group to gather results from. Defaults to all processes (world)sync_grads (
bool
) – flag that allows users to synchronize gradients for the all_gather operation
- Return type
Union
[Tensor
,Dict
,List
,Tuple
]- Returns
A tensor of shape (world_size, batch, …), or if the input was a collection the output will also be a collection with tensors of this shape. For the special case where world_size is 1, no additional dimension is added to the tensor(s).
- allow_zero_length_dataloader_with_multiple_devices: bool¶
- apply(fn)¶
Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters
fn (
Module
-> None) – function to be applied to each submodule- Returns
self
- Return type
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- property automatic_optimization: bool¶
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.- Return type
bool
- backward(loss, *args, **kwargs)¶
Called to perform backward on the loss returned in
training_step()
. Override this hook with your own implementation if you need to.- Parameters
loss (
Tensor
) – The loss tensor returned bytraining_step()
. If gradient accumulation is used, the loss here holds the normalized value (scaled by 1 / accumulation steps).
Example:
def backward(self, loss): loss.backward()
- Return type
None
- bfloat16()¶
Casts all floating point parameters and buffers to
bfloat16
datatype.Note
This method modifies the module in-place.
- Returns
self
- Return type
Module
- buffers(recurse=True)¶
Return an iterator over module buffers.
- Parameters
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Tensor
]
- call_super_init: bool = False¶
- children()¶
Return an iterator over immediate children modules.
- Yields
Module – a child module
- Return type
Iterator
[Module
]
- clip_gradients(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Handles gradient clipping internally.
Note
Do not override this method. If you want to customize gradient clipping, consider using
configure_gradient_clipping()
method.For manual optimization (
self.automatic_optimization = False
), if you want to use gradient clipping, consider callingself.clip_gradients(opt, gradient_clip_val=0.5, gradient_clip_algorithm="norm")
manually in the training step.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. Passgradient_clip_algorithm="value"
to clip by value, andgradient_clip_algorithm="norm"
to clip by norm.
- Return type
None
- compile(*args, **kwargs)¶
Compile this Module’s forward using
torch.compile()
.This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile()
.See
torch.compile()
for details on the arguments for this function.
- configure_callbacks()¶
Configure model-specific callbacks. When the model gets attached, e.g., when
.fit()
or.test()
gets called, the list or a callback returned here will be merged with the list of callbacks passed to the Trainer’scallbacks
argument. If a callback returned here has the same type as one or several callbacks already present in the Trainer’s callbacks list, it will take priority and replace them. In addition, Lightning will make sureModelCheckpoint
callbacks run last.- Return type
Union
[Sequence
[Callback
],Callback
]- Returns
A callback or a list of callbacks which will extend the list of callbacks in the Trainer.
Example:
def configure_callbacks(self): early_stop = EarlyStopping(monitor="val_acc", mode="max") checkpoint = ModelCheckpoint(monitor="val_loss") return [early_stop, checkpoint]
- configure_gradient_clipping(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Perform gradient clipping for the optimizer parameters. Called before
optimizer_step()
.- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients. By default, value passed in Trainer will be available here.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. By default, value passed in Trainer will be available here.
Example:
def configure_gradient_clipping(self, optimizer, gradient_clip_val, gradient_clip_algorithm): # Implement your own custom logic to clip gradients # You can call `self.clip_gradients` with your settings: self.clip_gradients( optimizer, gradient_clip_val=gradient_clip_val, gradient_clip_algorithm=gradient_clip_algorithm )
- Return type
None
- configure_model()¶
Hook to create modules in a strategy and precision aware context.
This is particularly useful for when using sharded strategies (FSDP and DeepSpeed), where we’d like to shard the model instantly to save memory and initialization time. For non-sharded strategies, you can choose to override this hook or to initialize your model under the
init_module()
context manager.This hook is called during each of fit/val/test/predict stages in the same process, so ensure that implementation of this hook is idempotent, i.e., after the first time the hook is called, subsequent calls to it should be a no-op.
- Return type
None
- configure_optimizers()¶
configures optimizers and learning rate schedulers for model optimization.
- configure_sharded_model()¶
Deprecated.
Use
configure_model()
instead.- Return type
None
- static configure_torch_metrics(torch_metrics)¶
process the torch_metrics parameter.
- Return type
MetricCollection
- cpu()¶
See
torch.nn.Module.cpu()
.- Return type
Self
- cuda(device=None)¶
Moves all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
- Parameters
device (
Union
[int
,device
,None
]) – If specified, all parameters will be copied to that device. If None, the current CUDA device index will be used.- Returns
self
- Return type
Module
- property current_epoch: int¶
The current epoch in the
Trainer
, or 0 if not attached.- Return type
int
- property device: device¶
- Return type
device
- property device_mesh: Optional[DeviceMesh]¶
Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.- Return type
Optional
[ForwardRef
]
- double()¶
See
torch.nn.Module.double()
.- Return type
Self
- property dtype: Union[str, dtype]¶
- Return type
Union
[str
,dtype
]
- dump_patches: bool = False¶
- property epochs_trained¶
- eval()¶
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.This is equivalent with
self.train(False)
.See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns
self
- Return type
Module
- property example_input_array: Optional[Union[Tensor, Tuple, Dict]]¶
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
Union
[Tensor
,Tuple
,Dict
,None
]
- extra_repr()¶
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type
str
- property fabric: Optional[Fabric]¶
- Return type
Optional
[Fabric
]
- float()¶
See
torch.nn.Module.float()
.- Return type
Self
- abstract forward(*args, **kwargs)¶
Same as
torch.nn.Module.forward()
.- Parameters
*args – Whatever you decide to pass into the forward method.
**kwargs – Keyword arguments are also possible.
- Return type
Any
- Returns
Your model’s output
- freeze()¶
Freeze all params for inference.
Example:
model = MyLightningModule(...) model.freeze()
- Return type
None
- get_buffer(target)¶
Return the buffer given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the buffer to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The buffer referenced by
target
- Return type
torch.Tensor
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()¶
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()
for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns
Any extra state to store in the module’s state_dict
- Return type
object
- get_parameter(target)¶
Return the parameter given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the Parameter to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The Parameter referenced by
target
- Return type
torch.nn.Parameter
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)¶
Return the submodule given by
target
if it exists, otherwise throw an error.For example, let’s say you have an
nn.Module
A
that looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )
(The diagram shows an
nn.Module
A
.A
has a nested submodulenet_b
, which itself has two submodulesnet_c
andlinear
.net_c
then has a submoduleconv
.)To check whether or not we have the
linear
submodule, we would callget_submodule("net_b.linear")
. To check whether we have theconv
submodule, we would callget_submodule("net_b.net_c.conv")
.The runtime of
get_submodule
is bounded by the degree of module nesting intarget
. A query againstnamed_modules
achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submodule
should always be used.- Parameters
target (
str
) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns
The submodule referenced by
target
- Return type
torch.nn.Module
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- property global_rank: int¶
The index of the current process across all nodes and devices.
- Return type
int
- property global_step: int¶
Total training batches seen across all epochs.
If no Trainer is attached, this propery is 0.
- Return type
int
- half()¶
See
torch.nn.Module.half()
.- Return type
Self
- property hparams: Union[AttributeDict, MutableMapping]¶
The collection of hyperparameters saved with
save_hyperparameters()
. It is mutable by the user. For the frozen set of initial hyperparameters, usehparams_initial
.- Return type
Union
[AttributeDict
,MutableMapping
]- Returns
Mutable hyperparameters dictionary
- property hparams_initial: AttributeDict¶
The collection of hyperparameters saved with
save_hyperparameters()
. These contents are read-only. Manual updates to the saved hyperparameters can instead be performed throughhparams
.- Returns
immutable initial hyperparameters
- Return type
AttributeDict
- ipu(device=None)¶
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- load_from_checkpoint(checkpoint_path, map_location=None, hparams_file=None, strict=None, **kwargs)¶
Primary way of loading a model from a checkpoint. When Lightning saves a checkpoint it stores the arguments passed to
__init__
in the checkpoint under"hyper_parameters"
.Any arguments specified through **kwargs will override args stored in
"hyper_parameters"
.- Parameters
checkpoint_path (
Union
[str
,Path
,IO
]) – Path to checkpoint. This can also be a URL, or file-like objectmap_location (
Union
[device
,str
,int
,Callable
[[UntypedStorage
,str
],Optional
[UntypedStorage
]],Dict
[Union
[device
,str
,int
],Union
[device
,str
,int
]],None
]) – If your checkpoint saved a GPU model and you now load on CPUs or a different number of GPUs, use this to map to the new setup. The behaviour is the same as intorch.load()
.hparams_file (
Union
[str
,Path
,None
]) –Optional path to a
.yaml
or.csv
file with hierarchical structure as in this example:drop_prob: 0.2 dataloader: batch_size: 32
You most likely won’t need this since Lightning will always save the hyperparameters to the checkpoint. However, if your checkpoint weights don’t have the hyperparameters saved, use this method to pass in a
.yaml
file with the hparams you’d like to use. These will be converted into adict
and passed into yourLightningModule
for use.If your model’s
hparams
argument isNamespace
and.yaml
file has hierarchical structure, you need to refactor your model to treathparams
asdict
.strict (
Optional
[bool
]) – Whether to strictly enforce that the keys incheckpoint_path
match the keys returned by this module’s state dict. Defaults toTrue
unlessLightningModule.strict_loading
is set, in which case it defaults to the value ofLightningModule.strict_loading
.**kwargs – Any extra keyword args needed to init the model. Can also be used to override saved hyperparameter values.
- Return type
Self
- Returns
LightningModule
instance with loaded weights and hyperparameters (if available).
Note
load_from_checkpoint
is a class method. You should use yourLightningModule
class to call it instead of theLightningModule
instance, or aTypeError
will be raised.Note
To ensure all layers can be loaded from the checkpoint, this function will call
configure_model()
directly after instantiating the model if this hook is overridden in your LightningModule. However, note thatload_from_checkpoint
does not support loading sharded checkpoints, and you may run out of memory if the model is too large. In this case, consider loading through the Trainer via.fit(ckpt_path=...)
.Example:
# load weights without mapping ... model = MyLightningModule.load_from_checkpoint('path/to/checkpoint.ckpt') # or load weights mapping all weights from GPU 1 to GPU 0 ... map_location = {'cuda:1':'cuda:0'} model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', map_location=map_location ) # or load weights and hyperparameters from separate files. model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', hparams_file='/path/to/hparams_file.yaml' ) # override some of the params with new values model = MyLightningModule.load_from_checkpoint( PATH, num_layers=128, pretrained_ckpt_path=NEW_PATH, ) # predict pretrained_model.eval() pretrained_model.freeze() y_hat = pretrained_model(x)
- load_state_dict(state_dict, strict=True, assign=False)¶
Copy parameters and buffers from
state_dict
into this module and its descendants.If
strict
isTrue
, then the keys ofstate_dict
must exactly match the keys returned by this module’sstate_dict()
function.Warning
If
assign
isTrue
the optimizer must be created after the call toload_state_dict
unlessget_swap_module_params_on_conversion()
isTrue
.- Parameters
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dict
match the keys returned by this module’sstate_dict()
function. Default:True
assign (bool, optional) – When
False
, the properties of the tensors in the current module are preserved while whenTrue
, the properties of the Tensors in the state dict are preserved. The only exception is therequires_grad
field ofDefault: ``False`
- Returns
- missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided
state_dict
.
- unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided
state_dict
.
- Return type
NamedTuple
withmissing_keys
andunexpected_keys
fields
Note
If a parameter or buffer is registered as
None
and its corresponding key exists instate_dict
,load_state_dict()
will raise aRuntimeError
.
- property local_rank: int¶
The index of the current process within a single node.
- Return type
int
- log(name, value, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, metric_attribute=None, rank_zero_only=False)¶
Log a key, value pair.
Example:
self.log('train_loss', loss)
The default behavior per hook is documented here: extensions/logging:Automatic Logging.
- Parameters
name (
str
) – key to log. Must be identical across all processes if using DDP or any other distributed strategy.value (
Union
[Metric
,Tensor
,int
,float
]) – value to log. Can be afloat
,Tensor
, or aMetric
.prog_bar (
bool
) – ifTrue
logs to the progress bar.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto detach the graph.sync_dist (
bool
) – ifTrue
, reduces the metric across devices. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the DDP group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple dataloaders). If False, user needs to give unique names for each dataloader to not mix the values.batch_size (
Optional
[int
]) – Current batch_size. This will be directly inferred from the loaded batch, but for some data structures you might need to explicitly provide it.metric_attribute (
Optional
[str
]) – To restore the metric state, Lightning requires the reference of thetorchmetrics.Metric
in your model. This is found automatically if it is a model attribute.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- log_dict(dictionary, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, rank_zero_only=False)¶
Log a dictionary of values at once.
Example:
values = {'loss': loss, 'acc': acc, ..., 'metric_n': metric_n} self.log_dict(values)
- Parameters
dictionary (
Union
[Mapping
[str
,Union
[Metric
,Tensor
,int
,float
]],MetricCollection
]) – key value pairs. Keys must be identical across all processes if using DDP or any other distributed strategy. The values can be afloat
,Tensor
,Metric
, orMetricCollection
.prog_bar (
bool
) – ifTrue
logs to the progress base.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step.None
auto-logs for training_step but not validation/test_step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics.None
auto-logs for val/test step but nottraining_step
. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto-detach the graphsync_dist (
bool
) – ifTrue
, reduces the metric across GPUs/TPUs. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the ddp group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple). IfFalse
, user needs to give unique names for each dataloader to not mix values.batch_size (
Optional
[int
]) – Current batch size. This will be directly inferred from the loaded batch, but some data structures might need to explicitly provide it.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- property logger: Optional[Union[Logger, Logger]]¶
Reference to the logger object in the Trainer.
- Return type
Union
[Logger
,Logger
,None
]
- property loggers: Union[List[Logger], List[Logger]]¶
Reference to the list of loggers in the Trainer.
- Return type
Union
[List
[Logger
],List
[Logger
]]
- lr_scheduler_step(scheduler, metric)¶
Override this method to adjust the default way the
Trainer
calls each scheduler. By default, Lightning callsstep()
and as shown in the example for each scheduler based on itsinterval
.- Parameters
scheduler (
Union
[LRScheduler
,ReduceLROnPlateau
]) – Learning rate scheduler.metric (
Optional
[Any
]) – Value of the monitor used for schedulers likeReduceLROnPlateau
.
Examples:
# DEFAULT def lr_scheduler_step(self, scheduler, metric): if metric is None: scheduler.step() else: scheduler.step(metric) # Alternative way to update schedulers if it requires an epoch value def lr_scheduler_step(self, scheduler, metric): scheduler.step(epoch=self.current_epoch)
- Return type
None
- lr_schedulers()¶
Returns the learning rate scheduler(s) that are being used during training. Useful for manual optimization.
- Return type
Union
[None
,List
[Union
[LRScheduler
,ReduceLROnPlateau
]],LRScheduler
,ReduceLROnPlateau
]- Returns
A single scheduler, or a list of schedulers in case multiple ones are present, or
None
if no schedulers were returned inconfigure_optimizers()
.
- manual_backward(loss, *args, **kwargs)¶
Call this directly from your
training_step()
when doing optimizations manually. By using this, Lightning can ensure that all the proper scaling gets applied when using mixed precision.See manual optimization for more examples.
Example:
def training_step(...): opt = self.optimizers() loss = ... opt.zero_grad() # automatically applies scaling, etc... self.manual_backward(loss) opt.step()
- Parameters
loss (
Tensor
) – The tensor on which to compute gradients. Must have a graph attached.*args – Additional positional arguments to be forwarded to
backward()
**kwargs – Additional keyword arguments to be forwarded to
backward()
- Return type
None
- modules()¶
Return an iterator over all modules in the network.
- Yields
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- Return type
Iterator
[Module
]
- named_buffers(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- Return type
Iterator
[Tuple
[str
,Tensor
]]
- named_children()¶
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- Return type
Iterator
[Tuple
[str
,Module
]]
- named_modules(memo=None, prefix='', remove_duplicate=True)¶
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters
memo (
Optional
[Set
[Module
]]) – a memo to store the set of modules already added to the resultprefix (
str
) – a prefix that will be added to the name of the moduleremove_duplicate (
bool
) – whether to remove the duplicated module instances in the result or not
- Yields
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- Return type
Iterator
[Tuple
[str
,Parameter
]]
- on_after_backward()¶
Called after
loss.backward()
and before optimizers are stepped.Note
If using native AMP, the gradients will not be unscaled at this point. Use the
on_before_optimizer_step
if you need the unscaled gradients.- Return type
None
- on_after_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch after it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_after_batch_transfer(self, batch, dataloader_idx): batch['x'] = gpu_transforms(batch['x']) return batch
- on_before_backward(loss)¶
Called before
loss.backward()
.- Parameters
loss (
Tensor
) – Loss divided by number of batches for gradient accumulation and scaled if using AMP.- Return type
None
- on_before_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch before it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_before_batch_transfer(self, batch, dataloader_idx): batch['x'] = transforms(batch['x']) return batch
- on_before_optimizer_step(optimizer)¶
Called before
optimizer.step()
.If using gradient accumulation, the hook is called once the gradients have been accumulated. See: :paramref:`~pytorch_lightning.trainer.trainer.Trainer.accumulate_grad_batches`.
If using AMP, the loss will be unscaled before calling this hook. See these docs for more information on the scaling of gradients.
If clipping gradients, the gradients will not have been clipped yet.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.
Example:
def on_before_optimizer_step(self, optimizer): # example to inspect gradient information in tensorboard if self.trainer.global_step % 25 == 0: # don't make the tf file huge for k, v in self.named_parameters(): self.logger.experiment.add_histogram( tag=k, values=v.grad, global_step=self.trainer.global_step )
- Return type
None
- on_before_zero_grad(optimizer)¶
Called after
training_step()
and beforeoptimizer.zero_grad()
.Called in the training loop after taking an optimizer step and before zeroing grads. Good place to inspect weight information with weights updated.
This is where it is called:
for optimizer in optimizers: out = training_step(...) model.on_before_zero_grad(optimizer) # < ---- called here optimizer.zero_grad() backward()
- Parameters
optimizer (
Optimizer
) – The optimizer for which grads should be zeroed.- Return type
None
- on_fit_end()¶
Called at the very end of fit.
If on DDP it is called on every process
- Return type
None
- on_fit_start()¶
Called at the very beginning of fit.
If on DDP it is called on every process
- Return type
None
- property on_gpu: bool¶
Returns
True
if this model is currently located on a GPU.Useful to set flags around the LightningModule for different CPU vs GPU behavior.
- Return type
bool
- on_load_checkpoint(checkpoint)¶
Called by Lightning to restore your model. If you saved something with
on_save_checkpoint()
this is your chance to restore this.- Parameters
checkpoint (
Dict
[str
,Any
]) – Loaded checkpoint
Example:
def on_load_checkpoint(self, checkpoint): # 99% of the time you don't need to implement this method self.something_cool_i_want_to_save = checkpoint['something_cool_i_want_to_save']
Note
Lightning auto-restores global step, epoch, and train state including amp scaling. There is no need for you to restore anything regarding training.
- Return type
None
- on_predict_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop after the batch.
- Parameters
outputs (
Optional
[Any
]) – The outputs of predict_step(x)batch (
Any
) – The batched data as it is returned by the prediction DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_start()¶
Called at the beginning of predicting.
- Return type
None
- on_predict_model_eval()¶
Called when the predict loop starts.
The predict loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior.- Return type
None
- on_predict_start()¶
Called at the beginning of predicting.
- Return type
None
- on_save_checkpoint(checkpoint)¶
Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
- Parameters
checkpoint (
Dict
[str
,Any
]) – The full checkpoint dictionary before it gets dumped to a file. Implementations of this hook can insert additional data into this dictionary.
Example:
def on_save_checkpoint(self, checkpoint): # 99% of use cases you don't need to implement this method checkpoint['something_cool_i_want_to_save'] = my_cool_pickable_object
Note
Lightning saves all aspects of training (epoch, global step, etc…) including amp scaling. There is no need for you to store anything about training.
- Return type
None
- on_test_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the test loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of test_step(x)batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the test loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_end()¶
Called at the end of testing.
- Return type
None
- on_test_epoch_end()¶
Called in the test loop at the very end of the epoch.
- Return type
None
- on_test_epoch_start()¶
Called in the test loop at the very beginning of the epoch.
- Return type
None
- on_test_model_eval()¶
Called when the test loop starts.
The test loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_test_model_train()
.- Return type
None
- on_test_model_train()¶
Called when the test loop ends.
The test loop by default restores the training mode of the LightningModule to what it was before starting testing. Override this hook to change the behavior. See also
on_test_model_eval()
.- Return type
None
- on_test_start()¶
Called at the beginning of testing.
- Return type
None
- on_train_batch_end(outputs, batch, batch_idx)¶
Called in the training loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of training_step(x)batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
Note
The value
outputs["loss"]
here will be the normalized value w.r.taccumulate_grad_batches
of the loss returned fromtraining_step
.- Return type
None
- on_train_batch_start(batch, batch_idx)¶
Called in the training loop before anything happens for that batch.
If you return -1 here, you will skip training for the rest of the current epoch.
- Parameters
batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
- Return type
Optional
[int
]
- on_train_end()¶
Called at the end of training before logger experiment is closed.
- Return type
None
- on_train_epoch_end()¶
Called in the training loop at the very end of the epoch.
To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the
LightningModule
and access them in this hook:class MyLightningModule(L.LightningModule): def __init__(self): super().__init__() self.training_step_outputs = [] def training_step(self): loss = ... self.training_step_outputs.append(loss) return loss def on_train_epoch_end(self): # do something with all training_step outputs, for example: epoch_mean = torch.stack(self.training_step_outputs).mean() self.log("training_epoch_mean", epoch_mean) # free up the memory self.training_step_outputs.clear()
- on_train_epoch_start()¶
Called in the training loop at the very beginning of the epoch.
- Return type
None
- on_train_start()¶
Called at the beginning of training after sanity check.
- Return type
None
- on_validation_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of validation_step(x)batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_end()¶
Called at the end of validation.
- Return type
None
- on_validation_epoch_end()¶
Called in the validation loop at the very end of the epoch.
- on_validation_epoch_start()¶
Called in the validation loop at the very beginning of the epoch.
- Return type
None
- on_validation_model_eval()¶
Called when the validation loop starts.
The validation loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_validation_model_train()
.- Return type
None
- on_validation_model_train()¶
Called when the validation loop ends.
The validation loop by default restores the training mode of the LightningModule to what it was before starting validation. Override this hook to change the behavior. See also
on_validation_model_eval()
.- Return type
None
- on_validation_model_zero_grad()¶
Called by the training loop to release gradients before entering the validation loop.
- Return type
None
- on_validation_start()¶
Called at the beginning of validation.
- Return type
None
- optimizer_step(epoch, batch_idx, optimizer, optimizer_closure=None)¶
Override this method to adjust the default way the
Trainer
calls the optimizer.By default, Lightning calls
step()
andzero_grad()
as shown in the example. This method (andzero_grad()
) won’t be called during the accumulation phase whenTrainer(accumulate_grad_batches != 1)
. Overriding this hook has no benefit with manual optimization.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Union
[Optimizer
,LightningOptimizer
]) – A PyTorch optimizeroptimizer_closure (
Optional
[Callable
[[],Any
]]) – The optimizer closure. This closure must be executed as it includes the calls totraining_step()
,optimizer.zero_grad()
, andbackward()
.
Examples:
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_closure): # Add your custom logic to run directly before `optimizer.step()` optimizer.step(closure=optimizer_closure) # Add your custom logic to run directly after `optimizer.step()`
- Return type
None
- optimizer_zero_grad(epoch, batch_idx, optimizer)¶
Override this method to change the default behaviour of
optimizer.zero_grad()
.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Optimizer
) – A PyTorch optimizer
Examples:
# DEFAULT def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad() # Set gradients to `None` instead of zero to improve performance (not required on `torch>=2.0.0`). def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad(set_to_none=True)
See
torch.optim.Optimizer.zero_grad()
for the explanation of the above example.- Return type
None
- optimizers(use_pl_optimizer=True)¶
Returns the optimizer(s) that are being used during training. Useful for manual optimization.
- Parameters
use_pl_optimizer (
bool
) – IfTrue
, will wrap the optimizer(s) in aLightningOptimizer
for automatic handling of precision, profiling, and counting of step calls for proper logging and checkpointing. It specifically wraps thestep
method and custom optimizers that don’t have this method are not supported.- Return type
Union
[Optimizer
,LightningOptimizer
,_FabricOptimizer
,List
[Optimizer
],List
[LightningOptimizer
],List
[_FabricOptimizer
]]- Returns
A single optimizer, or a list of optimizers in case multiple ones are present.
- property output_chunk_length: Optional[int]¶
Number of time steps predicted at once by the model.
- Return type
Optional
[int
]
- parameters(recurse=True)¶
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Parameter
]
- pred_batch_size: Optional[int]¶
- pred_mc_dropout: Optional[bool]¶
- pred_n: Optional[int]¶
- pred_n_jobs: Optional[int]¶
- pred_num_samples: Optional[int]¶
- pred_roll_size: Optional[int]¶
- predict_dataloader()¶
An iterable or collection of iterables specifying prediction samples.
For more information about multiple dataloaders, see this section.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.predict()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
- Return type
Any
- Returns
A
torch.utils.data.DataLoader
or a sequence of them specifying prediction samples.
- predict_likelihood_parameters: Optional[bool]¶
- predict_step(batch, batch_idx, dataloader_idx=None)¶
performs the prediction step
- batch
output of Darts’
InferenceDataset
- tuple of(past_target, past_covariates, historic_future_covariates, future_covariates, future_past_covariates, input time series, prediction start time step)
- batch_idx
the batch index of the current batch
- dataloader_idx
the dataloader index
- Return type
Sequence
[TimeSeries
]
- prepare_data()¶
Use this to download and prepare data. Downloading and saving data with multiple processes (distributed settings) will result in corrupted data. Lightning ensures this method is called only within a single process, so you can safely add your downloading logic within.
Warning
DO NOT set state to the model (use
setup
instead) since this is NOT called on every deviceExample:
def prepare_data(self): # good download_data() tokenize() etc() # bad self.split = data_split self.some_state = some_other_state()
In a distributed environment,
prepare_data
can be called in two ways (using prepare_data_per_node)Once per node. This is the default and is only called on LOCAL_RANK=0.
Once in total. Only called on GLOBAL_RANK=0.
Example:
# DEFAULT # called once per node on LOCAL_RANK=0 of that node class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = True # call on GLOBAL_RANK=0 (great for shared file systems) class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = False
This is called before requesting the dataloaders:
model.prepare_data() initialize_distributed() model.setup(stage) model.train_dataloader() model.val_dataloader() model.test_dataloader() model.predict_dataloader()
- Return type
None
- prepare_data_per_node: bool¶
- print(*args, **kwargs)¶
Prints only from process 0. Use this in any distributed mode to log only once.
- Parameters
*args – The thing to print. The same as for Python’s built-in print function.
**kwargs – The same as for Python’s built-in print function.
Example:
def forward(self, x): self.print(x, 'in forward')
- Return type
None
- register_backward_hook(hook)¶
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()
and the behavior of this function will change in future versions.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_buffer(name, tensor, persistent=True)¶
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_mean
is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistent
toFalse
. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict
.Buffers can be accessed as attributes using given names.
- Parameters
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None
, then operations that run on buffers, such ascuda
, are ignored. IfNone
, the buffer is not included in the module’sstate_dict
.persistent (bool) – whether the buffer is part of this module’s
state_dict
.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- Return type
None
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)¶
Register a forward hook on the module.
The hook will be called every time after
forward()
has computed an output.If
with_kwargs
isFalse
or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()
is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargs
isTrue
, the forward hook will be passed thekwargs
given to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True
, the providedhook
will be fired before all existingforward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward
hooks on thistorch.nn.modules.Module
. Note that globalforward
hooks registered withregister_module_forward_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If
True
, thehook
will be passed the kwargs given to the forward function. Default:False
always_call (bool) – If
True
thehook
will be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)¶
Register a forward pre-hook on the module.
The hook will be called every time before
forward()
is invoked.If
with_kwargs
is false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargs
is true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingforward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward_pre
hooks on thistorch.nn.modules.Module
. Note that globalforward_pre
hooks registered withregister_module_forward_pre_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If true, the
hook
will be passed the kwargs given to the forward function. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)¶
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_input
andgrad_output
are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_input
in subsequent computations.grad_input
will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_input
andgrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward
hooks on thistorch.nn.modules.Module
. Note that globalbackward
hooks registered withregister_module_full_backward_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)¶
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_output
is a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_output
in subsequent computations. Entries ingrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Note that globalbackward_pre
hooks registered withregister_module_full_backward_pre_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)¶
Register a post hook to be run after module’s
load_state_dict
is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
module
argument is the current module that this hook is registered on, and theincompatible_keys
argument is aNamedTuple
consisting of attributesmissing_keys
andunexpected_keys
.missing_keys
is alist
ofstr
containing the missing keys andunexpected_keys
is alist
ofstr
containing the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()
withstrict=True
are affected by modifications the hook makes tomissing_keys
orunexpected_keys
, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True
, and clearing out both missing and unexpected keys will avoid an error.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_module(name, module)¶
Alias for
add_module()
.- Return type
None
- register_parameter(name, param)¶
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None
, then operations that run on parameters, such ascuda
, are ignored. IfNone
, the parameter is not included in the module’sstate_dict
.
- Return type
None
- register_state_dict_pre_hook(hook)¶
Register a pre-hook for the
state_dict()
method.These hooks will be called with arguments:
self
,prefix
, andkeep_vars
before callingstate_dict
onself
. The registered hooks can be used to perform pre-processing before thestate_dict
call is made.
- requires_grad_(requires_grad=True)¶
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_grad
attributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True
.- Returns
self
- Return type
Module
- save_hyperparameters(*args, ignore=None, frame=None, logger=True)¶
Save arguments to
hparams
attribute.- Parameters
args (
Any
) – single object of dict, NameSpace or OmegaConf or string names or arguments from class__init__
ignore (
Union
[str
,Sequence
[str
],None
]) – an argument name or a list of argument names from class__init__
to be ignoredframe (
Optional
[frame
]) – a frame object. Default is Nonelogger (
bool
) – Whether to send the hyperparameters to the logger. Default: True
- Example::
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # manually assign arguments ... self.save_hyperparameters('arg1', 'arg3') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class AutomaticArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # equivalent automatic ... self.save_hyperparameters() ... def forward(self, *args, **kwargs): ... ... >>> model = AutomaticArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg2": abc "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class SingleArgModel(HyperparametersMixin): ... def __init__(self, params): ... super().__init__() ... # manually assign single argument ... self.save_hyperparameters(params) ... def forward(self, *args, **kwargs): ... ... >>> model = SingleArgModel(Namespace(p1=1, p2='abc', p3=3.14)) >>> model.hparams "p1": 1 "p2": abc "p3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # pass argument(s) to ignore as a string or in a list ... self.save_hyperparameters(ignore='arg2') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
- Return type
None
- set_extra_state(state)¶
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()
to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()
for your module if you need to store extra state within its state_dict.- Parameters
state (dict) – Extra state from the state_dict
- Return type
None
- set_mc_dropout(active)¶
- set_predict_parameters(n, num_samples, roll_size, batch_size, n_jobs, predict_likelihood_parameters, mc_dropout)¶
to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
- Return type
None
- setup(stage)¶
Called at the beginning of fit (train + validate), validate, test, or predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
Example:
class LitModel(...): def __init__(self): self.l1 = None def prepare_data(self): download_data() tokenize() # don't do this self.something = else def setup(self, stage): data = load_data(...) self.l1 = nn.Linear(28, data.num_classes)
- Return type
None
See
torch.Tensor.share_memory_()
.- Return type
~T
- state_dict(*args, destination=None, prefix='', keep_vars=False)¶
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
None
are not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()
also accepts positional arguments fordestination
,prefix
andkeep_vars
in order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destination
as it is not designed for end-users.- Parameters
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDict
will be created and returned. Default:None
.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''
.keep_vars (bool, optional) – by default the
Tensor
s returned in the state dict are detached from autograd. If it’s set toTrue
, detaching will not be performed. Default:False
.
- Returns
a dictionary containing a whole state of the module
- Return type
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- property strict_loading: bool¶
Determines how Lightning loads this model using .load_state_dict(…, strict=model.strict_loading).
- Return type
bool
- property supports_probabilistic_prediction: bool¶
- Return type
bool
- teardown(stage)¶
Called at the end of fit (train + validate), validate, test, or predict.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
- Return type
None
- test_dataloader()¶
An iterable or collection of iterables specifying test samples.
For more information about multiple dataloaders, see this section.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
test()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
Note
If you don’t need a test dataset and a
test_step()
, you don’t need to implement this method.- Return type
Any
- test_step(*args, **kwargs)¶
Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.
- Parameters
batch – The output of your data iterable, normally a
DataLoader
.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- Return type
Union
[Tensor
,Mapping
[str
,Any
],None
]- Returns
Tensor
- The loss tensordict
- A dictionary. Can include any keys, but must include the key'loss'
.None
- Skip to the next batch.
# if you have one test dataloader: def test_step(self, batch, batch_idx): ... # if you have multiple test dataloaders: def test_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single test dataset def test_step(self, batch, batch_idx): x, y = batch # implement your own out = self(x) loss = self.loss(out, y) # log 6 example images # or generated text... or whatever sample_imgs = x[:6] grid = torchvision.utils.make_grid(sample_imgs) self.logger.experiment.add_image('example_images', grid, 0) # calculate acc labels_hat = torch.argmax(out, dim=1) test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'test_loss': loss, 'test_acc': test_acc})
If you pass in multiple test dataloaders,
test_step()
will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.# CASE 2: multiple test dataloaders def test_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. ...
Note
If you don’t need to test you don’t need to implement this method.
Note
When the
test_step()
is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.
- to(*args, **kwargs)¶
See
torch.nn.Module.to()
.- Return type
Self
- to_dtype(dtype)¶
Cast module precision (float32 by default) to another precision.
- to_empty(*, device, recurse=True)¶
Move the parameters and buffers to the specified device without copying storage.
- Parameters
device (
torch.device
) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns
self
- Return type
Module
- to_onnx(file_path, input_sample=None, **kwargs)¶
Saves the model in ONNX format.
- Parameters
file_path (
Union
[str
,Path
]) – The path of the file the onnx model should be saved to.input_sample (
Optional
[Any
]) – An input for tracing. Default: None (Use self.example_input_array)**kwargs – Will be passed to torch.onnx.export function.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1) model = SimpleModel() input_sample = torch.randn(1, 64) model.to_onnx("export.onnx", input_sample, export_params=True)
- Return type
None
- to_torchscript(file_path=None, method='script', example_inputs=None, **kwargs)¶
By default compiles the whole model to a
ScriptModule
. If you want to use tracing, please provided the argumentmethod='trace'
and make sure that either the example_inputs argument is provided, or the model hasexample_input_array
set. If you would like to customize the modules that are scripted you should override this method. In case you want to return multiple modules, we recommend using a dictionary.- Parameters
file_path (
Union
[str
,Path
,None
]) – Path where to save the torchscript. Default: None (no file saved).method (
Optional
[str
]) – Whether to use TorchScript’s script or trace method. Default: ‘script’example_inputs (
Optional
[Any
]) – An input to be used to do tracing when method is set to ‘trace’. Default: None (usesexample_input_array
)**kwargs – Additional arguments that will be passed to the
torch.jit.script()
ortorch.jit.trace()
function.
Note
Requires the implementation of the
forward()
method.The exported script will be set to evaluation mode.
It is recommended that you install the latest supported version of PyTorch to use this feature without limitations. See also the
torch.jit
documentation for supported features.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1))) model = SimpleModel() model.to_torchscript(file_path="model.pt") torch.jit.save(model.to_torchscript( file_path="model_trace.pt", method='trace', example_inputs=torch.randn(1, 64)) )
- Return type
Union
[ScriptModule
,Dict
[str
,ScriptModule
]]- Returns
This LightningModule as a torchscript, regardless of whether file_path is defined or not.
- toggle_optimizer(optimizer)¶
Makes sure only the gradients of the current optimizer’s parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
It works with
untoggle_optimizer()
to make sureparam_requires_grad_state
is properly reset.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to toggle.- Return type
None
- train(mode=True)¶
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.- Parameters
mode (bool) – whether to set training mode (
True
) or evaluation mode (False
). Default:True
.- Returns
self
- Return type
Module
- train_criterion_reduction: Optional[str]¶
- train_dataloader()¶
An iterable or collection of iterables specifying training samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
fit()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
- Return type
Any
- property trainer: Trainer¶
- Return type
Trainer
- training: bool¶
- training_step(train_batch, batch_idx)¶
performs the training step
- Return type
Tensor
- transfer_batch_to_device(batch, device, dataloader_idx)¶
Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.The data types listed below (and any arbitrary nesting of them) are supported out of the box:
torch.Tensor
or anything that implements .to(…)list
dict
tuple
For anything else, you need to define how the data is moved to the target device (CPU, GPU, TPU, …).
Note
This hook should only transfer the data and not modify it, nor should it move the data to any other device than the one passed in as argument (unless you know what you are doing). To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be transferred to a new device.device (
device
) – The target device as defined in PyTorch.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A reference to the data on the new device.
Example:
def transfer_batch_to_device(self, batch, device, dataloader_idx): if isinstance(batch, CustomBatch): # move all tensors in your custom data structure to the device batch.samples = batch.samples.to(device) batch.targets = batch.targets.to(device) elif dataloader_idx == 0: # skip device transfer for the first dataloader or anything you wish pass else: batch = super().transfer_batch_to_device(batch, device, dataloader_idx) return batch
See also
move_data_to_device()
apply_to_collection()
- type(dst_type)¶
See
torch.nn.Module.type()
.- Return type
Self
- unfreeze()¶
Unfreeze all parameters for training.
model = MyLightningModule(...) model.unfreeze()
- Return type
None
- untoggle_optimizer(optimizer)¶
Resets the state of required gradients that were toggled with
toggle_optimizer()
.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to untoggle.- Return type
None
- val_criterion_reduction: Optional[str]¶
- val_dataloader()¶
An iterable or collection of iterables specifying validation samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.fit()
validate()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
Note
If you don’t need a validation dataset and a
validation_step()
, you don’t need to implement this method.- Return type
Any
- validation_step(val_batch, batch_idx)¶
performs the validation step
- Return type
Tensor
- xpu(device=None)¶
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- zero_grad(set_to_none=True)¶
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizer
for more context.- Parameters
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()
for details.- Return type
None
- class darts.models.forecasting.pl_forecasting_module.PLPastCovariatesModule(input_chunk_length, output_chunk_length, output_chunk_shift=0, train_sample_shape=None, loss_fn=MSELoss(), torch_metrics=None, likelihood=None, optimizer_cls=<class 'torch.optim.adam.Adam'>, optimizer_kwargs=None, lr_scheduler_cls=None, lr_scheduler_kwargs=None, use_reversible_instance_norm=False)[source]¶
Bases:
PLForecastingModule
,ABC
PyTorch Lightning-based Forecasting Module.
This class is meant to be inherited to create a new PyTorch Lightning-based forecasting module. When subclassing this class, please make sure to add the following methods with the given signatures:
PLForecastingModule.__init__()
PLForecastingModule._produce_train_output()
PLForecastingModule._get_batch_prediction()
In subclass MyModel’s
__init__()
function callsuper(MyModel, self).__init__(**kwargs)
wherekwargs
are the parameters ofPLForecastingModule
.- Parameters
input_chunk_length (
int
) – Number of time steps in the past to take as a model input (per chunk). Applies to the target series, and past and/or future covariates (if the model supports it).output_chunk_length (
int
) – Number of time steps predicted at once (per chunk) by the internal model. Also, the number of future values from future covariates to use as a model input (if the model supports future covariates). It is not the same as forecast horizon n used in predict(), which is the desired number of prediction points generated using either a one-shot- or autoregressive forecast. Setting n <= output_chunk_length prevents auto-regression. This is useful when the covariates don’t extend far enough into the future, or to prohibit the model from using future values of past and / or future covariates for prediction (depending on the model’s covariate support).train_sample_shape (
Optional
[Tuple
]) – Shape of the model’s input, used to instantiate model without callingfit_from_dataset
and perform sanity check on new training/inference datasets used for re-training or prediction.loss_fn (
_Loss
) – PyTorch loss function used for training. This parameter will be ignored for probabilistic models if thelikelihood
parameter is specified. Default:torch.nn.MSELoss()
.torch_metrics (
Union
[Metric
,MetricCollection
,None
]) – A torch metric or aMetricCollection
used for evaluation. A full list of available metrics can be found at https://torchmetrics.readthedocs.io/en/latest/. Default:None
.likelihood (
Optional
[Likelihood
]) – One of Darts’Likelihood
models to be used for probabilistic forecasts. Default:None
.optimizer_cls (
Optimizer
) – The PyTorch optimizer class to be used. Default:torch.optim.Adam
.optimizer_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch optimizer (e.g.,{'lr': 1e-3}
for specifying a learning rate). Otherwise the default values of the selectedoptimizer_cls
will be used. Default:None
.lr_scheduler_cls (
Optional
[_LRScheduler
]) – Optionally, the PyTorch learning rate scheduler class to be used. SpecifyingNone
corresponds to using a constant learning rate. Default:None
.lr_scheduler_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch learning rate scheduler. Default:None
.use_reversible_instance_norm (
bool
) – Whether to use reversible instance normalization RINorm against distribution shift as shown in [1]. It is only applied to the features of the target series and not the covariates.
References
- 1
T. Kim et al. “Reversible Instance Normalization for Accurate Time-Series Forecasting against Distribution Shift”, https://openreview.net/forum?id=cGDAkQo1C0p
Attributes
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.The current epoch in the
Trainer
, or 0 if not attached.Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.The example input array is a specification of what the module can consume in the
forward()
method.The index of the current process across all nodes and devices.
Total training batches seen across all epochs.
The collection of hyperparameters saved with
save_hyperparameters()
.The collection of hyperparameters saved with
save_hyperparameters()
.The index of the current process within a single node.
Reference to the logger object in the Trainer.
Reference to the list of loggers in the Trainer.
Returns
True
if this model is currently located on a GPU.Number of time steps predicted at once by the model.
Determines how Lightning loads this model using .load_state_dict(..., strict=model.strict_loading).
device
dtype
epochs_trained
fabric
supports_probabilistic_prediction
trainer
Methods
add_module
(name, module)Add a child module to the current module.
all_gather
(data[, group, sync_grads])Gather tensors or collections of tensors from multiple processes.
apply
(fn)Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.backward
(loss, *args, **kwargs)Called to perform backward on the loss returned in
training_step()
.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Return an iterator over module buffers.
children
()Return an iterator over immediate children modules.
clip_gradients
(optimizer[, ...])Handles gradient clipping internally.
compile
(*args, **kwargs)Compile this Module's forward using
torch.compile()
.Configure model-specific callbacks.
configure_gradient_clipping
(optimizer[, ...])Perform gradient clipping for the optimizer parameters.
Hook to create modules in a strategy and precision aware context.
configures optimizers and learning rate schedulers for model optimization.
Deprecated.
configure_torch_metrics
(torch_metrics)process the torch_metrics parameter.
cpu
()See
torch.nn.Module.cpu()
.cuda
([device])Moves all model parameters and buffers to the GPU.
double
()See
torch.nn.Module.double()
.eval
()Set the module in evaluation mode.
Set the extra representation of the module.
float
()See
torch.nn.Module.float()
.forward
(*args, **kwargs)Same as
torch.nn.Module.forward()
.freeze
()Freeze all params for inference.
get_buffer
(target)Return the buffer given by
target
if it exists, otherwise throw an error.Return any extra state to include in the module's state_dict.
get_parameter
(target)Return the parameter given by
target
if it exists, otherwise throw an error.get_submodule
(target)Return the submodule given by
target
if it exists, otherwise throw an error.half
()See
torch.nn.Module.half()
.ipu
([device])Move all model parameters and buffers to the IPU.
load_from_checkpoint
(checkpoint_path[, ...])Primary way of loading a model from a checkpoint.
load_state_dict
(state_dict[, strict, assign])Copy parameters and buffers from
state_dict
into this module and its descendants.log
(name, value[, prog_bar, logger, ...])Log a key, value pair.
log_dict
(dictionary[, prog_bar, logger, ...])Log a dictionary of values at once.
lr_scheduler_step
(scheduler, metric)Override this method to adjust the default way the
Trainer
calls each scheduler.Returns the learning rate scheduler(s) that are being used during training.
manual_backward
(loss, *args, **kwargs)Call this directly from your
training_step()
when doing optimizations manually.modules
()Return an iterator over all modules in the network.
named_buffers
([prefix, recurse, ...])Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse, ...])Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
Called after
loss.backward()
and before optimizers are stepped.on_after_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch after it is transferred to the device.
on_before_backward
(loss)Called before
loss.backward()
.on_before_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch before it is transferred to the device.
on_before_optimizer_step
(optimizer)Called before
optimizer.step()
.on_before_zero_grad
(optimizer)Called after
training_step()
and beforeoptimizer.zero_grad()
.Called at the very end of fit.
Called at the very beginning of fit.
on_load_checkpoint
(checkpoint)Called by Lightning to restore your model.
on_predict_batch_end
(outputs, batch, batch_idx)Called in the predict loop after the batch.
on_predict_batch_start
(batch, batch_idx[, ...])Called in the predict loop before anything happens for that batch.
Called at the end of predicting.
Called at the end of predicting.
Called at the beginning of predicting.
Called when the predict loop starts.
Called at the beginning of predicting.
on_save_checkpoint
(checkpoint)Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
on_test_batch_end
(outputs, batch, batch_idx)Called in the test loop after the batch.
on_test_batch_start
(batch, batch_idx[, ...])Called in the test loop before anything happens for that batch.
Called at the end of testing.
Called in the test loop at the very end of the epoch.
Called in the test loop at the very beginning of the epoch.
Called when the test loop starts.
Called when the test loop ends.
Called at the beginning of testing.
on_train_batch_end
(outputs, batch, batch_idx)Called in the training loop after the batch.
on_train_batch_start
(batch, batch_idx)Called in the training loop before anything happens for that batch.
Called at the end of training before logger experiment is closed.
Called in the training loop at the very end of the epoch.
Called in the training loop at the very beginning of the epoch.
Called at the beginning of training after sanity check.
on_validation_batch_end
(outputs, batch, ...)Called in the validation loop after the batch.
on_validation_batch_start
(batch, batch_idx)Called in the validation loop before anything happens for that batch.
Called at the end of validation.
Called in the validation loop at the very end of the epoch.
Called in the validation loop at the very beginning of the epoch.
Called when the validation loop starts.
Called when the validation loop ends.
Called by the training loop to release gradients before entering the validation loop.
Called at the beginning of validation.
optimizer_step
(epoch, batch_idx, optimizer)Override this method to adjust the default way the
Trainer
calls the optimizer.optimizer_zero_grad
(epoch, batch_idx, optimizer)Override this method to change the default behaviour of
optimizer.zero_grad()
.optimizers
([use_pl_optimizer])Returns the optimizer(s) that are being used during training.
parameters
([recurse])Return an iterator over module parameters.
An iterable or collection of iterables specifying prediction samples.
predict_step
(batch, batch_idx[, dataloader_idx])performs the prediction step
Use this to download and prepare data.
print
(*args, **kwargs)Prints only from process 0.
register_backward_hook
(hook)Register a backward hook on the module.
register_buffer
(name, tensor[, persistent])Add a buffer to the module.
register_forward_hook
(hook, *[, prepend, ...])Register a forward hook on the module.
register_forward_pre_hook
(hook, *[, ...])Register a forward pre-hook on the module.
register_full_backward_hook
(hook[, prepend])Register a backward hook on the module.
register_full_backward_pre_hook
(hook[, prepend])Register a backward pre-hook on the module.
Register a post hook to be run after module's
load_state_dict
is called.register_module
(name, module)Alias for
add_module()
.register_parameter
(name, param)Add a parameter to the module.
Register a pre-hook for the
state_dict()
method.requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
save_hyperparameters
(*args[, ignore, frame, ...])Save arguments to
hparams
attribute.set_extra_state
(state)Set extra state contained in the loaded state_dict.
set_predict_parameters
(n, num_samples, ...)to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
setup
(stage)Called at the beginning of fit (train + validate), validate, test, or predict.
See
torch.Tensor.share_memory_()
.state_dict
(*args[, destination, prefix, ...])Return a dictionary containing references to the whole state of the module.
teardown
(stage)Called at the end of fit (train + validate), validate, test, or predict.
An iterable or collection of iterables specifying test samples.
test_step
(*args, **kwargs)Operates on a single batch of data from the test set.
to
(*args, **kwargs)See
torch.nn.Module.to()
.to_dtype
(dtype)Cast module precision (float32 by default) to another precision.
to_empty
(*, device[, recurse])Move the parameters and buffers to the specified device without copying storage.
to_onnx
(file_path[, input_sample])Saves the model in ONNX format.
to_torchscript
([file_path, method, ...])By default compiles the whole model to a
ScriptModule
.toggle_optimizer
(optimizer)Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
train
([mode])Set the module in training mode.
An iterable or collection of iterables specifying training samples.
training_step
(train_batch, batch_idx)performs the training step
transfer_batch_to_device
(batch, device, ...)Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.type
(dst_type)See
torch.nn.Module.type()
.unfreeze
()Unfreeze all parameters for training.
untoggle_optimizer
(optimizer)Resets the state of required gradients that were toggled with
toggle_optimizer()
.An iterable or collection of iterables specifying validation samples.
validation_step
(val_batch, batch_idx)performs the validation step
xpu
([device])Move all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Reset gradients of all model parameters.
__call__
set_mc_dropout
- CHECKPOINT_HYPER_PARAMS_KEY = 'hyper_parameters'¶
- CHECKPOINT_HYPER_PARAMS_NAME = 'hparams_name'¶
- CHECKPOINT_HYPER_PARAMS_TYPE = 'hparams_type'¶
- T_destination¶
alias of TypeVar(‘T_destination’, bound=
Dict
[str
,Any
])
- add_module(name, module)¶
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- Return type
None
- all_gather(data, group=None, sync_grads=False)¶
Gather tensors or collections of tensors from multiple processes.
This method needs to be called on all processes and the tensors need to have the same shape across all processes, otherwise your program will stall forever.
- Parameters
data (
Union
[Tensor
,Dict
,List
,Tuple
]) – int, float, tensor of shape (batch, …), or a (possibly nested) collection thereof.group (
Optional
[Any
]) – the process group to gather results from. Defaults to all processes (world)sync_grads (
bool
) – flag that allows users to synchronize gradients for the all_gather operation
- Return type
Union
[Tensor
,Dict
,List
,Tuple
]- Returns
A tensor of shape (world_size, batch, …), or if the input was a collection the output will also be a collection with tensors of this shape. For the special case where world_size is 1, no additional dimension is added to the tensor(s).
- allow_zero_length_dataloader_with_multiple_devices: bool¶
- apply(fn)¶
Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters
fn (
Module
-> None) – function to be applied to each submodule- Returns
self
- Return type
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- property automatic_optimization: bool¶
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.- Return type
bool
- backward(loss, *args, **kwargs)¶
Called to perform backward on the loss returned in
training_step()
. Override this hook with your own implementation if you need to.- Parameters
loss (
Tensor
) – The loss tensor returned bytraining_step()
. If gradient accumulation is used, the loss here holds the normalized value (scaled by 1 / accumulation steps).
Example:
def backward(self, loss): loss.backward()
- Return type
None
- bfloat16()¶
Casts all floating point parameters and buffers to
bfloat16
datatype.Note
This method modifies the module in-place.
- Returns
self
- Return type
Module
- buffers(recurse=True)¶
Return an iterator over module buffers.
- Parameters
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Tensor
]
- call_super_init: bool = False¶
- children()¶
Return an iterator over immediate children modules.
- Yields
Module – a child module
- Return type
Iterator
[Module
]
- clip_gradients(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Handles gradient clipping internally.
Note
Do not override this method. If you want to customize gradient clipping, consider using
configure_gradient_clipping()
method.For manual optimization (
self.automatic_optimization = False
), if you want to use gradient clipping, consider callingself.clip_gradients(opt, gradient_clip_val=0.5, gradient_clip_algorithm="norm")
manually in the training step.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. Passgradient_clip_algorithm="value"
to clip by value, andgradient_clip_algorithm="norm"
to clip by norm.
- Return type
None
- compile(*args, **kwargs)¶
Compile this Module’s forward using
torch.compile()
.This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile()
.See
torch.compile()
for details on the arguments for this function.
- configure_callbacks()¶
Configure model-specific callbacks. When the model gets attached, e.g., when
.fit()
or.test()
gets called, the list or a callback returned here will be merged with the list of callbacks passed to the Trainer’scallbacks
argument. If a callback returned here has the same type as one or several callbacks already present in the Trainer’s callbacks list, it will take priority and replace them. In addition, Lightning will make sureModelCheckpoint
callbacks run last.- Return type
Union
[Sequence
[Callback
],Callback
]- Returns
A callback or a list of callbacks which will extend the list of callbacks in the Trainer.
Example:
def configure_callbacks(self): early_stop = EarlyStopping(monitor="val_acc", mode="max") checkpoint = ModelCheckpoint(monitor="val_loss") return [early_stop, checkpoint]
- configure_gradient_clipping(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Perform gradient clipping for the optimizer parameters. Called before
optimizer_step()
.- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients. By default, value passed in Trainer will be available here.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. By default, value passed in Trainer will be available here.
Example:
def configure_gradient_clipping(self, optimizer, gradient_clip_val, gradient_clip_algorithm): # Implement your own custom logic to clip gradients # You can call `self.clip_gradients` with your settings: self.clip_gradients( optimizer, gradient_clip_val=gradient_clip_val, gradient_clip_algorithm=gradient_clip_algorithm )
- Return type
None
- configure_model()¶
Hook to create modules in a strategy and precision aware context.
This is particularly useful for when using sharded strategies (FSDP and DeepSpeed), where we’d like to shard the model instantly to save memory and initialization time. For non-sharded strategies, you can choose to override this hook or to initialize your model under the
init_module()
context manager.This hook is called during each of fit/val/test/predict stages in the same process, so ensure that implementation of this hook is idempotent, i.e., after the first time the hook is called, subsequent calls to it should be a no-op.
- Return type
None
- configure_optimizers()¶
configures optimizers and learning rate schedulers for model optimization.
- configure_sharded_model()¶
Deprecated.
Use
configure_model()
instead.- Return type
None
- static configure_torch_metrics(torch_metrics)¶
process the torch_metrics parameter.
- Return type
MetricCollection
- cpu()¶
See
torch.nn.Module.cpu()
.- Return type
Self
- cuda(device=None)¶
Moves all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
- Parameters
device (
Union
[int
,device
,None
]) – If specified, all parameters will be copied to that device. If None, the current CUDA device index will be used.- Returns
self
- Return type
Module
- property current_epoch: int¶
The current epoch in the
Trainer
, or 0 if not attached.- Return type
int
- property device: device¶
- Return type
device
- property device_mesh: Optional[DeviceMesh]¶
Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.- Return type
Optional
[ForwardRef
]
- double()¶
See
torch.nn.Module.double()
.- Return type
Self
- property dtype: Union[str, dtype]¶
- Return type
Union
[str
,dtype
]
- dump_patches: bool = False¶
- property epochs_trained¶
- eval()¶
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.This is equivalent with
self.train(False)
.See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns
self
- Return type
Module
- property example_input_array: Optional[Union[Tensor, Tuple, Dict]]¶
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
Union
[Tensor
,Tuple
,Dict
,None
]
- extra_repr()¶
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type
str
- property fabric: Optional[Fabric]¶
- Return type
Optional
[Fabric
]
- float()¶
See
torch.nn.Module.float()
.- Return type
Self
- abstract forward(*args, **kwargs)¶
Same as
torch.nn.Module.forward()
.- Parameters
*args – Whatever you decide to pass into the forward method.
**kwargs – Keyword arguments are also possible.
- Return type
Any
- Returns
Your model’s output
- freeze()¶
Freeze all params for inference.
Example:
model = MyLightningModule(...) model.freeze()
- Return type
None
- get_buffer(target)¶
Return the buffer given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the buffer to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The buffer referenced by
target
- Return type
torch.Tensor
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()¶
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()
for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns
Any extra state to store in the module’s state_dict
- Return type
object
- get_parameter(target)¶
Return the parameter given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the Parameter to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The Parameter referenced by
target
- Return type
torch.nn.Parameter
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)¶
Return the submodule given by
target
if it exists, otherwise throw an error.For example, let’s say you have an
nn.Module
A
that looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )
(The diagram shows an
nn.Module
A
.A
has a nested submodulenet_b
, which itself has two submodulesnet_c
andlinear
.net_c
then has a submoduleconv
.)To check whether or not we have the
linear
submodule, we would callget_submodule("net_b.linear")
. To check whether we have theconv
submodule, we would callget_submodule("net_b.net_c.conv")
.The runtime of
get_submodule
is bounded by the degree of module nesting intarget
. A query againstnamed_modules
achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submodule
should always be used.- Parameters
target (
str
) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns
The submodule referenced by
target
- Return type
torch.nn.Module
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- property global_rank: int¶
The index of the current process across all nodes and devices.
- Return type
int
- property global_step: int¶
Total training batches seen across all epochs.
If no Trainer is attached, this propery is 0.
- Return type
int
- half()¶
See
torch.nn.Module.half()
.- Return type
Self
- property hparams: Union[AttributeDict, MutableMapping]¶
The collection of hyperparameters saved with
save_hyperparameters()
. It is mutable by the user. For the frozen set of initial hyperparameters, usehparams_initial
.- Return type
Union
[AttributeDict
,MutableMapping
]- Returns
Mutable hyperparameters dictionary
- property hparams_initial: AttributeDict¶
The collection of hyperparameters saved with
save_hyperparameters()
. These contents are read-only. Manual updates to the saved hyperparameters can instead be performed throughhparams
.- Returns
immutable initial hyperparameters
- Return type
AttributeDict
- ipu(device=None)¶
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- load_from_checkpoint(checkpoint_path, map_location=None, hparams_file=None, strict=None, **kwargs)¶
Primary way of loading a model from a checkpoint. When Lightning saves a checkpoint it stores the arguments passed to
__init__
in the checkpoint under"hyper_parameters"
.Any arguments specified through **kwargs will override args stored in
"hyper_parameters"
.- Parameters
checkpoint_path (
Union
[str
,Path
,IO
]) – Path to checkpoint. This can also be a URL, or file-like objectmap_location (
Union
[device
,str
,int
,Callable
[[UntypedStorage
,str
],Optional
[UntypedStorage
]],Dict
[Union
[device
,str
,int
],Union
[device
,str
,int
]],None
]) – If your checkpoint saved a GPU model and you now load on CPUs or a different number of GPUs, use this to map to the new setup. The behaviour is the same as intorch.load()
.hparams_file (
Union
[str
,Path
,None
]) –Optional path to a
.yaml
or.csv
file with hierarchical structure as in this example:drop_prob: 0.2 dataloader: batch_size: 32
You most likely won’t need this since Lightning will always save the hyperparameters to the checkpoint. However, if your checkpoint weights don’t have the hyperparameters saved, use this method to pass in a
.yaml
file with the hparams you’d like to use. These will be converted into adict
and passed into yourLightningModule
for use.If your model’s
hparams
argument isNamespace
and.yaml
file has hierarchical structure, you need to refactor your model to treathparams
asdict
.strict (
Optional
[bool
]) – Whether to strictly enforce that the keys incheckpoint_path
match the keys returned by this module’s state dict. Defaults toTrue
unlessLightningModule.strict_loading
is set, in which case it defaults to the value ofLightningModule.strict_loading
.**kwargs – Any extra keyword args needed to init the model. Can also be used to override saved hyperparameter values.
- Return type
Self
- Returns
LightningModule
instance with loaded weights and hyperparameters (if available).
Note
load_from_checkpoint
is a class method. You should use yourLightningModule
class to call it instead of theLightningModule
instance, or aTypeError
will be raised.Note
To ensure all layers can be loaded from the checkpoint, this function will call
configure_model()
directly after instantiating the model if this hook is overridden in your LightningModule. However, note thatload_from_checkpoint
does not support loading sharded checkpoints, and you may run out of memory if the model is too large. In this case, consider loading through the Trainer via.fit(ckpt_path=...)
.Example:
# load weights without mapping ... model = MyLightningModule.load_from_checkpoint('path/to/checkpoint.ckpt') # or load weights mapping all weights from GPU 1 to GPU 0 ... map_location = {'cuda:1':'cuda:0'} model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', map_location=map_location ) # or load weights and hyperparameters from separate files. model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', hparams_file='/path/to/hparams_file.yaml' ) # override some of the params with new values model = MyLightningModule.load_from_checkpoint( PATH, num_layers=128, pretrained_ckpt_path=NEW_PATH, ) # predict pretrained_model.eval() pretrained_model.freeze() y_hat = pretrained_model(x)
- load_state_dict(state_dict, strict=True, assign=False)¶
Copy parameters and buffers from
state_dict
into this module and its descendants.If
strict
isTrue
, then the keys ofstate_dict
must exactly match the keys returned by this module’sstate_dict()
function.Warning
If
assign
isTrue
the optimizer must be created after the call toload_state_dict
unlessget_swap_module_params_on_conversion()
isTrue
.- Parameters
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dict
match the keys returned by this module’sstate_dict()
function. Default:True
assign (bool, optional) – When
False
, the properties of the tensors in the current module are preserved while whenTrue
, the properties of the Tensors in the state dict are preserved. The only exception is therequires_grad
field ofDefault: ``False`
- Returns
- missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided
state_dict
.
- unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided
state_dict
.
- Return type
NamedTuple
withmissing_keys
andunexpected_keys
fields
Note
If a parameter or buffer is registered as
None
and its corresponding key exists instate_dict
,load_state_dict()
will raise aRuntimeError
.
- property local_rank: int¶
The index of the current process within a single node.
- Return type
int
- log(name, value, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, metric_attribute=None, rank_zero_only=False)¶
Log a key, value pair.
Example:
self.log('train_loss', loss)
The default behavior per hook is documented here: extensions/logging:Automatic Logging.
- Parameters
name (
str
) – key to log. Must be identical across all processes if using DDP or any other distributed strategy.value (
Union
[Metric
,Tensor
,int
,float
]) – value to log. Can be afloat
,Tensor
, or aMetric
.prog_bar (
bool
) – ifTrue
logs to the progress bar.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto detach the graph.sync_dist (
bool
) – ifTrue
, reduces the metric across devices. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the DDP group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple dataloaders). If False, user needs to give unique names for each dataloader to not mix the values.batch_size (
Optional
[int
]) – Current batch_size. This will be directly inferred from the loaded batch, but for some data structures you might need to explicitly provide it.metric_attribute (
Optional
[str
]) – To restore the metric state, Lightning requires the reference of thetorchmetrics.Metric
in your model. This is found automatically if it is a model attribute.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- log_dict(dictionary, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, rank_zero_only=False)¶
Log a dictionary of values at once.
Example:
values = {'loss': loss, 'acc': acc, ..., 'metric_n': metric_n} self.log_dict(values)
- Parameters
dictionary (
Union
[Mapping
[str
,Union
[Metric
,Tensor
,int
,float
]],MetricCollection
]) – key value pairs. Keys must be identical across all processes if using DDP or any other distributed strategy. The values can be afloat
,Tensor
,Metric
, orMetricCollection
.prog_bar (
bool
) – ifTrue
logs to the progress base.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step.None
auto-logs for training_step but not validation/test_step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics.None
auto-logs for val/test step but nottraining_step
. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto-detach the graphsync_dist (
bool
) – ifTrue
, reduces the metric across GPUs/TPUs. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the ddp group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple). IfFalse
, user needs to give unique names for each dataloader to not mix values.batch_size (
Optional
[int
]) – Current batch size. This will be directly inferred from the loaded batch, but some data structures might need to explicitly provide it.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- property logger: Optional[Union[Logger, Logger]]¶
Reference to the logger object in the Trainer.
- Return type
Union
[Logger
,Logger
,None
]
- property loggers: Union[List[Logger], List[Logger]]¶
Reference to the list of loggers in the Trainer.
- Return type
Union
[List
[Logger
],List
[Logger
]]
- lr_scheduler_step(scheduler, metric)¶
Override this method to adjust the default way the
Trainer
calls each scheduler. By default, Lightning callsstep()
and as shown in the example for each scheduler based on itsinterval
.- Parameters
scheduler (
Union
[LRScheduler
,ReduceLROnPlateau
]) – Learning rate scheduler.metric (
Optional
[Any
]) – Value of the monitor used for schedulers likeReduceLROnPlateau
.
Examples:
# DEFAULT def lr_scheduler_step(self, scheduler, metric): if metric is None: scheduler.step() else: scheduler.step(metric) # Alternative way to update schedulers if it requires an epoch value def lr_scheduler_step(self, scheduler, metric): scheduler.step(epoch=self.current_epoch)
- Return type
None
- lr_schedulers()¶
Returns the learning rate scheduler(s) that are being used during training. Useful for manual optimization.
- Return type
Union
[None
,List
[Union
[LRScheduler
,ReduceLROnPlateau
]],LRScheduler
,ReduceLROnPlateau
]- Returns
A single scheduler, or a list of schedulers in case multiple ones are present, or
None
if no schedulers were returned inconfigure_optimizers()
.
- manual_backward(loss, *args, **kwargs)¶
Call this directly from your
training_step()
when doing optimizations manually. By using this, Lightning can ensure that all the proper scaling gets applied when using mixed precision.See manual optimization for more examples.
Example:
def training_step(...): opt = self.optimizers() loss = ... opt.zero_grad() # automatically applies scaling, etc... self.manual_backward(loss) opt.step()
- Parameters
loss (
Tensor
) – The tensor on which to compute gradients. Must have a graph attached.*args – Additional positional arguments to be forwarded to
backward()
**kwargs – Additional keyword arguments to be forwarded to
backward()
- Return type
None
- modules()¶
Return an iterator over all modules in the network.
- Yields
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- Return type
Iterator
[Module
]
- named_buffers(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- Return type
Iterator
[Tuple
[str
,Tensor
]]
- named_children()¶
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- Return type
Iterator
[Tuple
[str
,Module
]]
- named_modules(memo=None, prefix='', remove_duplicate=True)¶
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters
memo (
Optional
[Set
[Module
]]) – a memo to store the set of modules already added to the resultprefix (
str
) – a prefix that will be added to the name of the moduleremove_duplicate (
bool
) – whether to remove the duplicated module instances in the result or not
- Yields
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- Return type
Iterator
[Tuple
[str
,Parameter
]]
- on_after_backward()¶
Called after
loss.backward()
and before optimizers are stepped.Note
If using native AMP, the gradients will not be unscaled at this point. Use the
on_before_optimizer_step
if you need the unscaled gradients.- Return type
None
- on_after_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch after it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_after_batch_transfer(self, batch, dataloader_idx): batch['x'] = gpu_transforms(batch['x']) return batch
- on_before_backward(loss)¶
Called before
loss.backward()
.- Parameters
loss (
Tensor
) – Loss divided by number of batches for gradient accumulation and scaled if using AMP.- Return type
None
- on_before_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch before it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_before_batch_transfer(self, batch, dataloader_idx): batch['x'] = transforms(batch['x']) return batch
- on_before_optimizer_step(optimizer)¶
Called before
optimizer.step()
.If using gradient accumulation, the hook is called once the gradients have been accumulated. See: :paramref:`~pytorch_lightning.trainer.trainer.Trainer.accumulate_grad_batches`.
If using AMP, the loss will be unscaled before calling this hook. See these docs for more information on the scaling of gradients.
If clipping gradients, the gradients will not have been clipped yet.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.
Example:
def on_before_optimizer_step(self, optimizer): # example to inspect gradient information in tensorboard if self.trainer.global_step % 25 == 0: # don't make the tf file huge for k, v in self.named_parameters(): self.logger.experiment.add_histogram( tag=k, values=v.grad, global_step=self.trainer.global_step )
- Return type
None
- on_before_zero_grad(optimizer)¶
Called after
training_step()
and beforeoptimizer.zero_grad()
.Called in the training loop after taking an optimizer step and before zeroing grads. Good place to inspect weight information with weights updated.
This is where it is called:
for optimizer in optimizers: out = training_step(...) model.on_before_zero_grad(optimizer) # < ---- called here optimizer.zero_grad() backward()
- Parameters
optimizer (
Optimizer
) – The optimizer for which grads should be zeroed.- Return type
None
- on_fit_end()¶
Called at the very end of fit.
If on DDP it is called on every process
- Return type
None
- on_fit_start()¶
Called at the very beginning of fit.
If on DDP it is called on every process
- Return type
None
- property on_gpu: bool¶
Returns
True
if this model is currently located on a GPU.Useful to set flags around the LightningModule for different CPU vs GPU behavior.
- Return type
bool
- on_load_checkpoint(checkpoint)¶
Called by Lightning to restore your model. If you saved something with
on_save_checkpoint()
this is your chance to restore this.- Parameters
checkpoint (
Dict
[str
,Any
]) – Loaded checkpoint
Example:
def on_load_checkpoint(self, checkpoint): # 99% of the time you don't need to implement this method self.something_cool_i_want_to_save = checkpoint['something_cool_i_want_to_save']
Note
Lightning auto-restores global step, epoch, and train state including amp scaling. There is no need for you to restore anything regarding training.
- Return type
None
- on_predict_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop after the batch.
- Parameters
outputs (
Optional
[Any
]) – The outputs of predict_step(x)batch (
Any
) – The batched data as it is returned by the prediction DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_start()¶
Called at the beginning of predicting.
- Return type
None
- on_predict_model_eval()¶
Called when the predict loop starts.
The predict loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior.- Return type
None
- on_predict_start()¶
Called at the beginning of predicting.
- Return type
None
- on_save_checkpoint(checkpoint)¶
Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
- Parameters
checkpoint (
Dict
[str
,Any
]) – The full checkpoint dictionary before it gets dumped to a file. Implementations of this hook can insert additional data into this dictionary.
Example:
def on_save_checkpoint(self, checkpoint): # 99% of use cases you don't need to implement this method checkpoint['something_cool_i_want_to_save'] = my_cool_pickable_object
Note
Lightning saves all aspects of training (epoch, global step, etc…) including amp scaling. There is no need for you to store anything about training.
- Return type
None
- on_test_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the test loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of test_step(x)batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the test loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_end()¶
Called at the end of testing.
- Return type
None
- on_test_epoch_end()¶
Called in the test loop at the very end of the epoch.
- Return type
None
- on_test_epoch_start()¶
Called in the test loop at the very beginning of the epoch.
- Return type
None
- on_test_model_eval()¶
Called when the test loop starts.
The test loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_test_model_train()
.- Return type
None
- on_test_model_train()¶
Called when the test loop ends.
The test loop by default restores the training mode of the LightningModule to what it was before starting testing. Override this hook to change the behavior. See also
on_test_model_eval()
.- Return type
None
- on_test_start()¶
Called at the beginning of testing.
- Return type
None
- on_train_batch_end(outputs, batch, batch_idx)¶
Called in the training loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of training_step(x)batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
Note
The value
outputs["loss"]
here will be the normalized value w.r.taccumulate_grad_batches
of the loss returned fromtraining_step
.- Return type
None
- on_train_batch_start(batch, batch_idx)¶
Called in the training loop before anything happens for that batch.
If you return -1 here, you will skip training for the rest of the current epoch.
- Parameters
batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
- Return type
Optional
[int
]
- on_train_end()¶
Called at the end of training before logger experiment is closed.
- Return type
None
- on_train_epoch_end()¶
Called in the training loop at the very end of the epoch.
To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the
LightningModule
and access them in this hook:class MyLightningModule(L.LightningModule): def __init__(self): super().__init__() self.training_step_outputs = [] def training_step(self): loss = ... self.training_step_outputs.append(loss) return loss def on_train_epoch_end(self): # do something with all training_step outputs, for example: epoch_mean = torch.stack(self.training_step_outputs).mean() self.log("training_epoch_mean", epoch_mean) # free up the memory self.training_step_outputs.clear()
- on_train_epoch_start()¶
Called in the training loop at the very beginning of the epoch.
- Return type
None
- on_train_start()¶
Called at the beginning of training after sanity check.
- Return type
None
- on_validation_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of validation_step(x)batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_end()¶
Called at the end of validation.
- Return type
None
- on_validation_epoch_end()¶
Called in the validation loop at the very end of the epoch.
- on_validation_epoch_start()¶
Called in the validation loop at the very beginning of the epoch.
- Return type
None
- on_validation_model_eval()¶
Called when the validation loop starts.
The validation loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_validation_model_train()
.- Return type
None
- on_validation_model_train()¶
Called when the validation loop ends.
The validation loop by default restores the training mode of the LightningModule to what it was before starting validation. Override this hook to change the behavior. See also
on_validation_model_eval()
.- Return type
None
- on_validation_model_zero_grad()¶
Called by the training loop to release gradients before entering the validation loop.
- Return type
None
- on_validation_start()¶
Called at the beginning of validation.
- Return type
None
- optimizer_step(epoch, batch_idx, optimizer, optimizer_closure=None)¶
Override this method to adjust the default way the
Trainer
calls the optimizer.By default, Lightning calls
step()
andzero_grad()
as shown in the example. This method (andzero_grad()
) won’t be called during the accumulation phase whenTrainer(accumulate_grad_batches != 1)
. Overriding this hook has no benefit with manual optimization.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Union
[Optimizer
,LightningOptimizer
]) – A PyTorch optimizeroptimizer_closure (
Optional
[Callable
[[],Any
]]) – The optimizer closure. This closure must be executed as it includes the calls totraining_step()
,optimizer.zero_grad()
, andbackward()
.
Examples:
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_closure): # Add your custom logic to run directly before `optimizer.step()` optimizer.step(closure=optimizer_closure) # Add your custom logic to run directly after `optimizer.step()`
- Return type
None
- optimizer_zero_grad(epoch, batch_idx, optimizer)¶
Override this method to change the default behaviour of
optimizer.zero_grad()
.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Optimizer
) – A PyTorch optimizer
Examples:
# DEFAULT def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad() # Set gradients to `None` instead of zero to improve performance (not required on `torch>=2.0.0`). def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad(set_to_none=True)
See
torch.optim.Optimizer.zero_grad()
for the explanation of the above example.- Return type
None
- optimizers(use_pl_optimizer=True)¶
Returns the optimizer(s) that are being used during training. Useful for manual optimization.
- Parameters
use_pl_optimizer (
bool
) – IfTrue
, will wrap the optimizer(s) in aLightningOptimizer
for automatic handling of precision, profiling, and counting of step calls for proper logging and checkpointing. It specifically wraps thestep
method and custom optimizers that don’t have this method are not supported.- Return type
Union
[Optimizer
,LightningOptimizer
,_FabricOptimizer
,List
[Optimizer
],List
[LightningOptimizer
],List
[_FabricOptimizer
]]- Returns
A single optimizer, or a list of optimizers in case multiple ones are present.
- property output_chunk_length: Optional[int]¶
Number of time steps predicted at once by the model.
- Return type
Optional
[int
]
- parameters(recurse=True)¶
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Parameter
]
- pred_batch_size: Optional[int]¶
- pred_mc_dropout: Optional[bool]¶
- pred_n: Optional[int]¶
- pred_n_jobs: Optional[int]¶
- pred_num_samples: Optional[int]¶
- pred_roll_size: Optional[int]¶
- predict_dataloader()¶
An iterable or collection of iterables specifying prediction samples.
For more information about multiple dataloaders, see this section.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.predict()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
- Return type
Any
- Returns
A
torch.utils.data.DataLoader
or a sequence of them specifying prediction samples.
- predict_likelihood_parameters: Optional[bool]¶
- predict_step(batch, batch_idx, dataloader_idx=None)¶
performs the prediction step
- batch
output of Darts’
InferenceDataset
- tuple of(past_target, past_covariates, historic_future_covariates, future_covariates, future_past_covariates, input time series, prediction start time step)
- batch_idx
the batch index of the current batch
- dataloader_idx
the dataloader index
- Return type
Sequence
[TimeSeries
]
- prepare_data()¶
Use this to download and prepare data. Downloading and saving data with multiple processes (distributed settings) will result in corrupted data. Lightning ensures this method is called only within a single process, so you can safely add your downloading logic within.
Warning
DO NOT set state to the model (use
setup
instead) since this is NOT called on every deviceExample:
def prepare_data(self): # good download_data() tokenize() etc() # bad self.split = data_split self.some_state = some_other_state()
In a distributed environment,
prepare_data
can be called in two ways (using prepare_data_per_node)Once per node. This is the default and is only called on LOCAL_RANK=0.
Once in total. Only called on GLOBAL_RANK=0.
Example:
# DEFAULT # called once per node on LOCAL_RANK=0 of that node class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = True # call on GLOBAL_RANK=0 (great for shared file systems) class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = False
This is called before requesting the dataloaders:
model.prepare_data() initialize_distributed() model.setup(stage) model.train_dataloader() model.val_dataloader() model.test_dataloader() model.predict_dataloader()
- Return type
None
- prepare_data_per_node: bool¶
- print(*args, **kwargs)¶
Prints only from process 0. Use this in any distributed mode to log only once.
- Parameters
*args – The thing to print. The same as for Python’s built-in print function.
**kwargs – The same as for Python’s built-in print function.
Example:
def forward(self, x): self.print(x, 'in forward')
- Return type
None
- register_backward_hook(hook)¶
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()
and the behavior of this function will change in future versions.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_buffer(name, tensor, persistent=True)¶
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_mean
is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistent
toFalse
. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict
.Buffers can be accessed as attributes using given names.
- Parameters
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None
, then operations that run on buffers, such ascuda
, are ignored. IfNone
, the buffer is not included in the module’sstate_dict
.persistent (bool) – whether the buffer is part of this module’s
state_dict
.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- Return type
None
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)¶
Register a forward hook on the module.
The hook will be called every time after
forward()
has computed an output.If
with_kwargs
isFalse
or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()
is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargs
isTrue
, the forward hook will be passed thekwargs
given to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True
, the providedhook
will be fired before all existingforward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward
hooks on thistorch.nn.modules.Module
. Note that globalforward
hooks registered withregister_module_forward_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If
True
, thehook
will be passed the kwargs given to the forward function. Default:False
always_call (bool) – If
True
thehook
will be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)¶
Register a forward pre-hook on the module.
The hook will be called every time before
forward()
is invoked.If
with_kwargs
is false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargs
is true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingforward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward_pre
hooks on thistorch.nn.modules.Module
. Note that globalforward_pre
hooks registered withregister_module_forward_pre_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If true, the
hook
will be passed the kwargs given to the forward function. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)¶
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_input
andgrad_output
are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_input
in subsequent computations.grad_input
will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_input
andgrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward
hooks on thistorch.nn.modules.Module
. Note that globalbackward
hooks registered withregister_module_full_backward_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)¶
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_output
is a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_output
in subsequent computations. Entries ingrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Note that globalbackward_pre
hooks registered withregister_module_full_backward_pre_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)¶
Register a post hook to be run after module’s
load_state_dict
is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
module
argument is the current module that this hook is registered on, and theincompatible_keys
argument is aNamedTuple
consisting of attributesmissing_keys
andunexpected_keys
.missing_keys
is alist
ofstr
containing the missing keys andunexpected_keys
is alist
ofstr
containing the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()
withstrict=True
are affected by modifications the hook makes tomissing_keys
orunexpected_keys
, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True
, and clearing out both missing and unexpected keys will avoid an error.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_module(name, module)¶
Alias for
add_module()
.- Return type
None
- register_parameter(name, param)¶
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None
, then operations that run on parameters, such ascuda
, are ignored. IfNone
, the parameter is not included in the module’sstate_dict
.
- Return type
None
- register_state_dict_pre_hook(hook)¶
Register a pre-hook for the
state_dict()
method.These hooks will be called with arguments:
self
,prefix
, andkeep_vars
before callingstate_dict
onself
. The registered hooks can be used to perform pre-processing before thestate_dict
call is made.
- requires_grad_(requires_grad=True)¶
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_grad
attributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True
.- Returns
self
- Return type
Module
- save_hyperparameters(*args, ignore=None, frame=None, logger=True)¶
Save arguments to
hparams
attribute.- Parameters
args (
Any
) – single object of dict, NameSpace or OmegaConf or string names or arguments from class__init__
ignore (
Union
[str
,Sequence
[str
],None
]) – an argument name or a list of argument names from class__init__
to be ignoredframe (
Optional
[frame
]) – a frame object. Default is Nonelogger (
bool
) – Whether to send the hyperparameters to the logger. Default: True
- Example::
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # manually assign arguments ... self.save_hyperparameters('arg1', 'arg3') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class AutomaticArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # equivalent automatic ... self.save_hyperparameters() ... def forward(self, *args, **kwargs): ... ... >>> model = AutomaticArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg2": abc "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class SingleArgModel(HyperparametersMixin): ... def __init__(self, params): ... super().__init__() ... # manually assign single argument ... self.save_hyperparameters(params) ... def forward(self, *args, **kwargs): ... ... >>> model = SingleArgModel(Namespace(p1=1, p2='abc', p3=3.14)) >>> model.hparams "p1": 1 "p2": abc "p3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # pass argument(s) to ignore as a string or in a list ... self.save_hyperparameters(ignore='arg2') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
- Return type
None
- set_extra_state(state)¶
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()
to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()
for your module if you need to store extra state within its state_dict.- Parameters
state (dict) – Extra state from the state_dict
- Return type
None
- set_mc_dropout(active)¶
- set_predict_parameters(n, num_samples, roll_size, batch_size, n_jobs, predict_likelihood_parameters, mc_dropout)¶
to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
- Return type
None
- setup(stage)¶
Called at the beginning of fit (train + validate), validate, test, or predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
Example:
class LitModel(...): def __init__(self): self.l1 = None def prepare_data(self): download_data() tokenize() # don't do this self.something = else def setup(self, stage): data = load_data(...) self.l1 = nn.Linear(28, data.num_classes)
- Return type
None
See
torch.Tensor.share_memory_()
.- Return type
~T
- state_dict(*args, destination=None, prefix='', keep_vars=False)¶
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
None
are not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()
also accepts positional arguments fordestination
,prefix
andkeep_vars
in order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destination
as it is not designed for end-users.- Parameters
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDict
will be created and returned. Default:None
.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''
.keep_vars (bool, optional) – by default the
Tensor
s returned in the state dict are detached from autograd. If it’s set toTrue
, detaching will not be performed. Default:False
.
- Returns
a dictionary containing a whole state of the module
- Return type
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- property strict_loading: bool¶
Determines how Lightning loads this model using .load_state_dict(…, strict=model.strict_loading).
- Return type
bool
- property supports_probabilistic_prediction: bool¶
- Return type
bool
- teardown(stage)¶
Called at the end of fit (train + validate), validate, test, or predict.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
- Return type
None
- test_dataloader()¶
An iterable or collection of iterables specifying test samples.
For more information about multiple dataloaders, see this section.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
test()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
Note
If you don’t need a test dataset and a
test_step()
, you don’t need to implement this method.- Return type
Any
- test_step(*args, **kwargs)¶
Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.
- Parameters
batch – The output of your data iterable, normally a
DataLoader
.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- Return type
Union
[Tensor
,Mapping
[str
,Any
],None
]- Returns
Tensor
- The loss tensordict
- A dictionary. Can include any keys, but must include the key'loss'
.None
- Skip to the next batch.
# if you have one test dataloader: def test_step(self, batch, batch_idx): ... # if you have multiple test dataloaders: def test_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single test dataset def test_step(self, batch, batch_idx): x, y = batch # implement your own out = self(x) loss = self.loss(out, y) # log 6 example images # or generated text... or whatever sample_imgs = x[:6] grid = torchvision.utils.make_grid(sample_imgs) self.logger.experiment.add_image('example_images', grid, 0) # calculate acc labels_hat = torch.argmax(out, dim=1) test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'test_loss': loss, 'test_acc': test_acc})
If you pass in multiple test dataloaders,
test_step()
will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.# CASE 2: multiple test dataloaders def test_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. ...
Note
If you don’t need to test you don’t need to implement this method.
Note
When the
test_step()
is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.
- to(*args, **kwargs)¶
See
torch.nn.Module.to()
.- Return type
Self
- to_dtype(dtype)¶
Cast module precision (float32 by default) to another precision.
- to_empty(*, device, recurse=True)¶
Move the parameters and buffers to the specified device without copying storage.
- Parameters
device (
torch.device
) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns
self
- Return type
Module
- to_onnx(file_path, input_sample=None, **kwargs)¶
Saves the model in ONNX format.
- Parameters
file_path (
Union
[str
,Path
]) – The path of the file the onnx model should be saved to.input_sample (
Optional
[Any
]) – An input for tracing. Default: None (Use self.example_input_array)**kwargs – Will be passed to torch.onnx.export function.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1) model = SimpleModel() input_sample = torch.randn(1, 64) model.to_onnx("export.onnx", input_sample, export_params=True)
- Return type
None
- to_torchscript(file_path=None, method='script', example_inputs=None, **kwargs)¶
By default compiles the whole model to a
ScriptModule
. If you want to use tracing, please provided the argumentmethod='trace'
and make sure that either the example_inputs argument is provided, or the model hasexample_input_array
set. If you would like to customize the modules that are scripted you should override this method. In case you want to return multiple modules, we recommend using a dictionary.- Parameters
file_path (
Union
[str
,Path
,None
]) – Path where to save the torchscript. Default: None (no file saved).method (
Optional
[str
]) – Whether to use TorchScript’s script or trace method. Default: ‘script’example_inputs (
Optional
[Any
]) – An input to be used to do tracing when method is set to ‘trace’. Default: None (usesexample_input_array
)**kwargs – Additional arguments that will be passed to the
torch.jit.script()
ortorch.jit.trace()
function.
Note
Requires the implementation of the
forward()
method.The exported script will be set to evaluation mode.
It is recommended that you install the latest supported version of PyTorch to use this feature without limitations. See also the
torch.jit
documentation for supported features.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1))) model = SimpleModel() model.to_torchscript(file_path="model.pt") torch.jit.save(model.to_torchscript( file_path="model_trace.pt", method='trace', example_inputs=torch.randn(1, 64)) )
- Return type
Union
[ScriptModule
,Dict
[str
,ScriptModule
]]- Returns
This LightningModule as a torchscript, regardless of whether file_path is defined or not.
- toggle_optimizer(optimizer)¶
Makes sure only the gradients of the current optimizer’s parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
It works with
untoggle_optimizer()
to make sureparam_requires_grad_state
is properly reset.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to toggle.- Return type
None
- train(mode=True)¶
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.- Parameters
mode (bool) – whether to set training mode (
True
) or evaluation mode (False
). Default:True
.- Returns
self
- Return type
Module
- train_criterion_reduction: Optional[str]¶
- train_dataloader()¶
An iterable or collection of iterables specifying training samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
fit()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
- Return type
Any
- property trainer: Trainer¶
- Return type
Trainer
- training: bool¶
- training_step(train_batch, batch_idx)¶
performs the training step
- Return type
Tensor
- transfer_batch_to_device(batch, device, dataloader_idx)¶
Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.The data types listed below (and any arbitrary nesting of them) are supported out of the box:
torch.Tensor
or anything that implements .to(…)list
dict
tuple
For anything else, you need to define how the data is moved to the target device (CPU, GPU, TPU, …).
Note
This hook should only transfer the data and not modify it, nor should it move the data to any other device than the one passed in as argument (unless you know what you are doing). To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be transferred to a new device.device (
device
) – The target device as defined in PyTorch.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A reference to the data on the new device.
Example:
def transfer_batch_to_device(self, batch, device, dataloader_idx): if isinstance(batch, CustomBatch): # move all tensors in your custom data structure to the device batch.samples = batch.samples.to(device) batch.targets = batch.targets.to(device) elif dataloader_idx == 0: # skip device transfer for the first dataloader or anything you wish pass else: batch = super().transfer_batch_to_device(batch, device, dataloader_idx) return batch
See also
move_data_to_device()
apply_to_collection()
- type(dst_type)¶
See
torch.nn.Module.type()
.- Return type
Self
- unfreeze()¶
Unfreeze all parameters for training.
model = MyLightningModule(...) model.unfreeze()
- Return type
None
- untoggle_optimizer(optimizer)¶
Resets the state of required gradients that were toggled with
toggle_optimizer()
.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to untoggle.- Return type
None
- val_criterion_reduction: Optional[str]¶
- val_dataloader()¶
An iterable or collection of iterables specifying validation samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.fit()
validate()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
Note
If you don’t need a validation dataset and a
validation_step()
, you don’t need to implement this method.- Return type
Any
- validation_step(val_batch, batch_idx)¶
performs the validation step
- Return type
Tensor
- xpu(device=None)¶
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- zero_grad(set_to_none=True)¶
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizer
for more context.- Parameters
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()
for details.- Return type
None
- class darts.models.forecasting.pl_forecasting_module.PLSplitCovariatesModule(input_chunk_length, output_chunk_length, output_chunk_shift=0, train_sample_shape=None, loss_fn=MSELoss(), torch_metrics=None, likelihood=None, optimizer_cls=<class 'torch.optim.adam.Adam'>, optimizer_kwargs=None, lr_scheduler_cls=None, lr_scheduler_kwargs=None, use_reversible_instance_norm=False)[source]¶
Bases:
PLForecastingModule
,ABC
PyTorch Lightning-based Forecasting Module.
This class is meant to be inherited to create a new PyTorch Lightning-based forecasting module. When subclassing this class, please make sure to add the following methods with the given signatures:
PLForecastingModule.__init__()
PLForecastingModule._produce_train_output()
PLForecastingModule._get_batch_prediction()
In subclass MyModel’s
__init__()
function callsuper(MyModel, self).__init__(**kwargs)
wherekwargs
are the parameters ofPLForecastingModule
.- Parameters
input_chunk_length (
int
) – Number of time steps in the past to take as a model input (per chunk). Applies to the target series, and past and/or future covariates (if the model supports it).output_chunk_length (
int
) – Number of time steps predicted at once (per chunk) by the internal model. Also, the number of future values from future covariates to use as a model input (if the model supports future covariates). It is not the same as forecast horizon n used in predict(), which is the desired number of prediction points generated using either a one-shot- or autoregressive forecast. Setting n <= output_chunk_length prevents auto-regression. This is useful when the covariates don’t extend far enough into the future, or to prohibit the model from using future values of past and / or future covariates for prediction (depending on the model’s covariate support).train_sample_shape (
Optional
[Tuple
]) – Shape of the model’s input, used to instantiate model without callingfit_from_dataset
and perform sanity check on new training/inference datasets used for re-training or prediction.loss_fn (
_Loss
) – PyTorch loss function used for training. This parameter will be ignored for probabilistic models if thelikelihood
parameter is specified. Default:torch.nn.MSELoss()
.torch_metrics (
Union
[Metric
,MetricCollection
,None
]) – A torch metric or aMetricCollection
used for evaluation. A full list of available metrics can be found at https://torchmetrics.readthedocs.io/en/latest/. Default:None
.likelihood (
Optional
[Likelihood
]) – One of Darts’Likelihood
models to be used for probabilistic forecasts. Default:None
.optimizer_cls (
Optimizer
) – The PyTorch optimizer class to be used. Default:torch.optim.Adam
.optimizer_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch optimizer (e.g.,{'lr': 1e-3}
for specifying a learning rate). Otherwise the default values of the selectedoptimizer_cls
will be used. Default:None
.lr_scheduler_cls (
Optional
[_LRScheduler
]) – Optionally, the PyTorch learning rate scheduler class to be used. SpecifyingNone
corresponds to using a constant learning rate. Default:None
.lr_scheduler_kwargs (
Optional
[Dict
]) – Optionally, some keyword arguments for the PyTorch learning rate scheduler. Default:None
.use_reversible_instance_norm (
bool
) – Whether to use reversible instance normalization RINorm against distribution shift as shown in [1]. It is only applied to the features of the target series and not the covariates.
References
- 1
T. Kim et al. “Reversible Instance Normalization for Accurate Time-Series Forecasting against Distribution Shift”, https://openreview.net/forum?id=cGDAkQo1C0p
Attributes
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.The current epoch in the
Trainer
, or 0 if not attached.Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.The example input array is a specification of what the module can consume in the
forward()
method.The index of the current process across all nodes and devices.
Total training batches seen across all epochs.
The collection of hyperparameters saved with
save_hyperparameters()
.The collection of hyperparameters saved with
save_hyperparameters()
.The index of the current process within a single node.
Reference to the logger object in the Trainer.
Reference to the list of loggers in the Trainer.
Returns
True
if this model is currently located on a GPU.Number of time steps predicted at once by the model.
Determines how Lightning loads this model using .load_state_dict(..., strict=model.strict_loading).
device
dtype
epochs_trained
fabric
supports_probabilistic_prediction
trainer
Methods
add_module
(name, module)Add a child module to the current module.
all_gather
(data[, group, sync_grads])Gather tensors or collections of tensors from multiple processes.
apply
(fn)Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.backward
(loss, *args, **kwargs)Called to perform backward on the loss returned in
training_step()
.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Return an iterator over module buffers.
children
()Return an iterator over immediate children modules.
clip_gradients
(optimizer[, ...])Handles gradient clipping internally.
compile
(*args, **kwargs)Compile this Module's forward using
torch.compile()
.Configure model-specific callbacks.
configure_gradient_clipping
(optimizer[, ...])Perform gradient clipping for the optimizer parameters.
Hook to create modules in a strategy and precision aware context.
configures optimizers and learning rate schedulers for model optimization.
Deprecated.
configure_torch_metrics
(torch_metrics)process the torch_metrics parameter.
cpu
()See
torch.nn.Module.cpu()
.cuda
([device])Moves all model parameters and buffers to the GPU.
double
()See
torch.nn.Module.double()
.eval
()Set the module in evaluation mode.
Set the extra representation of the module.
float
()See
torch.nn.Module.float()
.forward
(*args, **kwargs)Same as
torch.nn.Module.forward()
.freeze
()Freeze all params for inference.
get_buffer
(target)Return the buffer given by
target
if it exists, otherwise throw an error.Return any extra state to include in the module's state_dict.
get_parameter
(target)Return the parameter given by
target
if it exists, otherwise throw an error.get_submodule
(target)Return the submodule given by
target
if it exists, otherwise throw an error.half
()See
torch.nn.Module.half()
.ipu
([device])Move all model parameters and buffers to the IPU.
load_from_checkpoint
(checkpoint_path[, ...])Primary way of loading a model from a checkpoint.
load_state_dict
(state_dict[, strict, assign])Copy parameters and buffers from
state_dict
into this module and its descendants.log
(name, value[, prog_bar, logger, ...])Log a key, value pair.
log_dict
(dictionary[, prog_bar, logger, ...])Log a dictionary of values at once.
lr_scheduler_step
(scheduler, metric)Override this method to adjust the default way the
Trainer
calls each scheduler.Returns the learning rate scheduler(s) that are being used during training.
manual_backward
(loss, *args, **kwargs)Call this directly from your
training_step()
when doing optimizations manually.modules
()Return an iterator over all modules in the network.
named_buffers
([prefix, recurse, ...])Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse, ...])Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
Called after
loss.backward()
and before optimizers are stepped.on_after_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch after it is transferred to the device.
on_before_backward
(loss)Called before
loss.backward()
.on_before_batch_transfer
(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch before it is transferred to the device.
on_before_optimizer_step
(optimizer)Called before
optimizer.step()
.on_before_zero_grad
(optimizer)Called after
training_step()
and beforeoptimizer.zero_grad()
.Called at the very end of fit.
Called at the very beginning of fit.
on_load_checkpoint
(checkpoint)Called by Lightning to restore your model.
on_predict_batch_end
(outputs, batch, batch_idx)Called in the predict loop after the batch.
on_predict_batch_start
(batch, batch_idx[, ...])Called in the predict loop before anything happens for that batch.
Called at the end of predicting.
Called at the end of predicting.
Called at the beginning of predicting.
Called when the predict loop starts.
Called at the beginning of predicting.
on_save_checkpoint
(checkpoint)Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
on_test_batch_end
(outputs, batch, batch_idx)Called in the test loop after the batch.
on_test_batch_start
(batch, batch_idx[, ...])Called in the test loop before anything happens for that batch.
Called at the end of testing.
Called in the test loop at the very end of the epoch.
Called in the test loop at the very beginning of the epoch.
Called when the test loop starts.
Called when the test loop ends.
Called at the beginning of testing.
on_train_batch_end
(outputs, batch, batch_idx)Called in the training loop after the batch.
on_train_batch_start
(batch, batch_idx)Called in the training loop before anything happens for that batch.
Called at the end of training before logger experiment is closed.
Called in the training loop at the very end of the epoch.
Called in the training loop at the very beginning of the epoch.
Called at the beginning of training after sanity check.
on_validation_batch_end
(outputs, batch, ...)Called in the validation loop after the batch.
on_validation_batch_start
(batch, batch_idx)Called in the validation loop before anything happens for that batch.
Called at the end of validation.
Called in the validation loop at the very end of the epoch.
Called in the validation loop at the very beginning of the epoch.
Called when the validation loop starts.
Called when the validation loop ends.
Called by the training loop to release gradients before entering the validation loop.
Called at the beginning of validation.
optimizer_step
(epoch, batch_idx, optimizer)Override this method to adjust the default way the
Trainer
calls the optimizer.optimizer_zero_grad
(epoch, batch_idx, optimizer)Override this method to change the default behaviour of
optimizer.zero_grad()
.optimizers
([use_pl_optimizer])Returns the optimizer(s) that are being used during training.
parameters
([recurse])Return an iterator over module parameters.
An iterable or collection of iterables specifying prediction samples.
predict_step
(batch, batch_idx[, dataloader_idx])performs the prediction step
Use this to download and prepare data.
print
(*args, **kwargs)Prints only from process 0.
register_backward_hook
(hook)Register a backward hook on the module.
register_buffer
(name, tensor[, persistent])Add a buffer to the module.
register_forward_hook
(hook, *[, prepend, ...])Register a forward hook on the module.
register_forward_pre_hook
(hook, *[, ...])Register a forward pre-hook on the module.
register_full_backward_hook
(hook[, prepend])Register a backward hook on the module.
register_full_backward_pre_hook
(hook[, prepend])Register a backward pre-hook on the module.
Register a post hook to be run after module's
load_state_dict
is called.register_module
(name, module)Alias for
add_module()
.register_parameter
(name, param)Add a parameter to the module.
Register a pre-hook for the
state_dict()
method.requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
save_hyperparameters
(*args[, ignore, frame, ...])Save arguments to
hparams
attribute.set_extra_state
(state)Set extra state contained in the loaded state_dict.
set_predict_parameters
(n, num_samples, ...)to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
setup
(stage)Called at the beginning of fit (train + validate), validate, test, or predict.
See
torch.Tensor.share_memory_()
.state_dict
(*args[, destination, prefix, ...])Return a dictionary containing references to the whole state of the module.
teardown
(stage)Called at the end of fit (train + validate), validate, test, or predict.
An iterable or collection of iterables specifying test samples.
test_step
(*args, **kwargs)Operates on a single batch of data from the test set.
to
(*args, **kwargs)See
torch.nn.Module.to()
.to_dtype
(dtype)Cast module precision (float32 by default) to another precision.
to_empty
(*, device[, recurse])Move the parameters and buffers to the specified device without copying storage.
to_onnx
(file_path[, input_sample])Saves the model in ONNX format.
to_torchscript
([file_path, method, ...])By default compiles the whole model to a
ScriptModule
.toggle_optimizer
(optimizer)Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
train
([mode])Set the module in training mode.
An iterable or collection of iterables specifying training samples.
training_step
(train_batch, batch_idx)performs the training step
transfer_batch_to_device
(batch, device, ...)Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.type
(dst_type)See
torch.nn.Module.type()
.unfreeze
()Unfreeze all parameters for training.
untoggle_optimizer
(optimizer)Resets the state of required gradients that were toggled with
toggle_optimizer()
.An iterable or collection of iterables specifying validation samples.
validation_step
(val_batch, batch_idx)performs the validation step
xpu
([device])Move all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Reset gradients of all model parameters.
__call__
set_mc_dropout
- CHECKPOINT_HYPER_PARAMS_KEY = 'hyper_parameters'¶
- CHECKPOINT_HYPER_PARAMS_NAME = 'hparams_name'¶
- CHECKPOINT_HYPER_PARAMS_TYPE = 'hparams_type'¶
- T_destination¶
alias of TypeVar(‘T_destination’, bound=
Dict
[str
,Any
])
- add_module(name, module)¶
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- Return type
None
- all_gather(data, group=None, sync_grads=False)¶
Gather tensors or collections of tensors from multiple processes.
This method needs to be called on all processes and the tensors need to have the same shape across all processes, otherwise your program will stall forever.
- Parameters
data (
Union
[Tensor
,Dict
,List
,Tuple
]) – int, float, tensor of shape (batch, …), or a (possibly nested) collection thereof.group (
Optional
[Any
]) – the process group to gather results from. Defaults to all processes (world)sync_grads (
bool
) – flag that allows users to synchronize gradients for the all_gather operation
- Return type
Union
[Tensor
,Dict
,List
,Tuple
]- Returns
A tensor of shape (world_size, batch, …), or if the input was a collection the output will also be a collection with tensors of this shape. For the special case where world_size is 1, no additional dimension is added to the tensor(s).
- allow_zero_length_dataloader_with_multiple_devices: bool¶
- apply(fn)¶
Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters
fn (
Module
-> None) – function to be applied to each submodule- Returns
self
- Return type
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- property automatic_optimization: bool¶
If set to
False
you are responsible for calling.backward()
,.step()
,.zero_grad()
.- Return type
bool
- backward(loss, *args, **kwargs)¶
Called to perform backward on the loss returned in
training_step()
. Override this hook with your own implementation if you need to.- Parameters
loss (
Tensor
) – The loss tensor returned bytraining_step()
. If gradient accumulation is used, the loss here holds the normalized value (scaled by 1 / accumulation steps).
Example:
def backward(self, loss): loss.backward()
- Return type
None
- bfloat16()¶
Casts all floating point parameters and buffers to
bfloat16
datatype.Note
This method modifies the module in-place.
- Returns
self
- Return type
Module
- buffers(recurse=True)¶
Return an iterator over module buffers.
- Parameters
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Tensor
]
- call_super_init: bool = False¶
- children()¶
Return an iterator over immediate children modules.
- Yields
Module – a child module
- Return type
Iterator
[Module
]
- clip_gradients(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Handles gradient clipping internally.
Note
Do not override this method. If you want to customize gradient clipping, consider using
configure_gradient_clipping()
method.For manual optimization (
self.automatic_optimization = False
), if you want to use gradient clipping, consider callingself.clip_gradients(opt, gradient_clip_val=0.5, gradient_clip_algorithm="norm")
manually in the training step.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. Passgradient_clip_algorithm="value"
to clip by value, andgradient_clip_algorithm="norm"
to clip by norm.
- Return type
None
- compile(*args, **kwargs)¶
Compile this Module’s forward using
torch.compile()
.This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile()
.See
torch.compile()
for details on the arguments for this function.
- configure_callbacks()¶
Configure model-specific callbacks. When the model gets attached, e.g., when
.fit()
or.test()
gets called, the list or a callback returned here will be merged with the list of callbacks passed to the Trainer’scallbacks
argument. If a callback returned here has the same type as one or several callbacks already present in the Trainer’s callbacks list, it will take priority and replace them. In addition, Lightning will make sureModelCheckpoint
callbacks run last.- Return type
Union
[Sequence
[Callback
],Callback
]- Returns
A callback or a list of callbacks which will extend the list of callbacks in the Trainer.
Example:
def configure_callbacks(self): early_stop = EarlyStopping(monitor="val_acc", mode="max") checkpoint = ModelCheckpoint(monitor="val_loss") return [early_stop, checkpoint]
- configure_gradient_clipping(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)¶
Perform gradient clipping for the optimizer parameters. Called before
optimizer_step()
.- Parameters
optimizer (
Optimizer
) – Current optimizer being used.gradient_clip_val (
Union
[int
,float
,None
]) – The value at which to clip gradients. By default, value passed in Trainer will be available here.gradient_clip_algorithm (
Optional
[str
]) – The gradient clipping algorithm to use. By default, value passed in Trainer will be available here.
Example:
def configure_gradient_clipping(self, optimizer, gradient_clip_val, gradient_clip_algorithm): # Implement your own custom logic to clip gradients # You can call `self.clip_gradients` with your settings: self.clip_gradients( optimizer, gradient_clip_val=gradient_clip_val, gradient_clip_algorithm=gradient_clip_algorithm )
- Return type
None
- configure_model()¶
Hook to create modules in a strategy and precision aware context.
This is particularly useful for when using sharded strategies (FSDP and DeepSpeed), where we’d like to shard the model instantly to save memory and initialization time. For non-sharded strategies, you can choose to override this hook or to initialize your model under the
init_module()
context manager.This hook is called during each of fit/val/test/predict stages in the same process, so ensure that implementation of this hook is idempotent, i.e., after the first time the hook is called, subsequent calls to it should be a no-op.
- Return type
None
- configure_optimizers()¶
configures optimizers and learning rate schedulers for model optimization.
- configure_sharded_model()¶
Deprecated.
Use
configure_model()
instead.- Return type
None
- static configure_torch_metrics(torch_metrics)¶
process the torch_metrics parameter.
- Return type
MetricCollection
- cpu()¶
See
torch.nn.Module.cpu()
.- Return type
Self
- cuda(device=None)¶
Moves all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
- Parameters
device (
Union
[int
,device
,None
]) – If specified, all parameters will be copied to that device. If None, the current CUDA device index will be used.- Returns
self
- Return type
Module
- property current_epoch: int¶
The current epoch in the
Trainer
, or 0 if not attached.- Return type
int
- property device: device¶
- Return type
device
- property device_mesh: Optional[DeviceMesh]¶
Strategies like
ModelParallelStrategy
will create a device mesh that can be accessed in theconfigure_model()
hook to parallelize the LightningModule.- Return type
Optional
[ForwardRef
]
- double()¶
See
torch.nn.Module.double()
.- Return type
Self
- property dtype: Union[str, dtype]¶
- Return type
Union
[str
,dtype
]
- dump_patches: bool = False¶
- property epochs_trained¶
- eval()¶
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.This is equivalent with
self.train(False)
.See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns
self
- Return type
Module
- property example_input_array: Optional[Union[Tensor, Tuple, Dict]]¶
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
Union
[Tensor
,Tuple
,Dict
,None
]
- extra_repr()¶
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type
str
- property fabric: Optional[Fabric]¶
- Return type
Optional
[Fabric
]
- float()¶
See
torch.nn.Module.float()
.- Return type
Self
- abstract forward(*args, **kwargs)¶
Same as
torch.nn.Module.forward()
.- Parameters
*args – Whatever you decide to pass into the forward method.
**kwargs – Keyword arguments are also possible.
- Return type
Any
- Returns
Your model’s output
- freeze()¶
Freeze all params for inference.
Example:
model = MyLightningModule(...) model.freeze()
- Return type
None
- get_buffer(target)¶
Return the buffer given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the buffer to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The buffer referenced by
target
- Return type
torch.Tensor
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()¶
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()
for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns
Any extra state to store in the module’s state_dict
- Return type
object
- get_parameter(target)¶
Return the parameter given by
target
if it exists, otherwise throw an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters
target (
str
) – The fully-qualified string name of the Parameter to look for. (Seeget_submodule
for how to specify a fully-qualified string.)- Returns
The Parameter referenced by
target
- Return type
torch.nn.Parameter
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)¶
Return the submodule given by
target
if it exists, otherwise throw an error.For example, let’s say you have an
nn.Module
A
that looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )
(The diagram shows an
nn.Module
A
.A
has a nested submodulenet_b
, which itself has two submodulesnet_c
andlinear
.net_c
then has a submoduleconv
.)To check whether or not we have the
linear
submodule, we would callget_submodule("net_b.linear")
. To check whether we have theconv
submodule, we would callget_submodule("net_b.net_c.conv")
.The runtime of
get_submodule
is bounded by the degree of module nesting intarget
. A query againstnamed_modules
achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submodule
should always be used.- Parameters
target (
str
) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns
The submodule referenced by
target
- Return type
torch.nn.Module
- Raises
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- property global_rank: int¶
The index of the current process across all nodes and devices.
- Return type
int
- property global_step: int¶
Total training batches seen across all epochs.
If no Trainer is attached, this propery is 0.
- Return type
int
- half()¶
See
torch.nn.Module.half()
.- Return type
Self
- property hparams: Union[AttributeDict, MutableMapping]¶
The collection of hyperparameters saved with
save_hyperparameters()
. It is mutable by the user. For the frozen set of initial hyperparameters, usehparams_initial
.- Return type
Union
[AttributeDict
,MutableMapping
]- Returns
Mutable hyperparameters dictionary
- property hparams_initial: AttributeDict¶
The collection of hyperparameters saved with
save_hyperparameters()
. These contents are read-only. Manual updates to the saved hyperparameters can instead be performed throughhparams
.- Returns
immutable initial hyperparameters
- Return type
AttributeDict
- ipu(device=None)¶
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- load_from_checkpoint(checkpoint_path, map_location=None, hparams_file=None, strict=None, **kwargs)¶
Primary way of loading a model from a checkpoint. When Lightning saves a checkpoint it stores the arguments passed to
__init__
in the checkpoint under"hyper_parameters"
.Any arguments specified through **kwargs will override args stored in
"hyper_parameters"
.- Parameters
checkpoint_path (
Union
[str
,Path
,IO
]) – Path to checkpoint. This can also be a URL, or file-like objectmap_location (
Union
[device
,str
,int
,Callable
[[UntypedStorage
,str
],Optional
[UntypedStorage
]],Dict
[Union
[device
,str
,int
],Union
[device
,str
,int
]],None
]) – If your checkpoint saved a GPU model and you now load on CPUs or a different number of GPUs, use this to map to the new setup. The behaviour is the same as intorch.load()
.hparams_file (
Union
[str
,Path
,None
]) –Optional path to a
.yaml
or.csv
file with hierarchical structure as in this example:drop_prob: 0.2 dataloader: batch_size: 32
You most likely won’t need this since Lightning will always save the hyperparameters to the checkpoint. However, if your checkpoint weights don’t have the hyperparameters saved, use this method to pass in a
.yaml
file with the hparams you’d like to use. These will be converted into adict
and passed into yourLightningModule
for use.If your model’s
hparams
argument isNamespace
and.yaml
file has hierarchical structure, you need to refactor your model to treathparams
asdict
.strict (
Optional
[bool
]) – Whether to strictly enforce that the keys incheckpoint_path
match the keys returned by this module’s state dict. Defaults toTrue
unlessLightningModule.strict_loading
is set, in which case it defaults to the value ofLightningModule.strict_loading
.**kwargs – Any extra keyword args needed to init the model. Can also be used to override saved hyperparameter values.
- Return type
Self
- Returns
LightningModule
instance with loaded weights and hyperparameters (if available).
Note
load_from_checkpoint
is a class method. You should use yourLightningModule
class to call it instead of theLightningModule
instance, or aTypeError
will be raised.Note
To ensure all layers can be loaded from the checkpoint, this function will call
configure_model()
directly after instantiating the model if this hook is overridden in your LightningModule. However, note thatload_from_checkpoint
does not support loading sharded checkpoints, and you may run out of memory if the model is too large. In this case, consider loading through the Trainer via.fit(ckpt_path=...)
.Example:
# load weights without mapping ... model = MyLightningModule.load_from_checkpoint('path/to/checkpoint.ckpt') # or load weights mapping all weights from GPU 1 to GPU 0 ... map_location = {'cuda:1':'cuda:0'} model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', map_location=map_location ) # or load weights and hyperparameters from separate files. model = MyLightningModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', hparams_file='/path/to/hparams_file.yaml' ) # override some of the params with new values model = MyLightningModule.load_from_checkpoint( PATH, num_layers=128, pretrained_ckpt_path=NEW_PATH, ) # predict pretrained_model.eval() pretrained_model.freeze() y_hat = pretrained_model(x)
- load_state_dict(state_dict, strict=True, assign=False)¶
Copy parameters and buffers from
state_dict
into this module and its descendants.If
strict
isTrue
, then the keys ofstate_dict
must exactly match the keys returned by this module’sstate_dict()
function.Warning
If
assign
isTrue
the optimizer must be created after the call toload_state_dict
unlessget_swap_module_params_on_conversion()
isTrue
.- Parameters
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dict
match the keys returned by this module’sstate_dict()
function. Default:True
assign (bool, optional) – When
False
, the properties of the tensors in the current module are preserved while whenTrue
, the properties of the Tensors in the state dict are preserved. The only exception is therequires_grad
field ofDefault: ``False`
- Returns
- missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided
state_dict
.
- unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided
state_dict
.
- Return type
NamedTuple
withmissing_keys
andunexpected_keys
fields
Note
If a parameter or buffer is registered as
None
and its corresponding key exists instate_dict
,load_state_dict()
will raise aRuntimeError
.
- property local_rank: int¶
The index of the current process within a single node.
- Return type
int
- log(name, value, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, metric_attribute=None, rank_zero_only=False)¶
Log a key, value pair.
Example:
self.log('train_loss', loss)
The default behavior per hook is documented here: extensions/logging:Automatic Logging.
- Parameters
name (
str
) – key to log. Must be identical across all processes if using DDP or any other distributed strategy.value (
Union
[Metric
,Tensor
,int
,float
]) – value to log. Can be afloat
,Tensor
, or aMetric
.prog_bar (
bool
) – ifTrue
logs to the progress bar.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto detach the graph.sync_dist (
bool
) – ifTrue
, reduces the metric across devices. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the DDP group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple dataloaders). If False, user needs to give unique names for each dataloader to not mix the values.batch_size (
Optional
[int
]) – Current batch_size. This will be directly inferred from the loaded batch, but for some data structures you might need to explicitly provide it.metric_attribute (
Optional
[str
]) – To restore the metric state, Lightning requires the reference of thetorchmetrics.Metric
in your model. This is found automatically if it is a model attribute.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- log_dict(dictionary, prog_bar=False, logger=None, on_step=None, on_epoch=None, reduce_fx='mean', enable_graph=False, sync_dist=False, sync_dist_group=None, add_dataloader_idx=True, batch_size=None, rank_zero_only=False)¶
Log a dictionary of values at once.
Example:
values = {'loss': loss, 'acc': acc, ..., 'metric_n': metric_n} self.log_dict(values)
- Parameters
dictionary (
Union
[Mapping
[str
,Union
[Metric
,Tensor
,int
,float
]],MetricCollection
]) – key value pairs. Keys must be identical across all processes if using DDP or any other distributed strategy. The values can be afloat
,Tensor
,Metric
, orMetricCollection
.prog_bar (
bool
) – ifTrue
logs to the progress base.logger (
Optional
[bool
]) – ifTrue
logs to the logger.on_step (
Optional
[bool
]) – ifTrue
logs at this step.None
auto-logs for training_step but not validation/test_step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (
Optional
[bool
]) – ifTrue
logs epoch accumulated metrics.None
auto-logs for val/test step but nottraining_step
. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (
Union
[str
,Callable
]) – reduction function over step values for end of epoch.torch.mean()
by default.enable_graph (
bool
) – ifTrue
, will not auto-detach the graphsync_dist (
bool
) – ifTrue
, reduces the metric across GPUs/TPUs. Use with care as this may lead to a significant communication overhead.sync_dist_group (
Optional
[Any
]) – the ddp group to sync across.add_dataloader_idx (
bool
) – ifTrue
, appends the index of the current dataloader to the name (when using multiple). IfFalse
, user needs to give unique names for each dataloader to not mix values.batch_size (
Optional
[int
]) – Current batch size. This will be directly inferred from the loaded batch, but some data structures might need to explicitly provide it.rank_zero_only (
bool
) – Tells Lightning if you are callingself.log
from every process (default) or only from rank 0. IfTrue
, you won’t be able to use this metric as a monitor in callbacks (e.g., early stopping). Warning: Improper use can lead to deadlocks! See Advanced Logging for more details.
- Return type
None
- property logger: Optional[Union[Logger, Logger]]¶
Reference to the logger object in the Trainer.
- Return type
Union
[Logger
,Logger
,None
]
- property loggers: Union[List[Logger], List[Logger]]¶
Reference to the list of loggers in the Trainer.
- Return type
Union
[List
[Logger
],List
[Logger
]]
- lr_scheduler_step(scheduler, metric)¶
Override this method to adjust the default way the
Trainer
calls each scheduler. By default, Lightning callsstep()
and as shown in the example for each scheduler based on itsinterval
.- Parameters
scheduler (
Union
[LRScheduler
,ReduceLROnPlateau
]) – Learning rate scheduler.metric (
Optional
[Any
]) – Value of the monitor used for schedulers likeReduceLROnPlateau
.
Examples:
# DEFAULT def lr_scheduler_step(self, scheduler, metric): if metric is None: scheduler.step() else: scheduler.step(metric) # Alternative way to update schedulers if it requires an epoch value def lr_scheduler_step(self, scheduler, metric): scheduler.step(epoch=self.current_epoch)
- Return type
None
- lr_schedulers()¶
Returns the learning rate scheduler(s) that are being used during training. Useful for manual optimization.
- Return type
Union
[None
,List
[Union
[LRScheduler
,ReduceLROnPlateau
]],LRScheduler
,ReduceLROnPlateau
]- Returns
A single scheduler, or a list of schedulers in case multiple ones are present, or
None
if no schedulers were returned inconfigure_optimizers()
.
- manual_backward(loss, *args, **kwargs)¶
Call this directly from your
training_step()
when doing optimizations manually. By using this, Lightning can ensure that all the proper scaling gets applied when using mixed precision.See manual optimization for more examples.
Example:
def training_step(...): opt = self.optimizers() loss = ... opt.zero_grad() # automatically applies scaling, etc... self.manual_backward(loss) opt.step()
- Parameters
loss (
Tensor
) – The tensor on which to compute gradients. Must have a graph attached.*args – Additional positional arguments to be forwarded to
backward()
**kwargs – Additional keyword arguments to be forwarded to
backward()
- Return type
None
- modules()¶
Return an iterator over all modules in the network.
- Yields
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- Return type
Iterator
[Module
]
- named_buffers(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- Return type
Iterator
[Tuple
[str
,Tensor
]]
- named_children()¶
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- Return type
Iterator
[Tuple
[str
,Module
]]
- named_modules(memo=None, prefix='', remove_duplicate=True)¶
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters
memo (
Optional
[Set
[Module
]]) – a memo to store the set of modules already added to the resultprefix (
str
) – a prefix that will be added to the name of the moduleremove_duplicate (
bool
) – whether to remove the duplicated module instances in the result or not
- Yields
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)¶
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- Return type
Iterator
[Tuple
[str
,Parameter
]]
- on_after_backward()¶
Called after
loss.backward()
and before optimizers are stepped.Note
If using native AMP, the gradients will not be unscaled at this point. Use the
on_before_optimizer_step
if you need the unscaled gradients.- Return type
None
- on_after_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch after it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_after_batch_transfer(self, batch, dataloader_idx): batch['x'] = gpu_transforms(batch['x']) return batch
- on_before_backward(loss)¶
Called before
loss.backward()
.- Parameters
loss (
Tensor
) – Loss divided by number of batches for gradient accumulation and scaled if using AMP.- Return type
None
- on_before_batch_transfer(batch, dataloader_idx)¶
Override to alter or apply batch augmentations to your batch before it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be altered or augmented.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A batch of data
Example:
def on_before_batch_transfer(self, batch, dataloader_idx): batch['x'] = transforms(batch['x']) return batch
- on_before_optimizer_step(optimizer)¶
Called before
optimizer.step()
.If using gradient accumulation, the hook is called once the gradients have been accumulated. See: :paramref:`~pytorch_lightning.trainer.trainer.Trainer.accumulate_grad_batches`.
If using AMP, the loss will be unscaled before calling this hook. See these docs for more information on the scaling of gradients.
If clipping gradients, the gradients will not have been clipped yet.
- Parameters
optimizer (
Optimizer
) – Current optimizer being used.
Example:
def on_before_optimizer_step(self, optimizer): # example to inspect gradient information in tensorboard if self.trainer.global_step % 25 == 0: # don't make the tf file huge for k, v in self.named_parameters(): self.logger.experiment.add_histogram( tag=k, values=v.grad, global_step=self.trainer.global_step )
- Return type
None
- on_before_zero_grad(optimizer)¶
Called after
training_step()
and beforeoptimizer.zero_grad()
.Called in the training loop after taking an optimizer step and before zeroing grads. Good place to inspect weight information with weights updated.
This is where it is called:
for optimizer in optimizers: out = training_step(...) model.on_before_zero_grad(optimizer) # < ---- called here optimizer.zero_grad() backward()
- Parameters
optimizer (
Optimizer
) – The optimizer for which grads should be zeroed.- Return type
None
- on_fit_end()¶
Called at the very end of fit.
If on DDP it is called on every process
- Return type
None
- on_fit_start()¶
Called at the very beginning of fit.
If on DDP it is called on every process
- Return type
None
- property on_gpu: bool¶
Returns
True
if this model is currently located on a GPU.Useful to set flags around the LightningModule for different CPU vs GPU behavior.
- Return type
bool
- on_load_checkpoint(checkpoint)¶
Called by Lightning to restore your model. If you saved something with
on_save_checkpoint()
this is your chance to restore this.- Parameters
checkpoint (
Dict
[str
,Any
]) – Loaded checkpoint
Example:
def on_load_checkpoint(self, checkpoint): # 99% of the time you don't need to implement this method self.something_cool_i_want_to_save = checkpoint['something_cool_i_want_to_save']
Note
Lightning auto-restores global step, epoch, and train state including amp scaling. There is no need for you to restore anything regarding training.
- Return type
None
- on_predict_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop after the batch.
- Parameters
outputs (
Optional
[Any
]) – The outputs of predict_step(x)batch (
Any
) – The batched data as it is returned by the prediction DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the predict loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_predict_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_end()¶
Called at the end of predicting.
- Return type
None
- on_predict_epoch_start()¶
Called at the beginning of predicting.
- Return type
None
- on_predict_model_eval()¶
Called when the predict loop starts.
The predict loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior.- Return type
None
- on_predict_start()¶
Called at the beginning of predicting.
- Return type
None
- on_save_checkpoint(checkpoint)¶
Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
- Parameters
checkpoint (
Dict
[str
,Any
]) – The full checkpoint dictionary before it gets dumped to a file. Implementations of this hook can insert additional data into this dictionary.
Example:
def on_save_checkpoint(self, checkpoint): # 99% of use cases you don't need to implement this method checkpoint['something_cool_i_want_to_save'] = my_cool_pickable_object
Note
Lightning saves all aspects of training (epoch, global step, etc…) including amp scaling. There is no need for you to store anything about training.
- Return type
None
- on_test_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the test loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of test_step(x)batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the test loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the test DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_test_end()¶
Called at the end of testing.
- Return type
None
- on_test_epoch_end()¶
Called in the test loop at the very end of the epoch.
- Return type
None
- on_test_epoch_start()¶
Called in the test loop at the very beginning of the epoch.
- Return type
None
- on_test_model_eval()¶
Called when the test loop starts.
The test loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_test_model_train()
.- Return type
None
- on_test_model_train()¶
Called when the test loop ends.
The test loop by default restores the training mode of the LightningModule to what it was before starting testing. Override this hook to change the behavior. See also
on_test_model_eval()
.- Return type
None
- on_test_start()¶
Called at the beginning of testing.
- Return type
None
- on_train_batch_end(outputs, batch, batch_idx)¶
Called in the training loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of training_step(x)batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
Note
The value
outputs["loss"]
here will be the normalized value w.r.taccumulate_grad_batches
of the loss returned fromtraining_step
.- Return type
None
- on_train_batch_start(batch, batch_idx)¶
Called in the training loop before anything happens for that batch.
If you return -1 here, you will skip training for the rest of the current epoch.
- Parameters
batch (
Any
) – The batched data as it is returned by the training DataLoader.batch_idx (
int
) – the index of the batch
- Return type
Optional
[int
]
- on_train_end()¶
Called at the end of training before logger experiment is closed.
- Return type
None
- on_train_epoch_end()¶
Called in the training loop at the very end of the epoch.
To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the
LightningModule
and access them in this hook:class MyLightningModule(L.LightningModule): def __init__(self): super().__init__() self.training_step_outputs = [] def training_step(self): loss = ... self.training_step_outputs.append(loss) return loss def on_train_epoch_end(self): # do something with all training_step outputs, for example: epoch_mean = torch.stack(self.training_step_outputs).mean() self.log("training_epoch_mean", epoch_mean) # free up the memory self.training_step_outputs.clear()
- on_train_epoch_start()¶
Called in the training loop at the very beginning of the epoch.
- Return type
None
- on_train_start()¶
Called at the beginning of training after sanity check.
- Return type
None
- on_validation_batch_end(outputs, batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop after the batch.
- Parameters
outputs (
Union
[Tensor
,Mapping
[str
,Any
],None
]) – The outputs of validation_step(x)batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_batch_start(batch, batch_idx, dataloader_idx=0)¶
Called in the validation loop before anything happens for that batch.
- Parameters
batch (
Any
) – The batched data as it is returned by the validation DataLoader.batch_idx (
int
) – the index of the batchdataloader_idx (
int
) – the index of the dataloader
- Return type
None
- on_validation_end()¶
Called at the end of validation.
- Return type
None
- on_validation_epoch_end()¶
Called in the validation loop at the very end of the epoch.
- on_validation_epoch_start()¶
Called in the validation loop at the very beginning of the epoch.
- Return type
None
- on_validation_model_eval()¶
Called when the validation loop starts.
The validation loop by default calls
.eval()
on the LightningModule before it starts. Override this hook to change the behavior. See alsoon_validation_model_train()
.- Return type
None
- on_validation_model_train()¶
Called when the validation loop ends.
The validation loop by default restores the training mode of the LightningModule to what it was before starting validation. Override this hook to change the behavior. See also
on_validation_model_eval()
.- Return type
None
- on_validation_model_zero_grad()¶
Called by the training loop to release gradients before entering the validation loop.
- Return type
None
- on_validation_start()¶
Called at the beginning of validation.
- Return type
None
- optimizer_step(epoch, batch_idx, optimizer, optimizer_closure=None)¶
Override this method to adjust the default way the
Trainer
calls the optimizer.By default, Lightning calls
step()
andzero_grad()
as shown in the example. This method (andzero_grad()
) won’t be called during the accumulation phase whenTrainer(accumulate_grad_batches != 1)
. Overriding this hook has no benefit with manual optimization.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Union
[Optimizer
,LightningOptimizer
]) – A PyTorch optimizeroptimizer_closure (
Optional
[Callable
[[],Any
]]) – The optimizer closure. This closure must be executed as it includes the calls totraining_step()
,optimizer.zero_grad()
, andbackward()
.
Examples:
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_closure): # Add your custom logic to run directly before `optimizer.step()` optimizer.step(closure=optimizer_closure) # Add your custom logic to run directly after `optimizer.step()`
- Return type
None
- optimizer_zero_grad(epoch, batch_idx, optimizer)¶
Override this method to change the default behaviour of
optimizer.zero_grad()
.- Parameters
epoch (
int
) – Current epochbatch_idx (
int
) – Index of current batchoptimizer (
Optimizer
) – A PyTorch optimizer
Examples:
# DEFAULT def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad() # Set gradients to `None` instead of zero to improve performance (not required on `torch>=2.0.0`). def optimizer_zero_grad(self, epoch, batch_idx, optimizer): optimizer.zero_grad(set_to_none=True)
See
torch.optim.Optimizer.zero_grad()
for the explanation of the above example.- Return type
None
- optimizers(use_pl_optimizer=True)¶
Returns the optimizer(s) that are being used during training. Useful for manual optimization.
- Parameters
use_pl_optimizer (
bool
) – IfTrue
, will wrap the optimizer(s) in aLightningOptimizer
for automatic handling of precision, profiling, and counting of step calls for proper logging and checkpointing. It specifically wraps thestep
method and custom optimizers that don’t have this method are not supported.- Return type
Union
[Optimizer
,LightningOptimizer
,_FabricOptimizer
,List
[Optimizer
],List
[LightningOptimizer
],List
[_FabricOptimizer
]]- Returns
A single optimizer, or a list of optimizers in case multiple ones are present.
- property output_chunk_length: Optional[int]¶
Number of time steps predicted at once by the model.
- Return type
Optional
[int
]
- parameters(recurse=True)¶
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- Return type
Iterator
[Parameter
]
- pred_batch_size: Optional[int]¶
- pred_mc_dropout: Optional[bool]¶
- pred_n: Optional[int]¶
- pred_n_jobs: Optional[int]¶
- pred_num_samples: Optional[int]¶
- pred_roll_size: Optional[int]¶
- predict_dataloader()¶
An iterable or collection of iterables specifying prediction samples.
For more information about multiple dataloaders, see this section.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.predict()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
- Return type
Any
- Returns
A
torch.utils.data.DataLoader
or a sequence of them specifying prediction samples.
- predict_likelihood_parameters: Optional[bool]¶
- predict_step(batch, batch_idx, dataloader_idx=None)¶
performs the prediction step
- batch
output of Darts’
InferenceDataset
- tuple of(past_target, past_covariates, historic_future_covariates, future_covariates, future_past_covariates, input time series, prediction start time step)
- batch_idx
the batch index of the current batch
- dataloader_idx
the dataloader index
- Return type
Sequence
[TimeSeries
]
- prepare_data()¶
Use this to download and prepare data. Downloading and saving data with multiple processes (distributed settings) will result in corrupted data. Lightning ensures this method is called only within a single process, so you can safely add your downloading logic within.
Warning
DO NOT set state to the model (use
setup
instead) since this is NOT called on every deviceExample:
def prepare_data(self): # good download_data() tokenize() etc() # bad self.split = data_split self.some_state = some_other_state()
In a distributed environment,
prepare_data
can be called in two ways (using prepare_data_per_node)Once per node. This is the default and is only called on LOCAL_RANK=0.
Once in total. Only called on GLOBAL_RANK=0.
Example:
# DEFAULT # called once per node on LOCAL_RANK=0 of that node class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = True # call on GLOBAL_RANK=0 (great for shared file systems) class LitDataModule(LightningDataModule): def __init__(self): super().__init__() self.prepare_data_per_node = False
This is called before requesting the dataloaders:
model.prepare_data() initialize_distributed() model.setup(stage) model.train_dataloader() model.val_dataloader() model.test_dataloader() model.predict_dataloader()
- Return type
None
- prepare_data_per_node: bool¶
- print(*args, **kwargs)¶
Prints only from process 0. Use this in any distributed mode to log only once.
- Parameters
*args – The thing to print. The same as for Python’s built-in print function.
**kwargs – The same as for Python’s built-in print function.
Example:
def forward(self, x): self.print(x, 'in forward')
- Return type
None
- register_backward_hook(hook)¶
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()
and the behavior of this function will change in future versions.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_buffer(name, tensor, persistent=True)¶
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_mean
is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistent
toFalse
. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict
.Buffers can be accessed as attributes using given names.
- Parameters
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None
, then operations that run on buffers, such ascuda
, are ignored. IfNone
, the buffer is not included in the module’sstate_dict
.persistent (bool) – whether the buffer is part of this module’s
state_dict
.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- Return type
None
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)¶
Register a forward hook on the module.
The hook will be called every time after
forward()
has computed an output.If
with_kwargs
isFalse
or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()
is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargs
isTrue
, the forward hook will be passed thekwargs
given to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True
, the providedhook
will be fired before all existingforward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward
hooks on thistorch.nn.modules.Module
. Note that globalforward
hooks registered withregister_module_forward_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If
True
, thehook
will be passed the kwargs given to the forward function. Default:False
always_call (bool) – If
True
thehook
will be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)¶
Register a forward pre-hook on the module.
The hook will be called every time before
forward()
is invoked.If
with_kwargs
is false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargs
is true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingforward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward_pre
hooks on thistorch.nn.modules.Module
. Note that globalforward_pre
hooks registered withregister_module_forward_pre_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If true, the
hook
will be passed the kwargs given to the forward function. Default:False
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)¶
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_input
andgrad_output
are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_input
in subsequent computations.grad_input
will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_input
andgrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward
hooks on thistorch.nn.modules.Module
. Note that globalbackward
hooks registered withregister_module_full_backward_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)¶
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_output
is a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_output
in subsequent computations. Entries ingrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Note that globalbackward_pre
hooks registered withregister_module_full_backward_pre_hook()
will fire before all hooks registered by this method.
- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)¶
Register a post hook to be run after module’s
load_state_dict
is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
module
argument is the current module that this hook is registered on, and theincompatible_keys
argument is aNamedTuple
consisting of attributesmissing_keys
andunexpected_keys
.missing_keys
is alist
ofstr
containing the missing keys andunexpected_keys
is alist
ofstr
containing the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()
withstrict=True
are affected by modifications the hook makes tomissing_keys
orunexpected_keys
, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True
, and clearing out both missing and unexpected keys will avoid an error.- Returns
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type
torch.utils.hooks.RemovableHandle
- register_module(name, module)¶
Alias for
add_module()
.- Return type
None
- register_parameter(name, param)¶
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None
, then operations that run on parameters, such ascuda
, are ignored. IfNone
, the parameter is not included in the module’sstate_dict
.
- Return type
None
- register_state_dict_pre_hook(hook)¶
Register a pre-hook for the
state_dict()
method.These hooks will be called with arguments:
self
,prefix
, andkeep_vars
before callingstate_dict
onself
. The registered hooks can be used to perform pre-processing before thestate_dict
call is made.
- requires_grad_(requires_grad=True)¶
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_grad
attributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True
.- Returns
self
- Return type
Module
- save_hyperparameters(*args, ignore=None, frame=None, logger=True)¶
Save arguments to
hparams
attribute.- Parameters
args (
Any
) – single object of dict, NameSpace or OmegaConf or string names or arguments from class__init__
ignore (
Union
[str
,Sequence
[str
],None
]) – an argument name or a list of argument names from class__init__
to be ignoredframe (
Optional
[frame
]) – a frame object. Default is Nonelogger (
bool
) – Whether to send the hyperparameters to the logger. Default: True
- Example::
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # manually assign arguments ... self.save_hyperparameters('arg1', 'arg3') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class AutomaticArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # equivalent automatic ... self.save_hyperparameters() ... def forward(self, *args, **kwargs): ... ... >>> model = AutomaticArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg2": abc "arg3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class SingleArgModel(HyperparametersMixin): ... def __init__(self, params): ... super().__init__() ... # manually assign single argument ... self.save_hyperparameters(params) ... def forward(self, *args, **kwargs): ... ... >>> model = SingleArgModel(Namespace(p1=1, p2='abc', p3=3.14)) >>> model.hparams "p1": 1 "p2": abc "p3": 3.14
>>> from pytorch_lightning.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # pass argument(s) to ignore as a string or in a list ... self.save_hyperparameters(ignore='arg2') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
- Return type
None
- set_extra_state(state)¶
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()
to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()
for your module if you need to store extra state within its state_dict.- Parameters
state (dict) – Extra state from the state_dict
- Return type
None
- set_mc_dropout(active)¶
- set_predict_parameters(n, num_samples, roll_size, batch_size, n_jobs, predict_likelihood_parameters, mc_dropout)¶
to be set from TorchForecastingModel before calling trainer.predict() and reset at self.on_predict_end()
- Return type
None
- setup(stage)¶
Called at the beginning of fit (train + validate), validate, test, or predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
Example:
class LitModel(...): def __init__(self): self.l1 = None def prepare_data(self): download_data() tokenize() # don't do this self.something = else def setup(self, stage): data = load_data(...) self.l1 = nn.Linear(28, data.num_classes)
- Return type
None
See
torch.Tensor.share_memory_()
.- Return type
~T
- state_dict(*args, destination=None, prefix='', keep_vars=False)¶
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
None
are not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()
also accepts positional arguments fordestination
,prefix
andkeep_vars
in order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destination
as it is not designed for end-users.- Parameters
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDict
will be created and returned. Default:None
.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''
.keep_vars (bool, optional) – by default the
Tensor
s returned in the state dict are detached from autograd. If it’s set toTrue
, detaching will not be performed. Default:False
.
- Returns
a dictionary containing a whole state of the module
- Return type
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- property strict_loading: bool¶
Determines how Lightning loads this model using .load_state_dict(…, strict=model.strict_loading).
- Return type
bool
- property supports_probabilistic_prediction: bool¶
- Return type
bool
- teardown(stage)¶
Called at the end of fit (train + validate), validate, test, or predict.
- Parameters
stage (
str
) – either'fit'
,'validate'
,'test'
, or'predict'
- Return type
None
- test_dataloader()¶
An iterable or collection of iterables specifying test samples.
For more information about multiple dataloaders, see this section.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
test()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
Note
If you don’t need a test dataset and a
test_step()
, you don’t need to implement this method.- Return type
Any
- test_step(*args, **kwargs)¶
Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.
- Parameters
batch – The output of your data iterable, normally a
DataLoader
.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- Return type
Union
[Tensor
,Mapping
[str
,Any
],None
]- Returns
Tensor
- The loss tensordict
- A dictionary. Can include any keys, but must include the key'loss'
.None
- Skip to the next batch.
# if you have one test dataloader: def test_step(self, batch, batch_idx): ... # if you have multiple test dataloaders: def test_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single test dataset def test_step(self, batch, batch_idx): x, y = batch # implement your own out = self(x) loss = self.loss(out, y) # log 6 example images # or generated text... or whatever sample_imgs = x[:6] grid = torchvision.utils.make_grid(sample_imgs) self.logger.experiment.add_image('example_images', grid, 0) # calculate acc labels_hat = torch.argmax(out, dim=1) test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'test_loss': loss, 'test_acc': test_acc})
If you pass in multiple test dataloaders,
test_step()
will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.# CASE 2: multiple test dataloaders def test_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. ...
Note
If you don’t need to test you don’t need to implement this method.
Note
When the
test_step()
is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.
- to(*args, **kwargs)¶
See
torch.nn.Module.to()
.- Return type
Self
- to_dtype(dtype)¶
Cast module precision (float32 by default) to another precision.
- to_empty(*, device, recurse=True)¶
Move the parameters and buffers to the specified device without copying storage.
- Parameters
device (
torch.device
) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns
self
- Return type
Module
- to_onnx(file_path, input_sample=None, **kwargs)¶
Saves the model in ONNX format.
- Parameters
file_path (
Union
[str
,Path
]) – The path of the file the onnx model should be saved to.input_sample (
Optional
[Any
]) – An input for tracing. Default: None (Use self.example_input_array)**kwargs – Will be passed to torch.onnx.export function.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1) model = SimpleModel() input_sample = torch.randn(1, 64) model.to_onnx("export.onnx", input_sample, export_params=True)
- Return type
None
- to_torchscript(file_path=None, method='script', example_inputs=None, **kwargs)¶
By default compiles the whole model to a
ScriptModule
. If you want to use tracing, please provided the argumentmethod='trace'
and make sure that either the example_inputs argument is provided, or the model hasexample_input_array
set. If you would like to customize the modules that are scripted you should override this method. In case you want to return multiple modules, we recommend using a dictionary.- Parameters
file_path (
Union
[str
,Path
,None
]) – Path where to save the torchscript. Default: None (no file saved).method (
Optional
[str
]) – Whether to use TorchScript’s script or trace method. Default: ‘script’example_inputs (
Optional
[Any
]) – An input to be used to do tracing when method is set to ‘trace’. Default: None (usesexample_input_array
)**kwargs – Additional arguments that will be passed to the
torch.jit.script()
ortorch.jit.trace()
function.
Note
Requires the implementation of the
forward()
method.The exported script will be set to evaluation mode.
It is recommended that you install the latest supported version of PyTorch to use this feature without limitations. See also the
torch.jit
documentation for supported features.
Example:
class SimpleModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(in_features=64, out_features=4) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1))) model = SimpleModel() model.to_torchscript(file_path="model.pt") torch.jit.save(model.to_torchscript( file_path="model_trace.pt", method='trace', example_inputs=torch.randn(1, 64)) )
- Return type
Union
[ScriptModule
,Dict
[str
,ScriptModule
]]- Returns
This LightningModule as a torchscript, regardless of whether file_path is defined or not.
- toggle_optimizer(optimizer)¶
Makes sure only the gradients of the current optimizer’s parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
It works with
untoggle_optimizer()
to make sureparam_requires_grad_state
is properly reset.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to toggle.- Return type
None
- train(mode=True)¶
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.- Parameters
mode (bool) – whether to set training mode (
True
) or evaluation mode (False
). Default:True
.- Returns
self
- Return type
Module
- train_criterion_reduction: Optional[str]¶
- train_dataloader()¶
An iterable or collection of iterables specifying training samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
For data processing use the following pattern:
download in
prepare_data()
process and split in
setup()
However, the above are only necessary for distributed processing.
Warning
do not assign state in prepare_data
fit()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.
- Return type
Any
- property trainer: Trainer¶
- Return type
Trainer
- training: bool¶
- training_step(train_batch, batch_idx)¶
performs the training step
- Return type
Tensor
- transfer_batch_to_device(batch, device, dataloader_idx)¶
Override this hook if your
DataLoader
returns tensors wrapped in a custom data structure.The data types listed below (and any arbitrary nesting of them) are supported out of the box:
torch.Tensor
or anything that implements .to(…)list
dict
tuple
For anything else, you need to define how the data is moved to the target device (CPU, GPU, TPU, …).
Note
This hook should only transfer the data and not modify it, nor should it move the data to any other device than the one passed in as argument (unless you know what you are doing). To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predicting
so that you can add different logic as per your requirement.- Parameters
batch (
Any
) – A batch of data that needs to be transferred to a new device.device (
device
) – The target device as defined in PyTorch.dataloader_idx (
int
) – The index of the dataloader to which the batch belongs.
- Return type
Any
- Returns
A reference to the data on the new device.
Example:
def transfer_batch_to_device(self, batch, device, dataloader_idx): if isinstance(batch, CustomBatch): # move all tensors in your custom data structure to the device batch.samples = batch.samples.to(device) batch.targets = batch.targets.to(device) elif dataloader_idx == 0: # skip device transfer for the first dataloader or anything you wish pass else: batch = super().transfer_batch_to_device(batch, device, dataloader_idx) return batch
See also
move_data_to_device()
apply_to_collection()
- type(dst_type)¶
See
torch.nn.Module.type()
.- Return type
Self
- unfreeze()¶
Unfreeze all parameters for training.
model = MyLightningModule(...) model.unfreeze()
- Return type
None
- untoggle_optimizer(optimizer)¶
Resets the state of required gradients that were toggled with
toggle_optimizer()
.- Parameters
optimizer (
Union
[Optimizer
,LightningOptimizer
]) – The optimizer to untoggle.- Return type
None
- val_criterion_reduction: Optional[str]¶
- val_dataloader()¶
An iterable or collection of iterables specifying validation samples.
For more information about multiple dataloaders, see this section.
The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.
It’s recommended that all data downloads and preparation happen in
prepare_data()
.fit()
validate()
Note
Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.
Note
If you don’t need a validation dataset and a
validation_step()
, you don’t need to implement this method.- Return type
Any
- validation_step(val_batch, batch_idx)¶
performs the validation step
- Return type
Tensor
- xpu(device=None)¶
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters
device (int, optional) – if specified, all parameters will be copied to that device
- Returns
self
- Return type
Module
- zero_grad(set_to_none=True)¶
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizer
for more context.- Parameters
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()
for details.- Return type
None