Track IV · RL Fundamentals · 02/05

TD 학습과 Q-learningTD learning and Q-learning

모델 없이 경험만으로 가치를 배우는 두 길, Monte Carlo와 TD를 bias–variance로 비교하고, SARSA(on-policy)와 Q-learning(off-policy)이 절벽 앞에서 왜 다른 길을 고르는지 설명한다. 이 이분법이 PPO의 critic과 GRPO의 group baseline으로 그대로 이어진다.Compare the two ways of learning values from experience alone, without a model — Monte Carlo and TD — through bias–variance, and explain why SARSA (on-policy) and Q-learning (off-policy) choose different paths at the edge of a cliff. This dichotomy carries straight over to PPO's critic and GRPO's group baseline.

35 분min policy iteration · Monte Carlo · temporal difference · SARSA · Q-learning · on-policy · off-policy · DQN · deadly triad 먼저 볼 것:Before this: MDP와 Bellman 방정식MDPs and the Bellman equation

Value iteration in the last lesson assumed we know the transition probabilities PP and the rewards rr completely. For most problems no such table exists. All we can do is throw actions at the environment and watch the (s,a,r,s′)(s, a, r, s') that come back. This lesson covers the two ways of learning values without a model (model-free), from sampled experience alone — Monte Carlo and Temporal Difference (TD) — and goes on to SARSA and Q-learning, which use them to find an optimal policy.

Starting point: policy iteration

When the model is known, the other classical method besides value iteration is policy iteration. It alternates two steps.

  1. Evaluation: compute the current policy’s VπV^\pi (or QπQ^\pi). This is the linear solve from the last lesson.
  2. Improvement: make the policy greedy with respect to that value: π′(s)=arg⁡max⁡aQπ(s,a)\pi'(s) = \arg\max_a Q^\pi(s, a).

That the improvement step never makes the policy worse is the policy improvement theorem. If π′\pi' is greedy with respect to QπQ^\pi, then Qπ(s,π′(s))≥Vπ(s)Q^\pi(s, \pi'(s)) \ge V^\pi(s) for every ss, and unrolling this one step at a time gives

Vπ(s)≤Qπ(s,π′(s))=E[rt+γVπ(st+1)∣st=s,at=π′(s)]≤Eπ′[rt+γQπ(st+1,π′(st+1))∣st=s]≤⋯≤Vπ′(s)\begin{aligned} V^\pi(s) &\le Q^\pi(s, \pi'(s)) = \mathbb{E}\big[r_t + \gamma V^\pi(s_{t+1}) \mid s_t = s, a_t = \pi'(s)\big] \\ &\le \mathbb{E}_{\pi'}\big[r_t + \gamma Q^\pi(s_{t+1}, \pi'(s_{t+1})) \mid s_t = s\big] \le \cdots \le V^{\pi'}(s) \end{aligned}

Since there are finitely many deterministic policies, policy iteration stops at π⋆\pi^\star after finitely many rounds. Evaluating only partially before improving also converges; this general scheme of “interleaving evaluation and improvement a little at a time” is called generalized policy iteration (GPI). Almost every algorithm in this track is GPI. PPO, too, alternates critic training (evaluation) with actor updates (improvement).

Evaluating without a model: Monte Carlo

Since Vπ(s)=Eπ[Gt∣st=s]V^\pi(s) = \mathbb{E}_\pi[G_t \mid s_t = s], the most direct method is to run episodes to the end under the policy, collect the actual returns GtG_t, and average them. Written as a running average,

V(st)←V(st)+α[ Gt−V(st) ]V(s_t) \leftarrow V(s_t) + \alpha\big[\,G_t - V(s_t)\,\big]

GtG_t is an unbiased estimate of Vπ(st)V^\pi(s_t). On the other hand it can only be computed once the episode ends, and it contains the randomness of every subsequent action and transition at once, so it has high variance.

Temporal Difference: estimating from an estimate

Approximate the Bellman expectation equation Vπ(s)=E[rt+γVπ(st+1)∣st=s]V^\pi(s) = \mathbb{E}[r_t + \gamma V^\pi(s_{t+1}) \mid s_t = s] with a single sample. Instead of waiting until the end, use my own estimate one step later as the target.

V(st)←V(st)+α[ rt+γV(st+1)−V(st)⏟δt  (TD error) ]V(s_t) \leftarrow V(s_t) + \alpha\big[\,\underbrace{r_t + \gamma V(s_{t+1}) - V(s_t)}_{\delta_t \;(\text{TD error})}\,\big]

This is TD(0), and updating an estimate from an estimate is called bootstrapping. The target rt+γV(st+1)r_t + \gamma V(s_{t+1}) contains only one step’s worth of randomness (rt,st+1r_t, s_{t+1}), so it has low variance. But if V(st+1)V(s_{t+1}) is still wrong, the target is wrong, so there is bias. As learning proceeds and V→VπV \to V^\pi, the bias also disappears. And because it can update immediately at every step, it also works for tasks that never end.

Monte CarloTD(0)
targetGtG_trt+γV(st+1)r_t + \gamma V(s_{t+1})
biasnoneyes (as much as VV is wrong)
variancehigh (luck of the whole episode)low (luck of one step)
when it updatesend of episodeevery step
uses Markov structurenoyes

The last row matters. TD reuses the information “the value of st+1s_{t+1} has already been learned from other episodes”. If we have seen 100 episodes pass through state B, then when estimating the value of a state A visited for the first time, it combines the single A→B experience with the knowledge accumulated about B. MC leaves everything to the luck of that one episode that started at A.

지난 레슨의 가치 반복은 전이 확률 PP와 보상 rr을 전부 알고 있다고 가정했다. 대부분의 문제에서 그런 표는 없다. 환경에 행동을 던지고 돌아오는 (s,a,r,s′)(s, a, r, s')를 볼 수 있을 뿐이다. 이 레슨은 모델 없이(model-free), 샘플된 경험만으로 가치를 배우는 두 가지 방법, Monte Carlo 와 Temporal Difference(TD) 를 다루고, 그것으로 최적 정책을 찾는 SARSA 와 Q-learning 까지 간다.

출발점: 정책 반복

모델을 알 때 가치 반복 말고 또 하나의 고전적 방법이 정책 반복(policy iteration) 이다. 두 단계를 번갈아 한다.

  1. 평가: 현재 정책의 VπV^\pi (또는 QπQ^\pi)를 구한다. 지난 레슨의 선형 풀이다.
  2. 개선: 그 가치에 대해 탐욕적으로 바꾼다. π′(s)=arg⁡max⁡aQπ(s,a)\pi'(s) = \arg\max_a Q^\pi(s, a).

개선 단계가 정책을 나쁘게 만들지 않는다는 것이 정책 개선 정리(policy improvement theorem) 다. π′\pi'이 QπQ^\pi에 대해 탐욕적이면 모든 ss에서 Qπ(s,π′(s))≥Vπ(s)Q^\pi(s, \pi'(s)) \ge V^\pi(s)이고, 이것을 한 step씩 펼치면

Vπ(s)≤Qπ(s,π′(s))=E[rt+γVπ(st+1)∣st=s,at=π′(s)]≤Eπ′[rt+γQπ(st+1,π′(st+1))∣st=s]≤⋯≤Vπ′(s)\begin{aligned} V^\pi(s) &\le Q^\pi(s, \pi'(s)) = \mathbb{E}\big[r_t + \gamma V^\pi(s_{t+1}) \mid s_t = s, a_t = \pi'(s)\big] \\ &\le \mathbb{E}_{\pi'}\big[r_t + \gamma Q^\pi(s_{t+1}, \pi'(s_{t+1})) \mid s_t = s\big] \le \cdots \le V^{\pi'}(s) \end{aligned}

결정적 정책의 수가 유한하므로 정책 반복은 유한 번 만에 π⋆\pi^\star에서 멈춘다. 평가를 끝까지 하지 않고 조금만 하고 개선하는 것도 수렴하는데, 이 “평가와 개선을 엇갈려 조금씩” 하는 일반 틀을 일반화된 정책 반복(generalized policy iteration, GPI) 이라 부른다. 이 트랙에 나오는 거의 모든 알고리즘이 GPI다. PPO도 critic 학습(평가)과 actor 업데이트(개선)를 번갈아 한다.

모델 없이 평가하기: Monte Carlo

Vπ(s)=Eπ[Gt∣st=s]V^\pi(s) = \mathbb{E}_\pi[G_t \mid s_t = s]이니 가장 직접적인 방법은 정책대로 에피소드를 끝까지 돌려 실제 return GtG_t를 모으고 평균 내는 것이다. 이동평균으로 쓰면

V(st)←V(st)+α[ Gt−V(st) ]V(s_t) \leftarrow V(s_t) + \alpha\big[\,G_t - V(s_t)\,\big]

GtG_t는 Vπ(st)V^\pi(s_t)의 불편(unbiased) 추정 이다. 대신 에피소드가 끝나야 계산할 수 있고, 그 뒤의 모든 행동과 전이의 무작위성이 한꺼번에 들어 있어 분산이 크다.

Temporal Difference: 추정으로 추정하기

Bellman 기대 방정식 Vπ(s)=E[rt+γVπ(st+1)∣st=s]V^\pi(s) = \mathbb{E}[r_t + \gamma V^\pi(s_{t+1}) \mid s_t = s]를 샘플 하나로 근사한다. 끝까지 기다리지 않고 한 step 뒤의 내 추정 을 타깃으로 쓴다.

V(st)←V(st)+α[ rt+γV(st+1)−V(st)⏟δt  (TD error) ]V(s_t) \leftarrow V(s_t) + \alpha\big[\,\underbrace{r_t + \gamma V(s_{t+1}) - V(s_t)}_{\delta_t \;(\text{TD error})}\,\big]

이것이 TD(0)이고, 추정치로 추정치를 갱신하는 것을 bootstrapping 이라 한다. 타깃 rt+γV(st+1)r_t + \gamma V(s_{t+1})에는 무작위성이 한 step분(rt,st+1r_t, s_{t+1})만 들어 있어 분산이 작다. 대신 V(st+1)V(s_{t+1})이 아직 틀려 있으면 타깃이 틀리므로 편향(bias) 이 있다. 학습이 진행되며 V→VπV \to V^\pi가 되면 편향도 사라진다. 그리고 매 step 바로 갱신할 수 있어 끝나지 않는 과제에도 쓸 수 있다.

Monte CarloTD(0)
타깃GtG_trt+γV(st+1)r_t + \gamma V(s_{t+1})
편향없음있음 (VV가 틀린 만큼)
분산큼 (에피소드 전체의 운)작음 (한 step의 운)
갱신 시점에피소드 끝매 step
마르코프 구조 활용안 함함

마지막 줄이 중요하다. TD는 “st+1s_{t+1}의 가치는 이미 다른 에피소드들에서 배웠다”는 정보를 재사용한다. 상태 B를 지나는 에피소드를 100번 봤으면, 처음 지나가는 상태 A의 가치를 추정할 때 A→B 한 번의 경험과 B에 대해 쌓인 지식을 결합한다. MC는 A에서 시작한 그 한 에피소드의 운에 전부 맡긴다.

TD(0) RMS 오차error – MC RMS 오차error –
The walker moves randomly left or right among states A–E, receiving +1 on reaching the right end and 0 on the left end. The true values are 1/6, …, 5/6 (grey). Every V starts at 0.5. Left: the estimate of a single run after the n-th episode; right: the RMS error averaged over 100 runs. Increase α and both drop faster but fluctuate around a higher floor. At the same α, TD is usually lower, because it is less at the mercy of a single episode's luck (variance). 상태 A–E를 무작위로 좌우 이동하다 오른쪽 끝에 닿으면 +1, 왼쪽 끝이면 0을 받는다. 참 가치는 1/6, …, 5/6(회색). 모든 V는 0.5에서 시작한다. 왼쪽은 실행 하나의 n번째 에피소드 후 추정, 오른쪽은 실행 100개의 평균 RMS 오차다. α를 키우면 둘 다 빨리 내려가지만 더 높은 바닥에서 출렁인다. 같은 α에서 TD가 대체로 더 낮다: 한 에피소드의 운(분산)에 덜 휘둘리기 때문이다.

n-step: a knob between the two

TD bootstraps one step later; MC bootstraps at the end (strictly speaking, it does not bootstrap at all). We can cut anywhere in between.

Gt(n)=rt+γrt+1+⋯+γn−1rt+n−1+γnV(st+n)G_t^{(n)} = r_t + \gamma r_{t+1} + \cdots + \gamma^{n-1} r_{t+n-1} + \gamma^n V(s_{t+n})

n=1n = 1 gives the TD target, and n→∞n \to \infty (until the end of the episode) gives the MC return. The larger nn, the more real rewards go in, so bias falls and variance rises. Averaging all nn with weights λn−1\lambda^{n-1} gives the λ\lambda-return, and applying it to the advantage gives lesson 4’s GAE. The bias–variance knob reappears there under the name λ\lambda.

Control: learn Q and you no longer need a model

To find an optimal policy, evaluation has to be followed by improvement (making it greedy). With only VV, computing arg⁡max⁡a[r(s,a)+γ∑s′P(s′∣s,a)V(s′)]\arg\max_a [r(s,a) + \gamma \sum_{s'} P(s'|s,a) V(s')] needs the model again. So model-free control learns Q(s,a)Q(s, a) instead; making it greedy is then simply arg⁡max⁡aQ(s,a)\arg\max_a Q(s, a).

The other problem is exploration. If the agent only ever acts greedily, it never learns the value of an action it has never tried. The simplest remedy is ε-greedy: a random action with probability ε\varepsilon, otherwise arg⁡max⁡aQ\arg\max_a Q.

There are two ways to apply the TD idea to QQ. The only difference is how the next action in the target is chosen.

SARSA:Q(st,at)←Q(st,at)+α[rt+γ Q(st+1,at+1)−Q(st,at)]\textbf{SARSA:}\quad Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\big[r_t + \gamma\, Q(s_{t+1}, \textcolor{#2f5fb3}{a_{t+1}}) - Q(s_t, a_t)\big]Q-learning:Q(st,at)←Q(st,at)+α[rt+γ max⁡a′Q(st+1,a′)−Q(st,at)]\textbf{Q-learning:}\quad Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\big[r_t + \gamma\, \textcolor{#c0392b}{\max_{a'} Q(s_{t+1}, a')} - Q(s_t, a_t)\big]

SARSA (named after the s,a,r,s′,a′s, a, r, s', a' used in the update) uses the value of at+1a_{t+1} drawn by ε-greedy, i.e. the action it will actually take next. So it learns QπQ^\pi of the policy it is currently acting with (ε-greedy). The policy that acts and the policy being learned are the same: this is on-policy. Q-learning uses the value of the greedy action, whatever it does next. It is the sample version of the Bellman optimality equation, so it learns Q⋆Q^\star. The behavior policy that collects data and the target policy being learned differ: this is off-policy. Thanks to that, Q-learning can also use data collected by other policies, and old data. If every (s,a)(s, a) is visited infinitely often and the learning rate satisfies the Robbins–Monro conditions, tabular Q-learning converges to Q⋆Q^\star with probability 1 (Watkins & Dayan, 1992).

In a picture: cliff walking

Sutton & Barto’s cliff walking shows this difference most clearly. A 4×12 grid, −1 per step; falling off the cliff along the bottom gives −100 and sends the agent back to the start. The optimal path is the 13 steps running right along the top of the cliff.

n-step: 둘 사이의 손잡이

TD는 1 step 뒤에서, MC는 끝에서 bootstrapping을 한다(정확히는 안 한다). 그 사이 어디서든 끊을 수 있다.

Gt(n)=rt+γrt+1+⋯+γn−1rt+n−1+γnV(st+n)G_t^{(n)} = r_t + \gamma r_{t+1} + \cdots + \gamma^{n-1} r_{t+n-1} + \gamma^n V(s_{t+n})

n=1n = 1이면 TD 타깃, n→∞n \to \infty(에피소드 끝까지)이면 MC return이다. nn이 클수록 실제 보상이 더 많이 들어가 편향이 줄고 분산이 늘어난다. 모든 nn을 λn−1\lambda^{n-1}로 가중평균한 것이 λ\lambda-return이고, 이것을 advantage에 적용한 것이 4강의 GAE 다. bias–variance 손잡이는 그때 λ\lambda라는 이름으로 다시 나온다.

제어: Q를 배우면 모델이 필요 없다

최적 정책을 찾으려면 평가 뒤에 개선(탐욕화)을 해야 한다. VV만 있으면 arg⁡max⁡a[r(s,a)+γ∑s′P(s′∣s,a)V(s′)]\arg\max_a [r(s,a) + \gamma \sum_{s'} P(s'|s,a) V(s')]를 계산하는 데 모델이 다시 필요하다. 그래서 모델 없는 제어는 Q(s,a)Q(s, a)를 배운다. 탐욕화가 그냥 arg⁡max⁡aQ(s,a)\arg\max_a Q(s, a)가 된다.

또 하나의 문제는 탐험(exploration) 이다. 탐욕적으로만 행동하면 한 번도 안 해 본 행동의 가치를 영영 모른다. 가장 단순한 처방이 ε-greedy: 확률 ε\varepsilon으로 무작위 행동, 나머지는 arg⁡max⁡aQ\arg\max_a Q.

TD 아이디어를 QQ에 적용하는 방법이 둘 있다. 차이는 타깃에서 다음 행동을 어떻게 고르느냐 하나뿐이다.

SARSA:Q(st,at)←Q(st,at)+α[rt+γ Q(st+1,at+1)−Q(st,at)]\textbf{SARSA:}\quad Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\big[r_t + \gamma\, Q(s_{t+1}, \textcolor{#2f5fb3}{a_{t+1}}) - Q(s_t, a_t)\big]Q-learning:Q(st,at)←Q(st,at)+α[rt+γ max⁡a′Q(st+1,a′)−Q(st,at)]\textbf{Q-learning:}\quad Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\big[r_t + \gamma\, \textcolor{#c0392b}{\max_{a'} Q(s_{t+1}, a')} - Q(s_t, a_t)\big]

SARSA(이름은 업데이트에 쓰는 s,a,r,s′,a′s, a, r, s', a'에서 왔다)는 ε-greedy로 뽑은 at+1a_{t+1}, 즉 실제로 다음에 할 행동 의 가치를 쓴다. 그래서 지금 행동하는 정책(ε-greedy)의 QπQ^\pi를 배운다. 행동하는 정책과 배우는 정책이 같은 on-policy 다. Q-learning은 다음에 무엇을 하든 탐욕 행동 의 가치를 쓴다. Bellman 최적 방정식의 샘플 버전이므로 Q⋆Q^\star를 배운다. 데이터를 모으는 행동 정책(behavior policy) 과 배우는 목표 정책(target policy) 이 다른 off-policy 다. 그 덕분에 Q-learning은 다른 정책이 모은 데이터, 오래된 데이터도 쓸 수 있다. 모든 (s,a)(s, a)를 무한히 방문하고 학습률이 Robbins–Monro 조건을 만족하면 표 형태 Q-learning은 확률 1로 Q⋆Q^\star에 수렴한다(Watkins & Dayan, 1992).

그림으로: 절벽 걷기

Sutton & Barto의 절벽 걷기(cliff walking)는 이 차이를 가장 선명하게 보여 준다. 4×12 격자, 매 step −1, 아래쪽 절벽에 떨어지면 −100을 받고 출발점으로 돌아간다. 최적 경로는 절벽 바로 위를 따라가는 13 step이다.

episode 0 / 500 SARSA 최근 50회 평균mean of last 50 – Q-learning 최근 50회 평균mean of last 50 –
Both algorithms act with the same ε-greedy rule and learn simultaneously (each the mean of 20 independent runs; the path shown is the greedy path of the first run that reaches G). Every step gives −1; falling off the cliff (grey) gives −100 and sends the agent back to S. Q-learning (red) learns the optimal path right along the cliff (−13), but ε-exploration makes it fall off now and then, so its return during training is worse. SARSA (blue) takes its own exploration into account and learns a safe path that keeps well away. Set ε to 0 and restart, and the difference between the two disappears. 두 알고리즘이 같은 ε-greedy로 행동하며 동시에 학습한다(각각 독립 실행 20개의 평균, 위 경로는 그중 G에 도달하는 첫 실행의 탐욕 경로). 한 step마다 −1, 절벽(회색)에 떨어지면 −100을 받고 S로 돌아간다. Q-learning(빨강)은 절벽 바로 위의 최적 경로(−13)를 배우지만 ε 탐험 때문에 가끔 떨어져서 학습 중 return은 더 나쁘다. SARSA(파랑)는 자신의 탐험까지 계산에 넣어 멀찍이 돌아가는 안전한 경로를 배운다. ε를 0으로 내리고 처음부터 돌리면 두 방법의 차이가 사라진다.

Q-learning finds the optimal path exactly. But while it is learning it still takes a random action with probability ε, and a random ”↓” right above the cliff costs −100. Q-learning’s QQ assumes “from now on I will act perfectly”, so it does not reflect this risk. SARSA’s QQ reflects “I will keep making mistakes with probability ε”. SARSA rates the cells next to the cliff low, and so it takes a wide detour. What counts as a ‘good’ policy depends on how that policy will actually be executed. If ε is reduced towards 0 (GLIE: try every action infinitely often but become greedy over time), SARSA also converges to the optimal path.

확인 문제Check yourself

After training SARSA and Q-learning with ε = 0.1, we keep executing their greedy policies with ε = 0.1. Which has the higher average return?

Q-learning learns Q⋆Q^\star, the value “when acting perfectly from then on”. Its greedy policy is optimal at ε = 0, but executed with ε = 0.1 it often falls off next to the cliff. SARSA learned QπQ^\pi of the ε-greedy policy itself, so it finds the policy that is best when executed ε-greedily. If execution conditions match training conditions, on-policy learning directly optimises performance under those conditions.

Implementing it

We run the same experiment as the figure in NumPy. The two algorithms differ in one line, target. We measure separately the return during training (acting ε-greedily) and the return of the greedy policy after training (ε = 0).

NumPy Cliff walking: SARSA vs Q-learning
import numpy as np, random

H, W = 4, 12
START, GOAL = (3, 0), (3, 11)
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]          # ↑ → ↓ ←

def step(s, a):
    i = min(H - 1, max(0, s[0] + MOVES[a][0]))
    j = min(W - 1, max(0, s[1] + MOVES[a][1]))
    if i == 3 and 0 < j < 11:                        # cliff: -100, back to start
        return START, -100.0, False
    return (i, j), -1.0, (i, j) == GOAL

def eps_greedy(Q, s, eps, rnd):
    if rnd.random() < eps:
        return rnd.randrange(4)
    return int(Q[s].argmax())

def run(method, episodes=500, alpha=0.5, eps=0.1, gamma=1.0, seed=0):
    rnd = random.Random(seed)
    Q = np.zeros((H, W, 4))
    returns = np.zeros(episodes)
    for ep in range(episodes):
        s, G = START, 0.0
        a = eps_greedy(Q, s, eps, rnd)
        while True:
            s2, r, done = step(s, a)
            G += r
            a2 = eps_greedy(Q, s2, eps, rnd)          # the action actually taken next
            if method == "sarsa":                      # on-policy target
                target = r + gamma * Q[s2][a2] * (not done)
            else:                                      # off-policy target: value of the greedy action
                target = r + gamma * Q[s2].max() * (not done)
            Q[s][a] += alpha * (target - Q[s][a])
            s, a = s2, a2
            if done:
                break
        returns[ep] = G
    return Q, returns

def greedy_rollout(Q):
    grid = [["C" if (i == 3 and 0 < j < 11) else "." for j in range(W)] for i in range(H)]
    s, G = START, 0
    for _ in range(100):
        grid[s[0]][s[1]] = "*"
        if s == GOAL: break
        s, r, _ = step(s, int(Q[s].argmax()))
        G += r
    return G, "\n".join("   " + " ".join(row) for row in grid)

for method, name in [("sarsa", "SARSA"), ("q", "Q-learning")]:
    online = []
    for seed in range(5):
        Q, ret = run(method, seed=seed)
        online.append(ret[-100:].mean())
    G, picture = greedy_rollout(Q)
    print(f"{name}: training (ε=0.1) mean return of last 100 ep = {np.mean(online):6.1f}, "
          f"greedy policy (ε=0) return = {G}")
    print(picture, "\n")
 

Q-learning’s greedy policy gets −13 (optimal) and SARSA’s about −17 (the safe detour), while the return during training is the other way round: SARSA does better. Try lowering α to 0.1 or changing eps.

Function approximation and the deadly triad

A table is unusable once there are more than a few thousand states. Replace QQ by a neural network Qϕ(s,a)Q_\phi(s, a) with parameters ϕ\phi and reduce the TD error as a regression loss.

L(ϕ)=E(s,a,r,s′)∼D[(r+γmax⁡a′Qϕˉ(s′,a′)−Qϕ(s,a))2]\mathcal{L}(\phi) = \mathbb{E}_{(s,a,r,s') \sim \mathcal{D}}\Big[\big(r + \gamma \max_{a'} Q_{\bar\phi}(s', a') - Q_\phi(s, a)\big)^2\Big]

DQN (Mnih et al., 2015) reached human level on many Atari games this way. Two devices were key: a replay buffer that stores past transitions and samples them at random (breaking the correlation between consecutive samples), and a target network whose weights ϕˉ\bar\phi, used to compute the target, are updated slowly (so the target being chased does not shake every step).

Such devices are needed because of the combination Sutton & Barto call the deadly triad.

  1. Function approximation: fixing one state moves the values of other states too.
  2. Bootstrapping: the target depends on the model’s own estimate.
  3. Off-policy learning: the distribution being learned from differs from the distribution the target policy visits.

Any two of the three are usually fine, but with all three the value estimates can diverge (Baird’s counterexample is the famous one). The convergence guarantees of the tabular case break here, and in practice one holds on with engineering such as target networks, small learning rates and target normalisation. There is also maximization bias, where the max⁡\max picks out noise and overestimates values, so fixes like Double Q-learning (separate networks for selecting and evaluating the action) are used.

확인 문제Check yourself

Which statement about the TD(0) target r + γV(s') is correct?

The expectation of the TD target is E[r+γV(s′)]\mathbb{E}[r + \gamma V(s')] , which equals Vπ(s)V^\pi(s) only when V=VπV = V^\pi. Before that it is biased. In exchange, only one sampling of rtr_t and st+1s_{t+1} is random, so the variance is low. TD(0) is policy evaluation, so it has nothing to do with being on- or off-policy (trained on data from the same policy, it is on-policy).

Summary

  • Policy iteration = evaluation + greedy improvement. The policy improvement theorem guarantees monotone improvement. Almost every RL algorithm is GPI that approximates it.
  • MC uses the actual return GtG_t as the target (unbiased, high variance); TD uses rt+γV(st+1)r_t + \gamma V(s_{t+1}) (biased, low variance, every step). n-step connects the two.
  • SARSA bootstraps with the actual next action (on-policy: the value of the policy including exploration); Q-learning bootstraps with the max⁡\max (off-policy: Q⋆Q^\star).
  • Function approximation + bootstrapping + off-policy = the deadly triad. DQN holds on with a replay buffer and a target network.
  • In LLM RL, MC vs TD reappears as “GRPO/RLOO’s terminal reward + group baseline” vs “PPO’s token-level critic + GAE”.

Q-learning은 최적 경로를 정확히 찾는다. 하지만 학습하는 동안에는 여전히 ε 확률로 무작위 행동을 하고, 절벽 바로 위에서의 무작위 ”↓“는 −100이다. Q-learning의 QQ는 “앞으로는 완벽하게 행동할 것”을 전제로 한 값이라 이 위험을 반영하지 않는다. SARSA의 QQ는 “앞으로도 ε 확률로 실수할 것”을 반영한 값이다. 절벽 옆 칸의 SARSA 가치는 낮게 평가되고, 그래서 멀찍이 돌아간다. 무엇이 ‘좋은’ 정책인가는 그 정책이 실제로 어떻게 실행될지에 달려 있다. ε를 0으로 줄여 가면(GLIE: 모든 행동을 무한히 시도하되 점점 탐욕적으로) SARSA도 최적 경로로 수렴한다.

확인 문제Check yourself

ε = 0.1로 학습을 끝낸 SARSA와 Q-learning의 탐욕 정책을 ε = 0.1로 계속 실행한다. 평균 return이 더 높은 쪽은?

Q-learning은 Q⋆Q^\star, 즉 “이후 완벽하게 행동할 때”의 가치를 배운다. 그 탐욕 정책은 ε = 0일 때 최적이지만, ε = 0.1로 실행하면 절벽 옆에서 자주 떨어진다. SARSA는 ε-greedy 정책 자신의 QπQ^\pi를 배웠으므로 ε-greedy로 실행될 때 최선인 정책을 찾는다. 실행 조건이 학습 조건과 같다면 on-policy가 그 조건에서의 성능을 직접 최적화한다.

직접 구현하기

그림과 같은 실험을 NumPy로 한다. 두 알고리즘의 차이는 target 한 줄이다. 학습 중 return(ε-greedy로 행동)과 학습 후 탐욕 정책의 return(ε = 0)을 따로 잰다.

NumPy 절벽 걷기: SARSA vs Q-learning
import numpy as np, random

H, W = 4, 12
START, GOAL = (3, 0), (3, 11)
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]          # ↑ → ↓ ←

def step(s, a):
    i = min(H - 1, max(0, s[0] + MOVES[a][0]))
    j = min(W - 1, max(0, s[1] + MOVES[a][1]))
    if i == 3 and 0 < j < 11:                        # 절벽: -100, 출발점으로
        return START, -100.0, False
    return (i, j), -1.0, (i, j) == GOAL

def eps_greedy(Q, s, eps, rnd):
    if rnd.random() < eps:
        return rnd.randrange(4)
    return int(Q[s].argmax())

def run(method, episodes=500, alpha=0.5, eps=0.1, gamma=1.0, seed=0):
    rnd = random.Random(seed)
    Q = np.zeros((H, W, 4))
    returns = np.zeros(episodes)
    for ep in range(episodes):
        s, G = START, 0.0
        a = eps_greedy(Q, s, eps, rnd)
        while True:
            s2, r, done = step(s, a)
            G += r
            a2 = eps_greedy(Q, s2, eps, rnd)          # 실제로 다음에 할 행동
            if method == "sarsa":                      # on-policy 타깃
                target = r + gamma * Q[s2][a2] * (not done)
            else:                                      # off-policy 타깃: 탐욕 행동의 가치
                target = r + gamma * Q[s2].max() * (not done)
            Q[s][a] += alpha * (target - Q[s][a])
            s, a = s2, a2
            if done:
                break
        returns[ep] = G
    return Q, returns

def greedy_rollout(Q):
    grid = [["C" if (i == 3 and 0 < j < 11) else "." for j in range(W)] for i in range(H)]
    s, G = START, 0
    for _ in range(100):
        grid[s[0]][s[1]] = "*"
        if s == GOAL: break
        s, r, _ = step(s, int(Q[s].argmax()))
        G += r
    return G, "\n".join("   " + " ".join(row) for row in grid)

for method, name in [("sarsa", "SARSA"), ("q", "Q-learning")]:
    online = []
    for seed in range(5):
        Q, ret = run(method, seed=seed)
        online.append(ret[-100:].mean())
    G, picture = greedy_rollout(Q)
    print(f"{name}: 학습 중(ε=0.1) 마지막 100 ep 평균 return = {np.mean(online):6.1f}, "
          f"탐욕 정책(ε=0) return = {G}")
    print(picture, "\n")
 

Q-learning의 탐욕 정책은 −13(최적), SARSA는 −17 근처(안전한 우회)이고, 학습 중 return은 거꾸로 SARSA가 더 좋다. α를 0.1로 낮추거나 eps를 바꿔서 돌려 보자.

함수 근사와 deadly triad

표는 상태가 수천 개를 넘으면 쓸 수 없다. QQ를 매개변수 ϕ\phi를 가진 신경망 Qϕ(s,a)Q_\phi(s, a)로 바꾸고 TD 오차를 회귀 손실로 줄인다.

L(ϕ)=E(s,a,r,s′)∼D[(r+γmax⁡a′Qϕˉ(s′,a′)−Qϕ(s,a))2]\mathcal{L}(\phi) = \mathbb{E}_{(s,a,r,s') \sim \mathcal{D}}\Big[\big(r + \gamma \max_{a'} Q_{\bar\phi}(s', a') - Q_\phi(s, a)\big)^2\Big]

DQN(Mnih et al., 2015)은 이것으로 Atari 게임 다수에서 사람 수준에 도달했다. 두 장치가 핵심이었다. 과거 전이를 쌓아 두고 무작위로 뽑는 replay buffer (연속 샘플의 상관을 끊는다), 그리고 타깃 계산에 쓰는 가중치 ϕˉ\bar\phi를 천천히 갱신하는 target network (쫓아가는 타깃이 매 step 흔들리지 않게 한다).

이런 장치가 필요한 이유가 Sutton & Barto가 deadly triad 라고 부른 조합이다.

  1. 함수 근사: 한 상태를 고치면 다른 상태의 값도 같이 움직인다.
  2. bootstrapping: 타깃이 자기 자신의 추정에 의존한다.
  3. off-policy 학습: 학습하는 분포가 목표 정책이 방문하는 분포와 다르다.

셋 중 둘까지는 대체로 괜찮지만 셋이 모이면 가치 추정이 발산할 수 있다(Baird의 반례가 유명하다). 표 형태에서 성립한 수렴 보장은 여기서 깨지고, 실전에서는 target network, 작은 학습률, 타깃 정규화 같은 공학으로 버틴다. max⁡\max가 잡음까지 골라내 가치를 과대평가하는 maximization bias 도 있어서 Double Q-learning(행동 선택과 평가를 다른 네트워크로) 같은 수정이 쓰인다.

확인 문제Check yourself

다음 중 TD(0) 타깃 r + γV(s')에 대한 설명으로 옳은 것은?

TD 타깃의 기댓값은 E[r+γV(s′)]\mathbb{E}[r + \gamma V(s')] 이고, V=VπV = V^\pi일 때만 Vπ(s)V^\pi(s)와 같다. 그 전에는 편향된다. 대신 rtr_t와 st+1s_{t+1} 한 번의 샘플링만 무작위라 분산이 작다. TD(0)는 정책 평가이므로 on/off-policy 여부와는 상관이 없다(같은 정책의 데이터로 학습하면 on-policy).

정리

  • 정책 반복 = 평가 + 탐욕 개선. 정책 개선 정리가 단조 개선을 보장한다. 거의 모든 RL 알고리즘이 이를 근사하는 GPI다.
  • MC는 실제 return GtG_t를 타깃으로(불편, 고분산), TD는 rt+γV(st+1)r_t + \gamma V(s_{t+1})을 타깃으로(편향, 저분산, 매 step) 쓴다. n-step이 그 사이를 잇는다.
  • SARSA는 실제 다음 행동으로(on-policy, 탐험을 포함한 정책의 가치), Q-learning은 max⁡\max로(off-policy, Q⋆Q^\star) bootstrapping한다.
  • 함수 근사 + bootstrapping + off-policy = deadly triad. DQN은 replay buffer와 target network로 버틴다.
  • LLM RL에서 MC 대 TD는 “GRPO/RLOO의 종단 보상 + group baseline” 대 “PPO의 토큰 단위 critic + GAE”로 다시 나타난다.

더 읽을거리Further reading