Almost every object on this site is the solution of an optimisation problem. Training minimises a loss; softmax is the solution of a regularised argmax; the RLHF policy is the solution of a KL-constrained reward maximisation; PPO, TRPO and Kimi’s mirror descent are ways of taking a constrained step. This lesson collects the tools needed to read those statements: what a stationary point is and how curvature classifies it, why convexity makes “local” mean “global”, Jensen’s inequality, and Lagrange multipliers with the KKT conditions. We then use them to derive three results the later tracks lean on.
First- and second-order conditions
Take a twice-differentiable and expand it around (calculus lesson):
- First order (necessary). If is a local minimum then . Otherwise makes the linear term negative and, for small , dominates. Points with are stationary points.
- Second order. At a stationary point the quadratic term decides. A local minimum requires (positive semidefinite); and (positive definite) is sufficient for a strict local minimum.
Because is symmetric it has an orthonormal eigenbasis (eigen/SVD lesson). Writing , the quadratic term becomes , a sum of independent one-dimensional parabolas. The curvature in a unit direction is the Rayleigh quotient
a weighted average of eigenvalues, with the extremes reached on the eigenvectors. So the signs of the eigenvalues classify a stationary point: all positive → minimum, all negative → maximum, at least one positive and one negative → saddle (zero eigenvalues do not change this: is a saddle, since already rises along one axis and falls along another). Only when some eigenvalues are zero and the rest share one sign (a singular semidefinite ) does the second-order test say nothing (look at higher orders, e.g. versus ).
이 사이트의 거의 모든 대상은 어떤 최적화 문제의 해다. 학습은 손실을 최소화하고, softmax는 정규화된 argmax의 해이며, RLHF 정책은 KL로 제약된 보상 최대화의 해이고, PPO·TRPO·Kimi의 mirror descent는 제약 아래서 한 걸음을 내딛는 방법이다. 이 레슨은 그런 문장을 읽는 데 필요한 도구를 모은다. 정류점이 무엇이고 곡률이 그것을 어떻게 분류하는지, 왜 볼록성이 “국소”를 “전역”으로 만드는지, Jensen 부등식, 그리고 라그랑주 승수와 KKT 조건. 그 다음 이 도구로 뒤 트랙이 기대는 결과 셋을 유도한다.
1차·2차 조건
두 번 미분 가능한 를 근처에서 전개한다(미적분 레슨).
- 1차 조건(필요조건). 가 국소 최소이면 이다. 아니라면 가 1차 항을 음수로 만들고, 이 작으면 그 항이 나머지를 이긴다. 인 점을 정류점(stationary point) 이라 한다.
- 2차 조건. 정류점에서는 2차 항이 결정한다. 국소 최소이려면 (양의 준정부호)이어야 하고, 이고 (양의 정부호)이면 엄격한 국소 최소가 보장된다.
는 대칭이므로 정규직교 고유기저 를 가진다(고유값·SVD 레슨). 로 쓰면 2차 항은 , 서로 독립인 1차원 포물선들의 합이 된다. 단위 방향 의 곡률은 Rayleigh 몫이다.
고유값의 가중평균이고, 양 끝은 고유벡터 방향에서 나온다. 그래서 고유값의 부호가 정류점을 분류한다. 모두 양수면 최소, 모두 음수면 최대, 양수와 음수가 하나 이상씩 있으면 안장점(saddle)이다(0인 고유값이 있어도 마찬가지다. 은 한 축으로는 올라가고 다른 축으로는 내려가므로 안장점이다). 일부 고유값이 0이고 나머지가 모두 같은 부호일 때(특이한 반정부호 )만 2차 판정이 아무 말도 못 한다(더 높은 차수를 봐야 한다. 예: 와 ).
Things to try:
- With the bowl is convex and gradient descent zig-zags less along the flat eigenvector than along the steep one — the condition number of the gradient-descent lesson.
- Push to : a flat valley. Every point on the valley floor is a minimiser, gradient descent stops wherever it hits the floor, and the Newton step is undefined.
- Push to : a saddle. Gradient descent escapes along the negative-curvature eigenvector (that component is multiplied by each step), but Newton still jumps to the saddle.
Newton’s method minimises the quadratic model instead of the linear one: setting the gradient of to zero gives . On a quadratic it is exact in one step regardless of — it divides each eigen-direction by its own curvature. But it looks for , not for a minimum: with an indefinite it is attracted to saddles. And saddles are common in the loss landscapes we care about: for random-function models (Gaussian random fields, Bray & Dean 2007) and in the empirical study of neural-network losses by Dauphin et al. (2014), critical points with high loss are overwhelmingly saddles. This is an observation about such landscapes, not a law of high dimension: has exactly two minima and one saddle for every . Storing and inverting an Hessian is also out of the question for . What survives in deep learning are cheap preconditioners that imitate : Adam’s per-coordinate scaling (optimizers) and Muon’s orthogonalised update (Muon). GPTQ uses the exact Hessian of a layer-wise quadratic (quantisation).
Convexity
A set is convex if the segment between any two of its points stays inside. A function on a convex set is convex if
— the chord lies above the graph. For differentiable there are two equivalent tests:
The first-order form has the consequence that matters most: if , then for every . For a convex function every stationary point is a global minimum, and the set of minimisers is convex (a point, or a flat valley as in step 2 above). Strictly convex () means at most one minimiser. -strongly convex and -smooth () gives gradient descent its linear rate, governed by .
Convexity is preserved by non-negative sums, by composition with an affine map , and by pointwise maxima. The examples used later:
| Function | Why it is convex | Where it appears |
|---|---|---|
| with : a covariance matrix, hence | cross-entropy loss in the logits | |
| lse plus a linear term | softmax / logistic regression is a convex problem in its weights (affine composition) | |
| negative entropy | entropy bonus, KL | |
| jointly convex in | every KL penalty on this site | |
| , | triangle inequality; max of linear functions | regularisers, hinge losses |
A deep network is not convex in its weights (permuting hidden units already gives distinct equal minima), which is why everything we say about deep-net training is local. But many sub-problems are convex in the variable that matters: the loss in the logits, the KL-regularised objective in the distribution , the DPO loss in the implicit-reward margin.
Jensen’s inequality
For convex and any random variable with finite mean,
with the inequality reversed for concave . Proof in one line from the first-order condition: put and take any subgradient of at ; then pointwise, and taking expectations kills the linear term. Equality holds iff is affine on the support of (for strictly convex : iff is constant).
It is the most-used inequality in ML:
- KL ≥ 0 (Gibbs’ inequality): , using concavity of (probability and losses).
- Variational lower bounds: — the ELBO behind EM (unsupervised) and some distillation bounds.
- for the KL estimator in KL-regularised RL is the pointwise version , the tangent line of the concave at .
- Plug-in estimators of non-linear quantities are biased: plugging an unbiased into a convex function over-estimates on average. That is why the naive pass@k estimator is biased (statistics lesson).
import numpy as np
rng = np.random.default_rng(0)
# 1) second-order test: signs of the Hessian's eigenvalues
def classify(H, tol=1e-9):
lam = np.linalg.eigvalsh(H)
if lam.min() > tol: kind = "minimum (H ≻ 0)"
elif lam.max() < -tol: kind = "maximum (H ≺ 0)"
elif lam.min() < -tol and lam.max() > tol: kind = "saddle (indefinite)"
else: kind = "singular: the second-order test is silent"
return lam, kind
for H in [np.array([[2., .5], [.5, 1.]]), np.array([[1., 2.], [2., 1.]]), np.diag([1., 0.])]:
lam, kind = classify(H)
print(f"eigenvalues {np.round(lam, 3)} -> {kind}")
# Newton on a quadratic jumps to the stationary point in one step - even a saddle
H = np.array([[1., 2.], [2., 1.]]); x0 = np.array([0.7, -1.3])
x1 = x0 - np.linalg.solve(H, H @ x0)
print("Newton step from", x0, "->", np.round(x1, 12) + 0.0, "= the saddle")
# 2) log-sum-exp is convex: its Hessian is diag(p) - p p^T (a covariance matrix)
def lse(z):
m = z.max(); return m + np.log(np.exp(z - m).sum())
z = rng.normal(size=5); p = np.exp(z - lse(z))
H_an = np.diag(p) - np.outer(p, p)
e, I = 1e-4, np.eye(5)
H_fd = np.array([[(lse(z + e*I[i] + e*I[j]) - lse(z + e*I[i] - e*I[j])
- lse(z - e*I[i] + e*I[j]) + lse(z - e*I[i] - e*I[j])) / (4*e*e)
for j in range(5)] for i in range(5)])
print(f"\nmax |finite-difference H - (diag p - pp^T)| = {np.abs(H_fd - H_an).max():.1e}")
print("eigenvalues:", np.round(np.linalg.eigvalsh(H_an), 4) + 0.0, "-> PSD, zero along (1,...,1)")
# 3) Jensen: E[f(X)] >= f(E[X]) for convex f
X = rng.uniform(0.2, 3.0, size=200_000)
for name, f in [("x^2", np.square), ("exp(x)", np.exp), ("-log(x)", lambda x: -np.log(x))]:
print(f"{name:8s} E[f(X)] = {f(X).mean():7.4f} >= f(E[X]) = {f(X.mean()):7.4f}")The zero eigenvalue of the lse Hessian is along : adding a constant to every logit does not change the softmax. That flat direction is why logits are only defined up to a shift, and why the KL-regularised solution below carries a normaliser .
Equality constraints: Lagrange multipliers
Now minimise subject to . At a constrained optimum , moving along the constraint surface cannot decrease to first order. The feasible directions are those with ; for all of them we need . So is orthogonal to everything orthogonal to , i.e. it is parallel to :
Geometrically: the level set of through is tangent to the constraint. If it crossed the constraint, you could slide along the constraint into a lower level set. Packaging both conditions into the Lagrangian , the optimum is a stationary point of in both arguments: is tangency and is feasibility. (This needs , a “constraint qualification”; with several constraints, linearly independent gradients.)
A worked case — the figure below. Minimise with subject to . Stationarity gives , so . Substituting into the constraint,
The last identity is general (the envelope theorem): the multiplier is the sensitivity of the optimal value to the constraint level, the “shadow price” of the constraint. For , at a regular optimum.
해 볼 것:
- 이면 볼록한 그릇이고, 경사하강법은 가파른 고유벡터 방향으로는 빨리, 완만한 방향으로는 느리게 간다. 경사하강법 레슨의 조건수 이다.
- 를 으로: 평평한 골짜기다. 골짜기 바닥의 모든 점이 최소점이고, 경사하강법은 바닥에 닿은 곳에서 멈추며, Newton step은 정의되지 않는다.
- 를 로: 안장점이다. 경사하강법은 음의 곡률 고유벡터를 따라 빠져나가지만(그 성분은 매 step 배가 된다) Newton은 여전히 안장점으로 뛴다.
Newton법은 1차 모델 대신 2차 모델을 최소화한다. 의 기울기를 0으로 두면 다. 이차 함수에서는 와 상관없이 한 step에 정확하다. 고유 방향마다 그 방향의 곡률로 나누기 때문이다. 하지만 Newton은 최소점이 아니라 을 찾는다. 가 부정부호이면 안장점으로 끌려간다. 그리고 우리가 다루는 손실 지형에서는 안장점이 흔하다. 무작위 함수 모형(Gaussian random field, Bray & Dean 2007)과 신경망 손실을 실험으로 살핀 Dauphin et al.(2014)에서 손실이 높은 임계점은 압도적으로 안장점이다. 이는 그런 지형에 대한 관찰이지 고차원의 법칙이 아니다. 은 모든 에서 최소 두 개와 안장점 하나만 가진다. 에서 Hessian을 저장하고 역행렬을 구하는 것도 불가능하다. 딥러닝에 살아남은 것은 을 흉내 내는 값싼 preconditioner다. Adam의 좌표별 스케일링(옵티마이저)과 Muon의 직교화 업데이트(Muon)가 그렇다. GPTQ는 층 단위 이차 문제의 정확한 Hessian을 쓴다(양자화).
볼록성
집합 의 어떤 두 점을 이은 선분도 그 안에 머물면 는 볼록(convex) 하다. 볼록 집합 위의 함수 가
을 만족하면 볼록 함수다. 현(chord)이 그래프 위에 있다는 뜻이다. 미분 가능한 에는 동치인 판정이 둘 있다.
1차 형태에서 가장 중요한 결과가 나온다. 이면 모든 에 대해 다. 볼록 함수에서는 모든 정류점이 전역 최소이고, 최소점들의 집합은 볼록하다(한 점이거나, 위 2번처럼 평평한 골짜기). 엄격히 볼록()하면 최소점은 많아야 하나다. -강볼록이고 -smooth()이면 경사하강법이 선형 수렴하고, 그 속도를 가 정한다.
볼록성은 음이 아닌 가중합, 아핀 사상과의 합성 , 점별 최댓값으로 보존된다. 뒤에서 쓰는 예:
| 함수 | 왜 볼록인가 | 쓰이는 곳 |
|---|---|---|
| , : 공분산 행렬이라 | logit에 대한 cross-entropy 손실 | |
| lse + 선형항 | softmax·로지스틱 회귀는 가중치에 대해 볼록 문제(아핀 합성) | |
| 음의 엔트로피 | 엔트로피 보너스, KL | |
| 에 대해 결합 볼록 | 이 사이트의 모든 KL 패널티 | |
| , | 삼각부등식, 선형 함수들의 최댓값 | 정규화, hinge 손실 |
딥 네트워크는 가중치에 대해 볼록이 아니다(은닉 유닛의 순서만 바꿔도 값이 같은 서로 다른 최소점이 생긴다). 그래서 딥넷 학습에 관한 모든 이야기는 국소적이다. 하지만 중요한 변수에 대해서는 볼록인 부분 문제가 많다. logit에 대한 손실, 분포 에 대한 KL 정규화 목적함수, implicit reward 마진에 대한 DPO 손실이 그렇다.
Jensen 부등식
볼록 함수 와 평균이 유한한 확률변수 에 대해
이고, 오목 함수면 부등호가 뒤집힌다. 증명은 1차 조건에서 한 줄이다. 로 두고 에서 의 subgradient 를 아무거나 잡으면 점별로 이고, 기댓값을 취하면 선형항이 사라진다. 등호는 가 의 support 위에서 아핀일 때만 성립한다(엄격 볼록이면 가 상수일 때만).
ML에서 가장 많이 쓰이는 부등식이다.
- KL ≥ 0(Gibbs 부등식): 의 오목성으로 (확률로 보는 손실).
- 변분 하한: . EM(비지도)과 일부 증류 bound 뒤에 있는 ELBO다.
- KL 정규화 RL의 KL 추정량 은 점별 버전 , 즉 오목한 의 1에서의 접선이다.
- 비선형 양의 plug-in 추정량은 편향된다: 불편 추정량 를 볼록 함수에 넣으면 평균적으로 과대추정한다. 순진한 pass@k 추정량이 편향된 이유다(통계 레슨).
import numpy as np
rng = np.random.default_rng(0)
# 1) 2차 판정: Hessian 고유값의 부호
def classify(H, tol=1e-9):
lam = np.linalg.eigvalsh(H)
if lam.min() > tol: kind = "최소 (H ≻ 0)"
elif lam.max() < -tol: kind = "최대 (H ≺ 0)"
elif lam.min() < -tol and lam.max() > tol: kind = "안장점 (부정부호)"
else: kind = "특이: 2차 판정으로는 알 수 없음"
return lam, kind
for H in [np.array([[2., .5], [.5, 1.]]), np.array([[1., 2.], [2., 1.]]), np.diag([1., 0.])]:
lam, kind = classify(H)
print(f"고유값 {np.round(lam, 3)} -> {kind}")
# 이차 함수에서 Newton은 한 step에 정류점으로 간다 - 안장점이어도
H = np.array([[1., 2.], [2., 1.]]); x0 = np.array([0.7, -1.3])
x1 = x0 - np.linalg.solve(H, H @ x0)
print("Newton step", x0, "->", np.round(x1, 12) + 0.0, "= 안장점")
# 2) log-sum-exp는 볼록: Hessian = diag(p) - p p^T (공분산 행렬)
def lse(z):
m = z.max(); return m + np.log(np.exp(z - m).sum())
z = rng.normal(size=5); p = np.exp(z - lse(z))
H_an = np.diag(p) - np.outer(p, p)
e, I = 1e-4, np.eye(5)
H_fd = np.array([[(lse(z + e*I[i] + e*I[j]) - lse(z + e*I[i] - e*I[j])
- lse(z - e*I[i] + e*I[j]) + lse(z - e*I[i] - e*I[j])) / (4*e*e)
for j in range(5)] for i in range(5)])
print(f"\nmax |유한차분 H - (diag p - pp^T)| = {np.abs(H_fd - H_an).max():.1e}")
print("고유값:", np.round(np.linalg.eigvalsh(H_an), 4) + 0.0, "-> PSD, (1,...,1) 방향으로 0")
# 3) Jensen: 볼록 f에 대해 E[f(X)] >= f(E[X])
X = rng.uniform(0.2, 3.0, size=200_000)
for name, f in [("x^2", np.square), ("exp(x)", np.exp), ("-log(x)", lambda x: -np.log(x))]:
print(f"{name:8s} E[f(X)] = {f(X).mean():7.4f} >= f(E[X]) = {f(X.mean()):7.4f}")lse Hessian의 0 고유값은 방향이다. 모든 logit에 같은 상수를 더해도 softmax는 그대로다. logit이 평행이동만큼 정의되지 않는 이유이고, 아래 KL 정규화 해에 정규화 상수 가 붙는 이유다.
등식 제약: 라그랑주 승수
이제 아래서 를 최소화한다. 제약 최적점 에서는 제약면을 따라 움직여도 1차까지 가 줄지 않아야 한다. 허용되는 방향은 인 이고, 그 모두에 대해 이어야 한다. 즉 는 에 수직인 모든 것에 수직이므로 와 평행하다.
기하학적으로는 를 지나는 의 등위선이 제약에 접한다는 뜻이다. 등위선이 제약을 가로지른다면 제약을 따라 미끄러져 더 낮은 등위선으로 갈 수 있다. 두 조건을 라그랑지안 하나로 묶으면 최적점은 두 인자 모두에 대한 의 정류점이다. 은 접함, 은 허용 가능성이다. (여기에는 이라는 “제약 자격 조건”이 필요하다. 제약이 여럿이면 기울기들이 선형 독립이어야 한다.)
풀어 보는 예: 아래 그림. 인 를 아래서 최소화한다. 정류 조건은 이므로 . 이것을 제약에 넣으면
마지막 등식은 일반적이다(envelope theorem). 승수는 제약 수준에 대한 최적값의 민감도, 곧 제약의 “그림자 가격(shadow price)“이다. 이면 정칙인 최적점에서 다.
Inequality constraints: the KKT conditions
For subject to and , the Lagrangian is and, under a constraint qualification, a local optimum satisfies the Karush–Kuhn–Tucker conditions:
Dual feasibility says an inequality can only push ( points out of the feasible set, against the wall). Complementary slackness says each inequality is either active (, the wall is touched, ) or slack (, it is irrelevant, ) — exactly what the figure shows when you drag the line past the unconstrained minimum.
For a convex problem ( convex, affine) with a strictly feasible point (Slater’s condition), KKT is necessary and sufficient for a global optimum, and strong duality holds: the dual function is a lower bound on the optimum for every (weak duality — always true), and its maximum equals the optimum. Dual ascent — raise when the constraint is violated, lower it (not below 0) when it is slack — is how an adaptive KL controller tunes β toward a KL target (KL-regularised RL), and how Lagrangian methods enforce constraints such as a length budget.
import numpy as np
# the figure's problem: f(x) = 1/2 (x-c)^T A (x-c) s.t. a^T x = b
th = np.deg2rad(25); R = np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]])
A = R @ np.diag([1., 4.]) @ R.T
c = np.array([0.9, 0.5])
a = np.array([np.cos(np.deg2rad(35)), np.sin(np.deg2rad(35))])
def solve_eq(b):
# KKT system: stationarity A x + nu a = A c, feasibility a^T x = b
K = np.block([[A, a[:, None]], [a[None, :], np.zeros((1, 1))]])
sol = np.linalg.solve(K, np.r_[A @ c, b])
x, nu = sol[:2], sol[2]
return x, nu, 0.5 * (x - c) @ A @ (x - c)
b = 0.2
x, nu, f = solve_eq(b)
g = A @ (x - c)
print(f"x* = {np.round(x, 4)}, nu = {nu:.4f}, f* = {f:.4f}")
print(f"stationarity grad f + nu*a = {np.round(g + nu * a, 12) + 0.0}")
print(f"tangency cross(grad f, a) = {g[0]*a[1] - g[1]*a[0]:.1e}")
h = 1e-5
print(f"shadow price -(f*(b+h) - f*(b-h))/2h = {-(solve_eq(b+h)[2] - solve_eq(b-h)[2]) / (2*h):.4f} (= nu)")
# inequality a^T x <= b: stationarity, feasibility, mu >= 0, mu * (a^T x - b) = 0
for b in [0.2, 1.5]:
x, nu, f = solve_eq(b)
if nu < 0: # a negative multiplier is not allowed -> constraint is slack
x, nu, f = c.copy(), 0.0, 0.0
print(f"b={b}: x*={np.round(x, 3)}, mu={nu:.3f}, a^T x - b = {a @ x - b:+.3f}, |mu*(a^T x - b)| = {abs(nu*(a @ x - b)):.1e}")You minimise f(x) subject to h(x) ≤ b and the solver returns the multiplier μ = 0. What does this tell you?
Complementary slackness: . With the constraint exerts no force, and by the shadow-price identity — moving the wall a little does not change the optimum. (An active constraint can also have in degenerate cases, when the unconstrained minimum sits exactly on the wall; the shadow price is still 0.)
Softmax is the entropy-regularised argmax
Picking the best of options with scores is over the probability simplex . A linear function on a polytope is maximised at a vertex: a one-hot argmax, which is not differentiable in . Add an entropy bonus with temperature :
The objective is strictly concave (the Hessian of is ), so a stationary point of the Lagrangian on the simplex is the unique optimum. Attach a multiplier to :
The factor is the same for every ; normalisation fixes it, giving . The constraints never become active because as — the entropy acts as a barrier — so their multipliers are 0 and we could ignore them. Plugging back in, the optimal value is , a smooth upper bound on that converges to it as (and ). This is the variational reason the sampling temperature in decoding is a division of the logits, and the template for the next result.
The KL-regularised optimum
Replace the entropy bonus by a KL penalty to a reference distribution and the scores by rewards: for one prompt,
This is the objective of KL-regularised RL. Again the objective is strictly concave in (Hessian ), and the stationarity condition of the Lagrangian with multiplier for normalisation is
Substituting back, , so . This is the Gibbs variational principle: , attained by the Gibbs distribution (Kimi k1.5 writes τ where RLHF papers write β). Softmax is the special case of a uniform (KL to uniform = ). The rlhf-ppo lesson reaches the same formula by completing the KL, ; the Lagrangian route shows why it has this shape — every response must have the same marginal value at the optimum, otherwise moving mass from a low-value response to a high-value one would increase .
β as a multiplier. The penalised problem is the Lagrangian of the constrained one, subject to , with the multiplier of the KL budget. Each β traces one point of the reward–KL frontier, and the shadow-price identity says its slope is β. Directly: and , so and
부등식 제약: KKT 조건
, 아래서 이면 라그랑지안은 이고, 제약 자격 조건 아래서 국소 최적점은 Karush–Kuhn–Tucker(KKT) 조건을 만족한다.
쌍대 허용성은 부등식 제약이 밀어내기만 할 수 있다는 뜻이다(가 허용 영역 바깥, 벽 쪽을 향한다). 상보 여유성(complementary slackness)은 각 부등식이 활성(, 벽에 닿음, )이거나 느슨(, 무관함, )하다는 뜻이다. 직선을 제약 없는 최소점 너머로 끌었을 때 그림이 보여 준 그대로다.
볼록 문제( 볼록, 아핀)이고 엄격히 허용 가능한 점이 있으면(Slater 조건) KKT는 전역 최적의 필요충분조건이고 강쌍대성이 성립한다. 쌍대 함수 는 모든 에서 최적값의 하한이고(약쌍대성, 항상 참), 그 최댓값이 최적값과 같다. 쌍대 상승(제약을 어기면 를 올리고, 느슨하면 0 아래로는 내리지 않으며 낮춘다)이 adaptive KL controller가 KL 목표를 향해 β를 조정하는 방식이고(KL 정규화 RL), 길이 예산 같은 제약을 라그랑주 방식으로 강제하는 방식이다.
import numpy as np
# 그림의 문제: f(x) = 1/2 (x-c)^T A (x-c) s.t. a^T x = b
th = np.deg2rad(25); R = np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]])
A = R @ np.diag([1., 4.]) @ R.T
c = np.array([0.9, 0.5])
a = np.array([np.cos(np.deg2rad(35)), np.sin(np.deg2rad(35))])
def solve_eq(b):
# KKT 시스템: 정류성 A x + nu a = A c, 허용성 a^T x = b
K = np.block([[A, a[:, None]], [a[None, :], np.zeros((1, 1))]])
sol = np.linalg.solve(K, np.r_[A @ c, b])
x, nu = sol[:2], sol[2]
return x, nu, 0.5 * (x - c) @ A @ (x - c)
b = 0.2
x, nu, f = solve_eq(b)
g = A @ (x - c)
print(f"x* = {np.round(x, 4)}, nu = {nu:.4f}, f* = {f:.4f}")
print(f"정류성 grad f + nu*a = {np.round(g + nu * a, 12) + 0.0}")
print(f"접함 cross(grad f, a) = {g[0]*a[1] - g[1]*a[0]:.1e}")
h = 1e-5
print(f"그림자 가격 -(f*(b+h) - f*(b-h))/2h = {-(solve_eq(b+h)[2] - solve_eq(b-h)[2]) / (2*h):.4f} (= nu)")
# 부등식 a^T x <= b: 정류성, 허용성, mu >= 0, mu * (a^T x - b) = 0
for b in [0.2, 1.5]:
x, nu, f = solve_eq(b)
if nu < 0: # 음의 승수는 허용되지 않는다 -> 제약이 느슨하다
x, nu, f = c.copy(), 0.0, 0.0
print(f"b={b}: x*={np.round(x, 3)}, mu={nu:.3f}, a^T x - b = {a @ x - b:+.3f}, |mu*(a^T x - b)| = {abs(nu*(a @ x - b)):.1e}")h(x) ≤ b 아래서 f(x)를 최소화했더니 승수 μ = 0이 나왔다. 무엇을 알 수 있는가?
상보 여유성 . 이면 제약은 아무 힘도 쓰지 않고, 그림자 가격 등식에 의해 이다. 벽을 조금 옮겨도 최적점이 그대로다. (퇴화한 경우, 즉 제약 없는 최소점이 정확히 벽 위에 있으면 활성 제약도 일 수 있다. 그때도 그림자 가격은 0이다.)
softmax는 엔트로피 정규화 argmax다
점수 를 가진 개 중 최선을 고르는 것은 확률 simplex 위의 다. 다면체 위의 선형 함수는 꼭짓점에서 최대가 된다. one-hot argmax이고, 에 대해 미분할 수 없다. 온도 의 엔트로피 보너스를 더하자.
목적함수는 엄격히 오목하므로(의 Hessian이 ) simplex 위 라그랑지안의 정류점이 유일한 최적해다. 에 승수 를 붙인다.
는 모든 에 공통이고 정규화가 그 값을 정하므로 다. 이면 이므로 제약은 결코 활성이 되지 않는다(엔트로피가 장벽 역할을 한다). 그래서 그 승수는 0이고 무시해도 된다. 다시 대입하면 최적값은 , 의 매끄러운 상한이고 이면 그것으로 수렴한다(). 디코딩의 샘플링 온도가 logit을 나누는 것인 변분적 이유이고, 다음 결과의 틀이다.
KL 정규화의 최적해
엔트로피 보너스를 기준 분포에 대한 KL 패널티로, 점수를 보상으로 바꾼다. 프롬프트 하나에 대해
KL 정규화 RL의 목적함수다. 이번에도 에 대해 엄격히 오목하고(Hessian ), 정규화 승수 를 붙인 라그랑지안의 정류 조건은
다시 대입하면 이므로 다. 이것이 Gibbs 변분 원리다: 이고, Gibbs 분포 에서 달성된다(Kimi k1.5는 RLHF 논문의 β 자리에 τ를 쓴다). softmax는 가 균등한 특수한 경우다(균등 분포에 대한 KL = ). rlhf-ppo 레슨은 KL을 완성하는 방식 으로 같은 식에 닿는다. 라그랑주 경로는 해가 왜 이 모양인지 보여 준다. 최적점에서는 모든 응답의 한계 가치 가 같아야 한다. 아니라면 가치가 낮은 응답에서 높은 응답으로 질량을 옮겨 를 키울 수 있다.
승수로서의 β. 패널티 문제는 제약 문제 ” 아래서 “의 라그랑지안이고, β는 KL 예산의 승수다. β 하나가 보상–KL frontier 위의 점 하나를 그리고, 그림자 가격 등식은 그 기울기가 β라고 말한다. 직접 확인하면 이고 이므로 , 곧
Three consequences to read off the figure: π* never puts mass where has none (the multiplicative form); only matters (doubling every reward = halving β); and adding a constant to every reward changes nothing (it is absorbed by — the same flat direction as the lse Hessian). The last one is why baselines are free in policy gradients and why DPO’s reward is only identified up to a per-prompt constant (DPO).
Mirror descent: the same step, repeated
Gradient descent is itself the solution of a small regularised problem — a linear model of plus a squared-distance penalty:
The Euclidean distance is a poor fit for probability vectors: it ignores that moving 0.01 of mass matters far more for a token with probability 0.001 than for one with 0.5. Mirror descent replaces it by a Bregman divergence matched to the geometry; on the simplex, by the KL. Maximising a reward (gradient of is ):
This is the KL-regularised optimum with and : a multiplicative (exponentiated-gradient) update that never leaves the simplex and never needs a projection. Two readings follow. The RLHF solution is one mirror-ascent step of size from . And anchoring to the previous policy instead of a fixed reference, then repeating, is mirror descent proper — the view taken by Kimi k1.5’s policy optimisation (regularisation, Kimi k1.5 review). TRPO’s KL trust region and PPO’s clip (PPO) are approximations of the same “small step in KL” idea for a parametric policy; the natural gradient is its local quadratic version, with the Fisher matrix playing the role of the Hessian of the KL.
import numpy as np
rng = np.random.default_rng(0)
pi_ref = np.array([0.30, 0.25, 0.18, 0.12, 0.10, 0.05])
r = np.array([0.2, -0.4, 0.7, 1.1, -1.0, 1.8])
beta = 0.7
def kl(p, q): return np.sum(p * np.log(p / q))
def J(pi): return pi @ r - beta * kl(pi, pi_ref)
# closed form from the Lagrangian: pi* = pi_ref exp(r/beta) / Z
w = pi_ref * np.exp(r / beta); Z = w.sum(); pi_star = w / Z
print("pi* =", np.round(pi_star, 4))
print(f"J(pi*) = {J(pi_star):.6f} beta*log Z = {beta*np.log(Z):.6f}")
# stationarity: r_i - beta(log(pi_i/pi_ref_i) + 1) is the same constant for every i (= nu)
s = r - beta * (np.log(pi_star / pi_ref) + 1)
print(f"spread of r - beta(log pi*/pi_ref + 1) across i: {np.ptp(s):.1e}")
# no random distribution beats it
P = rng.dirichlet(np.ones(6), size=50_000)
Js = P @ r - beta * np.sum(P * np.log(P / pi_ref), axis=1)
print(f"best of 50k random pi: {Js.max():.4f} < J(pi*) = {J(pi_star):.4f}")
# frontier slope dE[r]/dKL = beta (finite differences in beta)
def point(b):
p = pi_ref * np.exp(r / b); p /= p.sum()
return p @ r, kl(p, pi_ref)
(e1, k1), (e2, k2) = point(beta * 1.001), point(beta * 0.999)
print(f"dE[r]/dKL along the frontier = {(e2 - e1) / (k2 - k1):.4f} (beta = {beta})")
# mirror ascent on J over the simplex: pi <- pi * exp(eta * grad) / norm, from pi_ref
for eta in [0.5, 1 / beta]:
pi = pi_ref.copy()
for t in range(1, 41):
g = r - beta * (np.log(pi / pi_ref) + 1)
pi = pi * np.exp(eta * g); pi /= pi.sum()
if kl(pi_star, pi) < 1e-12: break
print(f"eta={eta:.3f}: KL(pi*||pi_t) < 1e-12 after {t} step(s)")
# softmax = entropy-regularised argmax (uniform reference)
tau = 0.5
p = np.exp(r / tau - np.max(r / tau)); p /= p.sum()
H = -np.sum(p * np.log(p))
lse = tau * (np.max(r / tau) + np.log(np.sum(np.exp(r / tau - np.max(r / tau)))))
print(f"\nmax_p p.r + tau*H(p) = {p @ r + tau * H:.6f} = tau*logsumexp(r/tau) = {lse:.6f}")With mirror ascent lands on π* in one step from any start: the update is , and erases . With smaller η the error in shrinks by the factor per step.
In the KL-regularised objective, every reward is multiplied by 2 and every reward is also shifted by +5. Which β gives the same optimal policy as before?
The optimum depends on up to an additive constant: (the cancels in ). Matching gives .
Summary
- Stationary point: . The Hessian’s eigenvalues classify it; ranges over . Newton () finds stationary points, not minima.
- Convex ⇔ tangent planes under-estimate ⇔ ; then every stationary point is global. lse, negative entropy and KL are convex; deep nets are not.
- Jensen gives KL ≥ 0, the ELBO, , and the bias of plug-in estimators.
- Lagrange: at the optimum the level set is tangent to the constraint, ; the multiplier is the shadow price . KKT adds and complementary slackness.
- Entropy-regularised argmax = softmax; KL-regularised reward maximisation = with value , and β is the slope of the reward–KL frontier. Repeating that step from the previous policy is mirror descent.
Where this is used
- Curvature, κ and preconditioning — gradient descent, optimizers (Adam as a diagonal Newton surrogate), Muon, linear models (Hessian , convex logistic loss), GPTQ / OBS in quantisation.
- Lagrange multipliers — PCA as s.t. in unsupervised learning; the bigram MLE with a normalisation constraint in language modelling.
- Jensen — KL ≥ 0 in probability and losses; in KL-regularised RL; the pass@k estimator in statistics.
- Softmax as regularised argmax — temperature in decoding; attention weights in attention.
- π* ∝ π_ref·exp(r/β), β as a multiplier — derived again and used in KL-regularised RL, inverted in DPO, approximated by best-of-N, over-optimised in over-optimisation.
- Mirror descent and trust regions — PPO, regularisation (Kimi’s mirror descent), Kimi k1.5.
그림에서 읽을 결과 셋. π*는 가 0인 곳에 질량을 두지 않는다(곱셈 꼴이므로). 만 중요하다(보상을 모두 두 배 = β를 절반). 모든 보상에 상수를 더해도 아무것도 바뀌지 않는다(가 흡수한다. lse Hessian의 평평한 방향과 같은 이야기다). 마지막이 정책 경사에서 baseline이 공짜인 이유이고, DPO의 보상이 프롬프트별 상수만큼만 식별되는 이유다(DPO).
Mirror descent: 같은 한 걸음의 반복
경사하강법 자체가 작은 정규화 문제의 해다. 의 선형 모델에 제곱 거리 패널티를 더한 것이다.
유클리드 거리는 확률 벡터에 잘 맞지 않는다. 질량 0.01을 옮기는 일이 확률 0.5인 토큰보다 0.001인 토큰에 훨씬 큰 일이라는 점을 무시한다. Mirror descent는 이 거리를 기하에 맞는 Bregman divergence로 바꾼다. simplex 위에서는 KL이다. 보상 을 최대화하면(의 기울기는 )
, 로 바꾼 KL 정규화 최적해다. simplex를 벗어나지 않고 사영도 필요 없는 곱셈형(exponentiated-gradient) 업데이트다. 두 가지로 읽힌다. RLHF 해 는 에서 크기 로 내딛는 mirror ascent 한 걸음이다. 그리고 고정된 기준 대신 직전 정책에 묶고 반복하면 그것이 mirror descent 본래의 모습이다. Kimi k1.5의 정책 최적화가 이 관점을 쓴다(정규화, Kimi k1.5 리뷰). TRPO의 KL trust region과 PPO의 clip(PPO)은 매개변수화된 정책에서 같은 “KL로 잰 작은 걸음”을 근사한 것이고, natural gradient는 그 국소 2차 버전이다. 거기서는 Fisher 행렬이 KL의 Hessian 역할을 한다.
import numpy as np
rng = np.random.default_rng(0)
pi_ref = np.array([0.30, 0.25, 0.18, 0.12, 0.10, 0.05])
r = np.array([0.2, -0.4, 0.7, 1.1, -1.0, 1.8])
beta = 0.7
def kl(p, q): return np.sum(p * np.log(p / q))
def J(pi): return pi @ r - beta * kl(pi, pi_ref)
# 라그랑지안에서 얻은 닫힌 해: pi* = pi_ref exp(r/beta) / Z
w = pi_ref * np.exp(r / beta); Z = w.sum(); pi_star = w / Z
print("pi* =", np.round(pi_star, 4))
print(f"J(pi*) = {J(pi_star):.6f} beta*log Z = {beta*np.log(Z):.6f}")
# 정류성: r_i - beta(log(pi_i/pi_ref_i) + 1)가 모든 i에서 같은 상수(= nu)
s = r - beta * (np.log(pi_star / pi_ref) + 1)
print(f"i에 걸친 r - beta(log pi*/pi_ref + 1)의 범위: {np.ptp(s):.1e}")
# 어떤 무작위 분포도 이기지 못한다
P = rng.dirichlet(np.ones(6), size=50_000)
Js = P @ r - beta * np.sum(P * np.log(P / pi_ref), axis=1)
print(f"무작위 pi 5만 개 중 최고: {Js.max():.4f} < J(pi*) = {J(pi_star):.4f}")
# frontier 기울기 dE[r]/dKL = beta (beta에 대한 유한차분)
def point(b):
p = pi_ref * np.exp(r / b); p /= p.sum()
return p @ r, kl(p, pi_ref)
(e1, k1), (e2, k2) = point(beta * 1.001), point(beta * 0.999)
print(f"frontier를 따른 dE[r]/dKL = {(e2 - e1) / (k2 - k1):.4f} (beta = {beta})")
# simplex 위에서 J에 대한 mirror ascent: pi <- pi * exp(eta * grad) / 정규화, pi_ref에서 출발
for eta in [0.5, 1 / beta]:
pi = pi_ref.copy()
for t in range(1, 41):
g = r - beta * (np.log(pi / pi_ref) + 1)
pi = pi * np.exp(eta * g); pi /= pi.sum()
if kl(pi_star, pi) < 1e-12: break
print(f"eta={eta:.3f}: {t} step 만에 KL(pi*||pi_t) < 1e-12")
# softmax = 엔트로피 정규화 argmax (균등 기준 분포)
tau = 0.5
p = np.exp(r / tau - np.max(r / tau)); p /= p.sum()
H = -np.sum(p * np.log(p))
lse = tau * (np.max(r / tau) + np.log(np.sum(np.exp(r / tau - np.max(r / tau)))))
print(f"\nmax_p p.r + tau*H(p) = {p @ r + tau * H:.6f} = tau*logsumexp(r/tau) = {lse:.6f}")이면 mirror ascent는 어디서 출발해도 한 step에 π*에 내려앉는다. 업데이트가 이고 이 를 지우기 때문이다. η가 더 작으면 의 오차가 step마다 배로 줄어든다.
KL 정규화 목적함수에서 모든 보상을 2배 하고 동시에 +5만큼 평행이동했다. 이전과 같은 최적 정책을 주는 β는?
최적해는 덧셈 상수를 빼면 에만 의존한다. (는 에서 상쇄된다). 로 맞추면 .
정리
- 정류점: . Hessian 고유값이 분류하고, 는 안을 오간다. Newton()은 최소가 아니라 정류점을 찾는다.
- 볼록 ⇔ 접평면이 하한 ⇔ . 그러면 모든 정류점이 전역 최소다. lse, 음의 엔트로피, KL은 볼록이고 딥넷은 아니다.
- Jensen 에서 KL ≥ 0, ELBO, , plug-in 추정량의 편향이 나온다.
- 라그랑주: 최적점에서 등위선이 제약에 접한다, . 승수는 그림자 가격 다. KKT는 과 상보 여유성을 더한다.
- 엔트로피 정규화 argmax = softmax. KL 정규화 보상 최대화 = , 최적값 , β는 보상–KL frontier의 기울기다. 그 한 걸음을 직전 정책에서 반복하면 mirror descent다.
이 사이트에서 쓰이는 곳
- 곡률, κ, preconditioning: 경사하강법, 옵티마이저(Newton의 대각 대용인 Adam), Muon, 선형 모델(Hessian , 볼록한 로지스틱 손실), 양자화의 GPTQ / OBS.
- 라그랑주 승수: 비지도 학습의 PCA( 아래 ), 언어 모델링의 정규화 제약이 붙은 bigram MLE.
- Jensen: 확률로 보는 손실의 KL ≥ 0, KL 정규화 RL의 , 통계의 pass@k 추정량.
- 정규화 argmax로서의 softmax: 디코딩의 temperature, attention의 가중치.
- π* ∝ π_ref·exp(r/β), 승수로서의 β: KL 정규화 RL에서 다시 유도되어 쓰이고, DPO가 뒤집고, best-of-N이 근사하고, 과최적화에서 과하게 최적화된다.
- Mirror descent와 trust region: PPO, 정규화(Kimi의 mirror descent), Kimi k1.5.
더 읽을거리Further reading
- Boyd & Vandenberghe, Convex Optimization (Cambridge, 2004), ch. 3, 5 — 볼록 함수의 1·2차 조건(§3.1), Jensen(§3.1.8), 라그랑주 쌍대와 KKT(§5.1–5.5). 이 레슨의 표준 참고서.First- and second-order conditions for convexity (§3.1), Jensen (§3.1.8), Lagrange duality and KKT (§5.1–5.5). The standard reference for this lesson.
- Goodfellow, Bengio, Courville, Deep Learning (MIT Press, 2016), §4.3–4.4 — Hessian과 곡률, Newton법, 안장점, 일반화 라그랑지안(KKT)을 딥러닝 관점에서 짧게.Hessian and curvature, Newton's method, saddle points and the generalised Lagrangian (KKT), briefly and from the deep-learning side.
- Nocedal & Wright, Numerical Optimization, 2nd ed. (Springer, 2006), ch. 2, 12 — 비볼록 문제를 포함한 최적성 조건의 엄밀한 서술(2장 무제약, 12장 제약).Rigorous optimality conditions including non-convex problems (ch. 2 unconstrained, ch. 12 constrained).
- Beck & Teboulle, Mirror descent and nonlinear projected subgradient methods for convex optimization (Operations Research Letters, 2003) — mirror descent를 Bregman 거리를 쓴 근접 사상으로 다시 쓴 논문. simplex 위의 엔트로피 버전.Recasts mirror descent as a proximal step with a Bregman distance; includes the entropic version on the simplex.
- Bubeck, Convex Optimization: Algorithms and Complexity (Foundations and Trends in ML, 2015), ch. 4 — mirror descent와 exponentiated gradient의 수렴 분석.Convergence analysis of mirror descent and exponentiated gradient.
- Dauphin et al., Identifying and attacking the saddle point problem in high-dimensional non-convex optimization (NeurIPS 2014) — 무작위 함수 모형과 신경망 손실에서 손실이 높은 임계점이 대부분 안장점이라는 관찰과, 그것을 피하는 saddle-free Newton.The observation that high-loss critical points of random-function models and neural-network losses are mostly saddles, and saddle-free Newton to escape them.
- Rafailov et al., Direct Preference Optimization (NeurIPS 2023), Appendix A.1 — KL 정규화 목적함수의 최적해 유도. DPO가 이 식을 뒤집어 쓴다.Derivation of the optimum of the KL-regularised objective; DPO inverts this formula.