ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1, 512, 1, 1])

SSW·2024년 4월 19일
0

Trouble Shooting

목록 보기
8/9

Situation

Training 과정에서 'RuntimeError: CUDA error: out of memory' 문제를 해결하기 위해 6으로 설정했던 Batch Size를 1로 변경 후 아래의 error 발생

Error Message

File "C:\Users\my\anaconda3\envs\pidnet\lib\site-packages\torch\nn\modules\batchnorm.py", line 140, in forward
    self.weight, self.bias, bn_training, exponential_average_factor, self.eps)
  File "C:\Users\my\anaconda3\envs\pidnet\lib\site-packages\torch\nn\functional.py", line 2144, in batch_norm
    _verify_batch_size(input.size())
  File "C:\Users\my\anaconda3\envs\pidnet\lib\site-packages\torch\nn\functional.py", line 2111, in _verify_batch_size
    raise ValueError("Expected more than 1 value per channel when training, got input size {}".format(size))
ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1, 512, 1, 1])

Solution

Batch Size: 1 -> 2
Crop Size: (128, 256) -> (512, 1024)

Reason

Batch Normalization에서 발생할 수 있는 오류이다. Batch Size가 1로 설정될 경우, 각 channel에 대한 평균과 분산을 계산하여 정규화를 하게된다. 2 이상의 경우 여러 sample에 대한 통계량을 계산하게 되는데 Batch Size가 1일 경우 단일 sample만을 가지기 때문에 channel 당 하나 이상의 값을 제공받지 못하게 되어 오류가 발생하게 된다. 따라서 Batch Size를 1로 설정하는 것은 Batch Normalization을 사용하는 경우에는 적절하지 않으므로 Batch Size를 2 이상으로 설정하는 것이 좋다.


Plus

추가적으로 Train dataset의 크기가 15063개일 때 batch size=2인 경우 마지막에 1개의 data가 남을 때 위의 오류가 발생할 수 있다. 이 때, 다른 batch size로 설정하거나 drop_last=True를 설정하면 된다.

profile
ssw

0개의 댓글