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
pass2 오류: 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)한 가지 해결 방법은 해당 코드에 스레드 잠금(lock)을 사용하는 것입니다. 예를 들면 다음과 같습니다.
LightningModule의 __init__ 함수에 다음을 추가합니다.
self.mutex = threading.Lock()
train_step 등의 함수에서 스레드 안전하지 않은 코드에는 다음과 같이 사용합니다.
with self.mutex:
# Your drawing code here4 팁: 멀티스레드 환경에서 RANK=0에서만 호출할 함수에 @rank_zero_only 적용하기
분산 학습에서 일부 로깅이나 테스트 작업을 RANK=0에서만 실행해야 한다면, 관련 코드를 하나의 함수에 넣고 아래와 같이 @rank_zero_only 데코레이터를 적용할 수 있습니다.
@rank_zero_only
def do_evaluate_matches(self):다음과 같이 import해야 합니다.
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 속성이 없어 오류가 발생합니다.
현재로서는 어느 버전에서 이 문제가 해결될지 알 수 없습니다. 임시 해결책으로는 batch를 None으로 반환하지 않고 다음과 같은 값을 반환하는 방법이 있습니다.
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 None6 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 변화를 모니터링하려면 아래 예제 코드처럼 LearningRateMonitor를 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]9 LightningModule에서 현재 epoch와 step 가져오기
현재 epoch 가져오기:
curr_epoch = self.current_epoch
현재 step 가져오기:
curr_step = self.global_step