The gradient descent lesson ended with two problems. One is the condition number: the steepest direction caps the learning rate, so the gentle directions are slow. The other is noise: minibatch gradients fluctuate, so the iterate keeps jittering near the minimum. The history of optimizers over the past decade or so is the history of how to deal with these two problems, and as a result almost every LLM today is trained with the same combination: AdamW + warmup + decay + gradient clipping. This lesson assembles that combination one part at a time.
Notation follows the gradient descent lesson: (or its minibatch estimate), learning rate , and all operations are element-wise. Adam’s are the conventional names and have nothing to do with the RLHF KL coefficient .
1. Momentum: an exponential moving average of gradients
Momentum (heavy ball) was , . Unrolled, , an exponentially weighted sum of past gradients. It has two effects.
- Consistent directions accumulate. If the gradient stays the same, and the effective learning rate becomes . With β = 0.9 that is 10×.
- Alternating directions cancel. The zig-zag component across a narrow valley flips sign every step, so its sum stays small.
There is also a gain from the minibatch-noise point of view: averaging reduces the noise. On a quadratic loss the optimal β makes the convergence rate depend on instead of (gradient descent lesson).
Nesterov momentum measures the gradient not at the current position but at “where inertia is about to take you”.
Because it looks ahead and corrects its velocity, it slams into the far wall of the valley less. Changing variables to gives a form that uses only the gradient at the current position: , . PyTorch’s nesterov=True is this form.
2. Adaptive learning rates: a different η per coordinate
The fundamental fix for the condition-number problem is to divide the gradient by the curvature (Newton’s method: ). But the Hessian is far too large. So we use a diagonal approximation that only matches the per-coordinate scale. Instead of measuring curvature directly, we use “how large this coordinate’s gradient usually is” as a proxy.
AdaGrad divides by the sum of squared gradients so far.
Coordinates that are updated often and strongly get a smaller learning rate, while rarely seen features (such as embeddings of rare words) keep a large one. It is theoretically good for convex problems, but since never shrinks and keeps growing, the learning rate decays monotonically, roughly like . In long non-convex training it stops too early.
RMSProp (first introduced in Hinton’s lecture notes) replaces the cumulative sum with an exponential moving average so that old gradients are forgotten.
Because each coordinate’s gradient is divided by that coordinate’s RMS, scaling a coordinate’s gradient by leaves the update unchanged. A layer whose gradients are 1e-6 and one whose gradients are 1e+2 learn at the same speed. This is why adaptive methods are strong in deep networks.
3. Adam = momentum + RMSProp + bias correction
Adam tracks both the first moment (mean) and the second moment (mean square) of the gradient with exponential moving averages.
Why bias correction is needed
Starting from , the early is biased towards 0. Solving the recursion gives
If the gradient distribution is stationary, , then because of the geometric sum ,
So dividing by removes the bias. The same holds for . The correction matters most for : with , it takes thousands of steps for to approach 1. Without correction, the first step’s ratio is , an update inflated by that factor. With correction, at we have and , so the first update is exactly (ignoring ε).
The update size is roughly bounded by η
is “mean / RMS”, so it is usually at most 1. It is close to 1 when the gradient is consistent and smaller when noise makes the sign flip often. So Adam’s per-coordinate step is about η, almost independent of the gradient’s magnitude. The learning rate acquires an intuitive meaning, “how far to move the parameters in one step”, and the same hyperparameters keep working when the loss scale changes. ε protects the denominator when is close to 0 (typically 1e-8).
경사하강법 레슨은 두 가지 문제로 끝났다. 하나는 조건수다. 가장 가파른 방향이 학습률의 상한을 정해서 완만한 방향이 느리다. 다른 하나는 잡음이다. 미니배치 기울기는 흔들리므로 최소점 근처에서 계속 떤다. 지난 십여 년의 옵티마이저 역사는 이 두 문제를 어떻게 다루느냐의 역사이고, 그 결과로 오늘날 거의 모든 LLM이 같은 조합, AdamW + warmup + decay + gradient clipping으로 학습된다. 이 레슨은 그 조합을 한 부품씩 조립한다.
표기는 경사하강법 레슨을 따른다. (혹은 미니배치 추정치), 학습률 , 모든 연산은 좌표별(element-wise)이다. Adam의 는 관례상 쓰는 이름이고, RLHF의 KL 계수 와는 관계없다.
1. 모멘텀: 기울기의 지수이동평균
모멘텀(heavy ball)은 , 이었다. 풀어 쓰면 , 과거 기울기의 지수 가중합이다. 두 가지 효과가 있다.
- 일정한 방향은 누적된다. 기울기가 계속 같으면 , 실효 학습률이 가 된다. β = 0.9면 10배.
- 번갈아 바뀌는 방향은 상쇄된다. 좁은 골짜기를 가로지르는 지그재그 성분은 부호가 매 step 바뀌어 합이 작아진다.
미니배치 잡음 관점에서도 이득이 있다. 평균을 내니 잡음이 줄어든다. 이차 손실에서는 최적의 β로 수렴률이 대신 에 의존하게 된다(경사하강법 레슨).
Nesterov 모멘텀은 기울기를 현재 위치가 아니라 “관성으로 갈 곳”에서 잰다.
앞을 미리 보고 속도를 고치니 골짜기 반대편 벽을 덜 들이받는다. 변수를 로 바꾸면 현재 위치의 기울기만 쓰는 꼴, , 가 된다. PyTorch의 nesterov=True가 이 꼴이다.
2. 적응형 학습률: 좌표마다 다른 η
조건수 문제의 근본 해법은 곡률로 기울기를 나누는 것이다(뉴턴법: ). 하지만 Hessian은 너무 크다. 그래서 좌표별 크기만 맞추는 대각 근사를 쓴다. 곡률을 직접 재는 대신 “이 좌표의 기울기가 보통 얼마나 큰가”를 대리 지표로 쓴다.
AdaGrad는 지금까지의 기울기 제곱합으로 나눈다.
자주, 크게 업데이트된 좌표는 학습률이 줄고, 드물게 나타나는 특징(희소한 단어 임베딩 같은)은 큰 학습률을 유지한다. 볼록 문제에서는 이론적으로 좋지만, 가 줄지 않고 계속 커지므로 학습률이 대략 로 단조 감소한다. 긴 비볼록 학습에서는 너무 일찍 멈춘다.
RMSProp(Hinton의 강의 노트에서 처음 소개)은 누적합을 지수이동평균으로 바꿔 오래된 기울기를 잊게 한다.
좌표별 기울기를 그 좌표의 RMS로 나누므로, 어떤 좌표의 기울기 스케일을 배 해도 업데이트는 변하지 않는다. 기울기가 1e-6인 층과 1e+2인 층이 같은 속도로 배운다. 이것이 깊은 신경망에서 적응형 방법이 강한 이유다.
3. Adam = 모멘텀 + RMSProp + 편향 보정
Adam은 기울기의 1차 모멘트(평균)와 2차 모멘트(제곱 평균)를 모두 지수이동평균으로 추적한다.
편향 보정은 왜 필요한가
에서 시작하니 초반의 는 0 쪽으로 치우쳐 있다. 점화식을 풀면
기울기의 분포가 정상(stationary)이라 라 하면, 기하급수 합 때문에
그러니 로 나누면 편향이 사라진다. 도 똑같다. 이 보정이 특히 중요한 쪽은 다. 이면 가 1에 가까워지는 데 수천 step이 걸린다. 보정이 없으면 첫 step의 비율이 배로 부풀려진 업데이트가 나간다. 보정하면 에서 , 이므로 첫 업데이트는 정확히 (ε 무시)이다.
업데이트 크기는 대략 η로 묶인다
는 “평균 / RMS”라 보통 1 이하다. 기울기가 일관되면 1에 가깝고, 잡음이 많아 부호가 자주 바뀌면 작아진다. 그래서 Adam의 좌표별 이동량은 기울기의 크기와 거의 무관하게 η 정도다. 학습률이 “한 step에 매개변수를 얼마나 움직일지”라는 직관적인 의미를 갖게 되고, 손실 스케일을 바꿔도 같은 하이퍼파라미터가 통한다. ε은 가 0에 가까울 때의 분모 보호용이다(보통 1e-8).
- On Rosenbrock, SGD crawls very slowly along the floor of the curved valley. Momentum and Nesterov first bounce between the valley walls, then gain speed along the floor. Adam, thanks to its per-coordinate normalised steps, reaches the neighbourhood of (1, 1) first, but with a fixed learning rate its loss curve jitters like a saw blade. If you run the code below to 3000 steps, momentum eventually reaches a lower loss. This is why learning-rate decay is needed.
- Switch to the rotated valley and most of Adam’s and RMSProp’s advantage disappears. When the principal axes of curvature are 30° off the coordinate axes, per-coordinate scaling cannot make the bowl round. That is the limit of diagonal preconditioning.
- At the saddle point, the start sits almost exactly on the saddle’s stable direction, so the gradient is tiny. SGD lingers there for a long time, while Adam normalises even a small gradient and moves by about η, so it escapes quickly.
- Raise the gradient noise to around 1 and SGD and momentum scatter widely around the minimum, while AdaGrad, thanks to its shrinking learning rate, actually becomes calmer.
4. AdamW: decoupling weight decay
In the generalization lesson, L2 regularisation with SGD was the same as weight decay: descending along gives . What happens if we add the same L2 term to Adam? The gradient passes through the preconditioner as a whole.
Isolating the decay component, coordinate decays at a rate of roughly . Coordinates with large gradients are barely decayed, and coordinates with small gradients are over-decayed. The weights that most need regularisation (those updated often and strongly) are regularised the least. On top of that, is computed with the term mixed in, which contaminates the loss-gradient statistics.
Loshchilov & Hutter’s AdamW moves the decay outside the preconditioner.
Now every coordinate is pulled towards 0 by the same factor every step, and see only the loss gradient. PyTorch’s AdamW has exactly this form, so the amount of decay is lr × weight_decay. As the learning-rate schedule goes down, the decay shrinks with it.
5. Learning-rate schedules
Why decrease it. SGD with a fixed learning rate does not converge to the minimum; it oscillates around it with an amplitude proportional to (Adam in item 1 of the figure above). The basic logic of a schedule is to travel far and fast with a large learning rate, then lower it at the end to settle that oscillation.
Why warm up. Two things are unstable early in training. Adam’s is estimated from only the first few steps’ gradients, so its variance is large (RAdam came out of this observation), and the loss landscape right after random initialisation has large curvature (sharpness). Recall the condition from the gradient descent lesson: when curvature is large early on, a large learning rate diverges immediately. Raising the learning rate linearly from 0 buys the model time to move into a region of lower curvature.
Cosine. After warmup, , where is the progress through the remaining span. It is smooth and has few hyperparameters, and for a long time it was the default for LLM pre-training. Its drawback is that the total training length T must be fixed in advance to determine the curve. That makes it hard to extend training or to evaluate intermediate checkpoints.
WSD (warmup–stable–decay). After warmup, the maximum learning rate is held constant for a long time, then lowered quickly over the last 10–20%. Branching a short decay off any checkpoint in the stable phase yields “a model trained for that length”, which makes it convenient to run without fixing the training length or to continue training with a changed data mixture. MiniCPM used and analysed this schedule, and Hägele et al. (2024) reported that a constant learning rate with an appropriate cooldown matches cosine. A visible sudden drop in loss during the decay phase is the signature of a WSD learning curve.
- Rosenbrock에서 SGD는 휘어진 골짜기 바닥을 따라 아주 느리게 기어간다. Momentum·Nesterov는 처음에 골짜기 벽 사이를 튕기다가 바닥을 따라 속도를 얻는다. Adam은 좌표별로 정규화된 걸음 덕분에 가장 먼저 (1, 1) 근처에 도착하지만, 고정 학습률이라 손실 곡선이 톱니처럼 흔들린다. 아래 코드로 3000 step까지 돌려 보면 결국 모멘텀이 더 낮은 손실에 닿는다. 학습률 감쇠가 필요한 이유다.
- 회전된 골짜기로 바꾸면 Adam·RMSProp의 이점이 대부분 사라진다. 곡률의 주축이 좌표축과 30° 어긋나 있으면 좌표별 스케일링으로는 그릇을 둥글게 만들 수 없다. 대각 전처리의 한계다.
- 안장점에서는 출발점이 안장의 안정 방향에 거의 올라타 있어 기울기가 아주 작다. SGD는 거기서 한참 머물고, Adam은 작은 기울기도 정규화해 η 크기로 움직이므로 빨리 빠져나간다.
- 기울기 잡음을 1 정도로 올리면 SGD·모멘텀은 최소점 근처에서 넓게 흩어지고, AdaGrad는 학습률이 줄어드는 덕분에 오히려 얌전해진다.
4. AdamW: weight decay를 떼어 내기
일반화 레슨에서 SGD의 L2 정규화는 weight decay와 같았다. 를 따라 내려가면 . Adam에 똑같이 L2 항을 넣으면 어떻게 될까? 기울기 가 통째로 전처리를 통과한다.
감쇠 성분만 떼어 보면 좌표 의 감쇠율은 대략 다. 기울기가 큰 좌표는 거의 감쇠되지 않고, 기울기가 작은 좌표는 과하게 감쇠된다. 정규화가 필요한 쪽(자주 크게 업데이트되는 가중치)일수록 덜 정규화되는 셈이다. 게다가 가 항까지 섞여 계산되니 손실의 기울기 통계도 오염된다.
Loshchilov & Hutter의 AdamW는 감쇠를 전처리 바깥으로 뺀다.
이제 모든 좌표가 매 step 같은 비율 로 0 쪽으로 당겨지고, 는 손실의 기울기만 본다. PyTorch의 AdamW가 정확히 이 꼴이라 감쇠량이 lr × weight_decay다. 학습률 스케줄이 내려가면 감쇠도 같이 줄어든다.
5. 학습률 스케줄
왜 줄이는가. 고정 학습률의 SGD는 최소점에 수렴하지 않고 그 주변에서 에 비례하는 폭으로 흔들린다(위 그림 1번의 Adam). 큰 학습률로 멀리 빨리 가고, 끝에 학습률을 줄여 그 흔들림을 가라앉히는 것이 스케줄의 기본 논리다.
왜 warmup하는가. 학습 초반에는 두 가지가 불안정하다. Adam의 는 처음 몇 step의 기울기만으로 추정되니 분산이 크고(이 관찰에서 RAdam이 나왔다), 무작위 초기화 직후의 손실 지형은 곡률(sharpness)이 크다. 경사하강법 레슨의 조건을 떠올리면, 곡률이 큰 초반에 큰 학습률은 바로 발산한다. 학습률을 0에서 선형으로 올리면 모델이 곡률이 작은 영역으로 옮겨 갈 시간을 번다.
Cosine. warmup 뒤 , 는 남은 구간의 진행률. 매끄럽고 하이퍼파라미터가 적어 오랫동안 LLM 사전학습의 기본이었다. 단점은 전체 학습 길이 T를 미리 정해야 곡선이 정해진다는 것이다. 학습을 연장하거나 중간 체크포인트를 평가하기 어렵다.
WSD (warmup–stable–decay). warmup 뒤 최대 학습률을 상수로 오래 유지하다가, 마지막 10–20% 구간에서 빠르게 내린다. 안정 구간의 아무 체크포인트에서나 짧은 decay를 분기하면 “그 길이로 학습한 모델”을 얻을 수 있어서, 학습 길이를 정하지 않고 달리거나 데이터 혼합을 바꿔 이어 학습하기 좋다. MiniCPM이 이 스케줄을 쓰고 분석했고, Hägele et al.(2024)은 적절한 cooldown이 있는 상수 학습률이 cosine과 대등한 결과를 낸다고 보고했다. decay 구간에서 손실이 눈에 띄게 뚝 떨어지는 것이 WSD 학습 곡선의 특징이다.
Lengthen and shorten the warmup and watch how the area under the two curves (the mean learning rate) changes. For the same maximum learning rate, WSD stays at a high learning rate longer. The dashed line is a short decay branched off at the middle of training (50%).
6. Gradient clipping
When a rare, large gradient arrives (a bad batch, a cliff in the loss landscape), the parameters can jump a long way in one step and training can break. Global norm clipping treats the gradients of all parameters as one vector and shrinks it if its norm exceeds .
The important point is that it keeps the direction and only cuts the length. Clipping values per coordinate (value clipping) changes the direction. In LLM pre-training is a common default, and how often clipping kicks in (the gradient-norm curve) is a good diagnostic of training stability.
Implementing it
We implement every optimizer with the same interface (step(p, g) → new p) and race them on Rosenbrock. The learning rates match the figure’s defaults.
import numpy as np
class SGD:
def __init__(self, lr): self.lr = lr
def step(self, p, g): return p - self.lr * g
class Momentum: # v = βv + g ; θ -= η v (same form as the gradient descent lesson)
def __init__(self, lr, beta=0.9): self.lr, self.beta, self.v = lr, beta, 0.0
def step(self, p, g):
self.v = self.beta * self.v + g
return p - self.lr * self.v
class Nesterov: # look-ahead gradient rewritten with the current gradient (PyTorch nesterov=True)
def __init__(self, lr, beta=0.9): self.lr, self.beta, self.v = lr, beta, 0.0
def step(self, p, g):
self.v = self.beta * self.v + g
return p - self.lr * (g + self.beta * self.v)
class AdaGrad:
def __init__(self, lr, eps=1e-8): self.lr, self.eps, self.G = lr, eps, 0.0
def step(self, p, g):
self.G = self.G + g * g # cumulative sum of squared gradients (never shrinks)
return p - self.lr * g / (np.sqrt(self.G) + self.eps)
class RMSProp:
def __init__(self, lr, rho=0.9, eps=1e-8): self.lr, self.rho, self.eps, self.s = lr, rho, eps, 0.0
def step(self, p, g):
self.s = self.rho * self.s + (1 - self.rho) * g * g # an exponential moving average lets it "forget"
return p - self.lr * g / (np.sqrt(self.s) + self.eps)
class Adam:
def __init__(self, lr, b1=0.9, b2=0.999, eps=1e-8, weight_decay=0.0, decoupled=False):
self.lr, self.b1, self.b2, self.eps = lr, b1, b2, eps
self.wd, self.decoupled = weight_decay, decoupled
self.m = self.v = 0.0; self.t = 0
def step(self, p, g):
if self.wd and not self.decoupled:
g = g + self.wd * p # Adam + L2: the decay passes through the preconditioner
self.t += 1
self.m = self.b1 * self.m + (1 - self.b1) * g
self.v = self.b2 * self.v + (1 - self.b2) * g * g
m_hat = self.m / (1 - self.b1 ** self.t) # bias correction
v_hat = self.v / (1 - self.b2 ** self.t)
p = p - self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
if self.wd and self.decoupled:
p = p - self.lr * self.wd * p # AdamW: decay applied separately, same factor for every coordinate
return p
def AdamW(lr, weight_decay=0.01, **kw):
return Adam(lr, weight_decay=weight_decay, decoupled=True, **kw)
# ---- Rosenbrock race ----
f = lambda p: (1 - p[0]) ** 2 + 100 * (p[1] - p[0] ** 2) ** 2
grad = lambda p: np.array([-2 * (1 - p[0]) - 400 * p[0] * (p[1] - p[0] ** 2), 200 * (p[1] - p[0] ** 2)])
racers = {"SGD": SGD(2e-3), "Momentum": Momentum(1e-3), "Nesterov": Nesterov(1e-3),
"AdaGrad": AdaGrad(0.5), "RMSProp": RMSProp(1e-2), "Adam": Adam(0.2)}
print("optimizer step reaching loss<1e-4 loss after 3000 steps final θ")
for name, opt in racers.items():
p, hit = np.array([-1.2, 1.0]), None
for t in range(1, 3001):
p = opt.step(p, grad(p))
if hit is None and f(p) < 1e-4: hit = t
print(f"{name:10s} {str(hit):>18s} {f(p):16.2e} {np.round(p, 4)}")Adam is the first to drop below 1e-4, but it keeps oscillating at a fixed learning rate, so its final loss is larger than momentum’s. RMSProp hovers around 1e-2 for the same reason. Now let us see the difference between Adam + L2 and AdamW directly. Consider three coordinates where the loss is flat, so the gradient is pure noise. Only the noise scale differs: 10, 1 and 0.01.
rng = np.random.default_rng(0)
scales = np.array([10.0, 1.0, 0.01]) # per-coordinate gradient scale (e.g. frequently used weight vs rare feature)
lr, wd, T = 1e-3, 0.1, 5000
for name, opt in [("Adam + L2", Adam(lr, weight_decay=wd)), ("AdamW ", AdamW(lr, weight_decay=wd))]:
p = np.ones(3)
for t in range(T):
p = opt.step(p, scales * rng.normal(size=3))
print(f"{name} θ after {T} steps = {np.round(p, 3)}")
print(f"reference: pure decay (1 − η·λ)^T = {(1 - lr * wd) ** T:.3f}")With Adam + L2 the first coordinate, whose gradient is large, is barely decayed (≈ 0.94), and the third coordinate, whose gradient is small, vanishes to 0. With AdamW all three coordinates sit near the pure decay (the differences are a random walk caused by the noise).
A real LLM training loop assembles these parts like this.
import math
import torch
from torch import nn
model = nn.Sequential(nn.Linear(64, 256), nn.GELU(), nn.LayerNorm(256), nn.Linear(256, 64))
# Decay only weights with 2+ dimensions. Exclude biases and norm gains (1-D).
decay = [p for n, p in model.named_parameters() if p.requires_grad and p.ndim >= 2]
no_decay = [p for n, p in model.named_parameters() if p.requires_grad and p.ndim < 2]
opt = torch.optim.AdamW(
[{"params": decay, "weight_decay": 0.1},
{"params": no_decay, "weight_decay": 0.0}],
lr=3e-4, betas=(0.9, 0.95), eps=1e-8,
)
total, warmup, min_ratio = 10_000, 200, 0.1
def lr_lambda(step): # multiplier applied to the max lr
if step < warmup:
return (step + 1) / warmup
progress = (step - warmup) / max(1, total - warmup)
return min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * progress))
sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda)
for step in range(total):
x = torch.randn(32, 64)
loss = ((model(x) - x) ** 2).mean() # placeholder loss
opt.zero_grad(set_to_none=True)
loss.backward()
gnorm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) # returns the norm before clipping
opt.step()
sched.step()
if step % 2000 == 0:
print(step, f"loss={loss.item():.4f} gnorm={gnorm.item():.3f} lr={sched.get_last_lr()[0]:.2e}")You take the first step with Adam (β₁=0.9, β₂=0.999, with bias correction). If a coordinate's first gradient is g₁ = 0.003 and the learning rate is η = 1e-3, roughly how far does that coordinate move?
After correction and , so the step is (ignoring ε). It is the same whether the gradient is 0.003 or 300. This is the extreme case of the property that Adam’s update size is set by the learning rate, almost independently of the gradient scale. Without correction it would have been about 3e-3, times larger.
If you use Adam with an L2 term λθ added to the loss (not AdamW), how are weights with large gradients regularised compared with weights with small gradients?
The gradient of the L2 term, , is also divided by , so the effective decay rate is . The larger (the larger the gradient), the less the coordinate is decayed. AdamW moves the decay outside the preconditioner and multiplies every coordinate by the same .
Summary
- Momentum is an exponential moving average of gradients that accelerates consistent directions and cancels zig-zags. Nesterov looks ahead and corrects the velocity.
- AdaGrad, RMSProp and Adam are diagonal preconditioners that divide by the per-coordinate gradient RMS. They are invariant to gradient scale but cannot straighten curvature that is misaligned with the coordinate axes.
- Adam’s bias correction comes from . The update size is roughly η per coordinate.
- Adding L2 to Adam distorts the decay by . AdamW decouples the decay and usually does not apply it to biases and norms.
- Warmup fixes early instability (large curvature, inaccurate ); decay fixes the noise floor of a fixed learning rate. WSD does not require fixing the length in advance. Global norm clipping prevents blow-ups while preserving the direction.
warmup을 늘리고 줄이면서 두 곡선 아래 면적(평균 학습률)이 어떻게 달라지는지 보자. 같은 최대 학습률이면 WSD가 더 오래 높은 학습률에 머문다. 점선은 학습 중간(50%)에서 분기한 짧은 decay다.
6. Gradient clipping
드물게 큰 기울기(나쁜 배치, 손실 지형의 절벽)가 한 번 오면 한 step에 매개변수가 크게 튀고 학습이 망가질 수 있다. 전역 노름 클리핑은 모든 매개변수의 기울기를 하나의 벡터로 보고 노름이 를 넘으면 줄인다.
방향은 그대로 두고 길이만 자른다는 점이 중요하다. 좌표별로 값을 자르면(value clipping) 방향이 바뀐다. LLM 사전학습에서는 이 흔한 기본값이고, 클리핑이 얼마나 자주 걸리는지(기울기 노름 곡선)는 학습 안정성의 좋은 진단 지표다.
직접 구현하기
모든 옵티마이저를 같은 인터페이스(step(p, g) → 새 p)로 구현하고 Rosenbrock에서 경주시킨다. 학습률은 그림의 기본값과 같다.
import numpy as np
class SGD:
def __init__(self, lr): self.lr = lr
def step(self, p, g): return p - self.lr * g
class Momentum: # v = βv + g ; θ -= η v (경사하강법 레슨과 같은 꼴)
def __init__(self, lr, beta=0.9): self.lr, self.beta, self.v = lr, beta, 0.0
def step(self, p, g):
self.v = self.beta * self.v + g
return p - self.lr * self.v
class Nesterov: # 미리보기 기울기를 현재 기울기로 다시 쓴 꼴 (PyTorch nesterov=True)
def __init__(self, lr, beta=0.9): self.lr, self.beta, self.v = lr, beta, 0.0
def step(self, p, g):
self.v = self.beta * self.v + g
return p - self.lr * (g + self.beta * self.v)
class AdaGrad:
def __init__(self, lr, eps=1e-8): self.lr, self.eps, self.G = lr, eps, 0.0
def step(self, p, g):
self.G = self.G + g * g # 기울기 제곱의 누적합 (줄지 않는다)
return p - self.lr * g / (np.sqrt(self.G) + self.eps)
class RMSProp:
def __init__(self, lr, rho=0.9, eps=1e-8): self.lr, self.rho, self.eps, self.s = lr, rho, eps, 0.0
def step(self, p, g):
self.s = self.rho * self.s + (1 - self.rho) * g * g # 지수이동평균으로 바꿔 "잊게" 한다
return p - self.lr * g / (np.sqrt(self.s) + self.eps)
class Adam:
def __init__(self, lr, b1=0.9, b2=0.999, eps=1e-8, weight_decay=0.0, decoupled=False):
self.lr, self.b1, self.b2, self.eps = lr, b1, b2, eps
self.wd, self.decoupled = weight_decay, decoupled
self.m = self.v = 0.0; self.t = 0
def step(self, p, g):
if self.wd and not self.decoupled:
g = g + self.wd * p # Adam + L2: 감쇠가 전처리기를 통과한다
self.t += 1
self.m = self.b1 * self.m + (1 - self.b1) * g
self.v = self.b2 * self.v + (1 - self.b2) * g * g
m_hat = self.m / (1 - self.b1 ** self.t) # 편향 보정
v_hat = self.v / (1 - self.b2 ** self.t)
p = p - self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
if self.wd and self.decoupled:
p = p - self.lr * self.wd * p # AdamW: 감쇠를 따로, 모든 좌표에 같은 비율로
return p
def AdamW(lr, weight_decay=0.01, **kw):
return Adam(lr, weight_decay=weight_decay, decoupled=True, **kw)
# ---- Rosenbrock 경주 ----
f = lambda p: (1 - p[0]) ** 2 + 100 * (p[1] - p[0] ** 2) ** 2
grad = lambda p: np.array([-2 * (1 - p[0]) - 400 * p[0] * (p[1] - p[0] ** 2), 200 * (p[1] - p[0] ** 2)])
racers = {"SGD": SGD(2e-3), "Momentum": Momentum(1e-3), "Nesterov": Nesterov(1e-3),
"AdaGrad": AdaGrad(0.5), "RMSProp": RMSProp(1e-2), "Adam": Adam(0.2)}
print("optimizer loss<1e-4 도달 step 3000 step 후 loss 최종 θ")
for name, opt in racers.items():
p, hit = np.array([-1.2, 1.0]), None
for t in range(1, 3001):
p = opt.step(p, grad(p))
if hit is None and f(p) < 1e-4: hit = t
print(f"{name:10s} {str(hit):>18s} {f(p):16.2e} {np.round(p, 4)}")Adam은 가장 먼저 1e-4 아래로 내려가지만 고정 학습률로 계속 흔들려 최종 손실은 모멘텀보다 크다. RMSProp도 같은 이유로 1e-2 근처에서 맴돈다. 이제 Adam + L2와 AdamW의 차이를 직접 본다. 손실이 평평해서 기울기가 순수한 잡음뿐인 세 좌표를 생각하자. 잡음의 크기만 10, 1, 0.01로 다르다.
rng = np.random.default_rng(0)
scales = np.array([10.0, 1.0, 0.01]) # 좌표별 기울기 크기 (예: 자주 쓰이는 가중치 vs 드문 특징)
lr, wd, T = 1e-3, 0.1, 5000
for name, opt in [("Adam + L2", Adam(lr, weight_decay=wd)), ("AdamW ", AdamW(lr, weight_decay=wd))]:
p = np.ones(3)
for t in range(T):
p = opt.step(p, scales * rng.normal(size=3))
print(f"{name} θ after {T} steps = {np.round(p, 3)}")
print(f"참고: 순수 감쇠 (1 − η·λ)^T = {(1 - lr * wd) ** T:.3f}")Adam + L2에서는 기울기가 큰 첫 좌표가 거의 감쇠되지 않고(≈ 0.94), 기울기가 작은 셋째 좌표는 0으로 사라진다. AdamW에서는 세 좌표가 모두 순수 감쇠 근처에 있다(차이는 잡음에 의한 무작위 걸음이다).
실제 LLM 학습 루프는 이 부품들을 아래처럼 조립한다.
import math
import torch
from torch import nn
model = nn.Sequential(nn.Linear(64, 256), nn.GELU(), nn.LayerNorm(256), nn.Linear(256, 64))
# 2차원 이상 가중치에만 decay. bias와 norm의 gain(1차원)은 제외한다.
decay = [p for n, p in model.named_parameters() if p.requires_grad and p.ndim >= 2]
no_decay = [p for n, p in model.named_parameters() if p.requires_grad and p.ndim < 2]
opt = torch.optim.AdamW(
[{"params": decay, "weight_decay": 0.1},
{"params": no_decay, "weight_decay": 0.0}],
lr=3e-4, betas=(0.9, 0.95), eps=1e-8,
)
total, warmup, min_ratio = 10_000, 200, 0.1
def lr_lambda(step): # 최대 lr에 곱해지는 배율
if step < warmup:
return (step + 1) / warmup
progress = (step - warmup) / max(1, total - warmup)
return min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * progress))
sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda)
for step in range(total):
x = torch.randn(32, 64)
loss = ((model(x) - x) ** 2).mean() # 자리표시용 손실
opt.zero_grad(set_to_none=True)
loss.backward()
gnorm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) # 클리핑 전 노름을 돌려준다
opt.step()
sched.step()
if step % 2000 == 0:
print(step, f"loss={loss.item():.4f} gnorm={gnorm.item():.3f} lr={sched.get_last_lr()[0]:.2e}")Adam(β₁=0.9, β₂=0.999, 편향 보정 포함)으로 첫 step을 밟는다. 어떤 좌표의 첫 기울기가 g₁ = 0.003이고 학습률이 η = 1e-3이면 그 좌표의 이동량은 대략?
보정 후 , 이므로 이동량은 이다(ε 무시). 기울기가 0.003이든 300이든 같다. Adam의 업데이트 크기가 기울기 스케일과 거의 무관하게 학습률로 정해진다는 성질의 극단적인 경우다. 보정이 없었다면 배인 약 3e-3이 되었을 것이다.
Adam에 L2 정규화 항 λθ를 손실에 더해 쓰면(AdamW가 아니라), 기울기 크기가 큰 가중치는 기울기 크기가 작은 가중치에 비해 어떻게 정규화되는가?
L2 항의 기울기 도 로 나뉘므로 실효 감쇠율이 다. 가 큰(기울기가 큰) 좌표일수록 덜 감쇠된다. AdamW는 감쇠를 전처리 밖으로 빼서 모든 좌표에 를 똑같이 곱한다.
정리
- 모멘텀은 기울기의 지수이동평균으로 일관된 방향을 가속하고 지그재그를 상쇄한다. Nesterov는 앞을 보고 속도를 고친다.
- AdaGrad·RMSProp·Adam은 좌표별 기울기 RMS로 나누는 대각 전처리다. 기울기 스케일에 불변이지만 좌표축과 어긋난 곡률은 펴지 못한다.
- Adam의 편향 보정은 에서 나온다. 업데이트 크기는 좌표당 대략 η다.
- Adam에 L2를 넣으면 감쇠가 로 왜곡된다. AdamW는 감쇠를 분리하고, bias·norm에는 보통 걸지 않는다.
- warmup은 초반 불안정(큰 곡률, 부정확한 )을, decay는 고정 학습률의 잡음 바닥을 해결한다. WSD는 길이를 미리 정하지 않아도 된다. 전역 노름 클리핑은 방향을 지키며 폭주를 막는다.
더 읽을거리Further reading
- Kingma & Ba, Adam: A Method for Stochastic Optimization (ICLR 2015) — Adam과 편향 보정의 원 논문. 업데이트 크기가 대략 학습률로 묶인다는 "trust region" 해석도 있다.The original paper on Adam and its bias correction. It also offers a "trust region" reading: the update size is roughly bounded by the learning rate.
- Loshchilov & Hutter, Decoupled Weight Decay Regularization (ICLR 2019) — AdamW. 적응형 옵티마이저에서 L2 정규화와 weight decay가 다르다는 것을 보였다.AdamW. Shows that with adaptive optimizers L2 regularisation and weight decay are not the same thing.
- Duchi, Hazan, Singer, Adaptive Subgradient Methods for Online Learning and Stochastic Optimization (JMLR 2011) — AdaGrad. 좌표별 학습률의 출발점.AdaGrad. The starting point of per-coordinate learning rates.
- Sutskever, Martens, Dahl, Hinton, On the importance of initialization and momentum in deep learning (ICML 2013) — 딥러닝에서 모멘텀과 Nesterov 모멘텀의 역할, 그리고 현재 기울기만 쓰는 Nesterov 표기.The role of momentum and Nesterov momentum in deep learning, and the form of Nesterov that uses only the current gradient.
- Pascanu, Mikolov, Bengio, On the difficulty of training recurrent neural networks (ICML 2013) — 기울기 폭발과 노름 기준 gradient clipping.Exploding gradients and norm-based gradient clipping.
- Hu et al., MiniCPM: Unveiling the Potential of Small Language Models with Scalable Training Strategies (2024) — WSD(warmup–stable–decay) 스케줄을 LLM 사전학습에 쓰고 그 장점을 분석.Uses the WSD (warmup–stable–decay) schedule for LLM pre-training and analyses its advantages.
- Hägele et al., Scaling Laws and Compute-Optimal Training Beyond Fixed Training Durations (NeurIPS 2024) — 상수 lr + 짧은 cooldown이 cosine과 대등함을 보이고 cooldown 모양(1−√)을 비교.Shows that a constant lr plus a short cooldown matches cosine, and compares cooldown shapes (1−√).
- Touvron et al., LLaMA: Open and Efficient Foundation Language Models (2023) — AdamW(β₂=0.95), weight decay 0.1, clipping 1.0, warmup 2000 step, 최대의 10%까지 cosine — 전형적인 사전학습 설정.AdamW (β₂=0.95), weight decay 0.1, clipping 1.0, 2000 warmup steps, cosine down to 10% of the maximum — a typical pre-training setup.