---
title: LightningModule
canonical: >-
  https://lightning.ai/docs/pytorch/stable/optional-api/api/lightning.pytorch.core.LightningModule
---
# LightningModule {#lightningmodule}

### `class lightning.pytorch.core.LightningModule(*args, **kwargs)` {#lightning.pytorch.core.LightningModule}

Bases: `_DeviceDtypeModuleMixin`, [`HyperparametersMixin`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.mixins.HyperparametersMixin.md#lightning.pytorch.core.mixins.HyperparametersMixin "lightning.pytorch.core.mixins.hparams_mixin.HyperparametersMixin"), [`ModelHooks`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.hooks.ModelHooks.md#lightning.pytorch.core.hooks.ModelHooks "lightning.pytorch.core.hooks.ModelHooks"), [`DataHooks`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.hooks.DataHooks.md#lightning.pytorch.core.hooks.DataHooks "lightning.pytorch.core.hooks.DataHooks"), [`CheckpointHooks`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.hooks.CheckpointHooks.md#lightning.pytorch.core.hooks.CheckpointHooks "lightning.pytorch.core.hooks.CheckpointHooks"), [`Module`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "(in PyTorch v2.15)")

#### `all_gather(data, group=None, sync_grads=False)` {#lightning.pytorch.core.LightningModule.all_gather}

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`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)"), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)"), [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\]) – int, float, tensor of shape (batch, …), or a (possibly nested) collection thereof.
    
*   **group** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – the process group to gather results from. Defaults to all processes (world)
    
*   **sync\_grads** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – flag that allows users to synchronize gradients for the all\_gather operation
    

Return type:

`Union`\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)"), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)"), [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\]

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

#### `backward(loss, *args, **kwargs)` {#lightning.pytorch.core.LightningModule.backward}

Called to perform backward on the loss returned in [`training_step()`](#lightning.pytorch.core.LightningModule.training_step "lightning.pytorch.core.LightningModule.training_step"). Override this hook with your own implementation if you need to.

Parameters:

**loss** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – The loss tensor returned by [`training_step()`](#lightning.pytorch.core.LightningModule.training_step "lightning.pytorch.core.LightningModule.training_step"). If gradient accumulation is used, the loss here holds the normalized value (scaled by 1 / accumulation steps).

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

Example:

```python
def backward(self, loss):
    loss.backward()
```

#### `clip_gradients(optimizer, gradient_clip_val=None, gradient_clip_algorithm=None)` {#lightning.pytorch.core.LightningModule.clip_gradients}

Handles gradient clipping internally.

Note

*   Do not override this method. If you want to customize gradient clipping, consider using [`configure_gradient_clipping()`](#lightning.pytorch.core.LightningModule.configure_gradient_clipping "lightning.pytorch.core.LightningModule.configure_gradient_clipping") method.
    
*   For manual optimization (`self.automatic_optimization = False`), if you want to use gradient clipping, consider calling `self.clip_gradients(opt, gradient_clip_val=0.5, gradient_clip_algorithm="norm")` manually in the training step.
    

Parameters:

*   **optimizer** ([`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)")) – Current optimizer being used.
    
*   **gradient\_clip\_val** (`Union`\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – The value at which to clip gradients.
    
*   **gradient\_clip\_algorithm** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – The gradient clipping algorithm to use. Pass `gradient_clip_algorithm="value"` to clip by value, and `gradient_clip_algorithm="norm"` to clip by norm.
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `configure_callbacks()` {#lightning.pytorch.core.LightningModule.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’s `callbacks` 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 sure [`ModelCheckpoint`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.callbacks.ModelCheckpoint.md#lightning.pytorch.callbacks.ModelCheckpoint "lightning.pytorch.callbacks.model_checkpoint.ModelCheckpoint") callbacks run last.

Return type:

`Union`\[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[[`Callback`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.callbacks.Callback.md#lightning.pytorch.callbacks.Callback "lightning.pytorch.callbacks.callback.Callback")\], [`Callback`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.callbacks.Callback.md#lightning.pytorch.callbacks.Callback "lightning.pytorch.callbacks.callback.Callback")\]

Returns:

A callback or a list of callbacks which will extend the list of callbacks in the Trainer.

Example:

```python
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)` {#lightning.pytorch.core.LightningModule.configure_gradient_clipping}

Perform gradient clipping for the optimizer parameters. Called before [`optimizer_step()`](#lightning.pytorch.core.LightningModule.optimizer_step "lightning.pytorch.core.LightningModule.optimizer_step").

Parameters:

*   **optimizer** ([`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)")) – Current optimizer being used.
    
*   **gradient\_clip\_val** (`Union`\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – The value at which to clip gradients. By default, value passed in Trainer will be available here.
    
*   **gradient\_clip\_algorithm** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – The gradient clipping algorithm to use. By default, value passed in Trainer will be available here.
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

Example:

```python
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()` {#lightning.pytorch.core.LightningModule.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.

Return type:

`Union`\[[`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)"), [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[[`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)")\], [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[[`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)")\], [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[`Union`\[[`LRScheduler`](https://docs.pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.LRScheduler.html#torch.optim.lr_scheduler.LRScheduler "(in PyTorch v2.15)"), [`ReduceLROnPlateau`](https://docs.pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.ReduceLROnPlateau.html#torch.optim.lr_scheduler.ReduceLROnPlateau "(in PyTorch v2.15)"), `LRSchedulerConfig`\]\]\], `OptimizerConfig`, `OptimizerLRSchedulerConfig`, [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[`OptimizerConfig`\], [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[`OptimizerLRSchedulerConfig`\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]

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 or `lr_scheduler_config`.
    
*   **None** - Fit will run without any optimizer.
    

The `lr_scheduler_config` is a dictionary which contains the scheduler and its associated configuration. The default configuration is shown below.

```python
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 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 the [`torch.optim.lr_scheduler.ReduceLROnPlateau`](https://docs.pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.ReduceLROnPlateau.html#torch.optim.lr_scheduler.ReduceLROnPlateau "(in PyTorch v2.15)") scheduler, Lightning requires that the `lr_scheduler_config` contains the keyword `"monitor"` set to the metric name that the scheduler should be conditioned on.

```python
# 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 your [`LightningModule`](#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule").

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`](https://docs.pytorch.org/docs/stable/generated/torch.optim.LBFGS.html#torch.optim.LBFGS "(in PyTorch v2.15)"), 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()`](#lightning.pytorch.core.LightningModule.optimizer_step "lightning.pytorch.core.LightningModule.optimizer_step") hook.
    

#### `forward(*args, **kwargs)` {#lightning.pytorch.core.LightningModule.forward}

Same as [`torch.nn.Module.forward()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.forward "(in PyTorch v2.15)").

Parameters:

*   **\*args** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Whatever you decide to pass into the forward method.
    
*   **\*\*kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Keyword arguments are also possible.
    

Return type:

[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")

Returns:

Your model’s output

#### `freeze()` {#lightning.pytorch.core.LightningModule.freeze}

Freeze all params for inference.

Example:

```python
model = MyLightningModule(...)
model.freeze()
```

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `load_from_checkpoint(checkpoint_path, map_location=None, hparams_file=None, strict=None, **kwargs)` {#lightning.pytorch.core.LightningModule.load_from_checkpoint}

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`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`IO`](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.15)")\]) – Path to checkpoint. This can also be a URL, or file-like object
    
*   **map\_location** (`Union`\[[`device`](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "(in PyTorch v2.15)"), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.15)")\[\[[`UntypedStorage`](https://docs.pytorch.org/docs/stable/storage.html#torch.UntypedStorage "(in PyTorch v2.15)"), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\], [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`UntypedStorage`](https://docs.pytorch.org/docs/stable/storage.html#torch.UntypedStorage "(in PyTorch v2.15)")\]\], [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[`Union`\[[`device`](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "(in PyTorch v2.15)"), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\], `Union`\[[`device`](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "(in PyTorch v2.15)"), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – 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()`](https://docs.pytorch.org/docs/stable/generated/torch.load.html#torch.load "(in PyTorch v2.15)").
    
*   **hparams\_file** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) –
    
    Optional path to a `.yaml` or `.csv` file with hierarchical structure as in this example:
    
    ```python
    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 a [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)") and passed into your [`LightningModule`](#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule") for use.
    
    If your model’s `hparams` argument is [`Namespace`](https://docs.python.org/3/library/argparse.html#argparse.Namespace "(in Python v3.15)") and `.yaml` file has hierarchical structure, you need to refactor your model to treat `hparams` as [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)").
    
*   **strict** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – Whether to strictly enforce that the keys in `checkpoint_path` match the keys returned by this module’s state dict. Defaults to `True` unless `LightningModule.strict_loading` is set, in which case it defaults to the value of `LightningModule.strict_loading`.
    
*   **\*\*kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Any extra keyword args needed to init the model. Can also be used to override saved hyperparameter values.
    

Return type:

`Self`

Returns:

[`LightningModule`](#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule") instance with loaded weights and hyperparameters (if available).

Note

`load_from_checkpoint` is a **class** method. You should use your [`LightningModule`](#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule") **class** to call it instead of the [`LightningModule`](#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule") instance, or a `TypeError` will be raised.

Note

To ensure all layers can be loaded from the checkpoint, this function will call [`configure_model()`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.hooks.ModelHooks.md#lightning.pytorch.core.hooks.ModelHooks.configure_model "lightning.pytorch.core.hooks.ModelHooks.configure_model") directly after instantiating the model if this hook is overridden in your LightningModule. However, note that `load_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:

```python
# 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)` {#lightning.pytorch.core.LightningModule.log}

Log a key, value pair.

Example:

```python
self.log('train_loss', loss)
```

The default behavior per hook is documented here: [Automatic Logging](/docs/pytorch/2.5.5/reference/extensions/logging.md#automatic-logging).

Parameters:

*   **name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – key to log. Must be identical across all processes if using DDP or any other distributed strategy.
    
*   **value** (`Union`\[[`Metric`](/docs/torchmetrics/stable/references/metric#torchmetrics.Metric "(in PyTorch-Metrics v1.9.0)"), [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]) – value to log. Can be a `float`, `Tensor`, or a `Metric`.
    
*   **prog\_bar** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – if `True` logs to the progress bar.
    
*   **logger** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – if `True` logs to the logger.
    
*   **on\_step** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – if `True` logs at this step. The default value is determined by the hook. See [Automatic Logging](/docs/pytorch/2.5.5/reference/extensions/logging.md#automatic-logging) for details.
    
*   **on\_epoch** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – if `True` logs epoch accumulated metrics. The default value is determined by the hook. See [Automatic Logging](/docs/pytorch/2.5.5/reference/extensions/logging.md#automatic-logging) for details.
    
*   **reduce\_fx** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.15)")\[\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\], [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]\]) – reduction function over step values for end of epoch. `torch.mean()` by default.
    
*   **enable\_graph** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – if `True`, will not auto detach the graph.
    
*   **sync\_dist** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – if `True`, reduces the metric across devices. Use with care as this may lead to a significant communication overhead.
    
*   **sync\_dist\_group** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – the DDP group to sync across.
    
*   **add\_dataloader\_idx** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – 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** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – 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`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – To restore the metric state, Lightning requires the reference of the [`torchmetrics.Metric`](/docs/torchmetrics/stable/references/metric#torchmetrics.Metric "(in PyTorch-Metrics v1.9.0)") in your model. This is found automatically if it is a model attribute.
    
*   **rank\_zero\_only** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Tells Lightning if you are calling `self.log` from every process (default) or only from rank 0. If `True`, 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](/docs/pytorch/2.5.5/reference/visualize/logging_advanced.md#rank-zero-only) for more details.
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `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)` {#lightning.pytorch.core.LightningModule.log_dict}

Log a dictionary of values at once.

Example:

```python
values = {'loss': loss, 'acc': acc, ..., 'metric_n': metric_n}
self.log_dict(values)
```

Parameters:

*   **dictionary** (`Union`\[[`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), `Union`\[[`Metric`](/docs/torchmetrics/stable/references/metric#torchmetrics.Metric "(in PyTorch-Metrics v1.9.0)"), [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]\], [`MetricCollection`](/docs/torchmetrics/stable/pages/overview#torchmetrics.MetricCollection "(in PyTorch-Metrics v1.9.0)")\]) – 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`, or `MetricCollection`.
    
*   **prog\_bar** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – if `True` logs to the progress base.
    
*   **logger** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – if `True` logs to the logger.
    
*   **on\_step** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – if `True` logs at this step. `None` auto-logs for training\_step but not validation/test\_step. The default value is determined by the hook. See [Automatic Logging](/docs/pytorch/2.5.5/reference/extensions/logging.md#automatic-logging) for details.
    
*   **on\_epoch** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – if `True` logs epoch accumulated metrics. `None` auto-logs for val/test step but not `training_step`. The default value is determined by the hook. See [Automatic Logging](/docs/pytorch/2.5.5/reference/extensions/logging.md#automatic-logging) for details.
    
*   **reduce\_fx** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.15)")\[\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\], [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]\]) – reduction function over step values for end of epoch. `torch.mean()` by default.
    
*   **enable\_graph** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – if `True`, will not auto-detach the graph
    
*   **sync\_dist** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – if `True`, reduces the metric across GPUs/TPUs. Use with care as this may lead to a significant communication overhead.
    
*   **sync\_dist\_group** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – the ddp group to sync across.
    
*   **add\_dataloader\_idx** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – if `True`, appends the index of the current dataloader to the name (when using multiple). If `False`, user needs to give unique names for each dataloader to not mix values.
    
*   **batch\_size** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – 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`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Tells Lightning if you are calling `self.log` from every process (default) or only from rank 0. If `True`, 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](/docs/pytorch/2.5.5/reference/visualize/logging_advanced.md#rank-zero-only) for more details.
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `lr_scheduler_step(scheduler, metric)` {#lightning.pytorch.core.LightningModule.lr_scheduler_step}

Override this method to adjust the default way the [`Trainer`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.trainer.trainer.Trainer.md#lightning.pytorch.trainer.trainer.Trainer "lightning.pytorch.trainer.trainer.Trainer") calls each scheduler. By default, Lightning calls `step()` and as shown in the example for each scheduler based on its `interval`.

Parameters:

*   **scheduler** (`Union`\[[`LRScheduler`](https://docs.pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.LRScheduler.html#torch.optim.lr_scheduler.LRScheduler "(in PyTorch v2.15)"), [`ReduceLROnPlateau`](https://docs.pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.ReduceLROnPlateau.html#torch.optim.lr_scheduler.ReduceLROnPlateau "(in PyTorch v2.15)")\]) – Learning rate scheduler.
    
*   **metric** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – Value of the monitor used for schedulers like `ReduceLROnPlateau`.
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

Examples:

```python
# 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()` {#lightning.pytorch.core.LightningModule.lr_schedulers}

Returns the learning rate scheduler(s) that are being used during training. Useful for manual optimization.

Return type:

`Union`\[[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)"), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[`Union`\[[`LRScheduler`](https://docs.pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.LRScheduler.html#torch.optim.lr_scheduler.LRScheduler "(in PyTorch v2.15)"), [`ReduceLROnPlateau`](https://docs.pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.ReduceLROnPlateau.html#torch.optim.lr_scheduler.ReduceLROnPlateau "(in PyTorch v2.15)")\]\], [`LRScheduler`](https://docs.pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.LRScheduler.html#torch.optim.lr_scheduler.LRScheduler "(in PyTorch v2.15)"), [`ReduceLROnPlateau`](https://docs.pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.ReduceLROnPlateau.html#torch.optim.lr_scheduler.ReduceLROnPlateau "(in PyTorch v2.15)")\]

Returns:

A single scheduler, or a list of schedulers in case multiple ones are present, or `None` if no schedulers were returned in [`configure_optimizers()`](#lightning.pytorch.core.LightningModule.configure_optimizers "lightning.pytorch.core.LightningModule.configure_optimizers").

#### `manual_backward(loss, *args, **kwargs)` {#lightning.pytorch.core.LightningModule.manual_backward}

Call this directly from your [`training_step()`](#lightning.pytorch.core.LightningModule.training_step "lightning.pytorch.core.LightningModule.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](/docs/pytorch/2.5.5/reference/common/optimization.md#id2) for more examples.

Example:

```python
def training_step(...):
    opt = self.optimizers()
    loss = ...
    opt.zero_grad()
    # automatically applies scaling, etc...
    self.manual_backward(loss)
    opt.step()
```

Parameters:

*   **loss** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – The tensor on which to compute gradients. Must have a graph attached.
    
*   **\*args** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Additional positional arguments to be forwarded to [`backward()`](https://docs.pytorch.org/docs/stable/generated/torch.Tensor.backward.html#torch.Tensor.backward "(in PyTorch v2.15)")
    
*   **\*\*kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Additional keyword arguments to be forwarded to [`backward()`](https://docs.pytorch.org/docs/stable/generated/torch.Tensor.backward.html#torch.Tensor.backward "(in PyTorch v2.15)")
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `optimizer_step(epoch, batch_idx, optimizer, optimizer_closure=None)` {#lightning.pytorch.core.LightningModule.optimizer_step}

Override this method to adjust the default way the [`Trainer`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.trainer.trainer.Trainer.md#lightning.pytorch.trainer.trainer.Trainer "lightning.pytorch.trainer.trainer.Trainer") calls the optimizer.

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

Parameters:

*   **epoch** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – Current epoch
    
*   **batch\_idx** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – Index of current batch
    
*   **optimizer** (`Union`\[[`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)"), [`LightningOptimizer`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.optimizer.LightningOptimizer.md#lightning.pytorch.core.optimizer.LightningOptimizer "lightning.pytorch.core.optimizer.LightningOptimizer")\]) – A PyTorch optimizer
    
*   **optimizer\_closure** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.15)")\[\[\], [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]\]) – The optimizer closure. This closure must be executed as it includes the calls to `training_step()`, `optimizer.zero_grad()`, and `backward()`.
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

Examples:

```python
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)` {#lightning.pytorch.core.LightningModule.optimizer_zero_grad}

Override this method to change the default behaviour of `optimizer.zero_grad()`.

Parameters:

*   **epoch** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – Current epoch
    
*   **batch\_idx** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – Index of current batch
    
*   **optimizer** ([`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)")) – A PyTorch optimizer
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

Examples:

```python
# 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()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html#torch.optim.Optimizer.zero_grad "(in PyTorch v2.15)") for the explanation of the above example.

#### `optimizers(use_pl_optimizer=True)` {#lightning.pytorch.core.LightningModule.optimizers}

Returns the optimizer(s) that are being used during training. Useful for manual optimization.

Parameters:

**use\_pl\_optimizer** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – If `True`, will wrap the optimizer(s) in a [`LightningOptimizer`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.optimizer.LightningOptimizer.md#lightning.pytorch.core.optimizer.LightningOptimizer "lightning.pytorch.core.optimizer.LightningOptimizer") for automatic handling of precision, profiling, and counting of step calls for proper logging and checkpointing. It specifically wraps the `step` method and custom optimizers that don’t have this method are not supported.

Return type:

`Union`\[[`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)"), [`LightningOptimizer`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.optimizer.LightningOptimizer.md#lightning.pytorch.core.optimizer.LightningOptimizer "lightning.pytorch.core.optimizer.LightningOptimizer"), `_FabricOptimizer`, [`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)")\], [`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`LightningOptimizer`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.optimizer.LightningOptimizer.md#lightning.pytorch.core.optimizer.LightningOptimizer "lightning.pytorch.core.optimizer.LightningOptimizer")\], [`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[`_FabricOptimizer`\]\]

Returns:

A single optimizer, or a list of optimizers in case multiple ones are present.

#### `predict_step(*args, **kwargs)` {#lightning.pytorch.core.LightningModule.predict_step}

Step function called during [`predict()`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.trainer.trainer.Trainer.md#lightning.pytorch.trainer.trainer.Trainer.predict "lightning.pytorch.trainer.trainer.Trainer.predict"). By default, it calls [`forward()`](#lightning.pytorch.core.LightningModule.forward "lightning.pytorch.core.LightningModule.forward"). Override to add any processing logic.

The [`predict_step()`](#lightning.pytorch.core.LightningModule.predict_step "lightning.pytorch.core.LightningModule.predict_step") is used to scale inference on multi-devices.

To prevent an OOM error, it is possible to use [`BasePredictionWriter`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.callbacks.BasePredictionWriter.md#lightning.pytorch.callbacks.BasePredictionWriter "lightning.pytorch.callbacks.BasePredictionWriter") callback to write the predictions to disk or database after each batch or on epoch end.

The [`BasePredictionWriter`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.callbacks.BasePredictionWriter.md#lightning.pytorch.callbacks.BasePredictionWriter "lightning.pytorch.callbacks.BasePredictionWriter") should be used while using a spawn based accelerator. This happens for `Trainer(strategy="ddp_spawn")` or training on 8 TPU cores with `Trainer(accelerator="tpu", devices=8)` as predictions won’t be returned.

Parameters:

*   **batch** – The output of your data iterable, normally a [`DataLoader`](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader "(in PyTorch v2.15)").
    
*   **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:

[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")

Returns:

Predicted output (optional).

Example

```python
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)` {#lightning.pytorch.core.LightningModule.print}

Prints only from process 0. Use this in any distributed mode to log only once.

Parameters:

*   **\*args** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – The thing to print. The same as for Python’s built-in print function.
    
*   **\*\*kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – The same as for Python’s built-in print function.
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

Example:

```python
def forward(self, x):
    self.print(x, 'in forward')
```

#### `test_step(*args, **kwargs)` {#lightning.pytorch.core.LightningModule.test_step}

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`](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader "(in PyTorch v2.15)").
    
*   **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`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]

Returns:

*   [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)") - The loss tensor
    
*   `dict` - A dictionary. Can include any keys, but must include the key `'loss'`.
    
*   `None` - Skip to the next batch.
    

```python
# 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:

```python
# 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()`](#lightning.pytorch.core.LightningModule.test_step "lightning.pytorch.core.LightningModule.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.

```python
# CASE 2: multiple test dataloaders
def test_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    x, y = batch

    # implement your own
    out = self(x)

    if dataloader_idx == 0:
        loss = self.loss0(out, y)
    else:
        loss = self.loss1(out, y)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs separately for each dataloader
    self.log_dict({f"test_loss_{dataloader_idx}": loss, f"test_acc_{dataloader_idx}": acc})
```

Note

If you don’t need to test you don’t need to implement this method.

Note

When the [`test_step()`](#lightning.pytorch.core.LightningModule.test_step "lightning.pytorch.core.LightningModule.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=None, input_sample=None, **kwargs)` {#lightning.pytorch.core.LightningModule.to_onnx}

Saves the model in ONNX format.

Parameters:

*   **file\_path** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – The path of the file the onnx model should be saved to. Default: None (no file saved).
    
*   **input\_sample** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – An input for tracing. Default: None (Use self.example\_input\_array)
    
*   **\*\*kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Will be passed to torch.onnx.export function.
    

Return type:

[`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`ONNXProgram`](https://docs.pytorch.org/docs/stable/onnx_export.html#torch.onnx.ONNXProgram "(in PyTorch v2.15)")\]

Example:

```python
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)` {#lightning.pytorch.core.LightningModule.to_torchscript}

By default compiles the whole model to a `ScriptModule`. If you want to use tracing, please provided the argument `method='trace'` and make sure that either the example\_inputs argument is provided, or the model has [`example_input_array`](#lightning.pytorch.core.LightningModule.example_input_array "lightning.pytorch.core.LightningModule.example_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`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Path where to save the torchscript. Default: None (no file saved).
    
*   **method** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – Whether to use TorchScript’s script or trace method. Default: ‘script’
    
*   **example\_inputs** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – An input to be used to do tracing when method is set to ‘trace’. Default: None (uses [`example_input_array`](#lightning.pytorch.core.LightningModule.example_input_array "lightning.pytorch.core.LightningModule.example_input_array"))
    
*   **\*\*kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Additional arguments that will be passed to the `torch.jit.script()` or `torch.jit.trace()` function.
    

Note

*   Requires the implementation of the [`forward()`](#lightning.pytorch.core.LightningModule.forward "lightning.pytorch.core.LightningModule.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:

```python
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`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), `ScriptModule`\]\]

Returns:

This LightningModule as a torchscript, regardless of whether file\_path is defined or not.

#### `toggle_optimizer(optimizer)` {#lightning.pytorch.core.LightningModule.toggle_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()`](#lightning.pytorch.core.LightningModule.untoggle_optimizer "lightning.pytorch.core.LightningModule.untoggle_optimizer") to make sure `param_requires_grad_state` is properly reset.

Parameters:

**optimizer** (`Union`\[[`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)"), [`LightningOptimizer`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.optimizer.LightningOptimizer.md#lightning.pytorch.core.optimizer.LightningOptimizer "lightning.pytorch.core.optimizer.LightningOptimizer")\]) – The optimizer to toggle.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `toggled_optimizer(optimizer)` {#lightning.pytorch.core.LightningModule.toggled_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. Combines [`toggle_optimizer()`](#lightning.pytorch.core.LightningModule.toggle_optimizer "lightning.pytorch.core.LightningModule.toggle_optimizer") and [`untoggle_optimizer()`](#lightning.pytorch.core.LightningModule.untoggle_optimizer "lightning.pytorch.core.LightningModule.untoggle_optimizer") into context manager.

Parameters:

**optimizer** (`Union`\[[`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)"), [`LightningOptimizer`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.optimizer.LightningOptimizer.md#lightning.pytorch.core.optimizer.LightningOptimizer "lightning.pytorch.core.optimizer.LightningOptimizer")\]) – The optimizer to toggle.

Return type:

[`Generator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator "(in Python v3.15)")

Example:

```python
def training_step(...):
    opt = self.optimizers()
    with self.toggled_optimizer(opt):
        loss = ...
        opt.zero_grad()
        self.manual_backward(loss)
        opt.step()
```

#### `training_step(*args, **kwargs)` {#lightning.pytorch.core.LightningModule.training_step}

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`](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader "(in PyTorch v2.15)").
    
*   **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`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]

Returns:

*   [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)") - The loss tensor
    
*   `dict` - 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.
    

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:

```python
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:

```python
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 by `accumulate_grad_batches` internally.

#### `unfreeze()` {#lightning.pytorch.core.LightningModule.unfreeze}

Unfreeze all parameters for training.

```python
model = MyLightningModule(...)
model.unfreeze()
```

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `untoggle_optimizer(optimizer)` {#lightning.pytorch.core.LightningModule.untoggle_optimizer}

Resets the state of required gradients that were toggled with [`toggle_optimizer()`](#lightning.pytorch.core.LightningModule.toggle_optimizer "lightning.pytorch.core.LightningModule.toggle_optimizer").

Parameters:

**optimizer** (`Union`\[[`Optimizer`](https://docs.pytorch.org/docs/stable/optim.html#torch.optim.Optimizer "(in PyTorch v2.15)"), [`LightningOptimizer`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.optimizer.LightningOptimizer.md#lightning.pytorch.core.optimizer.LightningOptimizer "lightning.pytorch.core.optimizer.LightningOptimizer")\]) – The optimizer to untoggle.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `validation_step(*args, **kwargs)` {#lightning.pytorch.core.LightningModule.validation_step}

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`](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader "(in PyTorch v2.15)").
    
*   **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`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]

Returns:

*   [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)") - The loss tensor
    
*   `dict` - A dictionary. Can include any keys, but must include the key `'loss'`.
    
*   `None` - Skip to the next batch.
    

```python
# 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:

```python
# 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()`](#lightning.pytorch.core.LightningModule.validation_step "lightning.pytorch.core.LightningModule.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.

```python
# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    x, y = batch

    # implement your own
    out = self(x)

    if dataloader_idx == 0:
        loss = self.loss0(out, y)
    else:
        loss = self.loss1(out, y)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs separately for each dataloader
    self.log_dict({f"val_loss_{dataloader_idx}": loss, f"val_acc_{dataloader_idx}": acc})
```

Note

If you don’t need to validate you don’t need to implement this method.

Note

When the [`validation_step()`](#lightning.pytorch.core.LightningModule.validation_step "lightning.pytorch.core.LightningModule.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.

#### `property automatic_optimization: bool` {#lightning.pytorch.core.LightningModule.automatic_optimization}

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

#### `property current_epoch: int` {#lightning.pytorch.core.LightningModule.current_epoch}

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

#### `property device_mesh: Optional[DeviceMesh]` {#lightning.pytorch.core.LightningModule.device_mesh}

Strategies like `ModelParallelStrategy` will create a device mesh that can be accessed in the [`configure_model()`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.hooks.ModelHooks.md#lightning.pytorch.core.hooks.ModelHooks.configure_model "lightning.pytorch.core.hooks.ModelHooks.configure_model") hook to parallelize the LightningModule.

#### `property example_input_array: Optional[Union[Tensor, tuple, dict]]` {#lightning.pytorch.core.LightningModule.example_input_array}

The example input array is a specification of what the module can consume in the [`forward()`](#lightning.pytorch.core.LightningModule.forward "lightning.pytorch.core.LightningModule.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_rank: int` {#lightning.pytorch.core.LightningModule.global_rank}

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

#### `property global_step: int` {#lightning.pytorch.core.LightningModule.global_step}

Total training batches seen across all epochs.

If no Trainer is attached, this property is 0.

#### `property local_rank: int` {#lightning.pytorch.core.LightningModule.local_rank}

The index of the current process within a single node.

#### `property logger: Optional[Union[Logger, Logger]]` {#lightning.pytorch.core.LightningModule.logger}

Reference to the logger object in the Trainer.

#### `property loggers: Union[list[lightning.pytorch.loggers.logger.Logger], list[lightning.fabric.loggers.logger.Logger]]` {#lightning.pytorch.core.LightningModule.loggers}

Reference to the list of loggers in the Trainer.

#### `property on_gpu: bool` {#lightning.pytorch.core.LightningModule.on_gpu}

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

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

#### `property strict_loading: bool` {#lightning.pytorch.core.LightningModule.strict_loading}

Determines how Lightning loads this model using .load\_state\_dict(…, strict=model.strict\_loading).

---

**Navigation**

- Parent: [Api](/docs/pytorch/2.5.5/optional-api/api.md)
