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 at is the linear map that best approximates nearby:
This defines the gradient ; its components are the partial derivatives (take ). The slope along a unit direction is the directional derivative . For a vector-valued the same statement with a matrix defines the Jacobian , : . A gradient is the transpose of a Jacobian.
The gradient is the direction of steepest ascent
Among unit directions, by Cauchy–Schwarz, with equality only at . So the gradient points where rises fastest, its length is that fastest rate, and is steepest descent. Along a level set , so : the gradient is perpendicular to the contours. (“Steepest” here is measured in ; under another norm the steepest direction changes — see the norm-ball figure.)
학습은 “gradient를 따라간다”, 역전파는 “연쇄법칙을 거꾸로 적용한다”, Adam과 Muon은 “국소 정보로 더 좋은 step을 고른다”, policy gradient는 “기댓값을 미분한다”이다. 모두 미분의 아이디어 하나씩이다. 이 레슨은 그것들을 이 사이트가 쓰는 형태로 진술하고 하나씩 유도한 다음, 손으로 쓴 어떤 gradient든 검증할 수 있는 유한차분 검사기를 만든다.
선형 근사로서의 미분
의 에서의 미분은 근방에서 를 가장 잘 근사하는 선형 사상이다.
이것이 gradient 의 정의이고, 그 성분이 편미분 다(로 두면 된다). 단위 방향 로의 기울기는 방향 미분(directional derivative) 이다. 벡터값 에 대해 같은 진술을 행렬로 하면 Jacobian , 가 정의된다. . gradient는 Jacobian의 전치다.
Gradient는 최급상승 방향이다
단위 방향들 가운데 코시–슈바르츠에 의해 이고, 등호는 에서만 성립한다. 그러니 gradient는 가 가장 빨리 오르는 방향을 가리키고, 그 길이가 그 최대 속도이며, 가 최급강하 방향이다. 등위집합 위에서는 이므로 이다. gradient는 등고선에 수직이다. (여기서 “최급”은 로 잰 것이다. 다른 노름에서는 최급 방향이 바뀐다. 노름 공 그림 참고.)
The chain rule on a computation graph
If and , the linear approximations compose: , so
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 depends on through , then . Example: a residual block has , so the gradient reaching is — the identity path carries through untouched however small is. (Notation: , the “adjoint” of .)
Jacobians, JVPs and VJPs: why reverse mode
For a program from to , . We almost never form ; we multiply it by vectors, and the bracketing decides the cost:
Each is a chain of matrix–vector products costing a small constant times one evaluation of . A JVP gives one column combination of per pass, a VJP one row combination. For a loss () the whole gradient is one VJP with : one backward pass, whatever is. Forward mode would need passes — a billion for an LLM. The price of reverse mode is memory: the backward sweep needs the forward intermediates (each is evaluated at them), which is why activation memory and activation checkpointing exist.
계산 그래프 위의 연쇄법칙
, 이면 선형 근사가 합성된다. 이므로
프로그램은 이런 단계들의 그래프다. 한 변수가 여러 변수로 들어가면(갈래) 전체 미분은 자식들에 대한 합이다. 이 를 통해 에 의존하면 다. 예: residual 블록 는 이므로 에 도달하는 gradient는 다. 가 아무리 작아도 항등 경로가 를 그대로 전달한다. (표기: , 의 “adjoint”.)
Jacobian, JVP, VJP: 왜 reverse mode인가
에서 으로 가는 프로그램 에 대해 이다. 를 직접 만드는 일은 거의 없고 벡터에 곱한다. 괄호를 어디에 치느냐가 비용을 정한다.
둘 다 행렬-벡터 곱의 사슬이고, 비용은 를 한 번 계산하는 비용의 작은 상수배다. JVP는 패스마다 의 열 조합 하나, VJP는 행 조합 하나를 준다. 손실()이면 gradient 전체가 인 VJP 하나다. 이 얼마든 backward 한 번. forward mode라면 번이 필요하다. LLM이라면 십억 번이다. reverse mode의 대가는 메모리다. backward는 forward의 중간값이 필요하다(각 를 그 점에서 계산하므로). activation 메모리와 activation checkpointing이 존재하는 이유다.
The VJPs of a few primitives are all of backprop. For : and (for a batch, in row-major layout). For an elementwise : — 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 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 for all , then (same shape as ). Four results the site uses:
- Quadratic form. , so ( for symmetric ).
- Linear layer, squared error. : , so — an outer product of the output error and the input.
- Softmax and cross-entropy. With , , i.e.
It is symmetric PSD with (adding a constant to every logit changes nothing), and it vanishes as becomes one-hot — saturated attention passes almost no gradient. Its VJP needs no matrix: . Since has gradient , the cross-entropy has gradient .
- Log-determinant. Jacobi’s formula gives — the term that appears in Gaussian log-likelihoods and change-of-variables densities.
The checker below verifies each of these against central differences, , whose error is .
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 forward JVPs, and the explicit product of Jacobians.
# 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가 역전파의 전부다. 이면 , (batch에서는 행 우선 배치로 ). 원소별 이면 . 대각 Jacobian이라 만들지 않는다. Broadcasting과 합은 서로 수반이다. forward가 (D,) bias를 (B,T,D)로 broadcast하면 그 VJP는 를 B와 T에 대해 합한다. 이 합을 틀리는 것이 손으로 쓴 gradient의 고전적인 버그다.
미분(differential)으로 하는 행렬 미분
행렬 gradient를 확실하게 구하는 방법은 미분(differential) 을 쓰고 계수를 읽는 것이다. 모든 에 대해 이면 다(와 같은 shape). 이 사이트가 쓰는 네 가지:
- 이차형식. 이므로 (대칭 이면 ).
- 선형 layer, 제곱 오차. : 이므로 . 출력 오차와 입력의 외적이다.
- Softmax와 cross-entropy. 이면 , 즉
대칭 PSD이고 이다(모든 logit에 상수를 더해도 아무것도 바뀌지 않는다). 가 one-hot에 가까워지면 사라지므로, 포화된 attention은 gradient를 거의 전달하지 않는다. VJP는 행렬 없이 다. 의 gradient가 이므로 cross-entropy 의 gradient는 다.
- Log-determinant. 야코비 공식(Jacobi’s formula) 에서 . Gaussian 로그우도와 변수변환 밀도에 나오는 항이다.
아래 검사기는 이것들을 모두 중심차분 (오차 )과 비교한다.
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 번으로, 그리고 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,
the first-order model’s error is and the second-order model’s . Every optimiser on the site chooses by minimising some model of this kind:
- Gradient descent minimises the linear model plus a proximity penalty, , giving ; says how far the linear model is trusted.
- Newton minimises the quadratic model: , so . Near a minimum with it converges quadratically, but if 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 , with 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 everywhere (-smooth ), then , a guaranteed decrease for — the of the gradient descent lesson.
테일러 모델: GD, Newton, trust region
2차 항까지 더하면
이고, 1차 모델의 오차는 , 2차 모델은 이다. 이 사이트의 모든 optimizer는 이런 모델 하나를 최소화해 를 고른다.
- 경사하강법은 선형 모델에 근접 벌점을 더한 를 최소화해 를 얻는다. 는 선형 모델을 얼마나 멀리까지 믿을지다.
- Newton은 이차 모델을 최소화한다. 이므로 . 인 최솟점 근처에서는 이차 수렴하지만, 에 음의 고유값이 있으면 모델의 정류점이 안장점이나 극대점이 되고, 최솟점에서 멀면 모델이 크게 틀릴 수 있다.
- Trust region은 조건에서 이차 모델을 최소화하고, 모델이 실제 감소를 얼마나 잘 예측했는지에 따라 을 늘리거나 줄인다. TRPO와 PPO는 policy 공간에서의 trust-region 방법이고, KL divergence가 반경이다.
같은 전개에서 descent lemma가 나온다. 모든 곳에서 이면(-smooth ) 이므로 이면 감소가 보장된다. 경사하강법 레슨의 다.
The log-derivative identity
For a positive density , the chain rule on gives , i.e.
Differentiating an expectation then needs no derivative of :
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 shows that the score has zero mean, , so subtracting any constant baseline from leaves the estimator unbiased while possibly reducing its variance. For a softmax policy over logits , (result 3 above). This is REINFORCE, and every policy-gradient objective on the site is built on it.
# --- 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}")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 per pass, so it needs one pass per input direction: . Reverse mode gives per pass, and with output that is the entire gradient: one backward pass, at the price of storing the forward activations.
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, . The gradient is positive, so moving by goes uphill: with the parabola opens downward and its stationary point is a maximum. Practical second-order methods damp or modify (trust regions, Levenberg–Marquardt, positive-definite approximations such as Gauss–Newton) for this reason.
Summary
- The gradient is defined by the best linear approximation ; , maximised along , 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: , , , , . Check them with central differences.
- Taylor models give the steps: GD (linear model plus proximity), Newton (quadratic model), trust region (quadratic within a radius); -smoothness gives .
- turns the gradient of an expectation into an expectation; the score has zero mean, so baselines are free.
Where this is used
- Gradient descent — the first-order Taylor argument and ; optimizers — Newton and diagonal curvature approximations.
- Backprop and autograd — the VJP rules above, built into a working autograd.
- Linear models — cross-entropy gradient ; attention and stability components — the softmax Jacobian and why saturated logits stop learning.
- RNNs — gradients as long products of Jacobians; training deep nets — the of residual connections.
- Policy gradients — the log-derivative trick and baselines; PPO — trust regions; DPO — differentiating a log-sigmoid of log-ratios; the frontier-RL landscape — every objective as a token-weighted score function.
- Next in this track: optimisation (Hessians, convexity, constrained problems), probability (the log-derivative trick as an estimator) and numerics (gradient checking and floating-point error).
Log-derivative 항등식
양의 밀도 에 대해 에 연쇄법칙을 쓰면 , 즉
이다. 그러면 기댓값을 미분하는 데 의 미분이 필요 없다.
는 verifier가 주는 미분 불가능한 보상이어도 된다. 표본과, 표본으로 뽑힌 것의 로그확률 gradient만 있으면 된다. 로 두면 score의 평균이 0임을 알 수 있다. . 그래서 에서 어떤 상수 baseline 를 빼도 추정량은 편향되지 않고 분산만 줄어들 수 있다. logit 위의 softmax policy이면 다(위의 결과 3). 이것이 REINFORCE이고, 이 사이트의 모든 policy gradient 목적함수가 이 위에 서 있다.
# --- 테일러 차수: 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}")매개변수 10^9개, 스칼라 손실인 모델이 있다. 전체 gradient를 forward mode와 reverse mode로 구할 때 각각 대략 몇 번의 패스가 필요한가(패스 하나 ≈ forward 계산 한 번의 몇 배)?
forward mode는 패스마다 방향 미분 하나를 주므로 입력 방향마다 한 번, 번이 필요하다. reverse mode는 패스마다 를 주고, 출력이 개면 그것이 gradient 전체다. forward activation을 저장하는 대가로 backward 한 번이면 된다.
현재 점에서 1차원 손실의 f′ = 2, f″ = −1이다. 순수한 Newton step은 무엇을 하나?
Newton은 이차 모델의 정류점으로 뛴다. . gradient가 양수이므로 만큼 가면 오르막이다. 이면 포물선이 아래로 열려 정류점이 극대점이다. 실용적인 2차 방법이 를 감쇠하거나 고치는(trust region, Levenberg–Marquardt, Gauss–Newton 같은 양의 정부호 근사) 이유다.
정리
- gradient는 최선의 선형 근사 로 정의된다. 는 방향에서 최대, 등고선 방향에서 0이다.
- 연쇄법칙: Jacobian은 곱해지고, 갈래에서는 gradient가 더해진다. residual 연결은 Jacobian에 항등을 더한다.
- JVP는 패스마다 열 하나, VJP는 행 하나를 준다. 스칼라 출력 하나면 reverse mode가 한 번에 gradient를 얻고, 저장한 activation으로 값을 치른다.
- differential로 구하는 행렬 gradient: , , , , . 중심차분으로 확인한다.
- 테일러 모델이 step을 준다. GD(선형 모델 + 근접 항), Newton(이차 모델), trust region(반경 안의 이차 모델). -smooth이면 .
- 는 기댓값의 gradient를 기댓값으로 바꾼다. score의 평균이 0이라 baseline은 공짜다.
이 사이트에서 쓰이는 곳
- 경사하강법 — 1차 테일러 논증과 . Optimizer — Newton과 대각 곡률 근사.
- 역전파와 autograd — 위의 VJP 규칙으로 동작하는 autograd를 만든다.
- 선형 모델 — cross-entropy gradient . Attention과 안정화 구성요소 — softmax Jacobian과 포화된 logit이 학습을 멈추는 이유.
- RNN — Jacobian의 긴 곱으로서의 gradient. 깊은 망 학습 — residual 연결의 .
- Policy gradient — log-derivative trick과 baseline. PPO — trust region. DPO — log-ratio의 log-sigmoid 미분. Frontier RL 지형도 — token 가중 score function으로서의 모든 목적함수.
- 이 트랙의 다음: 최적화(Hessian, 볼록성, 제약 문제), 확률(추정량으로서의 log-derivative trick), 수치 계산(gradient 검사와 부동소수점 오차).
더 읽을거리Further reading
- Petersen & Pedersen, The Matrix Cookbook (2012) — 행렬 미분 공식 모음. 이 레슨의 항등식을 찾아볼 곳A compendium of matrix-derivative identities; where to look up the ones in this lesson
- Baydin, Pearlmutter, Radul, Siskind, Automatic Differentiation in Machine Learning: a Survey (JMLR 18, 2018) — forward/reverse mode, JVP/VJP와 비용을 정리한 서베이Forward and reverse mode, JVPs and VJPs and their costs
- Griewank & Walther, Evaluating Derivatives, 2nd ed. (SIAM, 2008) — 자동미분의 표준 교과서. reverse mode의 비용 상한The standard autodiff text, including cost bounds for reverse mode
- Magnus & Neudecker, Matrix Differential Calculus with Applications in Statistics and Econometrics, 3rd ed. (Wiley, 2019) — 미분(differential)으로 하는 행렬 미분의 정석The canonical treatment of matrix calculus via differentials
- Nocedal & Wright, Numerical Optimization, 2nd ed., ch. 2–4 (Springer, 2006) — 테일러 모델, Newton, trust regionTaylor models, Newton's method and trust regions
- Mohamed, Rosca, Figurnov, Mnih, Monte Carlo Gradient Estimation in Machine Learning (JMLR 21, 2020) — score-function(log-derivative) 추정량과 pathwise 추정량 비교Score-function (log-derivative) versus pathwise gradient estimators