Learning, in the end, is making one number smaller. There is a function that takes parameters and returns a loss , and we look for a that makes small. An LLM with hundreds of billions of parameters does not escape this sentence. This lesson covers the most basic way of “making it smaller”: gradient descent.
The one-step rule
At , the direction in which the loss increases fastest is the gradient . So we move a little the other way.
is the learning rate, the size of a step. The rule comes from the first-order Taylor approximation : for a fixed , the that lowers the most points along . Which also means the rule is only right where the first-order approximation holds. What sets that range is curvature.
In a picture: learning rate and curvature
The loss below is an elliptical bowl of the form (scaled by a constant to look nicer). The direction is times steeper than the direction.
학습은 결국 숫자 하나를 줄이는 일이다. 매개변수 를 넣으면 손실 가 나오는 함수가 있고, 우리는 이 작아지는 를 찾는다. 수억 개의 매개변수를 가진 LLM도 이 문장에서 벗어나지 않는다. 이 레슨은 그 “줄이는 방법”의 가장 기본형, 경사하강법(gradient descent) 을 다룬다.
한 걸음의 규칙
에서 손실이 가장 빨리 증가하는 방향은 기울기 다. 그러니 그 반대로 조금 움직인다.
는 학습률(learning rate), 한 걸음의 크기다. 이 식은 테일러 1차 근사 에서 를 고정했을 때 을 가장 많이 줄이는 가 방향이라는 사실에서 나온다. 1차 근사가 맞는 범위 안에서만 옳다는 뜻이기도 하다. 그 범위를 정하는 것이 곡률이다.
그림으로: 학습률과 곡률
아래 손실은 꼴의 타원형 그릇이다(보기 좋게 상수배 했다). 방향이 방향보다 배 가파르다.
Check a few things yourself.
- Push η all the way right: the path bounces along the axis and blows up. The steep direction diverges first.
- At an η just below divergence, goes to 0 almost immediately but shrinks very slowly. At the largest learning rate the steep direction allows, the gentle direction is slow. That is the conditioning problem.
- Set κ to 1 (a round bowl): from any start the path heads straight for the centre.
- Raise β to around 0.9: the zig-zag shrinks and the gentle direction picks up speed.
Why it blows up at 2/λ
For a quadratic loss the gradient is , so the update is a linear map.
Split along the eigenvectors of and each component is multiplied independently by every step. Hence
- if , i.e. , that direction converges;
- if , its sign flips every step (zig-zag) while it shrinks;
- if , the steepest direction diverges first.
Even with the best fixed learning rate, the error shrinks by a factor per step (). With κ = 100 that is only 2% per step.
Momentum
Momentum carries an exponential moving sum of past gradients around like a velocity.
In the zig-zag direction the sign alternates, so the sum cancels; in a consistent direction (the floor of a gentle valley) it accumulates, and the effective learning rate becomes roughly . On a quadratic with the optimal β the rate improves to . The key point is that replaces .
Implementing it
The code below does the same computation as the figure, in NumPy. Press ▶ Run and it runs inside your browser. Use Edit to change lr or kappa.
import numpy as np
kappa = 10.0
H = np.diag([1.0, kappa]) # curvature: eigenvalues 1 and kappa
def loss(theta): return 0.5 * theta @ H @ theta
def grad(theta): return H @ theta
def gd(lr, beta=0.0, steps=100, theta0=(-3.0, 1.5)):
theta = np.array(theta0)
v = np.zeros_like(theta)
hist = [loss(theta)]
for _ in range(steps):
v = beta * v + grad(theta)
theta = theta - lr * v
hist.append(loss(theta))
return theta, np.array(hist)
lam_max = np.linalg.eigvalsh(H).max()
print(f"divergence threshold 2/λ_max = {2/lam_max:.3f}")
for lr in [0.05, 0.15, 0.19, 0.21]:
theta, h = gd(lr)
print(f"lr={lr:<5} loss after 100 steps={h[-1]:.3e} theta={np.round(theta, 4)}")
theta, h = gd(0.15, beta=0.6)
print(f"\nmomentum β=0.6, lr=0.15 → loss={h[-1]:.3e}")In PyTorch you do not write the gradient yourself: autograd follows the computation graph to get (you build it by hand in Track II’s backprop lesson).
import torch
H = torch.diag(torch.tensor([1.0, 10.0]))
theta = torch.tensor([-3.0, 1.5], requires_grad=True)
opt = torch.optim.SGD([theta], lr=0.15, momentum=0.6)
for step in range(100):
opt.zero_grad()
loss = 0.5 * theta @ H @ theta
loss.backward() # theta.grad = H @ theta
opt.step() # v = μ v + g ; θ -= lr * v
print(loss.item(), theta.detach())Stochastic gradient descent (SGD)
The real loss is an average over data points, . Instead of looking at all of them every step, we estimate the gradient from a minibatch of .
The estimate is unbiased, so on average it follows the same path, but the noise keeps it jittering around the minimum. That is why a decaying learning-rate schedule is needed, and why growing the batch -fold lets you grow the learning rate roughly in proportion (the linear scaling rule).
A quadratic loss has H with eigenvalues 0.5 and 50. What is the largest fixed learning rate for which GD does not diverge?
The divergence threshold is . At that learning rate the gentle direction shrinks only by per step — the price of a condition number of 100.
Summary
- GD is ; curvature decides where the first-order approximation holds.
- The upper limit of a fixed learning rate is ; the convergence speed is set by the condition number .
- Momentum accumulates speed in consistent directions, reducing the dependence from to .
- SGD is an unbiased, noisy gradient; learning-rate decay and batch size manage that noise.
몇 가지를 직접 확인해 보자.
- η를 오른쪽 끝으로 밀면 경로가 축 방향으로 튕기다 터진다. 가파른 방향이 먼저 발산한다.
- 발산 직전의 η에서는 는 금방 0이 되지만 는 아주 느리게 줄어든다. 가파른 방향이 허용하는 최대 학습률로는 완만한 방향이 느리다. 이것이 조건수 문제다.
- κ를 1로 내리면(동그란 그릇) 어떤 출발점에서든 곧장 중심으로 간다.
- β를 0.9 근처로 올리면 지그재그가 줄고 완만한 방향으로 속도가 붙는다.
왜 2/λ에서 터지는가
이차 손실 에서 기울기는 이므로 업데이트는 선형 사상이 된다.
의 고유벡터 방향으로 쪼개 보면 각 성분은 독립적으로 배씩 곱해진다. 그러므로
- , 즉 이면 그 방향은 수렴하고,
- 이면 부호가 매 step 바뀌며(지그재그) 줄어들고,
- 이면 가장 가파른 방향부터 발산한다.
가장 좋은 고정 학습률을 골라도 수렴 속도는 배씩이다(). κ가 100이면 한 step에 2%만 줄어든다.
모멘텀
모멘텀은 지난 기울기들의 지수이동합을 속도처럼 들고 다닌다.
지그재그 방향은 부호가 번갈아 바뀌니 누적하면 상쇄되고, 일정한 방향(완만한 골짜기 바닥)은 누적되어 실효 학습률이 대략 가 된다. 이차 손실에서 최적의 β를 쓰면 수렴률이 로 좋아진다. κ 대신 가 들어간다는 점이 핵심이다.
직접 구현하기
아래 코드는 위 그림과 같은 계산을 NumPy로 한다. ▶ 실행을 누르면 브라우저 안에서 돌아간다. 편집으로 lr이나 kappa를 바꿔 보자.
import numpy as np
kappa = 10.0
H = np.diag([1.0, kappa]) # 곡률: 고유값 1, kappa
def loss(theta): return 0.5 * theta @ H @ theta
def grad(theta): return H @ theta
def gd(lr, beta=0.0, steps=100, theta0=(-3.0, 1.5)):
theta = np.array(theta0)
v = np.zeros_like(theta)
hist = [loss(theta)]
for _ in range(steps):
v = beta * v + grad(theta)
theta = theta - lr * v
hist.append(loss(theta))
return theta, np.array(hist)
lam_max = np.linalg.eigvalsh(H).max()
print(f"발산 경계 2/λ_max = {2/lam_max:.3f}")
for lr in [0.05, 0.15, 0.19, 0.21]:
theta, h = gd(lr)
print(f"lr={lr:<5} 100 step 뒤 loss={h[-1]:.3e} theta={np.round(theta, 4)}")
theta, h = gd(0.15, beta=0.6)
print(f"\n모멘텀 β=0.6, lr=0.15 → loss={h[-1]:.3e}")같은 일을 PyTorch로 하면 기울기를 직접 쓰지 않아도 된다. autograd가 계산 그래프를 따라 을 구해 준다(Track II의 역전파 레슨에서 직접 만든다).
import torch
H = torch.diag(torch.tensor([1.0, 10.0]))
theta = torch.tensor([-3.0, 1.5], requires_grad=True)
opt = torch.optim.SGD([theta], lr=0.15, momentum=0.6)
for step in range(100):
opt.zero_grad()
loss = 0.5 * theta @ H @ theta
loss.backward() # theta.grad = H @ theta
opt.step() # v = μ v + g ; θ -= lr * v
print(loss.item(), theta.detach())확률적 경사하강법(SGD)
실제 손실은 데이터 개의 평균 이다. 매 step 전체를 보는 대신 미니배치 개로 기울기를 추정한다.
추정이 편향 없이 맞으니 평균적으로는 같은 길을 가고, 잡음 때문에 최소점 근처에서 계속 흔들린다. 학습률을 줄여 나가는 스케줄(decay)이 필요한 이유이고, 배치를 배 키우면 학습률도 대략 비례해서 키울 수 있는 이유(linear scaling rule)다.
H의 고유값이 0.5와 50인 이차 손실에 고정 학습률 GD를 쓴다. 발산하지 않는 가장 큰 학습률은?
발산 경계는 . 이 학습률에서 완만한 방향은 매 step 배씩만 줄어든다. 조건수 100의 대가다.
정리
- GD는 . 1차 근사가 맞는 범위가 곡률로 정해진다.
- 고정 학습률의 상한은 , 수렴 속도는 조건수 가 결정한다.
- 모멘텀은 일정한 방향의 속도를 누적해 의존성을 로 줄인다.
- SGD는 편향 없는 잡음 섞인 기울기다. 학습률 감쇠와 배치 크기가 그 잡음을 다룬다.
더 읽을거리Further reading
- Goh, Why Momentum Really Works (Distill, 2017) — 모멘텀을 고유값 분해로 설명하는 인터랙티브 글. 이 레슨 그림의 원형.An interactive essay explaining momentum through the eigen-decomposition; the model for this lesson's figure.
- Boyd & Vandenberghe, Convex Optimization §9.3 — 경사하강법 수렴률과 조건수Convergence rate of gradient descent and the condition number
- Goodfellow, Bengio, Courville, Deep Learning §4.3, §8.3