topobench.model.model module#
This module defines the TBModel class.
- class Any(*args, **kwargs)#
Bases:
objectSpecial type indicating an unconstrained type.
Any is compatible with every type.
Any assumed to have all methods.
All values assumed to be instances of Any.
Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.
- class Data(x=None, edge_index=None, edge_attr=None, y=None, pos=None, time=None, **kwargs)#
Bases:
BaseData,FeatureStore,GraphStoreA data object describing a homogeneous graph. The data object can hold node-level, link-level and graph-level attributes. In general,
Datatries to mimic the behavior of a regular :python:`Python` dictionary. In addition, it provides useful functionality for analyzing graph structures, and provides basic PyTorch tensor functionalities. See here for the accompanying tutorial.from torch_geometric.data import Data data = Data(x=x, edge_index=edge_index, ...) # Add additional arguments to `data`: data.train_idx = torch.tensor([...], dtype=torch.long) data.test_mask = torch.tensor([...], dtype=torch.bool) # Analyzing the graph structure: data.num_nodes >>> 23 data.is_directed() >>> False # PyTorch tensor functionality: data = data.pin_memory() data = data.to('cuda:0', non_blocking=True)
- Parameters:
x (torch.Tensor, optional) – Node feature matrix with shape
[num_nodes, num_node_features]. (default:None)edge_index (LongTensor, optional) – Graph connectivity in COO format with shape
[2, num_edges]. (default:None)edge_attr (torch.Tensor, optional) – Edge feature matrix with shape
[num_edges, num_edge_features]. (default:None)y (torch.Tensor, optional) – Graph-level or node-level ground-truth labels with arbitrary shape. (default:
None)pos (torch.Tensor, optional) – Node position matrix with shape
[num_nodes, num_dimensions]. (default:None)time (torch.Tensor, optional) – The timestamps for each event with shape
[num_edges]or[num_nodes]. (default:None)**kwargs (optional) – Additional attributes.
- __init__(x=None, edge_index=None, edge_attr=None, y=None, pos=None, time=None, **kwargs)#
- connected_components()#
Extracts connected components of the graph using a union-find algorithm. The components are returned as a list of
Dataobjects, where each object represents a connected component of the graph.data = Data() data.x = torch.tensor([[1.0], [2.0], [3.0], [4.0]]) data.y = torch.tensor([[1.1], [2.1], [3.1], [4.1]]) data.edge_index = torch.tensor( [[0, 1, 2, 3], [1, 0, 3, 2]], dtype=torch.long ) components = data.connected_components() print(len(components)) >>> 2 print(components[0].x) >>> Data(x=[2, 1], y=[2, 1], edge_index=[2, 2])
- Returns:
A list of disconnected components.
- Return type:
List[Data]
- debug()#
- edge_subgraph(subset)#
Returns the induced subgraph given by the edge indices
subset. Will currently preserve all the nodes in the graph, even if they are isolated after subgraph computation.- Parameters:
subset (LongTensor or BoolTensor) – The edges to keep.
- classmethod from_dict(mapping)#
Creates a
Dataobject from a dictionary.
- get_all_edge_attrs()#
Returns all registered edge attributes.
- get_all_tensor_attrs()#
Obtains all feature attributes stored in Data.
- stores_as(data)#
- subgraph(subset)#
Returns the induced subgraph given by the node indices
subset.- Parameters:
subset (LongTensor or BoolTensor) – The nodes to keep.
- to_dict()#
Returns a dictionary of stored key/value pairs.
- to_heterogeneous(node_type=None, edge_type=None, node_type_names=None, edge_type_names=None)#
Converts a
Dataobject to a heterogeneousHeteroDataobject. For this, node and edge attributes are splitted according to the node-level and edge-level vectorsnode_typeandedge_type, respectively.node_type_namesandedge_type_namescan be used to give meaningful node and edge type names, respectively. That is, the node_type0is given bynode_type_names[0]. If theDataobject was constructed viato_homogeneous(), the object can be reconstructed without any need to pass in additional arguments.- Parameters:
node_type (torch.Tensor, optional) – A node-level vector denoting the type of each node. (default:
None)edge_type (torch.Tensor, optional) – An edge-level vector denoting the type of each edge. (default:
None)node_type_names (List[str], optional) – The names of node types. (default:
None)edge_type_names (List[Tuple[str, str, str]], optional) – The names of edge types. (default:
None)
- to_namedtuple()#
Returns a
NamedTupleof stored key/value pairs.
- update(data)#
Updates the data object with the elements from another data object. Added elements will override existing ones (in case of duplicates).
- validate(raise_on_error=True)#
Validates the correctness of the data.
- property num_features: int#
Returns the number of features per node in the graph. Alias for
num_node_features.
- property num_nodes: int | None#
Returns the number of nodes in the graph.
Note
The number of nodes in the data object is automatically inferred in case node-level attributes are present, e.g.,
data.x. In some cases, however, a graph may only be given without any node-level attributes. :pyg:`PyG` then guesses the number of nodes according toedge_index.max().item() + 1. However, in case there exists isolated nodes, this number does not have to be correct which can result in unexpected behavior. Thus, we recommend to set the number of nodes in your data object explicitly viadata.num_nodes = .... You will be given a warning that requests you to do so.
- class LightningModule(*args, **kwargs)#
Bases:
_DeviceDtypeModuleMixin,HyperparametersMixin,ModelHooks,DataHooks,CheckpointHooks,Module- __init__(*args, **kwargs)#
- 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 (Tensor | Dict | List | Tuple) – int, float, tensor of shape (batch, …), or a (possibly nested) collection thereof.
group (Any | None) – 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
- 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).
- Return type:
- 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 by
training_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()
- 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 (int | float | None) – The value at which to clip gradients.
gradient_clip_algorithm (str | None) – The gradient clipping algorithm to use. Pass
gradient_clip_algorithm="value"to clip by value, andgradient_clip_algorithm="norm"to clip by norm.
- 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’scallbacksargument. 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 sureModelCheckpointcallbacks run last.- Returns:
A callback or a list of callbacks which will extend the list of callbacks in the Trainer.
- Return type:
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 (int | float | None) – The value at which to clip gradients. By default, value passed in Trainer will be available here.
gradient_clip_algorithm (str | None) – 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 )
- configure_optimizers()#
Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you’d need one. But in the case of GANs or similar you might have multiple. Optimization with multiple optimizers only works in the manual optimization mode.
- Returns:
Any of these 6 options.
Single optimizer.
List or Tuple of optimizers.
Two lists - The first list has multiple optimizers, and the second has multiple LR schedulers (or multiple
lr_scheduler_config).Dictionary, with an
"optimizer"key, and (optionally) a"lr_scheduler"key whose value is a single LR scheduler orlr_scheduler_config.None - Fit will run without any optimizer.
- Return type:
Optimizer | Sequence[Optimizer] | Tuple[Sequence[Optimizer], Sequence[LRScheduler | ReduceLROnPlateau | LRSchedulerConfig]] | OptimizerLRSchedulerConfig | Sequence[OptimizerLRSchedulerConfig] | None
The
lr_scheduler_configis a dictionary which contains the scheduler and its associated configuration. The default configuration is shown below.lr_scheduler_config = { # REQUIRED: The scheduler instance "scheduler": lr_scheduler, # The unit of the scheduler's step size, could also be 'step'. # 'epoch' updates the scheduler on epoch end whereas 'step' # updates it after a optimizer update. "interval": "epoch", # How many epochs/steps should pass between calls to # `scheduler.step()`. 1 corresponds to updating the learning # rate after every epoch/step. "frequency": 1, # Metric to to monitor for schedulers like `ReduceLROnPlateau` "monitor": "val_loss", # If set to `True`, will enforce that the value specified 'monitor' # is available when the scheduler is updated, thus stopping # training if not found. If set to `False`, it will only produce a warning "strict": True, # If using the `LearningRateMonitor` callback to monitor the # learning rate progress, this keyword can be used to specify # a custom logged name "name": None, }
When there are schedulers in which the
.step()method is conditioned on a value, such as thetorch.optim.lr_scheduler.ReduceLROnPlateauscheduler, Lightning requires that thelr_scheduler_configcontains the keyword"monitor"set to the metric name that the scheduler should be conditioned on.# The ReduceLROnPlateau scheduler requires a monitor def configure_optimizers(self): optimizer = Adam(...) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": ReduceLROnPlateau(optimizer, ...), "monitor": "metric_to_track", "frequency": "indicates how often the metric is updated", # If "monitor" references validation metrics, then "frequency" should be set to a # multiple of "trainer.check_val_every_n_epoch". }, } # In the case of two optimizers, only one using the ReduceLROnPlateau scheduler def configure_optimizers(self): optimizer1 = Adam(...) optimizer2 = SGD(...) scheduler1 = ReduceLROnPlateau(optimizer1, ...) scheduler2 = LambdaLR(optimizer2, ...) return ( { "optimizer": optimizer1, "lr_scheduler": { "scheduler": scheduler1, "monitor": "metric_to_track", }, }, {"optimizer": optimizer2, "lr_scheduler": scheduler2}, )
Metrics can be made available to monitor by simply logging it using
self.log('metric_to_track', metric_val)in yourLightningModule.Note
Some things to know:
Lightning calls
.backward()and.step()automatically in case of automatic optimization.If a learning rate scheduler is specified in
configure_optimizers()with key"interval"(default “epoch”) in the scheduler configuration, Lightning will call the scheduler’s.step()method automatically in case of automatic optimization.If you use 16-bit precision (
precision=16), Lightning will automatically handle the optimizer.If you use
torch.optim.LBFGS, Lightning handles the closure function automatically for you.If you use multiple optimizers, you will have to switch to ‘manual optimization’ mode and step them yourself.
If you need to control how often the optimizer steps, override the
optimizer_step()hook.
- forward(*args, **kwargs)#
Same as
torch.nn.Module.forward().
- freeze()#
Freeze all params for inference.
Example:
model = MyLightningModule(...) model.freeze()
- 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 (str | Path | IO) – Path to checkpoint. This can also be a URL, or file-like object
map_location (device | str | int | Callable[[UntypedStorage, str], UntypedStorage | None] | Dict[device | str | int, 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 in
torch.load().hparams_file (str | Path | None) –
Optional path to a
.yamlor.csvfile 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
.yamlfile with the hparams you’d like to use. These will be converted into adictand passed into yourLightningModulefor use.If your model’s
hparamsargument isNamespaceand.yamlfile has hierarchical structure, you need to refactor your model to treathparamsasdict.strict (bool | None) – Whether to strictly enforce that the keys in
checkpoint_pathmatch the keys returned by this module’s state dict. Defaults toTrueunlessLightningModule.strict_loadingis set, in which case it defaults to the value ofLightningModule.strict_loading.**kwargs (Any) – Any extra keyword args needed to init the model. Can also be used to override saved hyperparameter values.
- Returns:
LightningModuleinstance with loaded weights and hyperparameters (if available).- Return type:
Note
load_from_checkpointis a class method. You should use yourLightningModuleclass to call it instead of theLightningModuleinstance, or aTypeErrorwill 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_checkpointdoes 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)
- 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 (Metric | Tensor | int | float) – value to log. Can be a
float,Tensor, or aMetric.prog_bar (bool) – if
Truelogs to the progress bar.logger (bool | None) – if
Truelogs to the logger.on_step (bool | None) – if
Truelogs at this step. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.on_epoch (bool | None) – if
Truelogs epoch accumulated metrics. The default value is determined by the hook. See extensions/logging:Automatic Logging for details.reduce_fx (str | Callable) – reduction function over step values for end of epoch.
torch.mean()by default.enable_graph (bool) – if
True, will not auto detach the graph.sync_dist (bool) – if
True, reduces the metric across devices. Use with care as this may lead to a significant communication overhead.sync_dist_group (Any | None) – the DDP group to sync across.
add_dataloader_idx (bool) – if
True, 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 (int | None) – 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 (str | None) – To restore the metric state, Lightning requires the reference of the
torchmetrics.Metricin your model. This is found automatically if it is a model attribute.rank_zero_only (bool) – Tells Lightning if you are calling
self.logfrom 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.
- 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 (Mapping[str, 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 a
float,Tensor,Metric, orMetricCollection.prog_bar (bool) – if
Truelogs to the progress base.logger (bool | None) – if
Truelogs to the logger.on_step (bool | None) – if
Truelogs at this step.Noneauto-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 (bool | None) – if
Truelogs epoch accumulated metrics.Noneauto-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 (str | Callable) – reduction function over step values for end of epoch.
torch.mean()by default.enable_graph (bool) – if
True, will not auto-detach the graphsync_dist (bool) – if
True, reduces the metric across GPUs/TPUs. Use with care as this may lead to a significant communication overhead.sync_dist_group (Any | None) – the ddp group to sync across.
add_dataloader_idx (bool) – if
True, 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 (int | None) – 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 calling
self.logfrom 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.
- lr_scheduler_step(scheduler, metric)#
Override this method to adjust the default way the
Trainercalls each scheduler. By default, Lightning callsstep()and as shown in the example for each scheduler based on itsinterval.- Parameters:
scheduler (LRScheduler | ReduceLROnPlateau) – Learning rate scheduler.
metric (Any | None) – Value of the monitor used for schedulers like
ReduceLROnPlateau.
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)
- lr_schedulers()#
Returns the learning rate scheduler(s) that are being used during training. Useful for manual optimization.
- Returns:
A single scheduler, or a list of schedulers in case multiple ones are present, or
Noneif no schedulers were returned inconfigure_optimizers().- Return type:
None | List[LRScheduler | ReduceLROnPlateau] | LRScheduler | ReduceLROnPlateau
- 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()
- optimizer_step(epoch, batch_idx, optimizer, optimizer_closure=None)#
Override this method to adjust the default way the
Trainercalls 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 epoch
batch_idx (int) – Index of current batch
optimizer (Optimizer | LightningOptimizer) – A PyTorch optimizer
optimizer_closure (Callable[[], Any] | None) – The optimizer closure. This closure must be executed as it includes the calls to
training_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()`
- optimizer_zero_grad(epoch, batch_idx, optimizer)#
Override this method to change the default behaviour of
optimizer.zero_grad().- Parameters:
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.
- optimizers(use_pl_optimizer: Literal[True] = True) LightningOptimizer | List[LightningOptimizer]#
- optimizers(use_pl_optimizer: Literal[False]) Optimizer | List[Optimizer]
- optimizers(use_pl_optimizer: bool) Optimizer | LightningOptimizer | _FabricOptimizer | List[Optimizer] | List[LightningOptimizer] | List[_FabricOptimizer]
Returns the optimizer(s) that are being used during training. Useful for manual optimization.
- Parameters:
use_pl_optimizer – If
True, will wrap the optimizer(s) in aLightningOptimizerfor automatic handling of precision, profiling, and counting of step calls for proper logging and checkpointing. It specifically wraps thestepmethod and custom optimizers that don’t have this method are not supported.- Returns:
A single optimizer, or a list of optimizers in case multiple ones are present.
- predict_step(*args, **kwargs)#
Step function called during
predict(). By default, it callsforward(). Override to add any processing logic.The
predict_step()is used to scale inference on multi-devices.To prevent an OOM error, it is possible to use
BasePredictionWritercallback to write the predictions to disk or database after each batch or on epoch end.The
BasePredictionWritershould be used while using a spawn based accelerator. This happens forTrainer(strategy="ddp_spawn")or training on 8 TPU cores withTrainer(accelerator="tpu", devices=8)as predictions won’t be returned.- 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)
- Returns:
Predicted output (optional).
- Return type:
Example
class MyModel(LightningModule): def predict_step(self, batch, batch_idx, dataloader_idx=0): return self(batch) dm = ... model = MyModel() trainer = Trainer(accelerator="gpu", devices=2) predictions = trainer.predict(model, dm)
- print(*args, **kwargs)#
Prints only from process 0. Use this in any distributed mode to log only once.
- Parameters:
Example:
def forward(self, x): self.print(x, 'in forward')
- 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)
- Returns:
Tensor- The loss tensordict- A dictionary. Can include any keys, but must include the key'loss'.None- Skip to the next batch.
- Return type:
# 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_onnx(file_path, input_sample=None, **kwargs)#
Saves the model in ONNX format.
- Parameters:
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)
- 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_arrayset. 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 (str | Path | None) – Path where to save the torchscript. Default: None (no file saved).
method (str | None) – Whether to use TorchScript’s script or trace method. Default: ‘script’
example_inputs (Any | None) – An input to be used to do tracing when method is set to ‘trace’. Default: None (uses
example_input_array)**kwargs (Any) – 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.jitdocumentation 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)) )
- 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_stateis properly reset.- Parameters:
optimizer (Optimizer | LightningOptimizer) – The optimizer to toggle.
- training_step(*args, **kwargs)#
Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.
- 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)
- Returns:
Tensor- The loss tensordict- A dictionary which can include any keys, but must include the key'loss'in the case of automatic optimization.None- In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.
- Return type:
In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.
Example:
def training_step(self, batch, batch_idx): x, y, z = batch out = self.encoder(x) loss = self.loss(out, x) return loss
To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:
def __init__(self): super().__init__() self.automatic_optimization = False # Multiple optimizers (e.g.: GANs) def training_step(self, batch, batch_idx): opt1, opt2 = self.optimizers() # do training_step with encoder ... opt1.step() # do training_step with decoder ... opt2.step()
Note
When
accumulate_grad_batches> 1, the loss returned here will be automatically normalized byaccumulate_grad_batchesinternally.
- unfreeze()#
Unfreeze all parameters for training.
model = MyLightningModule(...) model.unfreeze()
- untoggle_optimizer(optimizer)#
Resets the state of required gradients that were toggled with
toggle_optimizer().- Parameters:
optimizer (Optimizer | LightningOptimizer) – The optimizer to untoggle.
- validation_step(*args, **kwargs)#
Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like 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)
- Returns:
Tensor- The loss tensordict- A dictionary. Can include any keys, but must include the key'loss'.None- Skip to the next batch.
- Return type:
# if you have one val dataloader: def validation_step(self, batch, batch_idx): ... # if you have multiple val dataloaders: def validation_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single validation dataset def validation_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) val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'val_loss': loss, 'val_acc': val_acc})
If you pass in multiple val dataloaders,
validation_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 validation dataloaders def validation_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. ...
Note
If you don’t need to validate you don’t need to implement this method.
Note
When the
validation_step()is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.
- CHECKPOINT_HYPER_PARAMS_KEY = 'hyper_parameters'#
- CHECKPOINT_HYPER_PARAMS_NAME = 'hparams_name'#
- CHECKPOINT_HYPER_PARAMS_TYPE = 'hparams_type'#
- property automatic_optimization: bool#
If set to
Falseyou are responsible for calling.backward(),.step(),.zero_grad().
- property device_mesh: DeviceMesh | None#
Strategies like
ModelParallelStrategywill create a device mesh that can be accessed in theconfigure_model()hook to parallelize the LightningModule.
- property example_input_array: Tensor | Tuple | Dict | None#
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)
- property global_step: int#
Total training batches seen across all epochs.
If no Trainer is attached, this propery is 0.
- property on_gpu: bool#
Returns
Trueif this model is currently located on a GPU.Useful to set flags around the LightningModule for different CPU vs GPU behavior.
- class MeanMetric(nan_strategy='warn', **kwargs)#
Bases:
BaseAggregatorAggregate a stream of value into their mean value.
As input to
forwardandupdatethe metric accepts the following inputvalue(floatorTensor): a single float or an tensor of float values with arbitrary shape(...,).weight(floatorTensor): a single float or an tensor of float value with arbitrary shape(...,). Needs to be broadcastable with the shape ofvaluetensor.
As output of forward and compute the metric returns the following output
agg(Tensor): scalar float tensor with aggregated (weighted) mean over all inputs received
- Parameters:
nan_strategy (Literal['error', 'warn', 'ignore', 'disable'] | float) – options: -
'error': if any nan values are encountered will give a RuntimeError -'warn': if any nan values are encountered will give a warning and continue -'ignore': all nan values are silently removed -'disable': disable all nan checks - a float: if a float is provided will impute any nan values with this valuekwargs (Any) – Additional keyword arguments, see Metric kwargs for more info.
- Raises:
ValueError – If
nan_strategyis not one oferror,warn,ignore,disableor a float
Example
>>> from torchmetrics.aggregation import MeanMetric >>> metric = MeanMetric() >>> metric.update(1) >>> metric.update(torch.tensor([2, 3])) >>> metric.compute() tensor(2.)
- __init__(nan_strategy='warn', **kwargs)#
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- compute()#
Compute the aggregated value.
- plot(val=None, ax=None)#
Plot a single or multiple values from the metric.
- Parameters:
val (Tensor | Sequence[Tensor] | None) – Either a single result from calling metric.forward or metric.compute or a list of these results. If no value is provided, will automatically call metric.compute and plot that result.
ax (Axes | None) – An matplotlib axis object. If provided will add plot to that axis
- Returns:
Figure and Axes object
- Raises:
ModuleNotFoundError – If matplotlib is not installed
- Return type:
- update(value, weight=None)#
Update state with data.
- Parameters:
value (float | Tensor) – Either a float or tensor containing data. Additional tensor dimensions will be flattened
weight (float | Tensor | None) – Either a float or tensor containing weights for calculating the average. Shape of weight should be able to broadcast with the shape of value. Default to None corresponding to simple harmonic average.
- mean_value: Tensor#
- weight: Tensor#
- class TBModel(backbone, readout, loss, backbone_wrapper=None, feature_encoder=None, evaluator=None, optimizer=None, **kwargs)#
Bases:
LightningModuleA LightningModule to define a network.
- Parameters:
- backbonetorch.nn.Module
The backbone model to train.
- readouttorch.nn.Module
The readout class.
- losstorch.nn.Module
The loss class.
- backbone_wrappertorch.nn.Module, optional
The backbone wrapper class (default: None).
- feature_encodertorch.nn.Module, optional
The feature encoder (default: None).
- evaluatorAny, optional
The evaluator class (default: None).
- optimizerAny, optional
The optimizer class (default: None).
- **kwargsAny
Additional keyword arguments.
- __init__(backbone, readout, loss, backbone_wrapper=None, feature_encoder=None, evaluator=None, optimizer=None, **kwargs)#
- configure_optimizers()#
Configure optimizers and learning-rate schedulers.
Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you’d need one. But in the case of GANs or similar you might have multiple.
Examples
https://lightning.ai/docs/pytorch/latest/common/lightning_module.html#configure-optimizers
- Returns:
- dict:
A dict containing the configured optimizers and learning-rate schedulers to be used for training.
- forward(batch)#
Perform a forward pass through the model.
- Parameters:
- batchtorch_geometric.data.Data
Batch object containing the batched data.
- Returns:
- dict
Dictionary containing the model output, which includes the logits and other relevant information.
- log_metrics(mode=None)#
Log metrics.
- Parameters:
- modestr, optional
The mode of the model, either “train”, “val”, or “test” (default: None).
- model_step(batch)#
Perform a single model step on a batch of data.
- Parameters:
- batchtorch_geometric.data.Data
Batch object containing the batched data.
- Returns:
- dict
Dictionary containing the model output and the loss.
- on_test_epoch_end()#
Lightning hook that is called when a test epoch ends.
This hook is used to log the test metrics.
- on_test_epoch_start()#
Lightning hook that is called when a test epoch begins.
This hook is used to reset the test metrics.
- on_train_epoch_end()#
Lightning hook that is called when a train epoch ends.
This hook is used to log the train metrics.
- on_train_epoch_start()#
Lightning hook that is called when a train epoch begins.
This hook is used to reset the train metrics.
- on_val_epoch_start()#
Lightning hook that is called when a validation epoch begins.
This hook is used to reset the validation metrics.
- on_validation_epoch_end()#
Lightning hook that is called when a validation epoch ends.
This hook is used to log the validation metrics.
- on_validation_epoch_start()#
Hook called when a validation epoch begins.
According pytorch lightning documentation this hook is called at the beginning of the validation epoch.
https://lightning.ai/docs/pytorch/stable/common/lightning_module.html#hooks
Note that the validation step is within the train epoch. Hence here we have to log the train metrics before we reset the evaluator to start the validation loop.
- process_outputs(model_out, batch)#
Handle model outputs.
- Parameters:
- model_outdict
Dictionary containing the model output.
- batchtorch_geometric.data.Data
Batch object containing the batched data.
- Returns:
- dict
Dictionary containing the updated model output.
- setup(stage)#
Hook to call torch.compile.
Lightning hook that is 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:
- stagestr
Either “fit”, “validate”, “test”, or “predict”.
- test_step(batch, batch_idx)#
Perform a single test step on a batch of data.
- Parameters:
- batchtorch_geometric.data.Data
Batch object containing the batched data.
- batch_idxint
The index of the current batch.
- training_step(batch, batch_idx)#
Perform a single training step on a batch of data.
- Parameters:
- batchtorch_geometric.data.Data
Batch object containing the batched data.
- batch_idxint
The index of the current batch.
- Returns:
- torch.Tensor
A tensor of losses between model predictions and targets.
- validation_step(batch, batch_idx)#
Perform a single validation step on a batch of data.
- Parameters:
- batchtorch_geometric.data.Data
Batch object containing the batched data.
- batch_idxint
The index of the current batch.