policy optimization에서 monotonic improvement를 하기 위한 반복 프로시저.
이론적으로 성립하는 절차에 여러 근사를 가정함.
Trust Region Policy Optimization(TRPO) 이라 하는 practical한 알고리즘을 개발함.
이 알고리즘은 Natural Policy Gradient 메소드와 유사하고, 뉴럴넷과 같은 대규모 nonlinear policy의 최적화에 효과적임.
우리의 실험은 다양한 종류의 태스크에서 알고리즘의 강건한 성능을 보여줌.
근사치들이 이론에서 벗어나긴 해도, TRPO는 크게 하이퍼파라미터 튜닝 없이도 monotonic importvement를 보이는 경향이 있음.
Introduction
Background
flowchart TD
subgraph GB1[Policy Iteration]
GB1A[ADP]
GB1B[CPI]
end
subgraph GB2[Policy Gradient]
direction TB
GB2A[REINFORCE]
GB2B[NPG]
GB2C[Actor-Critic]
GB2A ~~~ GB2B
GB2A ~~~ GB2C
end
subgraph DFO[Derivative-Free]
DFO1[CEM]
DFO2[CMA]
end
GB[Gradient-Based]
GB --- GB1
GB --- GB2
A["Policy Optimization<br/>Algorithm"]
A === GB
A === DFO
Derivative-Free Stochastic Optimization, 예를 들어 CEM(cross-entropy)이나 CMA(covariance matrix)가 많이 쓰였음. 구현과 이해가 단순한 것에 비해 좋은 성능을 내기 때문에.
Tetris는 ADP(Approximate Dynamic Programming)의 고전적 벤치마크이지만, stochastic optimization을 이기기 어려움.
연속 제어 문제에서는 CMA가 좋았음.
Continuous Control Problem: 연속행동공간, 연속상태공간을 다루는 문제.
e.g. 로봇 관절 제어
Gradient 기반 최적화 알고리즘이 그래디언트 없는 방법보다 훨씬 더 나은 샘플 복잡성 보장을 제공함에도, ADP와 Gradient 기반 방법이 Gradient-free 랜덤 검색을 일관되게 능가하지 못함.
Is ADP one of the gradient-based methods? ─ 아님. ADP는 Policy Iteration 계열인데, 얘도 Gradient를 씀. 어찌 됐건 Gradient를 쓰는 방법이 안 쓰는 방법을 못 이기는 게 문제 의식.
Why does sample complexity matter? ─ Sample Complexity란, 일정 수준에 도달하기 위해 필요한 샘플링(에이전트-환경 상호작용) 수. RL에서는 샘플링 수가 곧 비용. Gradient 기반 방법론은 이론적으로 더 적은 샘플링으로 정책 향상이 가능해야 함.
Why “complexity”? ─ 계산이론 용어인 듯. 자세한 건 모르겠네…
continuous gradient 기반 optimization은 대규모 모델의 지도 학습 과제에서 function approximation 태스크에 성공적.
이것을 강화학습으로 확장하면 복잡하고 강력한 정책의 효율적 학습이 가능해질 것.
Insight Sources ─ 지금까진 지도학습에서 Gradient 기반 최적화가 수M~수B 파라미터의 대규모 비선형 함수 근사기(=뉴럴넷) 를 성공적으로 학습시킴. 그런데 RL은 대규모 비선형 정책 최적화가 어려워서, 저차원의 정책과 gradient-free 방법에 의존해왔음. SL의 성공을 RL로 adaptation한다면, 뉴럴넷 정책도 효율적으로 학습이 가능할 것.
Why is it so difficult to optimize large-scale policy in RL? ─ (1) RL의 목적 함수가 Non-stationary, (2) Policy가 데이터 분포 자체를 바꾸기 때문에 SGD를 적용하면 학습이 매우 불안정함. 최적화해야 하는 함수가 최적화 스텝마다 바뀌는 느낌. \(\rightarrow\) 핵심 Gap
delayed reward: credit assignment 문제의 원인
high variance: \(\sum_l \gamma^l r\) (MC return)의 추정이 trajectory 마다 크게 달라서 추정량 분산이 높음
catastrophic policy degradation: 스텝사이즈가 조금만 커도 붕괴함. bad policy \(\to\) bad data \(\to\) bad policy \(\to \cdots\) 악순환 발생
Intuition ─ 분포 \(q\) 로 \(p\) 를 encoding하려고 할 때 생기는 정보 손실. 이 손실이 클 수록, \(p\) 에서 나타나는 trajectory가 \(q\) 에서 발생하기 어려움. \(\to\) asymmetry. KL divergence가 distance가 아닌 divergence인 이유.
Why? ─ TRPO의 경우, old policy가 높은 확률을 메기는 곳에서 new policy가 낮은 확률을 줄 때 penalty를 가하기 위함. 반면, RLHF는 reward hacking을 막아야 함. 기존 모델이 거의 생성하지 않는 토큰을 생성하는 경우(mode-seeking)를 방지하기 위함.
The optimization problem \(\underset{\Delta\theta}{max} \;g^{T} \Delta\theta \quad \text{s.t.} \quad \lvert\lvert{\Delta\theta}\rvert\rvert^2 \leq \epsilon\)
Vanilla PG: \(\theta + \alpha g\)
The optimization problem \(\underset{\Delta\theta}{max} \;g^{T} \Delta\theta \quad \text{s.t.} \quad \Delta\theta^{T} F \Delta\theta \leq \epsilon\)
Natural PG: \(\theta + \alpha F^{-1}g\)
Key Result.
Policy Optimization 에 최초로 Fisher Information Matrix \(F\) 를 사용
왜 FIM 인가?
KL divergence 의 2차 approximation 으로 동작. (분포 간 거리 제약)
Limitations.
No principled way to choose \(\alpha\)
\(\rightarrow\) TRPO의 Trust Region 이 해결
Overview
Surrogate objective function
\(L_\pi (\tilde{\pi}) = \eta (\pi) + \sum_{s} {\rho_{\pi} (s) \sum_{a} {\tilde{\pi} (a \vert s) A^{\pi}(s, a)}}\)
대리 목적 함수를 최적화하면, 비자명한 스텝 사이즈로 정책 개선을 보장함. (to be proved)
왜 surrogate? max 문제를 min 문제로 변환하는 느낌인가?
No. 원래의 목적 함수 자체가 closed-form 최적화 불가능함.
Expected return(\(\eta\)) of policy \(\tilde{\pi}\)
\(\eta(\tilde{\pi}) = \eta(\pi) + \sum_{s} {\rho_{\tilde{\pi}} (s) \sum_{a} {\tilde{\pi} (a \vert s) A^{\pi}(s, a)}}\)
이게 원래의 목적 함수. \(\eta(\tilde{\pi})\) 를 계산하려면 \(\rho_{\tilde{\pi}}(s)\) 가 필요한데, \(\rho_{\tilde{\pi}}(s)\) 가 \(\tilde{\pi}\) 에 복잡하게 의존해버림(intractable). 그래서 \(\tilde{\pi}\) 를 \(\pi\) 로 대체한 surrogate objective function 을 생각.
\(\eta(\tilde{\pi})\) 와 \(L_{\pi} (\tilde{\pi})\) 는 \(\theta_0\) 근방에서 1차항까지 일치함.
Why? ─ 이론에서 얻은 페널티 계수 \(C = \frac{4\epsilon\gamma}{(1-\gamma)^2}\) 은 매우 큼. 경험적으로도 \(C\) 를 robust하게 선택하기 어려움. 대신, \(KL \leq \delta\) 라는 hard constraint 를 사용하면 하이퍼파라미터 \(\delta\) 만 선택하면 되고, 더 큰 업데이트를 강건하게 수행할 수 있음.
Why is \(C\) so big? ─ Thm.1 증명에 쓰인 보수적인 가정(worst-case bound) 때문. discount factor \(\gamma \to 1\) 이면 발산.
Why is hard constraint robust? ─ 페널티 방식은 \(L(\theta) - C \cdot \mathbb{D}_{KL}\) 을 maximize, \(C\) 값에 민감함(안 움직이거나 catastrophic update). 반면, 제약 방식은 \(\mathbb{D}_{KL} \leq \delta\) 가 보장되므로 이 영역 안에서 \(L(\theta)\) 를 maxiimize하면 됨. Catastrophic update를 방지, \(\delta\) 값 자체에 덜 민감함.
Is this conversion heuristic method? ─ 완전한 휴리스틱은 아님. Lagrangian duality 로, 적절한 \(\delta\) 에 대응하는 \(C\) 가 존재하여 같은 해를 찾을 수 있음. (TODO: 직접 해보기)
3. \(A_{\pi}\) estimation via Monte-Carlo sampling
Objective: \(\sum_a \pi_{\theta} (a \mid s) A_{\pi_{old}}(s, a)\) \(\sum_a \pi_{\theta} (a \mid s) A_{\pi_{old}}(s, a) = \sum_a \pi_{\theta} (a \mid s) Q_{\pi_{old}}(s, a) - \cancelto{1}{\sum_a \pi_{\theta}(a \mid s)} V_{\pi_{old}}(s)\)
Surrogate: \(\sum_a \pi_{\theta} (a \mid s) Q_{\pi_{old}}(s, a)\)
어드밴티지 대신 Q-value를 최대화, \(Q_{\pi_{old}}\) 를 몬테카를로 샘플링으로 추정.
Why? ─ 모든 state-action pairs에 대해 어드밴티지를 계산할 수 없으므로, trajectory 샘플로부터 Q-value 를 추정함.
The condition required to improve policy performance \(\sum_s \rho_{\tilde{\pi}}(s) \sum_a \tilde{\pi}(a \mid s) A_{\pi} (s, a) \geq 0\)
Surrogate
The local approximation using the visitation frequency \(\rho_{\pi}\) instead of \(\rho_{\tilde{\pi}}\) \(L_{\pi}(\tilde{\pi}) = \eta(\pi) + \sum_{s} \rho_{\pi} (s) \sum_a \tilde{\pi}(a \mid s) A_{\pi} (s, a)\)
\(L_{\pi}(\tilde{\pi})\) and \(\eta(\tilde{\pi})\) agree up to first order at \(\pi_{\theta_0}\) for any parameter value \(\theta_0\) \(\Delta_{\eta_\mu} = \frac{\alpha}{1-\gamma} \mathbb{A}_{\pi, \mu} (\pi') + O({\alpha}^2) \tag{Kakade-Langford}\)
Monotonic Improvement Guarantee for General Stochastic Policies
Definition (\(\alpha\)-coupling).
A policy pair \((\pi, \tilde{\pi})\) is \(\alpha\)-coupled if there exists a joint distribution \((a, \tilde{a}) \mid s\) with marginals \(\pi(\cdot \mid s)\), \(\tilde{\pi}(\cdot \mid s)\) such that \(P(a \ne \tilde{a} \mid s) \leq \alpha\)
Proposition.
(Levin et al.) If \(\mathbb{D}_{TV}^{max} (\pi, \tilde{\pi}) \leq \alpha\), then an \(\alpha\)-coupling exists.
Theorem 1. Policy Improvement Bound
Let \(\alpha = \mathbb{D}_{TV}^{max} (\pi_{old}, \pi_{new})\). Then the following bound holds: \(\eta({\pi_{new}}) \geq L_{\pi_{old}} (\pi_{new}) - \frac{4\epsilon\gamma}{(1-\gamma)^2} {\alpha}^2\) \(where \;\epsilon = \underset{s, a}{max} \lvert{A_\pi (s, a)}\rvert\) Proof. Taking expectation over trajectories \(\tau := (s_0, a_0, s_1, a_1, \cdots)\), \(\eta(\tilde{\pi}) = \eta(\pi) + \mathbb{E}_{\tau \sim \tilde{\pi}} \left[{\sum_{t=0}^{\infty} {\gamma}^t A_{\pi} (s_t, a_t)}\right]\) Define the expected advantage of \(\tilde{\pi}\) over \(\pi\) at state \(s\): \(\bar{A}(s) = \mathbb{E}_{a \sim \tilde{\pi}(\cdot \mid s)} \left[{A_{\pi}(s, a)}\right]\) Note that \(L_{\pi}\) can be written as \(L_{\pi}(\tilde{\pi}) = \eta(\pi) + \mathbb{E}_{\tau \sim \pi} \left[{\sum_{t=0}^{\infty} {\gamma}^t \bar{A} (s_t)}\right]\) The difference between \(\eta(\tilde{\pi})\) and \(L_\pi\) : \(\eta(\tilde{\pi}) - L_{\pi} (\tilde{\pi}) = \mathbb{E}_{\tau \sim \tilde{\pi}} \left[{\sum_{t=0}^{\infty} {\gamma}^t A_{\pi} (s_t, a_t)}\right] - \mathbb{E}_{\tau \sim \pi} \left[{\sum_{t=0}^{\infty} {\gamma}^t \bar{A} (s_t)}\right] \tag{*}\) To ensure monotonic improvement, the absolute value of \((*)\) should be bounded.
\(F^{-1} g\) 를 natural gradient 라고 함. - 일반적인 gradient \(g\) 는 유클리드 공간에서의 steepest ascent 방향. - natural gradient \(F^{-1} g\) 는 분포 공간(확률 다양체) 에서의 steepest ascent 방향. - Why is natural gradient better? ─ 파라미터 공간에서의 작은 변화가 정책 분포에 큰 영향을 줄 수도, 작은 영향을 줄 수ㅇ도 있음. FIM은 파라미터 변화가 분포 변화에 미치는 영향을 측정하므로, \(F^{-1}\) 을 곱하면 분포 공간에서 균일한 스텝을 취하게 됨. - \(\sqrt{\frac{2\delta}{g^T F^{-1} g}}\) 는 step size. trust region 크기 \(\delta\) 에 의해 결정됨.
Conjugate Gradient (CG) 로 \(F^{-1}g\) 근사
문제: \(F\) 는 $$
\theta
\times
\theta
\(행렬. 뉴럴넷의 파라미터가 수만~수백만 개이면\)F$$ 를 명시적으로 저장하거나 역행렬을 구하는 것이 불가능.
해결: \(Fx = g\) 를 iterative하게 풀어 \(x \approx F^{-1}g\) 를 구함. - \(F\) 자체를 저장하지 않고, Fisher-vector product \(Fv\) 만 계산할 수 있으면 됨. \(F = \nabla^2_\theta \;\mathbb{D}_{KL} (\theta_{old}, \theta) \big|_{\theta=\theta_{old}}\)
Why CG works here ─ \(F\) 는 positive semi-definite (FIM이므로). CG는 PSD 행렬에 대한 선형계를 효율적으로 풀 수 있고, 행렬 곱 연산만 필요. - damping: 수치 안정성을 위해 \(F \leftarrow F + \lambda I\) (\(\lambda \approx 0.1\)) 를 더해줌. 이러면 \(F\) 가 strictly positive definite가 됨.
Backtracking Line Search
CG로 search direction \(s = F^{-1}g\) 를 구한 뒤, KL constraint를 실제로 만족하는 step size를 찾아야 함. - 2차 근사는 \(\theta_{old}\) 근방에서만 정확. 큰 스텝에서는 실제 KL이 \(\delta\) 를 초과할 수 있음.
절차: 1. 이론적 최대 스텝: \(\beta_{max} = \sqrt{\frac{2\delta}{s^T F s}}\) 2. \(\beta = \beta_{max}\) 에서 시작 3. \(\theta_{new} = \theta_{old} + \beta \cdot s\) 로 업데이트 4. 다음 조건을 확인: - \(\bar{\mathbb{D}}_{KL}(\theta_{old}, \theta_{new}) \leq \delta\) (KL constraint 만족) - \(L_{\theta_{old}}(\theta_{new}) \geq L_{\theta_{old}}(\theta_{old})\) (surrogate objective 개선) 1. 만족하지 않으면 \(\beta \leftarrow c \cdot \beta\) (\(c \approx 0.5\)) 로 축소. 반복.
Why not just use the theoretical step? ─ 이론적 스텝은 \(L\) 과 \(\mathbb{D}_{KL}\) 모두 근사에 기반. 실제 \(\mathbb{D}_{KL}\) 이 \(\delta\) 를 초과하거나 \(L\) 이 감소할 수 있음. Line search로 이를 보정.
Sample-Based Estimation of the Objective and Constraint
위의 최적화 문제에서 expectation \(\mathbb{E}_s\), \(\mathbb{E}_a\) 를 정확히 계산할 수 없으므로, trajectory 샘플로 추정.
Importance Sampling
\(\theta_{old}\) 로 trajectory를 수집했으므로, \(a \sim \pi_{\theta_{old}}(\cdot \mid s)\) 에서 샘플링됨.
\(\lambda \in (0, 1)\): bias-variance tradeoff. 실용적으로 \(\lambda \approx 0.97\) 이 자주 쓰임. - Insight ─ TRPO 원논문(2015)에서는 single-path MC return을 사용. GAE(Schulman et al., 2016)는 후속 연구로, TRPO와 결합하여 성능을 크게 향상시킴. 실질적으로 TRPO 구현에서는 거의 항상 GAE를 사용.
for iteration = 1, 2, ... do
1. Rn policy π_θ_old to collect trajectories D = {τ_1, ..., τ_N}
2. Estimate avantages Â_t using GAE(γ, λ) with fitted value function V_φ
3. Compute policy gradient: g = ∇_θ L̂(θ)|_{θ=θ_old}
4. Use CG to compute: s ≈ F⁻¹g (K ≈ 10 iterations)
5. Compute max step: β = √(2δ / sᵀFs)
6. Backtracking line search:
θ_new = θ_old + c^j · β · s
where j is the smallest integer such that:
- KL(θ_old, θ_new) ≤ δ
- L̂(θ_new) ≥ L̂(θ_old)
7.Update value function V_φ by regression on collected returns
8. θ_old ← θ_new
end for
주요 하이퍼파라미터
하이퍼파라미터
의미
전형적 값
\(\delta\)
Trust region 크기 (KL constraint)
\(0.01\)
\(\gamma\)
Discount factor
\(0.99\)
\(\lambda\)
GAE parameter
\(0.97\)
\(K\)
CG iterations
\(10\)
damping
FIM regularization \(\lambda_{\text{damp}}\)
\(0.1\)
backtrack coeff
Line search 축소 비율
\(0.5\)
backtrack iters
Line search 최대 반복
\(10\)
TRPO vs. Natural Policy Gradient (NPG)
| | NPG | TRPO | | ————- | ————————- | —————————————– | | 업데이트 | \(\theta + \alpha F^{-1}g\) | \(\theta + \beta F^{-1}g\) with line search | | Step size | 고정 \(\alpha\) | Adaptive (trust region \(\delta\) 기반) | | KL constraint | 없음 (implicit) | 명시적 (\(\bar{\mathbb{D}}_{KL} \leq \delta\)) | | 안정성 | \(\alpha\) 에 민감 | Line search로 보정, 더 robust |
TRPO는 NPG에 trust region constraint와 line search를 추가한 것으로 이해할 수 있음.
NPG에서 step size를 잘못 설정하면 catastrophic update가 발생할 수 있지만, TRPO는 이를 line search로 방지.