PyTorch Lightingのよくある質問まとめ

0 システムバージョン

PyTorch Lighting 1.1.7

1 エラー:object has no attribute ‘_metrics_to_agg’

カスタム Logger を使用している際に上記のエラーが発生した場合、考えられる原因の一つは、カスタム __init__ 関数内で super().__init__() の呼び出しを忘れていることです。正しいカスタム初期化関数の使用方法は次のとおりです。

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

DataParallel モードを使用する場合、Loss は各 train_step から個別に返されます。単一の GPU ではスカラーが返されますが、複数の GPU では Tensor ベクトルが返されるため、Loss が要求するスカラー条件を満たさなくなります。
この問題は、次のような training_step_end 関数を追加して loss の mean を求めることで解決できます。

    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()}

上記の関数は、デフォルトで train_step が次の形式を返すことを前提としている点に注意してください。異なる場合は、適宜修正してください。

return {'loss': loss}

また、PyTorch Lightning はデフォルトで、直接返された Loss、または Dict 内で {‘loss’: loss} として返された値を受け取ります。それ以外の形式の場合は、さらに修正が必要になる可能性があります。

3 問題:分散トレーニングにおける training_step、validation_step、test_step のスレッドセーフ性

PyTorch Lightning のいくつかの例では、training_step 内で matplotlib による描画処理を行っている場合があります。これはシングルスレッドでは問題ありませんが、dp、ddp などのマルチスレッドモードを使用する場合、training_step、validation_step、test_step は実際には並列実行されます。一方、matplotlib はスレッドセーフではないため、デッドロックやクラッシュなどの問題が発生します。
したがって、分散トレーニングを使用する場合は、これらの関数内のコードがすべてスレッドセーフであることを必ず確認してください。

公式ドキュメントを参照すると、この問題をよりよく理解できます。
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html#methods

シングルスレッドでのトレーニングの流れは次のようになります。

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)

分散トレーニングでの流れは次のようになります。

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)

この部分のコードにスレッドロックを使用する方法が考えられます。例えば、LightningModule の __init__ 関数に次のように追加します。

self.mutex = threading.Lock()

train_step などのスレッドセーフではないコード内で次のように使用します。

        with self.mutex:

            # Your drawing code here

4 ヒント:@rank_zero_only を使用して、マルチスレッド中に RANK=0 でのみ呼び出される関数を修飾する

分散トレーニングで、ログ出力やテスト処理など、RANK=0 でのみ呼び出すべき処理がある場合は、関連するコードを一つの関数にまとめ、その関数を @rank_zero_only で修飾する方法を検討できます。例えば、次のとおりです。

    @rank_zero_only
    def do_evaluate_matches(self):

ヘッダーファイルをインポートする必要がある点に注意してください。

from pytorch_lightning.utilities import rank_zero_only

5 エラー:AttributeError: Missing attribute “training_step_output_for_epoch_end”

DDP などの分散トレーニングモードを使用している場合、現在の batch が 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"

コードを確認すると、batch=None の場合に論理エラーが発生している可能性があります。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,
            )

一方、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)

つまり、batch == None の場合、signal=0 の batch_output が返されますが、これは batch_output.training_step_output_for_epoch_end 属性を持たないため、エラーが発生します。

この問題がどのバージョンで解決されるのかは現時点では不明です。暫定的な対処方法として、None の batch を返さず、次のような値を返すことができます。

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

そのうえで、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 ReduceLROnPlateau の使用方法

PyTorch Lightning のデフォルトの automatic_optimization = True を使用する場合は、次のように設定する必要があります。

    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}

他のものとは少し異なり、ReduceLROnPlateau では monitor パラメータを設定する必要があります。設定しない場合、次のようなエラーが発生します。
`configure_optimizers` must include a monitor when a `ReduceLROnPlateau` scheduler is used.

7 Manual Optimization 方式による最適化ステップの手動制御

より細かい制御が必要な場合は、PyTorch Lightning の automatic_optimization 機能を有効にせず(False に設定し)、次のような方法で手動最適化を行うことができます。
例えば、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()

例えば、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()

参考:
[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 LearningRateMonitor で learning rate の変化を監視する

LearningRateMonitor で learning rate の変化を監視するには、以下のコード例のように callback として trainer に渡します。

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

learning rate は Logger::log_metrics(self, metrics, step) 内で取得できます。通常、lrAdam などの名前で記録されます。

        for key in metrics:

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

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

9 LightningModule で現在の epoch と step を取得する

現在の epoch を取得する:

curr_epoch = self.current_epoch

現在の step を取得する:

curr_step = self.global_step

Add a Comment

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です