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 模式時,每個 train_step 都會各自回傳 Loss。使用單個 GPU 時,回傳的是純量;使用多個 GPU 時,回傳的則是 Tensor 向量,但 Loss 必須是純量。
要解決這個問題,可以加入下列 training_step_end 函式,對 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()}

請注意,上述函式假設 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],
                         ...)

可以在 Logger::log_metrics(self, metrics, step) 中取得 learning rate,這項指標的名稱通常類似 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

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *