Mixed Precision 이란?
- 처리 속도를 높이기 위한 FP16 과 정확도 유지를 위한 FP 32 를 섞어서 학습하는 방법
gradient 값이 매우 작은 경우
에 문제가 발생FP32 로 진행하면 학습이 잘 되던 것이 FP16 으로 했을 때 발산하는 현상이 발생
학습에 관여하는 Tensor 는 4가지로 나눌 수 있는데,
이 중 FP16 으로 변경하여 학습을 진행할 때, weights 와 weight gradients 는 FP16 범위 내에 잘 들어오는 편이었다고 함
문제가 생기는 activation gradients 의 경우, 굉장히 크기가 작은 일부 값들이 관측되었고, FP16 으로 표현할 수 있는 범위를 넘어서면서 강제적으로 0이 되어버리는 현상이 발생함 (underflow
)
아래 그래프에서 빨간선 보다 왼쪽에 해당하는 케이스들이 become zero in FP16
FP32 값은 저장하는 상태로, FP16 값을 이용하여 forward/backward 진행 (+ scale factor). FP16 결과로 얻은 gradients 를 기반으로 FP32 weights 업데이트
""" define loss scaler for automatic mixed precision """
# Creates a GradScaler once at the beginning of training.
scaler = torch.cuda.amp.GradScaler()
for batch_idx, (inputs, labels) in enumerate(data_loader):
optimizer.zero_grad()
with torch.cuda.amp.autocast():
# Casts operations to mixed precision
outputs = model(inputs)
loss = criterion(outputs, labels)
# Scales the loss, and calls backward()
# to create scaled gradients
scaler.scale(loss).backward()
# Unscales gradients and calls
# or skips optimizer.step()
scaler.step(self.optimizer)
# Updates the scale for next iteration
scaler.update()