C.W.K.
Stream
Lesson 08 of 10 · published

Gradient Clipping

~14 min · clipping, stability

Level 0Curious
0 XP0/73 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

한 줄의 보험

Gradient clipping 은 optimizer step 전 gradient 의 global norm (또는 value) 을 cap. Unclipped norm 이 max_norm 초과하면 gradient 를 norm 이 max_norm 와 같게 scale down. Optimizer 가 bounded update 보고 wild step 못 해.

표준 default: transformer 와 RNN 에 max_norm=1.0, 매우 unstable training 에 max_norm=0.5, stable CNN training 에 clipping 없음. 비용은 step 당 작은 compute — 거의 무료.

팁: Training 이 경고 없이 NaN loss 뱉으면, 첫 patch 가 gradient clipping 추가. 둘째가 clip 전 gradient norm log 해서 얼마나 자주 본인을 살리는지 보기.

Norm clipping vs value clipping

Norm clipping (clip_grad_norm_) — 방향 보존, magnitude scale. 거의 항상 본인이 원하는 거.

Value clipping (clip_grad_value_) — 각 coordinate 독립적 cap. Gradient 방향 distort, RL 의 PPO 같은 specific 일 하는 거 아니면 거의 본인이 원하는 거 아냐.

Call 어디 둘지

loss.backward()opt.step() 사이. Mixed precision 과 함께면, scaler.unscale_(opt)scaler.step(opt) 사이. Clipping 이 actual gradient value 에 작동하니까 순서가 중요해.

원칙: Gradient clipping 이 싼 보험. 모든 training loop 에 default 로 두기, specific 이유 있을 때만 제거. Step 50,000 의 NaN 비용이 한 줄 추가 비용보다 훨씬 큼.

Code

Gradient clipping with mixed precision·python
import torch
from torch.cuda.amp import autocast, GradScaler
from torch.nn.utils import clip_grad_norm_

scaler = GradScaler()

opt.zero_grad()
with autocast():
    loss = loss_fn(model(xb), yb)

scaler.scale(loss).backward()
scaler.unscale_(opt)                # bring grads back to FP32 scale
clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(opt)
scaler.update()

External links

Exercise

LSTM 을 synthetic long-sequence task 에 gradient clipping 있고 없이 train. Step 마다 clip 전 gradient norm log. Unclipped run 이 언제 diverge 하고 clipped 가 언제 살아남는지 봐.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.