Track I · ML Fundamentals · 02/09

경사하강법Gradient descent

손실의 기울기를 따라 내려가는 가장 단순한 최적화. 학습률이 왜 그렇게 예민한지, 곡률과 조건수로 설명한다.The simplest optimiser — walk down the gradient of the loss. Why the learning rate is so touchy, explained through curvature and the condition number.

30 분min optimization · gradient · learning rate · momentum 먼저 볼 것:Before this: 학습이란 무엇인가What is learning?

Learning, in the end, is making one number smaller. There is a function that takes parameters θ\theta and returns a loss L(θ)L(\theta), and we look for a θ\theta that makes LL 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 θ\theta, the direction in which the loss increases fastest is the gradient ∇L(θ)\nabla L(\theta). So we move a little the other way.

θt+1=θt−η ∇L(θt)\theta_{t+1} = \theta_t - \eta\, \nabla L(\theta_t)

η\eta is the learning rate, the size of a step. The rule comes from the first-order Taylor approximation L(θ+Δ)≈L(θ)+∇L⊤ΔL(\theta + \Delta) \approx L(\theta) + \nabla L^\top \Delta: for a fixed ∥Δ∥\|\Delta\|, the Δ\Delta that lowers LL the most points along −∇L-\nabla L. 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 L(x,y)=12(x2+κy2)L(x, y) = \tfrac{1}{2}(x^2 + \kappa y^2) (scaled by a constant to look nicer). The yy direction is κ\kappa times steeper than the xx direction.

학습은 결국 숫자 하나를 줄이는 일이다. 매개변수 θ\theta를 넣으면 손실 L(θ)L(\theta)가 나오는 함수가 있고, 우리는 LL이 작아지는 θ\theta를 찾는다. 수억 개의 매개변수를 가진 LLM도 이 문장에서 벗어나지 않는다. 이 레슨은 그 “줄이는 방법”의 가장 기본형, 경사하강법(gradient descent) 을 다룬다.

한 걸음의 규칙

θ\theta에서 손실이 가장 빨리 증가하는 방향은 기울기 ∇L(θ)\nabla L(\theta)다. 그러니 그 반대로 조금 움직인다.

θt+1=θt−η ∇L(θt)\theta_{t+1} = \theta_t - \eta\, \nabla L(\theta_t)

η\eta는 학습률(learning rate), 한 걸음의 크기다. 이 식은 테일러 1차 근사 L(θ+Δ)≈L(θ)+∇L⊤ΔL(\theta + \Delta) \approx L(\theta) + \nabla L^\top \Delta에서 ∥Δ∥\|\Delta\|를 고정했을 때 LL을 가장 많이 줄이는 Δ\Delta가 −∇L-\nabla L 방향이라는 사실에서 나온다. 1차 근사가 맞는 범위 안에서만 옳다는 뜻이기도 하다. 그 범위를 정하는 것이 곡률이다.

그림으로: 학습률과 곡률

아래 손실은 L(x,y)=12(x2+κy2)L(x, y) = \tfrac{1}{2}(x^2 + \kappa y^2) 꼴의 타원형 그릇이다(보기 좋게 상수배 했다). yy 방향이 xx 방향보다 κ\kappa배 가파르다.

step 0loss –
Click the contour plot to pick a start point. As η grows the path zig-zags across the narrow valley and at some point diverges (η > 2/λmax). The larger the condition number κ = λmax/λmin, the slower the gentle direction shrinks at any safe η. Momentum β accumulates speed along that gentle direction. 왼쪽 등고선을 클릭해 출발점을 고르세요. η를 키우면 좁은 골짜기 방향으로 지그재그하다가 어느 순간 발산합니다(η > 2/λmax). 조건수 κ = λmax/λmin가 클수록 안전한 η로는 완만한 방향이 느리게 줄어듭니다. 모멘텀 β는 그 완만한 방향의 속도를 누적해 줍니다.

Check a few things yourself.

  1. Push η all the way right: the path bounces along the yy axis and blows up. The steep direction diverges first.
  2. At an η just below divergence, yy goes to 0 almost immediately but xx shrinks very slowly. At the largest learning rate the steep direction allows, the gentle direction is slow. That is the conditioning problem.
  3. Set κ to 1 (a round bowl): from any start the path heads straight for the centre.
  4. 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 L(θ)=12θ⊤HθL(\theta) = \tfrac12 \theta^\top H \theta the gradient is HθH\theta, so the update is a linear map.

θt+1=(I−ηH) θt\theta_{t+1} = (I - \eta H)\,\theta_t

Split along the eigenvectors of HH and each component is multiplied independently by (1−ηλi)(1 - \eta\lambda_i) every step. Hence

  • if ∣1−ηλi∣<1|1 - \eta\lambda_i| < 1, i.e. 0<η<2/λi0 < \eta < 2/\lambda_i, that direction converges;
  • if ηλi>1\eta\lambda_i > 1, its sign flips every step (zig-zag) while it shrinks;
  • if η>2/λmax⁡\eta > 2/\lambda_{\max}, the steepest direction diverges first.

Even with the best fixed learning rate, the error shrinks by a factor κ−1κ+1\frac{\kappa - 1}{\kappa + 1} per step (κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}). With κ = 100 that is only 2% per step.

Momentum

Momentum carries an exponential moving sum of past gradients around like a velocity.

vt+1=βvt+∇L(θt),θt+1=θt−η vt+1v_{t+1} = \beta v_t + \nabla L(\theta_t), \qquad \theta_{t+1} = \theta_t - \eta\, v_{t+1}

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 η/(1−β)\eta / (1-\beta). On a quadratic with the optimal β the rate improves to κ−1κ+1\frac{\sqrt\kappa - 1}{\sqrt\kappa + 1}. The key point is that κ\sqrt\kappa replaces κ\kappa.

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.

NumPy Gradient descent and momentum — quadratic loss
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 ∇L\nabla L (you build it by hand in Track II’s backprop lesson).

PyTorch PyTorch: what the optimizer does 로컬에서 실행run locally (pip install torch)
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 NN data points, L(θ)=1N∑iℓi(θ)L(\theta) = \frac1N\sum_i \ell_i(\theta). Instead of looking at all of them every step, we estimate the gradient from a minibatch of BB.

g^=1B∑i∈B∇ℓi(θ),E[g^]=∇L(θ),Var⁡[g^]∝1B\hat g = \frac{1}{B}\sum_{i \in \mathcal{B}} \nabla \ell_i(\theta), \qquad \mathbb{E}[\hat g] = \nabla L(\theta), \qquad \operatorname{Var}[\hat g] \propto \frac{1}{B}

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 kk-fold lets you grow the learning rate roughly in proportion (the linear scaling rule).

확인 문제Check yourself

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 2/λmax⁡=2/50=0.042/\lambda_{\max} = 2/50 = 0.04. At that learning rate the gentle direction shrinks only by (1−0.04×0.5)=0.98(1 - 0.04 \times 0.5) = 0.98 per step — the price of a condition number of 100.

Summary

  • GD is θ←θ−η∇L\theta \leftarrow \theta - \eta\nabla L; curvature decides where the first-order approximation holds.
  • The upper limit of a fixed learning rate is 2/λmax⁡2/\lambda_{\max}; the convergence speed is set by the condition number κ\kappa.
  • Momentum accumulates speed in consistent directions, reducing the dependence from κ\kappa to κ\sqrt\kappa.
  • SGD is an unbiased, noisy gradient; learning-rate decay and batch size manage that noise.

몇 가지를 직접 확인해 보자.

  1. η를 오른쪽 끝으로 밀면 경로가 yy축 방향으로 튕기다 터진다. 가파른 방향이 먼저 발산한다.
  2. 발산 직전의 η에서는 yy는 금방 0이 되지만 xx는 아주 느리게 줄어든다. 가파른 방향이 허용하는 최대 학습률로는 완만한 방향이 느리다. 이것이 조건수 문제다.
  3. κ를 1로 내리면(동그란 그릇) 어떤 출발점에서든 곧장 중심으로 간다.
  4. β를 0.9 근처로 올리면 지그재그가 줄고 완만한 방향으로 속도가 붙는다.

왜 2/λ에서 터지는가

이차 손실 L(θ)=12θ⊤HθL(\theta) = \tfrac12 \theta^\top H \theta에서 기울기는 HθH\theta이므로 업데이트는 선형 사상이 된다.

θt+1=(I−ηH) θt\theta_{t+1} = (I - \eta H)\,\theta_t

HH의 고유벡터 방향으로 쪼개 보면 각 성분은 독립적으로 (1−ηλi)(1 - \eta\lambda_i)배씩 곱해진다. 그러므로

  • ∣1−ηλi∣<1|1 - \eta\lambda_i| < 1, 즉 0<η<2/λi0 < \eta < 2/\lambda_i 이면 그 방향은 수렴하고,
  • ηλi>1\eta\lambda_i > 1 이면 부호가 매 step 바뀌며(지그재그) 줄어들고,
  • η>2/λmax⁡\eta > 2/\lambda_{\max} 이면 가장 가파른 방향부터 발산한다.

가장 좋은 고정 학습률을 골라도 수렴 속도는 κ−1κ+1\frac{\kappa - 1}{\kappa + 1} 배씩이다(κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}). κ가 100이면 한 step에 2%만 줄어든다.

모멘텀

모멘텀은 지난 기울기들의 지수이동합을 속도처럼 들고 다닌다.

vt+1=βvt+∇L(θt),θt+1=θt−η vt+1v_{t+1} = \beta v_t + \nabla L(\theta_t), \qquad \theta_{t+1} = \theta_t - \eta\, v_{t+1}

지그재그 방향은 부호가 번갈아 바뀌니 누적하면 상쇄되고, 일정한 방향(완만한 골짜기 바닥)은 누적되어 실효 학습률이 대략 η/(1−β)\eta / (1-\beta)가 된다. 이차 손실에서 최적의 β를 쓰면 수렴률이 κ−1κ+1\frac{\sqrt\kappa - 1}{\sqrt\kappa + 1}로 좋아진다. κ 대신 κ\sqrt\kappa가 들어간다는 점이 핵심이다.

직접 구현하기

아래 코드는 위 그림과 같은 계산을 NumPy로 한다. ▶ 실행을 누르면 브라우저 안에서 돌아간다. 편집으로 lr이나 kappa를 바꿔 보자.

NumPy 경사하강법과 모멘텀 — 이차 손실
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가 계산 그래프를 따라 ∇L\nabla L을 구해 준다(Track II의 역전파 레슨에서 직접 만든다).

PyTorch PyTorch: optimizer가 하는 일 로컬에서 실행run locally (pip install torch)
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)

실제 손실은 데이터 NN개의 평균 L(θ)=1N∑iℓi(θ)L(\theta) = \frac1N\sum_i \ell_i(\theta)이다. 매 step 전체를 보는 대신 미니배치 BB개로 기울기를 추정한다.

g^=1B∑i∈B∇ℓi(θ),E[g^]=∇L(θ),Var⁡[g^]∝1B\hat g = \frac{1}{B}\sum_{i \in \mathcal{B}} \nabla \ell_i(\theta), \qquad \mathbb{E}[\hat g] = \nabla L(\theta), \qquad \operatorname{Var}[\hat g] \propto \frac{1}{B}

추정이 편향 없이 맞으니 평균적으로는 같은 길을 가고, 잡음 때문에 최소점 근처에서 계속 흔들린다. 학습률을 줄여 나가는 스케줄(decay)이 필요한 이유이고, 배치를 kk배 키우면 학습률도 대략 비례해서 키울 수 있는 이유(linear scaling rule)다.

확인 문제Check yourself

H의 고유값이 0.5와 50인 이차 손실에 고정 학습률 GD를 쓴다. 발산하지 않는 가장 큰 학습률은?

발산 경계는 2/λmax⁡=2/50=0.042/\lambda_{\max} = 2/50 = 0.04. 이 학습률에서 완만한 방향은 매 step (1−0.04×0.5)=0.98(1 - 0.04 \times 0.5) = 0.98배씩만 줄어든다. 조건수 100의 대가다.

정리

  • GD는 θ←θ−η∇L\theta \leftarrow \theta - \eta\nabla L. 1차 근사가 맞는 범위가 곡률로 정해진다.
  • 고정 학습률의 상한은 2/λmax⁡2/\lambda_{\max}, 수렴 속도는 조건수 κ\kappa가 결정한다.
  • 모멘텀은 일정한 방향의 속도를 누적해 의존성을 κ→κ\kappa \to \sqrt\kappa로 줄인다.
  • SGD는 편향 없는 잡음 섞인 기울기다. 학습률 감쇠와 배치 크기가 그 잡음을 다룬다.

더 읽을거리Further reading