PyTorch Lighting FAQ

0 System Version

PyTorch Lighting 1.1.7

1 Error: object has no attribute ‘_metrics_to_agg’

If you encounter the error above when using a custom Logger, a likely cause is that you forgot to call super().__init__() in your custom __init__ method. Here’s how to initialize it correctly:

class MyLogger(LightningLoggerBase):

    def __init__(self, a):
        # Don't forget to call this
        super().__init__()

        self.a = a

    @property
    def name(self):
        return 'MyLogger'

    @property
    @rank_zero_experiment
    def experiment(self):
        # Return the experiment object associated with this logger.
        pass

    @property
    def version(self):
        # Return the experiment version, int or str.
        return '0.1'

    @rank_zero_only
    def log_hyperparams(self, params):
        # params is an argparse.Namespace
        # your code to record hyperparameters goes here
        pass

    @rank_zero_only
    def log_metrics(self, metrics, step):
        # metrics is a dictionary of metric names and values
        # your code to record metrics goes here
        pass

    @rank_zero_only
    def save(self):
        # Optional. Any code necessary to save logger data goes here
        # If you implement this, remember to call `super().save()`
        # at the start of the method (important for aggregation of metrics)
        super().save()

    @rank_zero_only
    def finalize(self, status):
        # Optional. Any code that needs to be run after training
        # finishes goes here
        pass

2 Error: RuntimeError: grad can be implicitly created only for scalar outputs

In DataParallel mode, each train_step returns its own loss. With a single GPU, the result is a scalar. With multiple GPUs, the results form a Tensor vector, but the loss must be a scalar.
To fix this, add the following training_step_end method to compute the mean loss:

    def training_step_end(self, outputs):

        if outputs is None:
            return None
        if outputs['loss'] is None:
            return None

        return {'epoch': self.current_epoch,
                'loss': outputs['loss'].mean()}

Note that the method above assumes train_step returns output in the format shown below. If your output differs, adjust the method accordingly.

return {'loss': loss}

By default, PyTorch Lightning accepts either the loss returned directly or a Dict containing {‘loss’: loss}. Other formats may require additional changes.

3 Issue: Thread Safety of training_step, validation_step, and test_step in Distributed Training

Some PyTorch Lightning examples use matplotlib to create plots inside training_step. This works fine in a single thread, but in parallel modes such as dp and ddp, training_step, validation_step, and test_step run in parallel. Since matplotlib is not thread-safe, this can lead to deadlocks or crashes.
If you use distributed training, make sure the code in these methods is thread-safe.

See the official documentation for more on how this works:
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html#methods

For single-threaded training, the flow looks like this:

outs = []
for batch in train_dataloader:
    # forward
    out = training_step(val_batch)

    # backward
    loss.backward()

    # apply and clear grads
    optimizer.step()
    optimizer.zero_grad()

training_epoch_end(outs)

For distributed training, the flow looks like this:

outs = []
for train_batch in train_dataloader:
    batches = split_batch(train_batch)
    dp_outs = []
    for sub_batch in batches:
        # 1
        dp_out = training_step(sub_batch)
        dp_outs.append(dp_out)

    # 2
    out = training_step_end(dp_outs)
    outs.append(out)

# do something with the outputs for all batches
# 3
training_epoch_end(outs)

One way to address this is to use a thread lock around the affected code. For example:
Add the following to the LightningModule’s __init__ method:

self.mutex = threading.Lock()

Then use the lock around code that isn’t thread-safe in train_step and similar methods:

        with self.mutex:

            # Your drawing code here

4 Tip: Use @rank_zero_only for Functions That Should Run Only on RANK=0

In distributed training, if certain logging or testing code should run only on RANK=0, put that code in a function and decorate it with @rank_zero_only. For example:

    @rank_zero_only
    def do_evaluate_matches(self):

Make sure to include the following import:

from pytorch_lightning.utilities import rank_zero_only

5 Error: AttributeError: Missing attribute “training_step_output_for_epoch_end”

When using a distributed training mode such as DDP, you may see the following error if the current batch is None:

Traceback (most recent call last):
  File "/home/liuxiao/anaconda3/envs/pytorch_env/lib/python3.7/site-packages/pytorch_lightning/utilities/parsing.py", line 183, in __getattr__
    return self[key]
KeyError: 'training_step_output_for_epoch_end'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/data/Develop/SuperGlue/train_pl.py", line 165, in 
    main()
  File "/data/Develop/SuperGlue/train_pl.py", line 161, in main
    trainer.fit(superglue_model, match_datamodule)
  File "/home/liuxiao/anaconda3/envs/pytorch_env/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 472, in fit
    results = self.accelerator_backend.train()
  File "/home/liuxiao/anaconda3/envs/pytorch_env/lib/python3.7/site-packages/pytorch_lightning/accelerators/ddp_accelerator.py", line 152, in train
    results = self.ddp_train(process_idx=self.task_idx, model=model)
  File "/home/liuxiao/anaconda3/envs/pytorch_env/lib/python3.7/site-packages/pytorch_lightning/accelerators/ddp_accelerator.py", line 307, in ddp_train
    results = self.train_or_test()
  File "/home/liuxiao/anaconda3/envs/pytorch_env/lib/python3.7/site-packages/pytorch_lightning/accelerators/accelerator.py", line 69, in train_or_test
    results = self.trainer.train()
  File "/home/liuxiao/anaconda3/envs/pytorch_env/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 523, in train
    self.train_loop.run_training_epoch()
  File "/home/liuxiao/anaconda3/envs/pytorch_env/lib/python3.7/site-packages/pytorch_lightning/trainer/training_loop.py", line 582, in run_training_epoch
    batch_output.training_step_output_for_epoch_end,
  File "/home/liuxiao/anaconda3/envs/pytorch_env/lib/python3.7/site-packages/pytorch_lightning/utilities/parsing.py", line 185, in __getattr__
    raise AttributeError(f'Missing attribute "{key}"') from exp
AttributeError: Missing attribute "training_step_output_for_epoch_end"

Looking at the source code, there may be a logic error when batch=None. In trainer/training_loop.py:

            # ------------------------------------
            # TRAINING_STEP + TRAINING_STEP_END
            # ------------------------------------
            with self.trainer.profiler.profile("run_training_batch"):
                batch_output = self.run_training_batch(batch, batch_idx, dataloader_idx)

            # when returning -1 from train_step, we end epoch early
            if batch_output.signal == -1:
                break

            # only track outputs when user implements training_epoch_end
            # otherwise we will build up unnecessary memory
            epoch_end_outputs = self.process_train_step_outputs(
                batch_output.training_step_output_for_epoch_end,
                self.early_stopping_accumulator,
                self.checkpoint_accumulator,
            )

And in the run_training_batch function:

    def run_training_batch(self, batch, batch_idx, dataloader_idx):
        # track grad norms
        grad_norm_dic = {}

        # bookkeeping
        using_results_obj = False
        self.trainer.hiddens = None

        # track all outputs across time and num of optimizers
        batch_outputs = [[] for _ in range(len(self.get_optimizers_iterable()))]

        if batch is None:
            return AttributeDict(signal=0, grad_norm_dic=grad_norm_dic)

        # hook
        response = self.trainer.call_hook("on_batch_start")
        if response == -1:
            return AttributeDict(signal=-1, grad_norm_dic=grad_norm_dic)

In other words, when batch == None, the function returns a batch_output with signal=0. That object has no batch_output.training_step_output_for_epoch_end attribute, which causes the error.

It’s not yet clear which version will fix this. As a workaround, avoid returning None for the batch and return something like this instead:

    if len(batch) == 0:
        return {
            'valid_batch': False
        }

Then add the following handling to training_step:

    def training_step(self, data, batch_idx):
        if data is None:
            return None
        if data['valid_batch'] == False:
            # pbar.update(batch_size)
            # print('data = {}'.format(data))
            return None

6 How to Use ReduceLROnPlateau

With PyTorch Lightning’s default setting of automatic_optimization = True, configure it as follows:

    def configure_optimizers(self):
        optimizer = torch.optim.Adam(self.parameters(), lr=self.learning_rate)
        lr_scheduler = {'scheduler': torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=5), 'monitor': 'val_loss'}
        return {'optimizer': optimizer,
                'lr_scheduler': lr_scheduler}

Unlike other schedulers, ReduceLROnPlateau requires the monitor parameter. If you don’t set it, you’ll get the following error:
`configure_optimizers` must include a monitor when a `ReduceLROnPlateau` scheduler is used.

7 Controlling Optimization Steps with Manual Optimization

If you need finer control, disable PyTorch Lightning’s automatic_optimization by setting it to False. You can then manage optimization manually as shown below.
For example, using Optimizer:

from pytorch_lightning import LightningModule

class MyModel(LightningModule):

    def __init__(self):
        super().__init__()
        # Important: This property activates manual optimization.
        self.automatic_optimization = False

    def training_step(batch, batch_idx):
        opt = self.optimizers()
        opt.zero_grad()
        loss = self.compute_loss(batch)
        self.manual_backward(loss)
        opt.step()

Or using lr_scheduler:

# step every batch
def __init__(self):
    super().__init__()
    self.automatic_optimization = False

def training_step(self, batch, batch_idx):
    # do forward, backward, and optimization
    ...

    # single scheduler
    sch = self.lr_schedulers()
    sch.step()

    # multiple schedulers
    sch1, sch2 = self.lr_schedulers()
    sch1.step()
    sch2.step()

References:
[1] https://pytorch-lightning.readthedocs.io/en/latest/common/optimizers.html#manual-optimization
[2] https://pytorch.org/docs/stable/optim.html#torch.optim.lr_scheduler.ReduceLROnPlateau
[3] https://pytorch-lightning.readthedocs.io/en/latest/common/optimizers.html#learning-rate-scheduling-manual

8 Using LearningRateMonitor to track changes in the learning rate

To track changes in the learning rate, pass LearningRateMonitor to the trainer as a callback, as shown in the example below:

import pytorch_lightning as pl
from pytorch_lightning.callbacks import LearningRateMonitor

lr_monitor = LearningRateMonitor(logging_interval='step')

trainer = pl.Trainer(gpus=ngpus_per_node,
                         callbacks=[..., lr_monitor],
                         ...)

You can retrieve the learning rate in Logger::log_metrics(self, metrics, step). The metric typically has a name like lrAdam:

        for key in metrics:

            # Log Learning Rate
            if re.search('lr', key) is not None:
                lr = metrics[key]

References:
[1] https://pytorch-lightning.readthedocs.io/en/stable/extensions/generated/pytorch_lightning.callbacks.LearningRateMonitor.html?highlight=LearningRateMonitor

9 Getting the current epoch and step in LightningModule

Get the current epoch:

curr_epoch = self.current_epoch

Get the current step:

curr_step = self.global_step

Add a Comment

Your email address will not be published. Required fields are marked *