Track 0 · Math Foundations · 03/10

미분·연쇄법칙·JacobianDerivatives, the chain rule and Jacobians

미분을 "가장 좋은 선형 근사"로 읽고, gradient가 왜 최급상승 방향인지, 연쇄법칙이 계산 그래프에서 어떻게 VJP의 사슬이 되는지(그래서 reverse mode), 행렬 미분 몇 가지와 테일러 근사(GD·Newton·trust region), log-derivative 항등식까지 유도하고 수치로 확인한다.Read the derivative as the best linear approximation, then derive why the gradient is the steepest-ascent direction, how the chain rule on a computation graph becomes a chain of VJPs (hence reverse mode), the matrix-calculus results the site uses, Taylor models behind GD, Newton and trust regions, and the log-derivative identity — all checked numerically.

45 분min calculus · gradient · chain rule · Jacobian · autodiff · matrix calculus · Taylor · log-derivative 먼저 볼 것:Before this: 벡터·행렬·텐서Vectors, matrices and tensors

Training is “follow the gradient”, backprop is “apply the chain rule backwards”, Adam and Muon are “choose a better step from local information”, and policy gradients are “differentiate an expectation”. Each of these is one idea from calculus. This lesson states them in the form the rest of the site uses, derives each one, and gives you a finite-difference checker to verify any gradient you ever write by hand.

Derivatives as linear approximations

The derivative of f:Rn→Rf:\mathbb R^n\to\mathbb R at xx is the linear map that best approximates ff nearby:

f(x+h)=f(x)+∇f(x)⊤h+o(∥h∥).f(x+h) = f(x) + \nabla f(x)^\top h + o(\|h\|).

This defines the gradient ∇f(x)∈Rn\nabla f(x)\in\mathbb R^n; its components are the partial derivatives ∂f/∂xi\partial f/\partial x_i (take h=teih = te_i). The slope along a unit direction uu is the directional derivative Duf(x)=lim⁡t→0f(x+tu)−f(x)t=∇f(x)⊤uD_uf(x) = \lim_{t\to0}\frac{f(x+tu)-f(x)}{t} = \nabla f(x)^\top u. For a vector-valued f:Rn→Rmf:\mathbb R^n\to\mathbb R^m the same statement with a matrix defines the Jacobian Jf(x)∈Rm×nJ_f(x)\in\mathbb R^{m\times n}, Jij=∂fi/∂xjJ_{ij} = \partial f_i/\partial x_j: f(x+h)=f(x)+Jf(x)h+o(∥h∥)f(x+h) = f(x) + J_f(x)h + o(\|h\|). A gradient is the transpose of a 1×n1\times n Jacobian.

The gradient is the direction of steepest ascent

Among unit directions, Duf=∇f⊤u≤∥∇f∥2∥u∥2=∥∇f∥2D_uf = \nabla f^\top u \le \|\nabla f\|_2\|u\|_2 = \|\nabla f\|_2 by Cauchy–Schwarz, with equality only at u=∇f/∥∇f∥u = \nabla f/\|\nabla f\|. So the gradient points where ff rises fastest, its length is that fastest rate, and −∇f-\nabla f is steepest descent. Along a level set f(c(t))=constf(c(t)) = \text{const}, so ∇f⊤c′(t)=0\nabla f^\top c'(t) = 0: the gradient is perpendicular to the contours. (“Steepest” here is measured in ℓ2\ell_2; under another norm the steepest direction changes — see the norm-ball figure.)

학습은 “gradient를 따라간다”, 역전파는 “연쇄법칙을 거꾸로 적용한다”, Adam과 Muon은 “국소 정보로 더 좋은 step을 고른다”, policy gradient는 “기댓값을 미분한다”이다. 모두 미분의 아이디어 하나씩이다. 이 레슨은 그것들을 이 사이트가 쓰는 형태로 진술하고 하나씩 유도한 다음, 손으로 쓴 어떤 gradient든 검증할 수 있는 유한차분 검사기를 만든다.

선형 근사로서의 미분

f:Rn→Rf:\mathbb R^n\to\mathbb R의 xx에서의 미분은 근방에서 ff를 가장 잘 근사하는 선형 사상이다.

f(x+h)=f(x)+∇f(x)⊤h+o(∥h∥).f(x+h) = f(x) + \nabla f(x)^\top h + o(\|h\|).

이것이 gradient ∇f(x)∈Rn\nabla f(x)\in\mathbb R^n의 정의이고, 그 성분이 편미분 ∂f/∂xi\partial f/\partial x_i다(h=teih = te_i로 두면 된다). 단위 방향 uu로의 기울기는 방향 미분(directional derivative) Duf(x)=lim⁡t→0f(x+tu)−f(x)t=∇f(x)⊤uD_uf(x) = \lim_{t\to0}\frac{f(x+tu)-f(x)}{t} = \nabla f(x)^\top u이다. 벡터값 f:Rn→Rmf:\mathbb R^n\to\mathbb R^m에 대해 같은 진술을 행렬로 하면 Jacobian Jf(x)∈Rm×nJ_f(x)\in\mathbb R^{m\times n}, Jij=∂fi/∂xjJ_{ij} = \partial f_i/\partial x_j가 정의된다. f(x+h)=f(x)+Jf(x)h+o(∥h∥)f(x+h) = f(x) + J_f(x)h + o(\|h\|). gradient는 1×n1\times n Jacobian의 전치다.

Gradient는 최급상승 방향이다

단위 방향들 가운데 코시–슈바르츠에 의해 Duf=∇f⊤u≤∥∇f∥2∥u∥2=∥∇f∥2D_uf = \nabla f^\top u \le \|\nabla f\|_2\|u\|_2 = \|\nabla f\|_2이고, 등호는 u=∇f/∥∇f∥u = \nabla f/\|\nabla f\|에서만 성립한다. 그러니 gradient는 ff가 가장 빨리 오르는 방향을 가리키고, 그 길이가 그 최대 속도이며, −∇f-\nabla f가 최급강하 방향이다. 등위집합 위에서는 f(c(t))=상수f(c(t)) = \text{상수}이므로 ∇f⊤c′(t)=0\nabla f^\top c'(t) = 0이다. gradient는 등고선에 수직이다. (여기서 “최급”은 ℓ2\ell_2로 잰 것이다. 다른 노름에서는 최급 방향이 바뀐다. 노름 공 그림 참고.)

∇f(P) – ‖∇f‖ – Duf = ∇f·u – 유한차분finite diff. (h=10⁻³) –
Drag the point P (or click anywhere) and turn the direction u. The red arrow ∇f is perpendicular to the contour through P, and the right panel shows the slope of f along every direction: exactly ‖∇f‖·cos(angle to ∇f). Its maximum is at u = ∇f/‖∇f‖ (steepest ascent), its minimum at −∇f (steepest descent), and it is zero along the contour. The dots are finite differences of f itself and sit on the cosine — the first-order Taylor model in action. At the saddle's centre and at the bottom of a well the gradient vanishes and every direction is flat to first order. 점 P를 끌거나(아무 곳이나 클릭) 방향 u를 돌려 보세요. 빨간 화살표 ∇f는 P를 지나는 등고선에 수직이고, 오른쪽은 모든 방향으로의 f의 기울기를 보여 준다. 정확히 ‖∇f‖·cos(∇f와의 각)이다. 최댓값은 u = ∇f/‖∇f‖(최급상승), 최솟값은 −∇f(최급강하), 등고선 방향으로는 0이다. 점들은 f 자체의 유한차분이고 코사인 위에 놓인다. 1차 테일러 모델이 작동하는 모습이다. 안장점 중심과 우물 바닥에서는 gradient가 0이 되어 1차까지는 모든 방향이 평평하다.

The chain rule on a computation graph

If y=g(x)y = g(x) and z=f(y)z = f(y), the linear approximations compose: z(x+h)≈f(g(x)+Jgh)≈z+JfJghz(x+h) \approx f(g(x) + J_g h) \approx z + J_fJ_gh, so

Jf∘g(x)=Jf(g(x)) Jg(x).J_{f\circ g}(x) = J_f(g(x))\,J_g(x).

A program is a graph of such steps. When one variable feeds several others (a fork), its total derivative is the sum over its children: if LL depends on xx through c1,…,ckc_1,\dots,c_k, then ∂L∂x=∑jJcj(x)⊤∂L∂cj\frac{\partial L}{\partial x} = \sum_j J_{c_j}(x)^\top\frac{\partial L}{\partial c_j}. Example: a residual block y=x+F(x)y = x + F(x) has J=I+JFJ = I + J_F, so the gradient reaching xx is yˉ+JF⊤yˉ\bar y + J_F^\top\bar y — the identity path carries yˉ\bar y through untouched however small JFJ_F is. (Notation: vˉ=∂L/∂v\bar v = \partial L/\partial v, the “adjoint” of vv.)

Jacobians, JVPs and VJPs: why reverse mode

For a program f=fK∘⋯∘f1f = f_K\circ\dots\circ f_1 from Rn\mathbb R^n to Rm\mathbb R^m, J=JK⋯J1J = J_K\cdots J_1. We almost never form JJ; we multiply it by vectors, and the bracketing decides the cost:

Jv=JK(⋯(J2(J1v)))⏟JVP: forward mode, with the computationu⊤J=((u⊤JK)JK−1)⋯J1⏟VJP: reverse mode, against it\underbrace{Jv = J_K(\cdots(J_2(J_1v)))}_{\text{JVP: forward mode, with the computation}} \qquad \underbrace{u^\top J = ((u^\top J_K)J_{K-1})\cdots J_1}_{\text{VJP: reverse mode, against it}}

Each is a chain of matrix–vector products costing a small constant times one evaluation of ff. A JVP gives one column combination of JJ per pass, a VJP one row combination. For a loss (m=1m = 1) the whole gradient is one VJP with u=1u = 1: one backward pass, whatever nn is. Forward mode would need nn passes — a billion for an LLM. The price of reverse mode is memory: the backward sweep needs the forward intermediates (each JkJ_k is evaluated at them), which is why activation memory and activation checkpointing exist.

계산 그래프 위의 연쇄법칙

y=g(x)y = g(x), z=f(y)z = f(y)이면 선형 근사가 합성된다. z(x+h)≈f(g(x)+Jgh)≈z+JfJghz(x+h) \approx f(g(x) + J_g h) \approx z + J_fJ_gh이므로

Jf∘g(x)=Jf(g(x)) Jg(x).J_{f\circ g}(x) = J_f(g(x))\,J_g(x).

프로그램은 이런 단계들의 그래프다. 한 변수가 여러 변수로 들어가면(갈래) 전체 미분은 자식들에 대한 합이다. LL이 c1,…,ckc_1,\dots,c_k를 통해 xx에 의존하면 ∂L∂x=∑jJcj(x)⊤∂L∂cj\frac{\partial L}{\partial x} = \sum_j J_{c_j}(x)^\top\frac{\partial L}{\partial c_j}다. 예: residual 블록 y=x+F(x)y = x + F(x)는 J=I+JFJ = I + J_F이므로 xx에 도달하는 gradient는 yˉ+JF⊤yˉ\bar y + J_F^\top\bar y다. JFJ_F가 아무리 작아도 항등 경로가 yˉ\bar y를 그대로 전달한다. (표기: vˉ=∂L/∂v\bar v = \partial L/\partial v, vv의 “adjoint”.)

Jacobian, JVP, VJP: 왜 reverse mode인가

Rn\mathbb R^n에서 Rm\mathbb R^m으로 가는 프로그램 f=fK∘⋯∘f1f = f_K\circ\dots\circ f_1에 대해 J=JK⋯J1J = J_K\cdots J_1이다. JJ를 직접 만드는 일은 거의 없고 벡터에 곱한다. 괄호를 어디에 치느냐가 비용을 정한다.

Jv=JK(⋯(J2(J1v)))⏟JVP: forward mode, 계산과 같은 방향u⊤J=((u⊤JK)JK−1)⋯J1⏟VJP: reverse mode, 반대 방향\underbrace{Jv = J_K(\cdots(J_2(J_1v)))}_{\text{JVP: forward mode, 계산과 같은 방향}} \qquad \underbrace{u^\top J = ((u^\top J_K)J_{K-1})\cdots J_1}_{\text{VJP: reverse mode, 반대 방향}}

둘 다 행렬-벡터 곱의 사슬이고, 비용은 ff를 한 번 계산하는 비용의 작은 상수배다. JVP는 패스마다 JJ의 열 조합 하나, VJP는 행 조합 하나를 준다. 손실(m=1m = 1)이면 gradient 전체가 u=1u = 1인 VJP 하나다. nn이 얼마든 backward 한 번. forward mode라면 nn번이 필요하다. LLM이라면 십억 번이다. reverse mode의 대가는 메모리다. backward는 forward의 중간값이 필요하다(각 JkJ_k를 그 점에서 계산하므로). activation 메모리와 activation checkpointing이 존재하는 이유다.

forward 패스forward passes = n = – reverse 패스reverse passes = m = –
Press a mode. A JVP pushes one input direction v through the program and returns J v — one column per pass when v = ej. A VJP pulls one output weighting u back and returns uᵀJ — one row per pass. Each pass costs a small constant times one evaluation of f. With a scalar loss (m = 1) reverse mode gets the whole gradient in one pass, however large n is; forward mode would need n. That asymmetry is why every deep-learning framework is built on reverse mode. Make m large and n small and the advantage flips. 모드를 눌러 보세요. JVP는 입력 방향 v 하나를 프로그램 앞으로 밀어 J v를 돌려준다. v = ej이면 패스 하나에 열 하나다. VJP는 출력 가중치 u 하나를 뒤로 당겨 uᵀJ를 돌려준다. 패스 하나에 행 하나다. 각 패스의 비용은 f를 한 번 계산하는 비용의 작은 상수배다. 스칼라 손실(m = 1)이면 reverse mode는 n이 아무리 커도 gradient 전체를 한 번에 얻는다. forward mode는 n번이 필요하다. 모든 딥러닝 프레임워크가 reverse mode 위에 세워진 이유가 이 비대칭이다. m을 크게, n을 작게 하면 유리함이 뒤집힌다.

The VJPs of a few primitives are all of backprop. For y=Wxy = Wx: xˉ=W⊤yˉ\bar x = W^\top\bar y and Wˉ=yˉ x⊤\bar W = \bar y\,x^\top (for a batch, Wˉ=Yˉ⊤X\bar W = \bar Y^\top X in row-major layout). For an elementwise y=σ(x)y = \sigma(x): xˉ=σ′(x)⊙yˉ\bar x = \sigma'(x)\odot\bar y — a diagonal Jacobian, never formed. Broadcasting and summing are adjoint: if a forward op broadcasts a (D,) bias over (B,T,D), its VJP sums yˉ\bar y over B and T. Getting that sum wrong is the classic hand-written-gradient bug.

Matrix calculus with differentials

The reliable way to get matrix gradients is to write the differential and read off the coefficient: if df=tr⁡(G⊤dX)df = \operatorname{tr}(G^\top dX) for all dXdX, then ∂f/∂X=G\partial f/\partial X = G (same shape as XX). Four results the site uses:

  1. Quadratic form. d(x⊤Ax)=dx⊤Ax+x⊤A dx=x⊤(A+A⊤)dxd(x^\top Ax) = dx^\top Ax + x^\top A\,dx = x^\top(A+A^\top)dx, so ∇x x⊤Ax=(A+A⊤)x\nabla_x\, x^\top Ax = (A + A^\top)x (=2Ax= 2Ax for symmetric AA).
  2. Linear layer, squared error. f=12∥Wx−y∥2f = \tfrac12\|Wx - y\|^2: df=(Wx−y)⊤dW x=tr⁡(x(Wx−y)⊤dW)df = (Wx-y)^\top dW\,x = \operatorname{tr}\big(x(Wx-y)^\top dW\big), so ∂f/∂W=(Wx−y) x⊤\partial f/\partial W = (Wx - y)\,x^\top — an outer product of the output error and the input.
  3. Softmax and cross-entropy. With pi=ezi/∑kezkp_i = e^{z_i}/\sum_k e^{z_k}, ∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j = p_i(\delta_{ij} - p_j), i.e.
Jsoftmax=diag⁡(p)−pp⊤.J_{\text{softmax}} = \operatorname{diag}(p) - pp^\top .

It is symmetric PSD with J1=0J\mathbf 1 = 0 (adding a constant to every logit changes nothing), and it vanishes as pp becomes one-hot — saturated attention passes almost no gradient. Its VJP needs no matrix: J⊤u=p⊙(u−p⊤u)J^\top u = p\odot(u - p^\top u). Since log⁡∑kezk\log\sum_k e^{z_k} has gradient pp, the cross-entropy −log⁡pk=−zk+log⁡∑ez-\log p_k = -z_k + \log\sum e^{z} has gradient p−ekp - e_k.

  1. Log-determinant. Jacobi’s formula dlog⁡det⁡X=tr⁡(X−1dX)d\log\det X = \operatorname{tr}(X^{-1}dX) gives ∂log⁡det⁡X/∂X=X−⊤\partial\log\det X/\partial X = X^{-\top} — the term that appears in Gaussian log-likelihoods and change-of-variables densities.

The checker below verifies each of these against central differences, f(x+ϵei)−f(x−ϵei)2ϵ\frac{f(x+\epsilon e_i) - f(x-\epsilon e_i)}{2\epsilon}, whose error is O(ϵ2)O(\epsilon^2).

NumPy A finite-difference gradient checker for matrix calculus
import numpy as np
rng = np.random.default_rng(0)

def num_grad(f, X, eps=1e-6):
    """Central-difference gradient of a scalar f with respect to an array X (any shape)."""
    G = np.zeros_like(X, dtype=float)
    it = np.nditer(X, flags=['multi_index'])
    for _ in it:
        i = it.multi_index
        old = X[i]
        X[i] = old + eps; fp = f(X)
        X[i] = old - eps; fm = f(X)
        X[i] = old
        G[i] = (fp - fm) / (2 * eps)
    return G

def check(name, analytic, numeric):
    rel = np.linalg.norm(analytic - numeric) / max(1e-12, np.linalg.norm(analytic) + np.linalg.norm(numeric))
    print(f"{name:36s} rel. error {rel:.1e}  {'✓' if rel < 1e-6 else '✗'}")

n = 5
A = rng.normal(size=(n, n)); x = rng.normal(size=n); y = rng.normal(size=3)
W = rng.normal(size=(3, n)); z = rng.normal(size=n)
Xpd = A @ A.T + n * np.eye(n)                                  # positive definite → det > 0

check("∂/∂x  xᵀAx = (A+Aᵀ)x", (A + A.T) @ x, num_grad(lambda v: v @ A @ v, x.copy()))
check("∂/∂X  tr(AX) = Aᵀ", A.T, num_grad(lambda M: np.trace(A @ M), rng.normal(size=(n, n))))
check("∂/∂W  ½‖Wx−y‖² = (Wx−y)xᵀ", np.outer(W @ x - y, x), num_grad(lambda M: 0.5 * np.sum((M @ x - y) ** 2), W.copy()))
check("∂/∂X  log det X = X⁻ᵀ", np.linalg.inv(Xpd).T, num_grad(lambda M: np.linalg.slogdet(M)[1], Xpd.copy()))
check("∂/∂x  ‖x‖₂ = x/‖x‖₂", x / np.linalg.norm(x), num_grad(lambda v: np.linalg.norm(v), x.copy()))

def softmax(z):
    e = np.exp(z - z.max())
    return e / e.sum()
p = softmax(z)
check("∂/∂z  logsumexp(z) = softmax(z)", p, num_grad(lambda v: np.log(np.exp(v).sum()), z.copy()))
J_num = np.stack([num_grad(lambda v: softmax(v)[i], z.copy()) for i in range(n)])   # row i = ∂p_i/∂z
check("softmax Jacobian = diag(p) − ppᵀ", np.diag(p) - np.outer(p, p), J_num)
k = 2
check("∂/∂z  −log softmax(z)_k = p − e_k", p - np.eye(n)[k], num_grad(lambda v: -np.log(softmax(v)[k]), z.copy()))
u = rng.normal(size=n)
check("VJP Jᵀu = p⊙(u − pᵀu), no J formed", (np.diag(p) - np.outer(p, p)).T @ u, p * (u - u @ p))
 

The second block runs the chain rule by hand on a two-layer network: one reverse sweep of VJPs, the same gradient by nn forward JVPs, and the explicit product of Jacobians.

NumPy Chain rule: reverse sweep vs forward passes vs Jacobian product
# L = w3ᵀ tanh(W2 tanh(W1 x)),  x ∈ R^200
n, h = 200, 64
W1 = rng.normal(size=(h, n)) / np.sqrt(n)
W2 = rng.normal(size=(h, h)) / np.sqrt(h)
w3 = rng.normal(size=h) / np.sqrt(h)
x = rng.normal(size=n)

# forward pass, keeping intermediates (reverse mode needs them)
a1 = W1 @ x; h1 = np.tanh(a1)
a2 = W2 @ h1; h2 = np.tanh(a2)
L = w3 @ h2

# reverse mode: one sweep of vector–Jacobian products, output → input
g_h2 = w3                         # ∂L/∂h2
g_a2 = g_h2 * (1 - h2**2)         # VJP through tanh: diagonal Jacobian
g_h1 = W2.T @ g_a2                # VJP through a matmul: multiply by the transpose
g_a1 = g_h1 * (1 - h1**2)
g_x = W1.T @ g_a1                 # ∂L/∂x, all n entries from ONE backward pass
g_W1 = np.outer(g_a1, x)          # weight gradients fall out on the way

# forward mode: one Jacobian–vector product per input direction
def jvp(v):
    d1 = (1 - h1**2) * (W1 @ v)
    d2 = (1 - h2**2) * (W2 @ d1)
    return w3 @ d2
g_x_fwd = np.array([jvp(e) for e in np.eye(n)])   # n passes for the same vector

# the same thing as an explicit product of Jacobians (1×h)(h×h)(h×h)(h×h)(h×n)
J = w3[None, :] @ np.diag(1 - h2**2) @ W2 @ np.diag(1 - h1**2) @ W1
print("reverse == forward == Jacobian product:", np.allclose(g_x, g_x_fwd), np.allclose(g_x, J[0]))
f = lambda v: w3 @ np.tanh(W2 @ np.tanh(W1 @ v))
print("reverse == finite differences (first 5):", np.allclose(g_x[:5], num_grad(f, x.copy())[:5], atol=1e-7))
E = np.zeros_like(W1); E[3, 7] = 1e-6
fW = lambda M: w3 @ np.tanh(W2 @ np.tanh(M @ x))
print("∂L/∂W1[3,7] == finite difference:", np.isclose(g_W1[3, 7], (fW(W1 + E) - fW(W1 - E)) / 2e-6))
macs = h * n + h * h + h          # multiply-adds of one pass through the three linear maps
print(f"\nfull gradient: reverse 1 pass ≈ {macs:,} MACs;  forward {n} passes ≈ {n * macs:,} MACs")
 

몇 가지 기본 연산의 VJP가 역전파의 전부다. y=Wxy = Wx이면 xˉ=W⊤yˉ\bar x = W^\top\bar y, Wˉ=yˉ x⊤\bar W = \bar y\,x^\top(batch에서는 행 우선 배치로 Wˉ=Yˉ⊤X\bar W = \bar Y^\top X). 원소별 y=σ(x)y = \sigma(x)이면 xˉ=σ′(x)⊙yˉ\bar x = \sigma'(x)\odot\bar y. 대각 Jacobian이라 만들지 않는다. Broadcasting과 합은 서로 수반이다. forward가 (D,) bias를 (B,T,D)로 broadcast하면 그 VJP는 yˉ\bar y를 B와 T에 대해 합한다. 이 합을 틀리는 것이 손으로 쓴 gradient의 고전적인 버그다.

미분(differential)으로 하는 행렬 미분

행렬 gradient를 확실하게 구하는 방법은 미분(differential) 을 쓰고 계수를 읽는 것이다. 모든 dXdX에 대해 df=tr⁡(G⊤dX)df = \operatorname{tr}(G^\top dX)이면 ∂f/∂X=G\partial f/\partial X = G다(XX와 같은 shape). 이 사이트가 쓰는 네 가지:

  1. 이차형식. d(x⊤Ax)=dx⊤Ax+x⊤A dx=x⊤(A+A⊤)dxd(x^\top Ax) = dx^\top Ax + x^\top A\,dx = x^\top(A+A^\top)dx이므로 ∇x x⊤Ax=(A+A⊤)x\nabla_x\, x^\top Ax = (A + A^\top)x(대칭 AA이면 2Ax2Ax).
  2. 선형 layer, 제곱 오차. f=12∥Wx−y∥2f = \tfrac12\|Wx - y\|^2: df=(Wx−y)⊤dW x=tr⁡(x(Wx−y)⊤dW)df = (Wx-y)^\top dW\,x = \operatorname{tr}\big(x(Wx-y)^\top dW\big)이므로 ∂f/∂W=(Wx−y) x⊤\partial f/\partial W = (Wx - y)\,x^\top. 출력 오차와 입력의 외적이다.
  3. Softmax와 cross-entropy. pi=ezi/∑kezkp_i = e^{z_i}/\sum_k e^{z_k}이면 ∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j = p_i(\delta_{ij} - p_j), 즉
Jsoftmax=diag⁡(p)−pp⊤.J_{\text{softmax}} = \operatorname{diag}(p) - pp^\top .

대칭 PSD이고 J1=0J\mathbf 1 = 0이다(모든 logit에 상수를 더해도 아무것도 바뀌지 않는다). pp가 one-hot에 가까워지면 사라지므로, 포화된 attention은 gradient를 거의 전달하지 않는다. VJP는 행렬 없이 J⊤u=p⊙(u−p⊤u)J^\top u = p\odot(u - p^\top u)다. log⁡∑kezk\log\sum_k e^{z_k}의 gradient가 pp이므로 cross-entropy −log⁡pk=−zk+log⁡∑ez-\log p_k = -z_k + \log\sum e^{z}의 gradient는 p−ekp - e_k다.

  1. Log-determinant. 야코비 공식(Jacobi’s formula) dlog⁡det⁡X=tr⁡(X−1dX)d\log\det X = \operatorname{tr}(X^{-1}dX)에서 ∂log⁡det⁡X/∂X=X−⊤\partial\log\det X/\partial X = X^{-\top}. Gaussian 로그우도와 변수변환 밀도에 나오는 항이다.

아래 검사기는 이것들을 모두 중심차분 f(x+ϵei)−f(x−ϵei)2ϵ\frac{f(x+\epsilon e_i) - f(x-\epsilon e_i)}{2\epsilon}(오차 O(ϵ2)O(\epsilon^2))과 비교한다.

NumPy 행렬 미분을 위한 유한차분 gradient 검사기
import numpy as np
rng = np.random.default_rng(0)

def num_grad(f, X, eps=1e-6):
    """스칼라 f 의 배열 X(임의 shape)에 대한 중심차분 gradient."""
    G = np.zeros_like(X, dtype=float)
    it = np.nditer(X, flags=['multi_index'])
    for _ in it:
        i = it.multi_index
        old = X[i]
        X[i] = old + eps; fp = f(X)
        X[i] = old - eps; fm = f(X)
        X[i] = old
        G[i] = (fp - fm) / (2 * eps)
    return G

def check(name, analytic, numeric):
    rel = np.linalg.norm(analytic - numeric) / max(1e-12, np.linalg.norm(analytic) + np.linalg.norm(numeric))
    print(f"{name:36s} 상대 오차 {rel:.1e}  {'✓' if rel < 1e-6 else '✗'}")

n = 5
A = rng.normal(size=(n, n)); x = rng.normal(size=n); y = rng.normal(size=3)
W = rng.normal(size=(3, n)); z = rng.normal(size=n)
Xpd = A @ A.T + n * np.eye(n)                                  # 양의 정부호 → det > 0

check("∂/∂x  xᵀAx = (A+Aᵀ)x", (A + A.T) @ x, num_grad(lambda v: v @ A @ v, x.copy()))
check("∂/∂X  tr(AX) = Aᵀ", A.T, num_grad(lambda M: np.trace(A @ M), rng.normal(size=(n, n))))
check("∂/∂W  ½‖Wx−y‖² = (Wx−y)xᵀ", np.outer(W @ x - y, x), num_grad(lambda M: 0.5 * np.sum((M @ x - y) ** 2), W.copy()))
check("∂/∂X  log det X = X⁻ᵀ", np.linalg.inv(Xpd).T, num_grad(lambda M: np.linalg.slogdet(M)[1], Xpd.copy()))
check("∂/∂x  ‖x‖₂ = x/‖x‖₂", x / np.linalg.norm(x), num_grad(lambda v: np.linalg.norm(v), x.copy()))

def softmax(z):
    e = np.exp(z - z.max())
    return e / e.sum()
p = softmax(z)
check("∂/∂z  logsumexp(z) = softmax(z)", p, num_grad(lambda v: np.log(np.exp(v).sum()), z.copy()))
J_num = np.stack([num_grad(lambda v: softmax(v)[i], z.copy()) for i in range(n)])   # i 행 = ∂p_i/∂z
check("softmax Jacobian = diag(p) − ppᵀ", np.diag(p) - np.outer(p, p), J_num)
k = 2
check("∂/∂z  −log softmax(z)_k = p − e_k", p - np.eye(n)[k], num_grad(lambda v: -np.log(softmax(v)[k]), z.copy()))
u = rng.normal(size=n)
check("VJP Jᵀu = p⊙(u − pᵀu), J 없이", (np.diag(p) - np.outer(p, p)).T @ u, p * (u - u @ p))
 

두 번째 블록은 2층 신경망에서 연쇄법칙을 손으로 돌린다. VJP의 reverse sweep 한 번, 같은 gradient를 forward JVP nn번으로, 그리고 Jacobian들의 명시적 곱으로.

NumPy 연쇄법칙: reverse sweep vs forward 패스 vs Jacobian 곱
# L = w3ᵀ tanh(W2 tanh(W1 x)),  x ∈ R^200
n, h = 200, 64
W1 = rng.normal(size=(h, n)) / np.sqrt(n)
W2 = rng.normal(size=(h, h)) / np.sqrt(h)
w3 = rng.normal(size=h) / np.sqrt(h)
x = rng.normal(size=n)

# forward pass, 중간값을 저장한다 (reverse mode 에 필요)
a1 = W1 @ x; h1 = np.tanh(a1)
a2 = W2 @ h1; h2 = np.tanh(a2)
L = w3 @ h2

# reverse mode: 출력 → 입력으로 vector–Jacobian product 를 한 번 훑는다
g_h2 = w3                         # ∂L/∂h2
g_a2 = g_h2 * (1 - h2**2)         # tanh 의 VJP: 대각 Jacobian
g_h1 = W2.T @ g_a2                # matmul 의 VJP: 전치를 곱한다
g_a1 = g_h1 * (1 - h1**2)
g_x = W1.T @ g_a1                 # ∂L/∂x, n 개 성분 전부가 backward 한 번에서
g_W1 = np.outer(g_a1, x)          # weight gradient 는 가는 길에 나온다

# forward mode: 입력 방향마다 Jacobian–vector product 하나
def jvp(v):
    d1 = (1 - h1**2) * (W1 @ v)
    d2 = (1 - h2**2) * (W2 @ d1)
    return w3 @ d2
g_x_fwd = np.array([jvp(e) for e in np.eye(n)])   # 같은 벡터를 위해 n 번

# 같은 것을 Jacobian 의 명시적 곱으로 (1×h)(h×h)(h×h)(h×h)(h×n)
J = w3[None, :] @ np.diag(1 - h2**2) @ W2 @ np.diag(1 - h1**2) @ W1
print("reverse == forward == Jacobian 곱:", np.allclose(g_x, g_x_fwd), np.allclose(g_x, J[0]))
f = lambda v: w3 @ np.tanh(W2 @ np.tanh(W1 @ v))
print("reverse == 유한차분 (앞 5개):", np.allclose(g_x[:5], num_grad(f, x.copy())[:5], atol=1e-7))
E = np.zeros_like(W1); E[3, 7] = 1e-6
fW = lambda M: w3 @ np.tanh(W2 @ np.tanh(M @ x))
print("∂L/∂W1[3,7] == 유한차분:", np.isclose(g_W1[3, 7], (fW(W1 + E) - fW(W1 - E)) / 2e-6))
macs = h * n + h * h + h          # 세 선형 사상을 한 번 통과하는 곱셈-덧셈 수
print(f"\n전체 gradient: reverse 1 패스 ≈ {macs:,} MACs;  forward {n} 패스 ≈ {n * macs:,} MACs")
 

Taylor models: GD, Newton and trust regions

Adding the second-order term,

f(x+Δ)=f(x)+g⊤Δ+12Δ⊤HΔ+O(∥Δ∥3),g=∇f(x), H=∇2f(x),f(x+\Delta) = f(x) + g^\top\Delta + \tfrac12\Delta^\top H\Delta + O(\|\Delta\|^3), \qquad g = \nabla f(x),\ H = \nabla^2 f(x),

the first-order model’s error is O(∥Δ∥2)O(\|\Delta\|^2) and the second-order model’s O(∥Δ∥3)O(\|\Delta\|^3). Every optimiser on the site chooses Δ\Delta by minimising some model of this kind:

  • Gradient descent minimises the linear model plus a proximity penalty, g⊤Δ+12η∥Δ∥2g^\top\Delta + \frac1{2\eta}\|\Delta\|^2, giving Δ=−ηg\Delta = -\eta g; η\eta says how far the linear model is trusted.
  • Newton minimises the quadratic model: g+HΔ=0g + H\Delta = 0, so Δ=−H−1g\Delta = -H^{-1}g. Near a minimum with H≻0H\succ0 it converges quadratically, but if HH has a negative eigenvalue the model’s stationary point is a saddle or maximum, and far from the minimum the model can be badly wrong.
  • Trust region minimises the quadratic model subject to ∥Δ∥≤r\|\Delta\| \le r, with rr grown or shrunk according to how well the model predicted the actual decrease. TRPO and PPO are trust-region methods in policy space, with KL divergence as the radius.

The same expansion gives the descent lemma. If ∥H∥2≤L\|H\|_2 \le L everywhere (LL-smooth ff), then f(x−ηg)≤f(x)−η(1−ηL2)∥g∥2f(x - \eta g) \le f(x) - \eta\big(1 - \tfrac{\eta L}{2}\big)\|g\|^2, a guaranteed decrease for η<2/L\eta < 2/L — the 2/λmax⁡2/\lambda_{\max} of the gradient descent lesson.

테일러 모델: GD, Newton, trust region

2차 항까지 더하면

f(x+Δ)=f(x)+g⊤Δ+12Δ⊤HΔ+O(∥Δ∥3),g=∇f(x), H=∇2f(x)f(x+\Delta) = f(x) + g^\top\Delta + \tfrac12\Delta^\top H\Delta + O(\|\Delta\|^3), \qquad g = \nabla f(x),\ H = \nabla^2 f(x)

이고, 1차 모델의 오차는 O(∥Δ∥2)O(\|\Delta\|^2), 2차 모델은 O(∥Δ∥3)O(\|\Delta\|^3)이다. 이 사이트의 모든 optimizer는 이런 모델 하나를 최소화해 Δ\Delta를 고른다.

  • 경사하강법은 선형 모델에 근접 벌점을 더한 g⊤Δ+12η∥Δ∥2g^\top\Delta + \frac1{2\eta}\|\Delta\|^2를 최소화해 Δ=−ηg\Delta = -\eta g를 얻는다. η\eta는 선형 모델을 얼마나 멀리까지 믿을지다.
  • Newton은 이차 모델을 최소화한다. g+HΔ=0g + H\Delta = 0이므로 Δ=−H−1g\Delta = -H^{-1}g. H≻0H\succ0인 최솟점 근처에서는 이차 수렴하지만, HH에 음의 고유값이 있으면 모델의 정류점이 안장점이나 극대점이 되고, 최솟점에서 멀면 모델이 크게 틀릴 수 있다.
  • Trust region은 ∥Δ∥≤r\|\Delta\| \le r 조건에서 이차 모델을 최소화하고, 모델이 실제 감소를 얼마나 잘 예측했는지에 따라 rr을 늘리거나 줄인다. TRPO와 PPO는 policy 공간에서의 trust-region 방법이고, KL divergence가 반경이다.

같은 전개에서 descent lemma가 나온다. 모든 곳에서 ∥H∥2≤L\|H\|_2 \le L이면(LL-smooth ff) f(x−ηg)≤f(x)−η(1−ηL2)∥g∥2f(x - \eta g) \le f(x) - \eta\big(1 - \tfrac{\eta L}{2}\big)\|g\|^2이므로 η<2/L\eta < 2/L이면 감소가 보장된다. 경사하강법 레슨의 2/λmax⁡2/\lambda_{\max}다.

f′(x₀) – f″(x₀) – GD x₀−ηf′ – Newton x₀−f′/f″ – trust region –
Move x₀ and the probe Δ. Blue is the tangent (1st order), red the parabola (2nd order); the shaded band is where the parabola is within 0.05 of f — the region you can trust it. On the right, both errors fall as straight lines on log–log axes with slopes 2 and 3: halving Δ cuts the linear model's error 4× and the quadratic's 8×. The green dot is a GD step: it uses only the slope, and η decides how far to believe it. The violet dot is Newton's step to the parabola's vertex: excellent near a minimum, but on the double well with f″ < 0 it jumps to a maximum, and on log cosh far from the minimum it overshoots wildly. The amber trust-region step minimises the parabola only inside the band. x₀와 탐침 Δ를 움직여 보세요. 파랑은 접선(1차), 빨강은 포물선(2차)이고, 색칠된 띠는 포물선이 f와 0.05 이내로 맞는 영역, 즉 믿어도 되는 곳이다. 오른쪽에서 두 오차는 log–log 축 위의 기울기 2와 3인 직선이다. Δ를 반으로 줄이면 1차 모델 오차는 4배, 2차는 8배 줄어든다. 초록 점은 GD step이다. 기울기만 쓰고, η가 그것을 얼마나 믿을지 정한다. 보라 점은 포물선 꼭짓점으로 가는 Newton step이다. 최솟점 근처에서는 훌륭하지만, 이중 우물에서 f″ < 0이면 극대점으로 뛰고, log cosh에서 최솟점과 멀면 크게 지나친다. 주황 trust-region step은 띠 안에서만 포물선을 최소화한다.

The log-derivative identity

For a positive density pθp_\theta, the chain rule on log⁡\log gives ∇θlog⁡pθ=∇θpθ/pθ\nabla_\theta\log p_\theta = \nabla_\theta p_\theta/p_\theta, i.e.

∇θpθ(x)=pθ(x) ∇θlog⁡pθ(x).\nabla_\theta p_\theta(x) = p_\theta(x)\,\nabla_\theta\log p_\theta(x).

Differentiating an expectation then needs no derivative of ff:

∇θ Ex∼pθ[f(x)]=∫f(x) ∇θpθ(x) dx=Ex∼pθ[f(x) ∇θlog⁡pθ(x)].\nabla_\theta\,\mathbb E_{x\sim p_\theta}[f(x)] = \int f(x)\,\nabla_\theta p_\theta(x)\,dx = \mathbb E_{x\sim p_\theta}\big[f(x)\,\nabla_\theta\log p_\theta(x)\big].

ff can be a non-differentiable reward from a verifier; we only need samples and the gradient of the log-probability of what was sampled. Taking f≡1f \equiv 1 shows that the score has zero mean, E[∇log⁡pθ]=∇∫pθ=0\mathbb E[\nabla\log p_\theta] = \nabla\int p_\theta = 0, so subtracting any constant baseline bb from ff leaves the estimator unbiased while possibly reducing its variance. For a softmax policy over logits θ\theta, ∇θlog⁡softmax⁡(θ)x=ex−p\nabla_\theta\log\operatorname{softmax}(\theta)_x = e_x - p (result 3 above). This is REINFORCE, and every policy-gradient objective on the site is built on it.

NumPy Taylor orders, GD vs Newton, and the log-derivative trick
# --- Taylor orders: halve h, the error drops 4× (1st order) and 8× (2nd order)
f   = lambda x: np.exp(np.sin(x))
df  = lambda x: np.cos(x) * f(x)
d2f = lambda x: (np.cos(x)**2 - np.sin(x)) * f(x)
x0 = -0.5
print(" h        |f−T1|     ratio   |f−T2|     ratio")
prev = None
for h in [0.1, 0.05, 0.025, 0.0125]:
    e1 = abs(f(x0 + h) - (f(x0) + df(x0) * h))
    e2 = abs(f(x0 + h) - (f(x0) + df(x0) * h + 0.5 * d2f(x0) * h**2))
    r = f"{prev[0]/e1:6.2f}   {e2:.2e}  {prev[1]/e2:6.2f}" if prev else f"   –     {e2:.2e}     –"
    print(f"{h:<8} {e1:.2e}  {r}")
    prev = (e1, e2)

# --- GD vs Newton on g(x) = eˣ − 2x (minimum at ln 2) ------------------------
xg = xn = 2.0
print("\niter   GD error (lr 0.2)   Newton error")
for it in range(1, 7):
    xg -= 0.2 * (np.exp(xg) - 2)
    xn -= (np.exp(xn) - 2) / np.exp(xn)        # minimise the local quadratic
    print(f"{it:4d}   {abs(xg - np.log(2)):.3e}          {abs(xn - np.log(2)):.3e}")

# --- log-derivative trick: ∇θ E_{x~pθ}[f(x)] = E[f(x) ∇θ log pθ(x)] ------------
theta = np.array([0.5, -0.2, 0.1, 1.0])          # logits of a categorical "policy"
r = np.array([1.0, 0.0, 2.0, -1.0])              # reward of each action
p = np.exp(theta - theta.max()); p /= p.sum()
exact = p * (r - p @ r)                           # Jᵀ r with J = diag(p) − ppᵀ
x = rng.choice(4, size=200_000, p=p)              # sample actions
score = np.eye(4)[x] - p                          # ∇θ log softmax(θ)_x = e_x − p
est = (r[x][:, None] * score).mean(0)
est_b = ((r[x] - p @ r)[:, None] * score).mean(0) # with a baseline b = E[r]
print("\nexact gradient   ", np.round(exact, 4))
print("score-function MC", np.round(est, 4))
print("  with baseline   ", np.round(est_b, 4))
print(f"per-sample variance: no baseline {(r[x][:, None] * score).var(0).sum():.3f}  with baseline {((r[x] - p @ r)[:, None] * score).var(0).sum():.3f}")
 
확인 문제Check yourself

A model has 10^9 parameters and a scalar loss. Roughly how many passes does computing the full gradient take in forward mode and in reverse mode (each pass ≈ a few times the cost of one forward evaluation)?

Forward mode gives one directional derivative JvJv per pass, so it needs one pass per input direction: 10910^9. Reverse mode gives u⊤Ju^\top J per pass, and with m=1m = 1 output that is the entire gradient: one backward pass, at the price of storing the forward activations.

확인 문제Check yourself

At the current point a 1-D loss has f′ = 2 and f″ = −1. What does a pure Newton step do?

Newton jumps to the stationary point of the quadratic model, Δ=−f′/f′′=−2/(−1)=+2\Delta = -f'/f'' = -2/(-1) = +2. The gradient is positive, so moving by +2+2 goes uphill: with f′′<0f'' < 0 the parabola opens downward and its stationary point is a maximum. Practical second-order methods damp or modify HH (trust regions, Levenberg–Marquardt, positive-definite approximations such as Gauss–Newton) for this reason.

Summary

  • The gradient is defined by the best linear approximation f(x+h)≈f(x)+∇f⊤hf(x+h)\approx f(x)+\nabla f^\top h; Duf=∇f⊤uD_uf = \nabla f^\top u, maximised along ∇f\nabla f, zero along contours.
  • Chain rule: Jacobians multiply; at forks, gradients add. Residual connections add an identity to the Jacobian.
  • A JVP gives a column per pass, a VJP a row. With one scalar output reverse mode gets the gradient in one pass, paying in stored activations.
  • Matrix gradients from differentials: (A+A⊤)x(A+A^\top)x, (Wx−y)x⊤(Wx-y)x^\top, diag⁡(p)−pp⊤\operatorname{diag}(p)-pp^\top, p−ekp - e_k, X−⊤X^{-\top}. Check them with central differences.
  • Taylor models give the steps: GD (linear model plus proximity), Newton (quadratic model), trust region (quadratic within a radius); LL-smoothness gives η<2/L\eta < 2/L.
  • ∇p=p∇log⁡p\nabla p = p\nabla\log p turns the gradient of an expectation into an expectation; the score has zero mean, so baselines are free.

Where this is used

Log-derivative 항등식

양의 밀도 pθp_\theta에 대해 log⁡\log에 연쇄법칙을 쓰면 ∇θlog⁡pθ=∇θpθ/pθ\nabla_\theta\log p_\theta = \nabla_\theta p_\theta/p_\theta, 즉

∇θpθ(x)=pθ(x) ∇θlog⁡pθ(x)\nabla_\theta p_\theta(x) = p_\theta(x)\,\nabla_\theta\log p_\theta(x)

이다. 그러면 기댓값을 미분하는 데 ff의 미분이 필요 없다.

∇θ Ex∼pθ[f(x)]=∫f(x) ∇θpθ(x) dx=Ex∼pθ[f(x) ∇θlog⁡pθ(x)].\nabla_\theta\,\mathbb E_{x\sim p_\theta}[f(x)] = \int f(x)\,\nabla_\theta p_\theta(x)\,dx = \mathbb E_{x\sim p_\theta}\big[f(x)\,\nabla_\theta\log p_\theta(x)\big].

ff는 verifier가 주는 미분 불가능한 보상이어도 된다. 표본과, 표본으로 뽑힌 것의 로그확률 gradient만 있으면 된다. f≡1f \equiv 1로 두면 score의 평균이 0임을 알 수 있다. E[∇log⁡pθ]=∇∫pθ=0\mathbb E[\nabla\log p_\theta] = \nabla\int p_\theta = 0. 그래서 ff에서 어떤 상수 baseline bb를 빼도 추정량은 편향되지 않고 분산만 줄어들 수 있다. logit θ\theta 위의 softmax policy이면 ∇θlog⁡softmax⁡(θ)x=ex−p\nabla_\theta\log\operatorname{softmax}(\theta)_x = e_x - p다(위의 결과 3). 이것이 REINFORCE이고, 이 사이트의 모든 policy gradient 목적함수가 이 위에 서 있다.

NumPy 테일러 차수, GD vs Newton, log-derivative trick
# --- 테일러 차수: h 를 반으로 줄이면 오차가 4배(1차), 8배(2차) 줄어든다
f   = lambda x: np.exp(np.sin(x))
df  = lambda x: np.cos(x) * f(x)
d2f = lambda x: (np.cos(x)**2 - np.sin(x)) * f(x)
x0 = -0.5
print(" h        |f−T1|     비      |f−T2|     비")
prev = None
for h in [0.1, 0.05, 0.025, 0.0125]:
    e1 = abs(f(x0 + h) - (f(x0) + df(x0) * h))
    e2 = abs(f(x0 + h) - (f(x0) + df(x0) * h + 0.5 * d2f(x0) * h**2))
    r = f"{prev[0]/e1:6.2f}   {e2:.2e}  {prev[1]/e2:6.2f}" if prev else f"   –     {e2:.2e}     –"
    print(f"{h:<8} {e1:.2e}  {r}")
    prev = (e1, e2)

# --- g(x) = eˣ − 2x 에서 GD vs Newton (최솟점 ln 2) ---------------------------
xg = xn = 2.0
print("\niter   GD 오차 (lr 0.2)    Newton 오차")
for it in range(1, 7):
    xg -= 0.2 * (np.exp(xg) - 2)
    xn -= (np.exp(xn) - 2) / np.exp(xn)        # 국소 이차 모델의 최소점
    print(f"{it:4d}   {abs(xg - np.log(2)):.3e}          {abs(xn - np.log(2)):.3e}")

# --- log-derivative trick: ∇θ E_{x~pθ}[f(x)] = E[f(x) ∇θ log pθ(x)] ------------
theta = np.array([0.5, -0.2, 0.1, 1.0])          # 범주형 "policy" 의 logit
r = np.array([1.0, 0.0, 2.0, -1.0])              # 행동별 보상
p = np.exp(theta - theta.max()); p /= p.sum()
exact = p * (r - p @ r)                           # Jᵀ r, J = diag(p) − ppᵀ
x = rng.choice(4, size=200_000, p=p)              # 행동 표본
score = np.eye(4)[x] - p                          # ∇θ log softmax(θ)_x = e_x − p
est = (r[x][:, None] * score).mean(0)
est_b = ((r[x] - p @ r)[:, None] * score).mean(0) # baseline b = E[r] 를 뺀 것
print("\n정확한 gradient  ", np.round(exact, 4))
print("score-function MC", np.round(est, 4))
print("  baseline 포함   ", np.round(est_b, 4))
print(f"표본당 분산: baseline 없음 {(r[x][:, None] * score).var(0).sum():.3f}  baseline 있음 {((r[x] - p @ r)[:, None] * score).var(0).sum():.3f}")
 
확인 문제Check yourself

매개변수 10^9개, 스칼라 손실인 모델이 있다. 전체 gradient를 forward mode와 reverse mode로 구할 때 각각 대략 몇 번의 패스가 필요한가(패스 하나 ≈ forward 계산 한 번의 몇 배)?

forward mode는 패스마다 방향 미분 JvJv 하나를 주므로 입력 방향마다 한 번, 10910^9번이 필요하다. reverse mode는 패스마다 u⊤Ju^\top J를 주고, 출력이 m=1m = 1개면 그것이 gradient 전체다. forward activation을 저장하는 대가로 backward 한 번이면 된다.

확인 문제Check yourself

현재 점에서 1차원 손실의 f′ = 2, f″ = −1이다. 순수한 Newton step은 무엇을 하나?

Newton은 이차 모델의 정류점으로 뛴다. Δ=−f′/f′′=−2/(−1)=+2\Delta = -f'/f'' = -2/(-1) = +2. gradient가 양수이므로 +2+2만큼 가면 오르막이다. f′′<0f'' < 0이면 포물선이 아래로 열려 정류점이 극대점이다. 실용적인 2차 방법이 HH를 감쇠하거나 고치는(trust region, Levenberg–Marquardt, Gauss–Newton 같은 양의 정부호 근사) 이유다.

정리

  • gradient는 최선의 선형 근사 f(x+h)≈f(x)+∇f⊤hf(x+h)\approx f(x)+\nabla f^\top h로 정의된다. Duf=∇f⊤uD_uf = \nabla f^\top u는 ∇f\nabla f 방향에서 최대, 등고선 방향에서 0이다.
  • 연쇄법칙: Jacobian은 곱해지고, 갈래에서는 gradient가 더해진다. residual 연결은 Jacobian에 항등을 더한다.
  • JVP는 패스마다 열 하나, VJP는 행 하나를 준다. 스칼라 출력 하나면 reverse mode가 한 번에 gradient를 얻고, 저장한 activation으로 값을 치른다.
  • differential로 구하는 행렬 gradient: (A+A⊤)x(A+A^\top)x, (Wx−y)x⊤(Wx-y)x^\top, diag⁡(p)−pp⊤\operatorname{diag}(p)-pp^\top, p−ekp - e_k, X−⊤X^{-\top}. 중심차분으로 확인한다.
  • 테일러 모델이 step을 준다. GD(선형 모델 + 근접 항), Newton(이차 모델), trust region(반경 안의 이차 모델). LL-smooth이면 η<2/L\eta < 2/L.
  • ∇p=p∇log⁡p\nabla p = p\nabla\log p는 기댓값의 gradient를 기댓값으로 바꾼다. score의 평균이 0이라 baseline은 공짜다.

이 사이트에서 쓰이는 곳

더 읽을거리Further reading