PyTorch Lighting : compilation des questions fréquemment posées

0 Version du système

PyTorch Lighting 1.1.7

1 Erreur : object has no attribute ‘_metrics_to_agg’

Si l’erreur ci-dessus survient lorsque vous utilisez un Logger personnalisé, vous avez probablement oublié d’appeler super().__init__() dans votre fonction __init__. Voici comment définir correctement la fonction d’initialisation :

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 Erreur : RuntimeError: grad can be implicitly created only for scalar outputs

En mode DataParallel, chaque train_step renvoie sa propre valeur de Loss. Avec un seul GPU, on obtient un scalaire, mais avec plusieurs GPU, on obtient un Tensor vectoriel. Or, Loss doit être un scalaire.
Pour résoudre ce problème, vous pouvez ajouter la fonction training_step_end ci-dessous, qui calcule la moyenne de 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()}

Notez que la fonction ci-dessus suppose que train_step renvoie une valeur au format indiqué ci-dessous. Si ce n’est pas le cas, adaptez-la en conséquence.

return {'loss': loss}

Par défaut, PyTorch Lightning s’attend à ce que Loss soit renvoyée directement ou dans un Dict sous la forme {‘loss’: loss}. D’autres formats peuvent nécessiter des modifications supplémentaires.

3 Problème : sécurité des threads pour training_step, validation_step et test_step en entraînement distribué

Dans certains exemples de PyTorch Lightning, des graphiques sont tracés avec matplotlib dans training_step. Cela ne pose aucun problème avec un seul thread. En revanche, dans des modes multithreads comme dp ou ddp, training_step, validation_step et test_step s’exécutent en parallèle. Comme matplotlib n’est pas thread-safe, cela peut entraîner des interblocages ou des plantages.
Si vous utilisez l’entraînement distribué, assurez-vous donc que le code de ces fonctions est thread-safe.

Pour mieux comprendre ce problème, consultez la documentation officielle :
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html#methods

Avec un seul thread, l’entraînement se déroule à peu près comme suit :

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)

En mode distribué, l’entraînement se déroule à peu près comme suit :

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)

Une solution consiste à protéger cette partie du code à l’aide d’un verrou. Par exemple :
Dans la fonction __init__ de LightningModule, ajoutez :

self.mutex = threading.Lock()

Puis utilisez ce verrou dans les parties du code qui ne sont pas thread-safe, dans train_step ou dans d’autres fonctions :

        with self.mutex:

            # Your drawing code here

4 Astuce : utiliser le décorateur @rank_zero_only pour les fonctions à appeler uniquement sur RANK=0 en mode multithread

En entraînement distribué, si certaines opérations de journalisation ou de test ne doivent s’exécuter que sur RANK=0, vous pouvez regrouper le code correspondant dans une fonction et lui appliquer le décorateur @rank_zero_only, par exemple :

    @rank_zero_only
    def do_evaluate_matches(self):

N’oubliez pas l’import suivant :

from pytorch_lightning.utilities import rank_zero_only

5 Erreur : AttributeError: Missing attribute « training_step_output_for_epoch_end »

En mode d’entraînement distribué, par exemple avec DDP, l’erreur suivante peut se produire si le batch courant renvoie 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"

À la lecture du code, il semble qu’une erreur de logique puisse se produire lorsque batch=None. Dans le fichier 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,
            )

Et dans la fonction run_training_batch :

    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)

Autrement dit, lorsque batch == None, la fonction renvoie un batch_output avec signal=0. Or, cet objet ne possède pas l’attribut batch_output.training_step_output_for_epoch_end, d’où l’erreur.

On ne sait pas encore dans quelle version ce problème sera résolu. En attendant, vous pouvez éviter de renvoyer un batch égal à None et renvoyer plutôt une valeur comme celle-ci :

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

Ajoutez ensuite le traitement suivant dans 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 Utiliser ReduceLROnPlateau

Avec le réglage par défaut de PyTorch Lightning, automatic_optimization = True, procédez comme suit :

    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}

Contrairement à d’autres, ReduceLROnPlateau exige que le paramètre monitor soit renseigné. Sinon, l’erreur suivante se produit :
`configure_optimizers` must include a monitor when a `ReduceLROnPlateau` scheduler is used.

7 Contrôler manuellement les étapes d’optimisation avec Manual Optimization

Si vous avez besoin d’un contrôle plus fin, vous pouvez désactiver la fonctionnalité automatic_optimization de PyTorch Lightning (en la réglant sur False) et effectuer l’optimisation manuellement, comme dans les exemples suivants :
Exemple avec 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()

Exemple avec 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()

Références :
[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 Suivre l’évolution du learning rate avec LearningRateMonitor

Pour suivre l’évolution du learning rate, passez LearningRateMonitor au trainer en tant que callback, comme dans l’exemple de code ci-dessous :

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

Vous pouvez récupérer le learning rate dans Logger::log_metrics(self, metrics, step). La métrique porte généralement un nom comme lrAdam :

        for key in metrics:

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

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

9 Récupérer les valeurs courantes d’epoch et de step dans LightningModule

Récupérer la valeur courante d’epoch :

curr_epoch = self.current_epoch

Récupérer la valeur courante de step :

curr_step = self.global_step

Add a Comment

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *