Track 0 · Math Foundations · 04/10

최적화의 수학The mathematics of optimisation

정류점의 1·2차 조건과 Hessian의 곡률, 볼록성과 Jensen 부등식, 라그랑주 승수와 KKT 조건을 유도하고, 같은 도구로 softmax(엔트로피 정규화 argmax)와 KL 정규화 RL의 닫힌 해 π* ∝ π_ref·exp(r/β), 그리고 mirror descent를 한 줄씩 끌어낸다.First- and second-order conditions and Hessian curvature, convexity and Jensen's inequality, Lagrange multipliers and the KKT conditions — then the same tools derive softmax as the entropy-regularised argmax, the closed form π* ∝ π_ref·exp(r/β) of KL-regularised RL, and mirror descent, one line at a time.

45 분min optimization · convexity · hessian · newton · jensen · lagrange multiplier · KKT · duality · softmax · KL regularization · mirror descent 먼저 볼 것:Before this: 미분·연쇄법칙·JacobianDerivatives, the chain rule and Jacobians, 고유값·SVD·저랭크Eigenvalues, SVD and low rank

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 f:Rn→Rf:\mathbb{R}^n\to\mathbb{R} and expand it around xx (calculus lesson):

f(x+d)=f(x)+∇f(x)⊤d+12 d⊤H(x) d+o(∥d∥2),Hij=∂2f∂xi ∂xj.f(x+d) = f(x) + \nabla f(x)^\top d + \tfrac12\, d^\top H(x)\, d + o(\|d\|^2), \qquad H_{ij} = \frac{\partial^2 f}{\partial x_i\,\partial x_j}.
  • First order (necessary). If x∗x^* is a local minimum then ∇f(x∗)=0\nabla f(x^*) = 0. Otherwise d=−ϵ∇fd = -\epsilon\nabla f makes the linear term negative and, for small ϵ\epsilon, dominates. Points with ∇f=0\nabla f = 0 are stationary points.
  • Second order. At a stationary point the quadratic term decides. A local minimum requires H(x∗)⪰0H(x^*) \succeq 0 (positive semidefinite); ∇f=0\nabla f = 0 and H≻0H \succ 0 (positive definite) is sufficient for a strict local minimum.

Because HH is symmetric it has an orthonormal eigenbasis H=QΛQ⊤H = Q\Lambda Q^\top (eigen/SVD lesson). Writing d=Qzd = Qz, the quadratic term becomes 12∑iλizi2\tfrac12\sum_i \lambda_i z_i^2, a sum of independent one-dimensional parabolas. The curvature in a unit direction uu is the Rayleigh quotient

u⊤Hu=∑iλi(qi⊤u)2∈[λmin⁡,λmax⁡],u^\top H u = \sum_i \lambda_i (q_i^\top u)^2 \in [\lambda_{\min}, \lambda_{\max}],

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: diag(−1,0,1)\mathrm{diag}(-1, 0, 1) is a saddle, since ff already rises along one axis and falls along another). Only when some eigenvalues are zero and the rest share one sign (a singular semidefinite HH) does the second-order test say nothing (look at higher orders, e.g. x4x^4 versus x3x^3).

이 사이트의 거의 모든 대상은 어떤 최적화 문제의 해다. 학습은 손실을 최소화하고, softmax는 정규화된 argmax의 해이며, RLHF 정책은 KL로 제약된 보상 최대화의 해이고, PPO·TRPO·Kimi의 mirror descent는 제약 아래서 한 걸음을 내딛는 방법이다. 이 레슨은 그런 문장을 읽는 데 필요한 도구를 모은다. 정류점이 무엇이고 곡률이 그것을 어떻게 분류하는지, 왜 볼록성이 “국소”를 “전역”으로 만드는지, Jensen 부등식, 그리고 라그랑주 승수와 KKT 조건. 그 다음 이 도구로 뒤 트랙이 기대는 결과 셋을 유도한다.

1차·2차 조건

두 번 미분 가능한 f:Rn→Rf:\mathbb{R}^n\to\mathbb{R}를 xx 근처에서 전개한다(미적분 레슨).

f(x+d)=f(x)+∇f(x)⊤d+12 d⊤H(x) d+o(∥d∥2),Hij=∂2f∂xi ∂xj.f(x+d) = f(x) + \nabla f(x)^\top d + \tfrac12\, d^\top H(x)\, d + o(\|d\|^2), \qquad H_{ij} = \frac{\partial^2 f}{\partial x_i\,\partial x_j}.
  • 1차 조건(필요조건). x∗x^*가 국소 최소이면 ∇f(x∗)=0\nabla f(x^*) = 0이다. 아니라면 d=−ϵ∇fd = -\epsilon\nabla f가 1차 항을 음수로 만들고, ϵ\epsilon이 작으면 그 항이 나머지를 이긴다. ∇f=0\nabla f = 0인 점을 정류점(stationary point) 이라 한다.
  • 2차 조건. 정류점에서는 2차 항이 결정한다. 국소 최소이려면 H(x∗)⪰0H(x^*) \succeq 0(양의 준정부호)이어야 하고, ∇f=0\nabla f = 0 이고 H≻0H \succ 0(양의 정부호)이면 엄격한 국소 최소가 보장된다.

HH는 대칭이므로 정규직교 고유기저 H=QΛQ⊤H = Q\Lambda Q^\top를 가진다(고유값·SVD 레슨). d=Qzd = Qz로 쓰면 2차 항은 12∑iλizi2\tfrac12\sum_i \lambda_i z_i^2, 서로 독립인 1차원 포물선들의 합이 된다. 단위 방향 uu의 곡률은 Rayleigh 몫이다.

u⊤Hu=∑iλi(qi⊤u)2∈[λmin⁡,λmax⁡]u^\top H u = \sum_i \lambda_i (q_i^\top u)^2 \in [\lambda_{\min}, \lambda_{\max}]

고유값의 가중평균이고, 양 끝은 고유벡터 방향에서 나온다. 그래서 고유값의 부호가 정류점을 분류한다. 모두 양수면 최소, 모두 음수면 최대, 양수와 음수가 하나 이상씩 있으면 안장점(saddle)이다(0인 고유값이 있어도 마찬가지다. diag(−1,0,1)\mathrm{diag}(-1, 0, 1)은 한 축으로는 올라가고 다른 축으로는 내려가므로 안장점이다). 일부 고유값이 0이고 나머지가 모두 같은 부호일 때(특이한 반정부호 HH)만 2차 판정이 아무 말도 못 한다(더 높은 차수를 봐야 한다. 예: x4x^4와 x3x^3).

det H – tr H – κ –
Drag on the map to move the start point. The red dots are 25 steps of gradient descent (η = 0.25); the dashed violet segment is the Newton step −H⁻¹∇f. With both λ positive the bowl is convex and both methods head for the centre. Pull λ₂ below zero: the centre becomes a saddle, gradient descent slides off along the negative-curvature eigenvector, but Newton still jumps straight to the saddle — it finds stationary points, not minima. Right: the curvature uᵀHu in direction u sweeps between λmin and λmax, which are attained exactly on the eigenvectors. 왼쪽 지도를 끌어 출발점을 옮겨 보라. 빨간 점은 경사하강법 25 step(η = 0.25), 보라 점선은 Newton step −H⁻¹∇f다. 두 λ가 모두 양수면 볼록한 그릇이고 두 방법 모두 중심으로 간다. λ₂를 0 아래로 내리면 중심이 안장점이 된다. 경사하강법은 음의 곡률 고유벡터를 따라 미끄러져 나가지만 Newton은 여전히 안장점으로 곧장 뛴다. Newton은 최소점이 아니라 정류점을 찾는다. 오른쪽: 방향 u의 곡률 uᵀHu는 λmin과 λmax 사이를 오가고, 그 양 끝은 정확히 고유벡터 방향에서 나온다.

Things to try:

  1. With λ1=2, λ2=0.5\lambda_1 = 2,\ \lambda_2 = 0.5 the bowl is convex and gradient descent zig-zags less along the flat eigenvector than along the steep one — the condition number κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min} of the gradient-descent lesson.
  2. Push λ2\lambda_2 to 00: 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.
  3. Push λ2\lambda_2 to −1-1: a saddle. Gradient descent escapes along the negative-curvature eigenvector (that component is multiplied by 1+η∣λ2∣1 + \eta|\lambda_2| 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 f+g⊤d+12d⊤Hdf + g^\top d + \tfrac12 d^\top H d to zero gives d=−H−1gd = -H^{-1}g. On a quadratic it is exact in one step regardless of κ\kappa — it divides each eigen-direction by its own curvature. But it looks for ∇f=0\nabla f = 0, not for a minimum: with an indefinite HH 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: (x12−1)2+∑j=2dxj2(x_1^2-1)^2 + \sum_{j=2}^d x_j^2 has exactly two minima and one saddle for every d≥2d \ge 2. Storing and inverting an n×nn\times n Hessian is also out of the question for n∼1010n \sim 10^{10}. What survives in deep learning are cheap preconditioners that imitate H−1H^{-1}: 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 C\mathcal{C} is convex if the segment between any two of its points stays inside. A function ff on a convex set is convex if

f(θx+(1−θ)y)≤θf(x)+(1−θ)f(y)∀x,y, θ∈[0,1]f(\theta x + (1-\theta) y) \le \theta f(x) + (1-\theta) f(y) \qquad \forall x, y,\ \theta\in[0,1]

— the chord lies above the graph. For differentiable ff there are two equivalent tests:

f(y)≥f(x)+∇f(x)⊤(y−x)  ∀x,y⏟first order: tangent planes are global under-estimators⟺H(x)⪰0  ∀x⏟second order\underbrace{f(y) \ge f(x) + \nabla f(x)^\top (y - x)\ \ \forall x,y}_{\text{first order: tangent planes are global under-estimators}} \qquad\Longleftrightarrow\qquad \underbrace{H(x) \succeq 0\ \ \forall x}_{\text{second order}}

The first-order form has the consequence that matters most: if ∇f(x∗)=0\nabla f(x^*) = 0, then f(y)≥f(x∗)f(y) \ge f(x^*) for every yy. 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 (H≻0H\succ 0) means at most one minimiser. μ\mu-strongly convex and LL-smooth (μI⪯H⪯LI\mu I \preceq H \preceq LI) gives gradient descent its linear rate, governed by κ=L/μ\kappa = L/\mu.

Convexity is preserved by non-negative sums, by composition with an affine map x↦f(Ax+b)x \mapsto f(Ax + b), and by pointwise maxima. The examples used later:

FunctionWhy it is convexWhere it appears
lse(z)=log⁡∑iezi\mathrm{lse}(z) = \log\sum_i e^{z_i}H=diag(p)−pp⊤H = \mathrm{diag}(p) - pp^\top with p=softmax(z)p = \mathrm{softmax}(z): a covariance matrix, hence ⪰0\succeq 0cross-entropy loss in the logits
−log⁡py(z)=lse(z)−zy-\log p_y(z) = \mathrm{lse}(z) - z_ylse plus a linear termsoftmax / logistic regression is a convex problem in its weights (affine composition)
negative entropy ∑ipilog⁡pi\sum_i p_i\log p_iH=diag(1/pi)≻0H = \mathrm{diag}(1/p_i) \succ 0entropy bonus, KL
KL(p∥q)\mathrm{KL}(p\Vert q)jointly convex in (p,q)(p, q)every KL penalty on this site
∥x∥\Vert x\Vert, max⁡ixi\max_i x_itriangle inequality; max of linear functionsregularisers, 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 π\pi, the DPO loss in the implicit-reward margin.

Jensen’s inequality

For convex ff and any random variable XX with finite mean,

E[f(X)]  ≥  f(E[X]),\mathbb{E}[f(X)] \;\ge\; f(\mathbb{E}[X]),

with the inequality reversed for concave ff. Proof in one line from the first-order condition: put μ=E[X]\mu = \mathbb{E}[X] and take any subgradient gg of ff at μ\mu; then f(X)≥f(μ)+g⊤(X−μ)f(X) \ge f(\mu) + g^\top(X - \mu) pointwise, and taking expectations kills the linear term. Equality holds iff ff is affine on the support of XX (for strictly convex ff: iff XX is constant).

It is the most-used inequality in ML:

  • KL ≥ 0 (Gibbs’ inequality): −KL(p∥q)=Ep[log⁡(q/p)]≤log⁡Ep[q/p]=log⁡1=0-\mathrm{KL}(p\|q) = \mathbb{E}_p[\log(q/p)] \le \log\mathbb{E}_p[q/p] = \log 1 = 0, using concavity of log⁡\log (probability and losses).
  • Variational lower bounds: log⁡p(x)=log⁡Eq[p(x,z)/q(z)]≥Eq[log⁡p(x,z)−log⁡q(z)]\log p(x) = \log\mathbb{E}_q[p(x,z)/q(z)] \ge \mathbb{E}_q[\log p(x,z) - \log q(z)] — the ELBO behind EM (unsupervised) and some distillation bounds.
  • k3≥0k_3 \ge 0 for the KL estimator in KL-regularised RL is the pointwise version log⁡u≤u−1\log u \le u - 1, the tangent line of the concave log⁡\log at 11.
  • Plug-in estimators of non-linear quantities are biased: plugging an unbiased p^\hat p into a convex function over-estimates on average. That is why the naive pass@k estimator is biased (statistics lesson).
NumPy Hessian test, convexity of log-sum-exp, Jensen
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 (1,…,1)(1,\dots,1): 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 ZZ.

Equality constraints: Lagrange multipliers

Now minimise f(x)f(x) subject to g(x)=0g(x) = 0. At a constrained optimum x∗x^*, moving along the constraint surface cannot decrease ff to first order. The feasible directions are those with ∇g(x∗)⊤d=0\nabla g(x^*)^\top d = 0; for all of them we need ∇f(x∗)⊤d=0\nabla f(x^*)^\top d = 0. So ∇f\nabla f is orthogonal to everything orthogonal to ∇g\nabla g, i.e. it is parallel to ∇g\nabla g:

∇f(x∗)+ν ∇g(x∗)=0for some ν∈R.\nabla f(x^*) + \nu\, \nabla g(x^*) = 0 \quad\text{for some } \nu\in\mathbb{R}.

Geometrically: the level set of ff through x∗x^* 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 L(x,ν)=f(x)+ν g(x)\mathcal{L}(x,\nu) = f(x) + \nu\, g(x), the optimum is a stationary point of L\mathcal{L} in both arguments: ∇xL=0\nabla_x\mathcal{L} = 0 is tangency and ∂νL=g(x)=0\partial_\nu\mathcal{L} = g(x) = 0 is feasibility. (This needs ∇g(x∗)≠0\nabla g(x^*) \ne 0, a “constraint qualification”; with several constraints, linearly independent gradients.)

A worked case — the figure below. Minimise f(x)=12(x−c)⊤A(x−c)f(x) = \tfrac12(x-c)^\top A(x-c) with A≻0A\succ 0 subject to a⊤x=ba^\top x = b. Stationarity gives A(x−c)+νa=0A(x - c) + \nu a = 0, so x=c−νA−1ax = c - \nu A^{-1}a. Substituting into the constraint,

ν=a⊤c−ba⊤A−1a,f∗(b)=(a⊤c−b)22 a⊤A−1a,∂f∗∂b=−ν.\nu = \frac{a^\top c - b}{a^\top A^{-1}a}, \qquad f^*(b) = \frac{(a^\top c - b)^2}{2\, a^\top A^{-1}a}, \qquad \frac{\partial f^*}{\partial b} = -\nu .

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 g(x)=h(x)−bg(x) = h(x) - b, ∂f∗/∂b=−ν\partial f^*/\partial b = -\nu at a regular optimum.

해 볼 것:

  1. λ1=2, λ2=0.5\lambda_1 = 2,\ \lambda_2 = 0.5이면 볼록한 그릇이고, 경사하강법은 가파른 고유벡터 방향으로는 빨리, 완만한 방향으로는 느리게 간다. 경사하강법 레슨의 조건수 κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}이다.
  2. λ2\lambda_2를 00으로: 평평한 골짜기다. 골짜기 바닥의 모든 점이 최소점이고, 경사하강법은 바닥에 닿은 곳에서 멈추며, Newton step은 정의되지 않는다.
  3. λ2\lambda_2를 −1-1로: 안장점이다. 경사하강법은 음의 곡률 고유벡터를 따라 빠져나가지만(그 성분은 매 step 1+η∣λ2∣1 + \eta|\lambda_2|배가 된다) Newton은 여전히 안장점으로 뛴다.

Newton법은 1차 모델 대신 2차 모델을 최소화한다. f+g⊤d+12d⊤Hdf + g^\top d + \tfrac12 d^\top H d의 기울기를 0으로 두면 d=−H−1gd = -H^{-1}g다. 이차 함수에서는 κ\kappa와 상관없이 한 step에 정확하다. 고유 방향마다 그 방향의 곡률로 나누기 때문이다. 하지만 Newton은 최소점이 아니라 ∇f=0\nabla f = 0을 찾는다. HH가 부정부호이면 안장점으로 끌려간다. 그리고 우리가 다루는 손실 지형에서는 안장점이 흔하다. 무작위 함수 모형(Gaussian random field, Bray & Dean 2007)과 신경망 손실을 실험으로 살핀 Dauphin et al.(2014)에서 손실이 높은 임계점은 압도적으로 안장점이다. 이는 그런 지형에 대한 관찰이지 고차원의 법칙이 아니다. (x12−1)2+∑j=2dxj2(x_1^2-1)^2 + \sum_{j=2}^d x_j^2은 모든 d≥2d \ge 2에서 최소 두 개와 안장점 하나만 가진다. n∼1010n \sim 10^{10}에서 n×nn\times n Hessian을 저장하고 역행렬을 구하는 것도 불가능하다. 딥러닝에 살아남은 것은 H−1H^{-1}을 흉내 내는 값싼 preconditioner다. Adam의 좌표별 스케일링(옵티마이저)과 Muon의 직교화 업데이트(Muon)가 그렇다. GPTQ는 층 단위 이차 문제의 정확한 Hessian을 쓴다(양자화).

볼록성

집합 C\mathcal{C}의 어떤 두 점을 이은 선분도 그 안에 머물면 C\mathcal{C}는 볼록(convex) 하다. 볼록 집합 위의 함수 ff가

f(θx+(1−θ)y)≤θf(x)+(1−θ)f(y)∀x,y, θ∈[0,1]f(\theta x + (1-\theta) y) \le \theta f(x) + (1-\theta) f(y) \qquad \forall x, y,\ \theta\in[0,1]

을 만족하면 볼록 함수다. 현(chord)이 그래프 위에 있다는 뜻이다. 미분 가능한 ff에는 동치인 판정이 둘 있다.

f(y)≥f(x)+∇f(x)⊤(y−x)  ∀x,y⏟1차: 접평면이 전역 하한⟺H(x)⪰0  ∀x⏟2차\underbrace{f(y) \ge f(x) + \nabla f(x)^\top (y - x)\ \ \forall x,y}_{\text{1차: 접평면이 전역 하한}} \qquad\Longleftrightarrow\qquad \underbrace{H(x) \succeq 0\ \ \forall x}_{\text{2차}}

1차 형태에서 가장 중요한 결과가 나온다. ∇f(x∗)=0\nabla f(x^*) = 0이면 모든 yy에 대해 f(y)≥f(x∗)f(y) \ge f(x^*)다. 볼록 함수에서는 모든 정류점이 전역 최소이고, 최소점들의 집합은 볼록하다(한 점이거나, 위 2번처럼 평평한 골짜기). 엄격히 볼록(H≻0H\succ 0)하면 최소점은 많아야 하나다. μ\mu-강볼록이고 LL-smooth(μI⪯H⪯LI\mu I \preceq H \preceq LI)이면 경사하강법이 선형 수렴하고, 그 속도를 κ=L/μ\kappa = L/\mu가 정한다.

볼록성은 음이 아닌 가중합, 아핀 사상과의 합성 x↦f(Ax+b)x \mapsto f(Ax + b), 점별 최댓값으로 보존된다. 뒤에서 쓰는 예:

함수왜 볼록인가쓰이는 곳
lse(z)=log⁡∑iezi\mathrm{lse}(z) = \log\sum_i e^{z_i}H=diag(p)−pp⊤H = \mathrm{diag}(p) - pp^\top, p=softmax(z)p = \mathrm{softmax}(z): 공분산 행렬이라 ⪰0\succeq 0logit에 대한 cross-entropy 손실
−log⁡py(z)=lse(z)−zy-\log p_y(z) = \mathrm{lse}(z) - z_ylse + 선형항softmax·로지스틱 회귀는 가중치에 대해 볼록 문제(아핀 합성)
음의 엔트로피 ∑ipilog⁡pi\sum_i p_i\log p_iH=diag(1/pi)≻0H = \mathrm{diag}(1/p_i) \succ 0엔트로피 보너스, KL
KL(p∥q)\mathrm{KL}(p\Vert q)(p,q)(p, q)에 대해 결합 볼록이 사이트의 모든 KL 패널티
∥x∥\Vert x\Vert, max⁡ixi\max_i x_i삼각부등식, 선형 함수들의 최댓값정규화, hinge 손실

딥 네트워크는 가중치에 대해 볼록이 아니다(은닉 유닛의 순서만 바꿔도 값이 같은 서로 다른 최소점이 생긴다). 그래서 딥넷 학습에 관한 모든 이야기는 국소적이다. 하지만 중요한 변수에 대해서는 볼록인 부분 문제가 많다. logit에 대한 손실, 분포 π\pi에 대한 KL 정규화 목적함수, implicit reward 마진에 대한 DPO 손실이 그렇다.

Jensen 부등식

볼록 함수 ff와 평균이 유한한 확률변수 XX에 대해

E[f(X)]  ≥  f(E[X])\mathbb{E}[f(X)] \;\ge\; f(\mathbb{E}[X])

이고, 오목 함수면 부등호가 뒤집힌다. 증명은 1차 조건에서 한 줄이다. μ=E[X]\mu = \mathbb{E}[X]로 두고 μ\mu에서 ff의 subgradient gg를 아무거나 잡으면 점별로 f(X)≥f(μ)+g⊤(X−μ)f(X) \ge f(\mu) + g^\top(X - \mu)이고, 기댓값을 취하면 선형항이 사라진다. 등호는 ff가 XX의 support 위에서 아핀일 때만 성립한다(엄격 볼록이면 XX가 상수일 때만).

ML에서 가장 많이 쓰이는 부등식이다.

  • KL ≥ 0(Gibbs 부등식): log⁡\log의 오목성으로 −KL(p∥q)=Ep[log⁡(q/p)]≤log⁡Ep[q/p]=log⁡1=0-\mathrm{KL}(p\|q) = \mathbb{E}_p[\log(q/p)] \le \log\mathbb{E}_p[q/p] = \log 1 = 0(확률로 보는 손실).
  • 변분 하한: log⁡p(x)=log⁡Eq[p(x,z)/q(z)]≥Eq[log⁡p(x,z)−log⁡q(z)]\log p(x) = \log\mathbb{E}_q[p(x,z)/q(z)] \ge \mathbb{E}_q[\log p(x,z) - \log q(z)]. EM(비지도)과 일부 증류 bound 뒤에 있는 ELBO다.
  • KL 정규화 RL의 KL 추정량 k3≥0k_3 \ge 0 은 점별 버전 log⁡u≤u−1\log u \le u - 1, 즉 오목한 log⁡\log의 1에서의 접선이다.
  • 비선형 양의 plug-in 추정량은 편향된다: 불편 추정량 p^\hat p를 볼록 함수에 넣으면 평균적으로 과대추정한다. 순진한 pass@k 추정량이 편향된 이유다(통계 레슨).
NumPy Hessian 판정, log-sum-exp의 볼록성, Jensen
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 고유값은 (1,…,1)(1,\dots,1) 방향이다. 모든 logit에 같은 상수를 더해도 softmax는 그대로다. logit이 평행이동만큼 정의되지 않는 이유이고, 아래 KL 정규화 해에 정규화 상수 ZZ가 붙는 이유다.

등식 제약: 라그랑주 승수

이제 g(x)=0g(x) = 0 아래서 f(x)f(x)를 최소화한다. 제약 최적점 x∗x^*에서는 제약면을 따라 움직여도 1차까지 ff가 줄지 않아야 한다. 허용되는 방향은 ∇g(x∗)⊤d=0\nabla g(x^*)^\top d = 0인 dd이고, 그 모두에 대해 ∇f(x∗)⊤d=0\nabla f(x^*)^\top d = 0이어야 한다. 즉 ∇f\nabla f는 ∇g\nabla g에 수직인 모든 것에 수직이므로 ∇g\nabla g와 평행하다.

∇f(x∗)+ν ∇g(x∗)=0어떤 ν∈R에 대해.\nabla f(x^*) + \nu\, \nabla g(x^*) = 0 \quad\text{어떤 } \nu\in\mathbb{R}\text{에 대해}.

기하학적으로는 x∗x^*를 지나는 ff의 등위선이 제약에 접한다는 뜻이다. 등위선이 제약을 가로지른다면 제약을 따라 미끄러져 더 낮은 등위선으로 갈 수 있다. 두 조건을 라그랑지안 L(x,ν)=f(x)+ν g(x)\mathcal{L}(x,\nu) = f(x) + \nu\, g(x) 하나로 묶으면 최적점은 두 인자 모두에 대한 L\mathcal{L}의 정류점이다. ∇xL=0\nabla_x\mathcal{L} = 0은 접함, ∂νL=g(x)=0\partial_\nu\mathcal{L} = g(x) = 0은 허용 가능성이다. (여기에는 ∇g(x∗)≠0\nabla g(x^*) \ne 0이라는 “제약 자격 조건”이 필요하다. 제약이 여럿이면 기울기들이 선형 독립이어야 한다.)

풀어 보는 예: 아래 그림. A≻0A\succ 0인 f(x)=12(x−c)⊤A(x−c)f(x) = \tfrac12(x-c)^\top A(x-c)를 a⊤x=ba^\top x = b 아래서 최소화한다. 정류 조건은 A(x−c)+νa=0A(x - c) + \nu a = 0이므로 x=c−νA−1ax = c - \nu A^{-1}a. 이것을 제약에 넣으면

ν=a⊤c−ba⊤A−1a,f∗(b)=(a⊤c−b)22 a⊤A−1a,∂f∗∂b=−ν.\nu = \frac{a^\top c - b}{a^\top A^{-1}a}, \qquad f^*(b) = \frac{(a^\top c - b)^2}{2\, a^\top A^{-1}a}, \qquad \frac{\partial f^*}{\partial b} = -\nu .

마지막 등식은 일반적이다(envelope theorem). 승수는 제약 수준에 대한 최적값의 민감도, 곧 제약의 “그림자 가격(shadow price)“이다. g(x)=h(x)−bg(x) = h(x) - b이면 정칙인 최적점에서 ∂f∗/∂b=−ν\partial f^*/\partial b = -\nu다.

x* – f(x*) – ν – −∂f*/∂b (수치)(numerical) –
Drag on the plane to slide the constraint line through the pointer, or turn its normal a. Blue ellipses are level sets of f, × is the unconstrained minimum. At the constrained optimum the level set through x* just touches the line, so ∇f (blue) and the constraint normal a (red) are parallel: ∇f + ν a = 0. The readout −∂f*/∂b, measured by moving b a little, always equals ν — the multiplier is the price of the constraint. Switch to the inequality and pull the line past ×: once × is feasible the constraint goes slack and μ drops to exactly 0 (complementary slackness). 평면을 끌면 제약 직선이 포인터를 지나도록 옮겨지고, 법선 a의 방향도 돌릴 수 있다. 파란 타원은 f의 등위선, ×는 제약 없는 최소점이다. 제약 최적점에서는 x*를 지나는 등위선이 직선에 꼭 접하므로 ∇f(파랑)와 제약의 법선 a(빨강)가 평행하다: ∇f + ν a = 0. b를 조금 움직여 잰 −∂f*/∂b는 언제나 ν와 같다. 승수는 제약의 가격이다. 부등식으로 바꾸고 직선을 × 너머로 밀어 보라. ×가 허용 영역에 들어오는 순간 제약이 느슨해지고 μ는 정확히 0이 된다(complementary slackness).

Inequality constraints: the KKT conditions

For min⁡f(x)\min f(x) subject to gi(x)≤0g_i(x) \le 0 and hj(x)=0h_j(x) = 0, the Lagrangian is L=f+∑iμigi+∑jνjhj\mathcal{L} = f + \sum_i \mu_i g_i + \sum_j \nu_j h_j and, under a constraint qualification, a local optimum satisfies the Karush–Kuhn–Tucker conditions:

stationarity∇f(x∗)+∑iμi∇gi(x∗)+∑jνj∇hj(x∗)=0primal feasibilitygi(x∗)≤0,hj(x∗)=0dual feasibilityμi≥0complementary slacknessμi gi(x∗)=0.\begin{aligned} &\text{stationarity} && \nabla f(x^*) + \textstyle\sum_i \mu_i \nabla g_i(x^*) + \sum_j \nu_j \nabla h_j(x^*) = 0\\ &\text{primal feasibility} && g_i(x^*) \le 0,\quad h_j(x^*) = 0\\ &\text{dual feasibility} && \mu_i \ge 0\\ &\text{complementary slackness} && \mu_i\, g_i(x^*) = 0 . \end{aligned}

Dual feasibility says an inequality can only push (−∇f-\nabla f points out of the feasible set, against the wall). Complementary slackness says each inequality is either active (gi=0g_i = 0, the wall is touched, μi≥0\mu_i \ge 0) or slack (gi<0g_i < 0, it is irrelevant, μi=0\mu_i = 0) — exactly what the figure shows when you drag the line past the unconstrained minimum.

For a convex problem (f,gif, g_i convex, hjh_j 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 q(μ,ν)=inf⁡xL(x,μ,ν)q(\mu,\nu) = \inf_x \mathcal{L}(x,\mu,\nu) is a lower bound on the optimum for every μ≥0\mu \ge 0 (weak duality — always true), and its maximum equals the optimum. Dual ascent — raise μ\mu 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.

NumPy KKT as a linear system; the multiplier is the shadow price
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}")
 
확인 문제Check yourself

You minimise f(x) subject to h(x) ≤ b and the solver returns the multiplier μ = 0. What does this tell you?

Complementary slackness: μ (h(x∗)−b)=0\mu\,(h(x^*) - b) = 0. With μ=0\mu = 0 the constraint exerts no force, and by the shadow-price identity ∂f∗/∂b=−μ=0\partial f^*/\partial b = -\mu = 0 — moving the wall a little does not change the optimum. (An active constraint can also have μ=0\mu = 0 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 nn options with scores zz is max⁡p∈Δ p⊤z\max_{p\in\Delta}\ p^\top z over the probability simplex Δ={p≥0, ∑ipi=1}\Delta = \{p \ge 0,\ \sum_i p_i = 1\}. A linear function on a polytope is maximised at a vertex: a one-hot argmax, which is not differentiable in zz. Add an entropy bonus with temperature τ>0\tau > 0:

max⁡p∈Δ ∑ipizi+τH(p),H(p)=−∑ipilog⁡pi.\max_{p\in\Delta}\ \sum_i p_i z_i + \tau H(p), \qquad H(p) = -\sum_i p_i \log p_i .

The objective is strictly concave (the Hessian of τH\tau H is −τ diag(1/pi)≺0-\tau\,\mathrm{diag}(1/p_i) \prec 0), so a stationary point of the Lagrangian on the simplex is the unique optimum. Attach a multiplier ν\nu to ∑ipi=1\sum_i p_i = 1:

∂∂pi[∑kpkzk−τ∑kpklog⁡pk+ν(1−∑kpk)]=zi−τ(log⁡pi+1)−ν=0  ⇒  pi=ezi/τ e−1−ν/τ.\frac{\partial}{\partial p_i}\Big[\sum_k p_k z_k - \tau\sum_k p_k\log p_k + \nu\big(1 - \textstyle\sum_k p_k\big)\Big] = z_i - \tau(\log p_i + 1) - \nu = 0 \;\Rightarrow\; p_i = e^{z_i/\tau}\, e^{-1-\nu/\tau}.

The factor e−1−ν/τe^{-1-\nu/\tau} is the same for every ii; normalisation fixes it, giving p=softmax(z/τ)p = \mathrm{softmax}(z/\tau). The constraints pi≥0p_i \ge 0 never become active because −log⁡pi→∞-\log p_i \to \infty as pi→0p_i \to 0 — the entropy acts as a barrier — so their multipliers are 0 and we could ignore them. Plugging back in, the optimal value is τ lse(z/τ)\tau\,\mathrm{lse}(z/\tau), a smooth upper bound on max⁡izi\max_i z_i that converges to it as τ→0\tau \to 0 (and ∇z τ lse(z/τ)=softmax(z/τ)\nabla_z\, \tau\,\mathrm{lse}(z/\tau) = \mathrm{softmax}(z/\tau)). 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,

max⁡π∈Δ J(π)=∑yπ(y) r(y)−β∑yπ(y)log⁡π(y)πref(y).\max_{\pi\in\Delta}\ J(\pi) = \sum_y \pi(y)\,r(y) - \beta\sum_y \pi(y)\log\frac{\pi(y)}{\pi_{\text{ref}}(y)} .

This is the objective of KL-regularised RL. Again the objective is strictly concave in π\pi (Hessian −β diag(1/π)-\beta\,\mathrm{diag}(1/\pi)), and the stationarity condition of the Lagrangian with multiplier ν\nu for normalisation is

r(y)−β(log⁡π(y)πref(y)+1)−ν=0  ⇒  π∗(y)=1Z πref(y)exp⁡ ⁣(r(y)β),Z=∑yπref(y) er(y)/β.r(y) - \beta\Big(\log\frac{\pi(y)}{\pi_{\text{ref}}(y)} + 1\Big) - \nu = 0 \;\Rightarrow\; \pi^*(y) = \frac{1}{Z}\,\pi_{\text{ref}}(y)\exp\!\Big(\frac{r(y)}{\beta}\Big),\quad Z = \sum_y \pi_{\text{ref}}(y)\,e^{r(y)/\beta}.

Substituting back, log⁡π∗πref=r/β−log⁡Z\log\frac{\pi^*}{\pi_{\text{ref}}} = r/\beta - \log Z, so J(π∗)=Eπ∗[r]−Eπ∗[r]+βlog⁡Z=βlog⁡ZJ(\pi^*) = \mathbb{E}_{\pi^*}[r] - \mathbb{E}_{\pi^*}[r] + \beta\log Z = \beta\log Z. This is the Gibbs variational principle: max⁡π Eπ[r]−τ KL(π∥πref)=τlog⁡Eπref[er/τ]\max_\pi\ \mathbb{E}_\pi[r] - \tau\,\mathrm{KL}(\pi\|\pi_{\text{ref}}) = \tau\log\mathbb{E}_{\pi_{\text{ref}}}[e^{r/\tau}], attained by the Gibbs distribution π∗∝πrefer/τ\pi^* \propto \pi_{\text{ref}}e^{r/\tau} (Kimi k1.5 writes τ where RLHF papers write β). Softmax is the special case of a uniform πref\pi_{\text{ref}} (KL to uniform = log⁡n−H\log n - H). The rlhf-ppo lesson reaches the same formula by completing the KL, J(π)=βlog⁡Z−β KL(π∥π∗)J(\pi) = \beta\log Z - \beta\,\mathrm{KL}(\pi\|\pi^*); the Lagrangian route shows why it has this shape — every response must have the same marginal value r−β(log⁡ππref+1)r - \beta(\log\frac{\pi}{\pi_{\text{ref}}} + 1) at the optimum, otherwise moving mass from a low-value response to a high-value one would increase JJ.

β as a multiplier. The penalised problem is the Lagrangian of the constrained one, max⁡ Eπ[r]\max\ \mathbb{E}_\pi[r] subject to KL(π∥πref)≤ϵ\mathrm{KL}(\pi\|\pi_{\text{ref}}) \le \epsilon, with β\beta the multiplier of the KL budget. Each β traces one point (K(β),R(β))=(KL(πβ∗∥πref),Eπβ∗[r])(K(\beta), R(\beta)) = (\mathrm{KL}(\pi^*_\beta\|\pi_{\text{ref}}), \mathbb{E}_{\pi^*_\beta}[r]) of the reward–KL frontier, and the shadow-price identity says its slope is β. Directly: K=R/β−log⁡ZK = R/\beta - \log Z and dlog⁡Zdβ=−R/β2\frac{d\log Z}{d\beta} = -R/\beta^2, so dKdβ=1βdRdβ\frac{dK}{d\beta} = \frac{1}{\beta}\frac{dR}{d\beta} and

dRdK=β.\frac{dR}{dK} = \beta .

부등식 제약: KKT 조건

gi(x)≤0g_i(x) \le 0, hj(x)=0h_j(x) = 0 아래서 min⁡f(x)\min f(x)이면 라그랑지안은 L=f+∑iμigi+∑jνjhj\mathcal{L} = f + \sum_i \mu_i g_i + \sum_j \nu_j h_j이고, 제약 자격 조건 아래서 국소 최적점은 Karush–Kuhn–Tucker(KKT) 조건을 만족한다.

정류성∇f(x∗)+∑iμi∇gi(x∗)+∑jνj∇hj(x∗)=0원문제 허용성gi(x∗)≤0,hj(x∗)=0쌍대 허용성μi≥0상보 여유성μi gi(x∗)=0.\begin{aligned} &\text{정류성} && \nabla f(x^*) + \textstyle\sum_i \mu_i \nabla g_i(x^*) + \sum_j \nu_j \nabla h_j(x^*) = 0\\ &\text{원문제 허용성} && g_i(x^*) \le 0,\quad h_j(x^*) = 0\\ &\text{쌍대 허용성} && \mu_i \ge 0\\ &\text{상보 여유성} && \mu_i\, g_i(x^*) = 0 . \end{aligned}

쌍대 허용성은 부등식 제약이 밀어내기만 할 수 있다는 뜻이다(−∇f-\nabla f가 허용 영역 바깥, 벽 쪽을 향한다). 상보 여유성(complementary slackness)은 각 부등식이 활성(gi=0g_i = 0, 벽에 닿음, μi≥0\mu_i \ge 0)이거나 느슨(gi<0g_i < 0, 무관함, μi=0\mu_i = 0)하다는 뜻이다. 직선을 제약 없는 최소점 너머로 끌었을 때 그림이 보여 준 그대로다.

볼록 문제(f,gif, g_i 볼록, hjh_j 아핀)이고 엄격히 허용 가능한 점이 있으면(Slater 조건) KKT는 전역 최적의 필요충분조건이고 강쌍대성이 성립한다. 쌍대 함수 q(μ,ν)=inf⁡xL(x,μ,ν)q(\mu,\nu) = \inf_x \mathcal{L}(x,\mu,\nu)는 모든 μ≥0\mu \ge 0에서 최적값의 하한이고(약쌍대성, 항상 참), 그 최댓값이 최적값과 같다. 쌍대 상승(제약을 어기면 μ\mu를 올리고, 느슨하면 0 아래로는 내리지 않으며 낮춘다)이 adaptive KL controller가 KL 목표를 향해 β를 조정하는 방식이고(KL 정규화 RL), 길이 예산 같은 제약을 라그랑주 방식으로 강제하는 방식이다.

NumPy 선형 시스템으로 푸는 KKT; 승수 = 그림자 가격
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}")
 
확인 문제Check yourself

h(x) ≤ b 아래서 f(x)를 최소화했더니 승수 μ = 0이 나왔다. 무엇을 알 수 있는가?

상보 여유성 μ (h(x∗)−b)=0\mu\,(h(x^*) - b) = 0. μ=0\mu = 0이면 제약은 아무 힘도 쓰지 않고, 그림자 가격 등식에 의해 ∂f∗/∂b=−μ=0\partial f^*/\partial b = -\mu = 0이다. 벽을 조금 옮겨도 최적점이 그대로다. (퇴화한 경우, 즉 제약 없는 최소점이 정확히 벽 위에 있으면 활성 제약도 μ=0\mu = 0일 수 있다. 그때도 그림자 가격은 0이다.)

softmax는 엔트로피 정규화 argmax다

점수 zz를 가진 nn개 중 최선을 고르는 것은 확률 simplex Δ={p≥0, ∑ipi=1}\Delta = \{p \ge 0,\ \sum_i p_i = 1\} 위의 max⁡p∈Δ p⊤z\max_{p\in\Delta}\ p^\top z다. 다면체 위의 선형 함수는 꼭짓점에서 최대가 된다. one-hot argmax이고, zz에 대해 미분할 수 없다. 온도 τ>0\tau > 0의 엔트로피 보너스를 더하자.

max⁡p∈Δ ∑ipizi+τH(p),H(p)=−∑ipilog⁡pi.\max_{p\in\Delta}\ \sum_i p_i z_i + \tau H(p), \qquad H(p) = -\sum_i p_i \log p_i .

목적함수는 엄격히 오목하므로(τH\tau H의 Hessian이 −τ diag(1/pi)≺0-\tau\,\mathrm{diag}(1/p_i) \prec 0) simplex 위 라그랑지안의 정류점이 유일한 최적해다. ∑ipi=1\sum_i p_i = 1에 승수 ν\nu를 붙인다.

∂∂pi[∑kpkzk−τ∑kpklog⁡pk+ν(1−∑kpk)]=zi−τ(log⁡pi+1)−ν=0  ⇒  pi=ezi/τ e−1−ν/τ.\frac{\partial}{\partial p_i}\Big[\sum_k p_k z_k - \tau\sum_k p_k\log p_k + \nu\big(1 - \textstyle\sum_k p_k\big)\Big] = z_i - \tau(\log p_i + 1) - \nu = 0 \;\Rightarrow\; p_i = e^{z_i/\tau}\, e^{-1-\nu/\tau}.

e−1−ν/τe^{-1-\nu/\tau}는 모든 ii에 공통이고 정규화가 그 값을 정하므로 p=softmax(z/τ)p = \mathrm{softmax}(z/\tau)다. pi→0p_i \to 0이면 −log⁡pi→∞-\log p_i \to \infty이므로 pi≥0p_i \ge 0 제약은 결코 활성이 되지 않는다(엔트로피가 장벽 역할을 한다). 그래서 그 승수는 0이고 무시해도 된다. 다시 대입하면 최적값은 τ lse(z/τ)\tau\,\mathrm{lse}(z/\tau), max⁡izi\max_i z_i의 매끄러운 상한이고 τ→0\tau \to 0이면 그것으로 수렴한다(∇z τ lse(z/τ)=softmax(z/τ)\nabla_z\, \tau\,\mathrm{lse}(z/\tau) = \mathrm{softmax}(z/\tau)). 디코딩의 샘플링 온도가 logit을 나누는 것인 변분적 이유이고, 다음 결과의 틀이다.

KL 정규화의 최적해

엔트로피 보너스를 기준 분포에 대한 KL 패널티로, 점수를 보상으로 바꾼다. 프롬프트 하나에 대해

max⁡π∈Δ J(π)=∑yπ(y) r(y)−β∑yπ(y)log⁡π(y)πref(y).\max_{\pi\in\Delta}\ J(\pi) = \sum_y \pi(y)\,r(y) - \beta\sum_y \pi(y)\log\frac{\pi(y)}{\pi_{\text{ref}}(y)} .

KL 정규화 RL의 목적함수다. 이번에도 π\pi에 대해 엄격히 오목하고(Hessian −β diag(1/π)-\beta\,\mathrm{diag}(1/\pi)), 정규화 승수 ν\nu를 붙인 라그랑지안의 정류 조건은

r(y)−β(log⁡π(y)πref(y)+1)−ν=0  ⇒  π∗(y)=1Z πref(y)exp⁡ ⁣(r(y)β),Z=∑yπref(y) er(y)/β.r(y) - \beta\Big(\log\frac{\pi(y)}{\pi_{\text{ref}}(y)} + 1\Big) - \nu = 0 \;\Rightarrow\; \pi^*(y) = \frac{1}{Z}\,\pi_{\text{ref}}(y)\exp\!\Big(\frac{r(y)}{\beta}\Big),\quad Z = \sum_y \pi_{\text{ref}}(y)\,e^{r(y)/\beta}.

다시 대입하면 log⁡π∗πref=r/β−log⁡Z\log\frac{\pi^*}{\pi_{\text{ref}}} = r/\beta - \log Z이므로 J(π∗)=Eπ∗[r]−Eπ∗[r]+βlog⁡Z=βlog⁡ZJ(\pi^*) = \mathbb{E}_{\pi^*}[r] - \mathbb{E}_{\pi^*}[r] + \beta\log Z = \beta\log Z다. 이것이 Gibbs 변분 원리다: max⁡π Eπ[r]−τ KL(π∥πref)=τlog⁡Eπref[er/τ]\max_\pi\ \mathbb{E}_\pi[r] - \tau\,\mathrm{KL}(\pi\|\pi_{\text{ref}}) = \tau\log\mathbb{E}_{\pi_{\text{ref}}}[e^{r/\tau}]이고, Gibbs 분포 π∗∝πrefer/τ\pi^* \propto \pi_{\text{ref}}e^{r/\tau}에서 달성된다(Kimi k1.5는 RLHF 논문의 β 자리에 τ를 쓴다). softmax는 πref\pi_{\text{ref}}가 균등한 특수한 경우다(균등 분포에 대한 KL = log⁡n−H\log n - H). rlhf-ppo 레슨은 KL을 완성하는 방식 J(π)=βlog⁡Z−β KL(π∥π∗)J(\pi) = \beta\log Z - \beta\,\mathrm{KL}(\pi\|\pi^*)으로 같은 식에 닿는다. 라그랑주 경로는 해가 왜 이 모양인지 보여 준다. 최적점에서는 모든 응답의 한계 가치 r−β(log⁡ππref+1)r - \beta(\log\frac{\pi}{\pi_{\text{ref}}} + 1)가 같아야 한다. 아니라면 가치가 낮은 응답에서 높은 응답으로 질량을 옮겨 JJ를 키울 수 있다.

승수로서의 β. 패널티 문제는 제약 문제 ”KL(π∥πref)≤ϵ\mathrm{KL}(\pi\|\pi_{\text{ref}}) \le \epsilon 아래서 max⁡ Eπ[r]\max\ \mathbb{E}_\pi[r]“의 라그랑지안이고, β는 KL 예산의 승수다. β 하나가 보상–KL frontier 위의 점 (K(β),R(β))=(KL(πβ∗∥πref),Eπβ∗[r])(K(\beta), R(\beta)) = (\mathrm{KL}(\pi^*_\beta\|\pi_{\text{ref}}), \mathbb{E}_{\pi^*_\beta}[r]) 하나를 그리고, 그림자 가격 등식은 그 기울기가 β라고 말한다. 직접 확인하면 K=R/β−log⁡ZK = R/\beta - \log Z이고 dlog⁡Zdβ=−R/β2\frac{d\log Z}{d\beta} = -R/\beta^2이므로 dKdβ=1βdRdβ\frac{dK}{d\beta} = \frac{1}{\beta}\frac{dR}{d\beta}, 곧

dRdK=β.\frac{dR}{dK} = \beta .
Eπ*[r] – KL(π*‖πref) – J = E[r] − β·KL – β log Z –
Six candidate responses. Grey bars are πref, blue bars the optimum π* ∝ πref·er/β; drag the dots in the lower strip to change the rewards. Large β leaves πref almost untouched; small β piles everything on the best response. The optimal value J always equals β log Z. Right: every β gives one point (KL, E[r]) on a concave frontier, and the tangent there has slope exactly β — β is the exchange rate between reward and KL, the Lagrange multiplier of a KL budget. Tick uniform πref: the same formula becomes softmax(r/β), the entropy-regularised argmax. 응답 후보 여섯 개. 회색 막대는 πref, 파란 막대는 최적해 π* ∝ πref·er/β다. 아래 띠의 점을 끌어 보상을 바꿔 보라. β가 크면 πref가 거의 그대로이고, 작으면 가장 좋은 응답에 질량이 몰린다. 최적값 J는 언제나 β log Z와 같다. 오른쪽: β 하나마다 오목한 frontier 위의 점 (KL, E[r])이 하나 생기고, 그 점의 접선 기울기가 정확히 β다. β는 보상과 KL의 교환비, 곧 KL 예산 제약의 라그랑주 승수다. 균등 πref를 켜면 같은 식이 softmax(r/β), 즉 엔트로피 정규화된 argmax가 된다.

Three consequences to read off the figure: π* never puts mass where πref\pi_{\text{ref}} has none (the multiplicative form); only r/βr/\beta matters (doubling every reward = halving β); and adding a constant to every reward changes nothing (it is absorbed by ZZ — 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 ff plus a squared-distance penalty:

xt+1=arg⁡min⁡x ⟨∇f(xt),x⟩+12η∥x−xt∥22=xt−η∇f(xt).x_{t+1} = \arg\min_x\ \langle \nabla f(x_t), x\rangle + \frac{1}{2\eta}\|x - x_t\|_2^2 = x_t - \eta\nabla f(x_t).

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 rr (gradient of ⟨π,r⟩\langle\pi, r\rangle is rr):

πt+1=arg⁡max⁡π∈Δ ⟨r,π⟩−1η KL(π∥πt)  =  πt eηrZt.\pi_{t+1} = \arg\max_{\pi\in\Delta}\ \langle r, \pi\rangle - \frac{1}{\eta}\,\mathrm{KL}(\pi\|\pi_t) \;=\; \frac{\pi_t\, e^{\eta r}}{Z_t}.

This is the KL-regularised optimum with πref→πt\pi_{\text{ref}} \to \pi_t and β→1/η\beta \to 1/\eta: a multiplicative (exponentiated-gradient) update that never leaves the simplex and never needs a projection. Two readings follow. The RLHF solution π∗\pi^* is one mirror-ascent step of size 1/β1/\beta from πref\pi_{\text{ref}}. 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.

NumPy π* from the Lagrangian, the frontier slope, mirror ascent, softmax
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 η=1/β\eta = 1/\beta mirror ascent lands on π* in one step from any start: the update is πt+1∝πt1−ηβ πrefηβ eηr\pi_{t+1} \propto \pi_t^{1-\eta\beta}\,\pi_{\text{ref}}^{\eta\beta}\, e^{\eta r}, and ηβ=1\eta\beta = 1 erases πt\pi_t. With smaller η the error in log⁡π\log\pi shrinks by the factor 1−ηβ1-\eta\beta per step.

확인 문제Check yourself

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 r/βr/\beta up to an additive constant: π∗∝πref e(2r+5)/β′∝πref e2r/β′\pi^* \propto \pi_{\text{ref}}\,e^{(2r+5)/\beta'} \propto \pi_{\text{ref}}\,e^{2r/\beta'} (the e5/β′e^{5/\beta'} cancels in ZZ). Matching 2/β′=1/β2/\beta' = 1/\beta gives β′=2β\beta' = 2\beta.

Summary

  • Stationary point: ∇f=0\nabla f = 0. The Hessian’s eigenvalues classify it; u⊤Huu^\top Hu ranges over [λmin⁡,λmax⁡][\lambda_{\min}, \lambda_{\max}]. Newton (−H−1g-H^{-1}g) finds stationary points, not minima.
  • Convex ⇔ tangent planes under-estimate ⇔ H⪰0H \succeq 0; then every stationary point is global. lse, negative entropy and KL are convex; deep nets are not.
  • Jensen Ef(X)≥f(EX)\mathbb{E}f(X) \ge f(\mathbb{E}X) gives KL ≥ 0, the ELBO, k3≥0k_3 \ge 0, and the bias of plug-in estimators.
  • Lagrange: at the optimum the level set is tangent to the constraint, ∇f+ν∇g=0\nabla f + \nu\nabla g = 0; the multiplier is the shadow price −∂f∗/∂b-\partial f^*/\partial b. KKT adds μ≥0\mu \ge 0 and complementary slackness.
  • Entropy-regularised argmax = softmax(z/τ)(z/\tau); KL-regularised reward maximisation = πrefer/β/Z\pi_{\text{ref}}e^{r/\beta}/Z with value βlog⁡Z\beta\log Z, and β is the slope of the reward–KL frontier. Repeating that step from the previous policy is mirror descent.

Where this is used

그림에서 읽을 결과 셋. π*는 πref\pi_{\text{ref}}가 0인 곳에 질량을 두지 않는다(곱셈 꼴이므로). r/βr/\beta만 중요하다(보상을 모두 두 배 = β를 절반). 모든 보상에 상수를 더해도 아무것도 바뀌지 않는다(ZZ가 흡수한다. lse Hessian의 평평한 방향과 같은 이야기다). 마지막이 정책 경사에서 baseline이 공짜인 이유이고, DPO의 보상이 프롬프트별 상수만큼만 식별되는 이유다(DPO).

Mirror descent: 같은 한 걸음의 반복

경사하강법 자체가 작은 정규화 문제의 해다. ff의 선형 모델에 제곱 거리 패널티를 더한 것이다.

xt+1=arg⁡min⁡x ⟨∇f(xt),x⟩+12η∥x−xt∥22=xt−η∇f(xt).x_{t+1} = \arg\min_x\ \langle \nabla f(x_t), x\rangle + \frac{1}{2\eta}\|x - x_t\|_2^2 = x_t - \eta\nabla f(x_t).

유클리드 거리는 확률 벡터에 잘 맞지 않는다. 질량 0.01을 옮기는 일이 확률 0.5인 토큰보다 0.001인 토큰에 훨씬 큰 일이라는 점을 무시한다. Mirror descent는 이 거리를 기하에 맞는 Bregman divergence로 바꾼다. simplex 위에서는 KL이다. 보상 rr을 최대화하면(⟨π,r⟩\langle\pi, r\rangle의 기울기는 rr)

πt+1=arg⁡max⁡π∈Δ ⟨r,π⟩−1η KL(π∥πt)  =  πt eηrZt.\pi_{t+1} = \arg\max_{\pi\in\Delta}\ \langle r, \pi\rangle - \frac{1}{\eta}\,\mathrm{KL}(\pi\|\pi_t) \;=\; \frac{\pi_t\, e^{\eta r}}{Z_t}.

πref→πt\pi_{\text{ref}} \to \pi_t, β→1/η\beta \to 1/\eta로 바꾼 KL 정규화 최적해다. simplex를 벗어나지 않고 사영도 필요 없는 곱셈형(exponentiated-gradient) 업데이트다. 두 가지로 읽힌다. RLHF 해 π∗\pi^*는 πref\pi_{\text{ref}}에서 크기 1/β1/\beta로 내딛는 mirror ascent 한 걸음이다. 그리고 고정된 기준 대신 직전 정책에 묶고 반복하면 그것이 mirror descent 본래의 모습이다. Kimi k1.5의 정책 최적화가 이 관점을 쓴다(정규화, Kimi k1.5 리뷰). TRPO의 KL trust region과 PPO의 clip(PPO)은 매개변수화된 정책에서 같은 “KL로 잰 작은 걸음”을 근사한 것이고, natural gradient는 그 국소 2차 버전이다. 거기서는 Fisher 행렬이 KL의 Hessian 역할을 한다.

NumPy 라그랑지안으로 얻은 π*, frontier 기울기, mirror ascent, softmax
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}")
 

η=1/β\eta = 1/\beta이면 mirror ascent는 어디서 출발해도 한 step에 π*에 내려앉는다. 업데이트가 πt+1∝πt1−ηβ πrefηβ eηr\pi_{t+1} \propto \pi_t^{1-\eta\beta}\,\pi_{\text{ref}}^{\eta\beta}\, e^{\eta r}이고 ηβ=1\eta\beta = 1이 πt\pi_t를 지우기 때문이다. η가 더 작으면 log⁡π\log\pi의 오차가 step마다 1−ηβ1-\eta\beta배로 줄어든다.

확인 문제Check yourself

KL 정규화 목적함수에서 모든 보상을 2배 하고 동시에 +5만큼 평행이동했다. 이전과 같은 최적 정책을 주는 β는?

최적해는 덧셈 상수를 빼면 r/βr/\beta에만 의존한다. π∗∝πref e(2r+5)/β′∝πref e2r/β′\pi^* \propto \pi_{\text{ref}}\,e^{(2r+5)/\beta'} \propto \pi_{\text{ref}}\,e^{2r/\beta'}(e5/β′e^{5/\beta'}는 ZZ에서 상쇄된다). 2/β′=1/β2/\beta' = 1/\beta로 맞추면 β′=2β\beta' = 2\beta.

정리

  • 정류점: ∇f=0\nabla f = 0. Hessian 고유값이 분류하고, u⊤Huu^\top Hu는 [λmin⁡,λmax⁡][\lambda_{\min}, \lambda_{\max}] 안을 오간다. Newton(−H−1g-H^{-1}g)은 최소가 아니라 정류점을 찾는다.
  • 볼록 ⇔ 접평면이 하한 ⇔ H⪰0H \succeq 0. 그러면 모든 정류점이 전역 최소다. lse, 음의 엔트로피, KL은 볼록이고 딥넷은 아니다.
  • Jensen Ef(X)≥f(EX)\mathbb{E}f(X) \ge f(\mathbb{E}X)에서 KL ≥ 0, ELBO, k3≥0k_3 \ge 0, plug-in 추정량의 편향이 나온다.
  • 라그랑주: 최적점에서 등위선이 제약에 접한다, ∇f+ν∇g=0\nabla f + \nu\nabla g = 0. 승수는 그림자 가격 −∂f∗/∂b-\partial f^*/\partial b다. KKT는 μ≥0\mu \ge 0과 상보 여유성을 더한다.
  • 엔트로피 정규화 argmax = softmax(z/τ)(z/\tau). KL 정규화 보상 최대화 = πrefer/β/Z\pi_{\text{ref}}e^{r/\beta}/Z, 최적값 βlog⁡Z\beta\log Z, β는 보상–KL frontier의 기울기다. 그 한 걸음을 직전 정책에서 반복하면 mirror descent다.

이 사이트에서 쓰이는 곳

더 읽을거리Further reading