In supervised learning the answer was given. In reinforcement learning (RL) what comes back instead of the answer is a single number, the reward, and it usually arrives late. In Go the game is decided after hundreds of moves; an LLM solving a math problem only hears whether its answer was right after it has generated the last token. The five lessons of this track cover the classical RL that learns “which action was good” in that setting, and at each step point out what it becomes in LLM post-training. The first lesson is the language for writing the problem down: the MDP and the Bellman equation.
The agent–environment loop
At time the agent observes a state and picks an action . The environment returns a reward and the next state . The record of this repeated exchange is a trajectory.
The rule by which the agent picks actions is the policy . A stochastic policy is a distribution over actions for each state; a deterministic policy is a function . When it is parameterised by a neural network we write . An LLM is itself a policy: it is a function that outputs the next-token distribution .
MDP: the problem in five symbols
A Markov decision process (MDP) is specified by a tuple together with an initial state distribution .
- : the set of states, : the set of actions
- : the transition probabilities (transition dynamics)
- : the reward function (if it is random, use its expectation)
- : the discount factor
The key assumption is the Markov property: the distribution of the next state is determined by the current state and action alone; the history before that is not needed.
Whether this holds depends on how the “state” is defined. Put the entire history into the state and anything becomes Markov. That is exactly what an LLM does (we will see this below).
Return and discounting
What the agent maximises is not a single reward but the sum of future rewards, the return.
does three things. (1) If rewards are bounded, the infinite sum converges (). (2) The further into the future, the more uncertain, so it is trusted less. (3) Given the same reward, it prefers receiving it sooner. It takes about steps for to fall to , so this value is called the effective horizon. With the agent looks roughly 100 steps ahead.
The return has a recursive structure. This one line is the root of the whole lesson.
The goal is to find the policy that maximises the expected return.
Value functions
We define “how good this state is” as the expected return when following policy .
is the state value, and is the action value, with the first action fixed to . Their relationship follows directly from the definitions.
Their difference is the advantage , the protagonist of the second half of this track. It measures “how much better this action is than usual”.
The Bellman expectation equation
Take expectations of both sides of . Unrolling the conditional expectations in turn, over the first action and the next state , gives
The braced term becomes thanks to the Markov property: once is known, what happened before it has no effect on the distribution of future returns. In the same way,
With finitely many states this is a system of linear equations. Writing and ,
is a stochastic matrix, so its eigenvalues have absolute value at most 1, and for the matrix is always invertible. Computing the value of a single policy like this is called policy evaluation.
The Bellman optimality equation
The optimal value satisfies an equation of the same form, with a maximum in place of the average.
If we know , the optimal policy is simply . There is no need to compute the future separately: that information is already compressed into . This is why value functions are useful.
Because of the , the equation is no longer linear. Instead we solve it by iteration. Treating the right-hand side as an operator and repeating is value iteration. Why does it converge? For any two functions , since ,
is a γ-contraction in the sup norm. By the Banach fixed-point theorem a unique fixed point exists, and from any starting point the iterates approach it geometrically, . The closer is to 1, the slower.
In a picture: value iteration
In the grid world below the agent moves up, down, left or right; with probability it goes in the intended direction and with probability each it slips to either side. Bumping into a wall or the boundary leaves it in place. Entering a +1 or −1 cell gives that reward and ends the episode, and every move earns a step reward (a cost if negative). The default map pits a short corridor right above the row of pits against a long detour above the wall.
지도학습에서는 정답이 주어졌다. 강화학습(reinforcement learning, RL)에서는 정답 대신 보상(reward) 이라는 숫자 하나가 돌아오고, 그것도 대개 늦게 온다. 바둑에서는 수백 수를 둔 뒤에 승패가 나오고, 수학 문제를 푸는 LLM은 마지막 토큰까지 생성한 뒤에야 답이 맞았는지 듣는다. 이 트랙의 다섯 레슨은 그런 상황에서 “어떤 행동이 좋았는가”를 배우는 고전 RL을 다루고, 매 단계마다 그것이 LLM 사후학습에서 무엇이 되는지 짚는다. 첫 레슨은 문제를 적는 언어, MDP 와 Bellman 방정식 이다.
에이전트–환경 루프
에이전트는 시각 에 상태 를 보고 행동 를 고른다. 환경은 보상 와 다음 상태 을 돌려준다. 이것이 반복된 기록이 궤적(trajectory) 이다.
에이전트가 행동을 고르는 규칙이 정책(policy) 다. 확률적 정책이면 상태마다 행동의 분포이고, 결정적 정책이면 함수 다. 신경망으로 매개화하면 라고 쓴다. LLM은 그 자체로 정책이다. 다음 토큰의 분포 를 내놓는 함수이기 때문이다.
MDP: 문제를 다섯 개의 기호로 적기
마르코프 결정 과정(Markov decision process, MDP) 은 튜플 와 초기 상태 분포 로 정해진다.
- : 상태 집합, : 행동 집합
- : 전이 확률(transition dynamics)
- : 보상 함수 (확률적이면 기댓값을 쓴다)
- : 할인율(discount factor)
핵심 가정은 마르코프 성질 이다. 다음 상태의 분포는 현재 상태와 행동만으로 정해지고, 그 이전의 역사는 필요 없다.
이 가정은 “상태”를 어떻게 정의하느냐에 달린 문제다. 역사 전체를 상태에 넣으면 무엇이든 마르코프가 된다. LLM이 정확히 그렇게 한다(아래에서 본다).
Return과 할인
에이전트가 최대화하려는 것은 한 번의 보상이 아니라 미래 보상의 합, return 이다.
이 하는 일은 세 가지다. (1) 보상이 유계이면 무한 합이 수렴한다(). (2) 먼 미래일수록 불확실하니 덜 믿는다. (3) 같은 보상이면 빨리 받는 쪽을 선호하게 만든다. 가 로 떨어지는 데 약 step이 걸리므로 이 값을 유효 지평(effective horizon) 이라 부른다. 면 대략 100 step 앞까지 본다.
return은 재귀 구조를 가진다. 이 한 줄이 이 레슨 전체의 뿌리다.
목표는 기대 return을 최대화하는 정책을 찾는 것이다.
가치함수
“이 상태가 얼마나 좋은가”를 정책 를 따랐을 때의 기대 return으로 정의한다.
는 상태 가치(state value), 는 첫 행동을 로 고정한 행동 가치(action value) 다. 둘의 관계는 정의에서 바로 나온다.
둘의 차이가 이 트랙 후반의 주인공인 advantage 다. “평소보다 이 행동이 얼마나 나은가”를 잰다.
Bellman 기대 방정식
의 양변에 기댓값을 씌운다. 첫 행동 , 다음 상태 에 대해 조건부 기댓값을 차례로 풀면
중괄호 부분이 가 되는 것이 마르코프 성질 덕분이다. 을 알면 그 전에 무슨 일이 있었는지는 미래 return의 분포에 영향을 주지 않는다. 같은 방법으로
상태가 유한하면 이것은 연립 일차방정식이다. , 로 두면
는 확률 행렬이라 고유값의 절댓값이 1 이하이고, 이면 는 항상 역행렬이 있다. 이렇게 정책 하나의 가치를 구하는 일을 정책 평가(policy evaluation) 라 한다.
Bellman 최적 방정식
최적 가치 는 평균 대신 최댓값이 들어간 같은 꼴의 방정식을 만족한다.
를 알면 최적 정책은 그냥 다. 미래를 따로 계산할 필요가 없다. 그 정보가 이미 안에 압축되어 있다. 이것이 가치함수가 쓸모 있는 이유다.
때문에 더 이상 선형이 아니다. 대신 반복으로 푼다. 오른쪽을 연산자 로 보고 를 되풀이하는 것이 가치 반복(value iteration) 이다. 왜 수렴하는가? 임의의 두 함수 에 대해 이므로
는 sup norm에서 γ-수축 사상(contraction) 이다. Banach 고정점 정리에 의해 고정점 가 유일하게 존재하고, 어디서 출발하든 로 기하급수적으로 다가간다. 가 1에 가까울수록 느리다.
그림으로: 가치 반복
아래 격자 세계에서 에이전트는 상하좌우로 움직이고, 확률 로 의도한 방향으로, 씩 양옆으로 미끄러진다. 벽이나 경계에 부딪히면 제자리다. +1 또는 −1 칸에 들어가면 그 보상을 받고 끝나며, 매 이동마다 이동 보상 (음수면 비용)를 받는다. 기본 지도는 함정 줄 바로 위의 짧은 복도와 벽 위쪽의 긴 우회로를 경쟁시킨다.
Things to try:
- p = 0: with no slipping, the agent goes straight through the corridor. It arrives in 7 steps.
- p at 0.1 or above: while crossing the corridor, the agent falls into a pit with probability every step. The upper detour (11 steps) gets the higher value and the arrows flip. Only the transition probabilities changed, yet the optimal action changes.
- At p = 0.06, γ from 0.95 → 0.9: the chance of an accident in the corridor is small, and the 4 extra steps of the detour are discounted by . With less patience the risky shortcut wins again. Conversely, with γ = 0.99 the agent takes the detour even at p = 0.04. The discount factor is “how patient you are”.
- Step reward c at −0.15: walking for a long time now costs more, so the agent hurries through the corridor again. Push it down to −0.2 and the arrows in a few bottom-left cells point at the pit: rather than pay the cost forever, it is better to take −1 and end it. This is a first example of how a slightly mis-designed reward makes an unintended behaviour optimal (Track V’s reward hacking).
- The residual plot: every sweep the error shrinks by at least a factor γ. The greedy policy settles long before V converges.
Implementing it
On the same map as the figure, we build the transition tensor and run value iteration and policy evaluation. Policy evaluation is done two ways, by a linear solve and by repeated backups, to check they give the same values. Finally we evaluate “a policy planned under the belief that there is no slipping” in the real (slippery) environment and compare it with the optimal value.
import numpy as np
MAP = ["........",
".######.",
"S......+",
".------.",
"........"]
H, W = len(MAP), len(MAP[0])
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)] # ↑ → ↓ ←
ARROW = "↑→↓←"
def build(slip=0.2, step=-0.02):
"""P[s, a, s'] transition probabilities, R[s, a] expected reward"""
S = H * W
P = np.zeros((S, 4, S)); R = np.zeros((S, 4))
for i in range(H):
for j in range(W):
s = i * W + j
if MAP[i][j] in "#+-": # wall / terminal: absorbing, reward 0
P[s, :, s] = 1.0
continue
for a in range(4):
# intended direction 1-slip, slip/2 to each side
for d, p in [(a, 1 - slip), ((a + 1) % 4, slip / 2), ((a + 3) % 4, slip / 2)]:
ni, nj = i + MOVES[d][0], j + MOVES[d][1]
if not (0 <= ni < H and 0 <= nj < W) or MAP[ni][nj] == "#":
ni, nj = i, j # bump into wall / boundary: stay put
P[s, a, ni * W + nj] += p
R[s, a] += p * (step + {"+": 1.0, "-": -1.0}.get(MAP[ni][nj], 0.0))
return P, R
def value_iteration(P, R, gamma, tol=1e-8):
V = np.zeros(P.shape[0]); hist = []
while True:
Q = R + gamma * P @ V # (S, A): Bellman optimality backup
V_new = Q.max(axis=1)
hist.append(np.abs(V_new - V).max())
V = V_new
if hist[-1] < tol:
return V, Q.argmax(axis=1), np.array(hist)
def show(V, pi):
for i in range(H):
cells = []
for j in range(W):
s, c = i * W + j, MAP[i][j]
if c == "#": cells.append(" ### ")
elif c in "+-": cells.append(f" {c}1 ")
elif V is None: cells.append(f" {ARROW[pi[s]]} ")
else: cells.append(f"{V[s]:+.2f}{ARROW[pi[s]]}")
print(" ".join(cells))
gamma = 0.95
P, R = build(slip=0.2)
V, pi, hist = value_iteration(P, R, gamma)
print(f"slip=0.2, γ={gamma}: converged after {len(hist)} sweeps. V* and greedy policy:")
show(V, pi)
print(f"\nresidual: k=1 {hist[0]:.2e} → k=20 {hist[19]:.2e} → k=40 {hist[39]:.2e}")
print(f"max ratio of residuals in consecutive sweeps = {(hist[1:] / hist[:-1]).max():.3f} (≤ γ: contraction)")Now policy evaluation. We solve directly and compare it with the result of repeated Bellman expectation backups.
def policy_eval_exact(P, R, pi, gamma):
S = P.shape[0]
P_pi = P[np.arange(S), pi] # (S, S'): transitions of the action the policy picks
r_pi = R[np.arange(S), pi]
return np.linalg.solve(np.eye(S) - gamma * P_pi, r_pi)
def policy_eval_iter(P, R, pi, gamma, n=500):
S = P.shape[0]; V = np.zeros(S)
for _ in range(n): # V ← r_π + γ P_π V
V = R[np.arange(S), pi] + gamma * P[np.arange(S), pi] @ V
return V
P0, R0 = build(slip=0.0) # wrong model: "no slipping"
_, pi0, _ = value_iteration(P0, R0, gamma)
print("policy planned with the slip=0 model (goes straight through the corridor):")
show(None, pi0)
s0 = 2 * W # start cell S
Ve, Vi = policy_eval_exact(P, R, pi0, gamma), policy_eval_iter(P, R, pi0, gamma)
print(f"\nV^π(S) of that policy in the real env (slip=0.2): linear solve {Ve[s0]:+.4f}, iterative {Vi[s0]:+.4f}")
print(f"optimal value V*(S) in the real env: {V[s0]:+.4f}")The corridor policy’s true value is negative: the chance of falling into a pit more than cancels the chance of reaching +1. If the model is wrong, the policy that is optimal under that model can be bad in reality. This is one of the reasons the next lesson moves to model-free methods that learn directly from experience.
With γ = 0.99, roughly how many steps until the weight on future rewards falls to about 1/e — the 'effective horizon'?
Since , it reaches at . is standard on Atari-style tasks roughly because many tasks only need you to look a few dozen to a few hundred steps ahead. An LLM’s responses are thousands of tokens long with reward only at the end, so it uses . Because every episode is guaranteed to end, the sum does not diverge.
Viewing an LLM as an MDP
Now put an LLM into the same symbols. Taking a prompt and generating a completion is the following MDP.
| RL | LLM generation |
|---|---|
| initial state | prompt (sampled from a prompt dataset) |
| state | : the prompt + the tokens generated so far |
| action | the next token (vocabulary of tens to hundreds of thousands) |
| transition | deterministic: , just concatenation |
| policy | the language model’s next-token distribution |
| reward | (), and only at the end (reward model or verifier) |
| discount factor | |
| episode | one completion, ending at EOS or the maximum length |
A few things differ sharply from classical RL.
- The state is the entire history, so the Markov property holds for free. In exchange the state space is astronomically large and the same state is almost never visited twice. Storing values in a table is impossible; function approximation is mandatory.
- Transitions are deterministic and known. There is no uncertainty in the environment; all randomness comes from sampling the policy.
- Reward is sparse and only at the end. So with and zero intermediate rewards, the value function has a very clean meaning. is “the expected reward if we continue from this prefix”, and with a 0/1 verifier it is the probability of reaching a correct answer if we continue from this prefix. And since transitions are deterministic,
The advantage of a single token is “how much that token changed the probability of success”. Ideal credit assignment would give a large advantage to the decisive line in the middle of a solution and an advantage near 0 to mechanical tokens. The problem is that we do not know ; the rest of Track IV is about ways to estimate it or avoid it.
The bandit view. We can also treat the whole completion as a single action. The policy is the sequence probability
and the problem becomes a contextual bandit: look at the context , pick one action , receive the reward , done. The time structure disappears and credit assignment is lumped into “the whole completion was good/bad”. Surprisingly, much of LLM RL works well from this view. REINFORCE, RLOO and GRPO all give one advantage per completion and share that value equally across all tokens. PPO for RLHF, by contrast, learns a token-level value function and gives each token a different advantage (the token-MDP view). The difference between the two runs through lessons 4–5 of Track IV and all of Track V.
An LLM is trained with γ = 1, zero intermediate rewards, and a verifier reward that gives 1 at the end if the answer is correct and 0 otherwise. What is V^π(s_t) here?
. The reward received so far is always 0, so it carries no information; the value function is purely a prediction about the future. Learning a critic that predicts this probability accurately at every token is hard, which is one reason GRPO-style methods drop the critic.
Summary
- An MDP is plus . The Markov property is a matter of how the state is defined.
- The goal is the expected return . is the effective horizon.
- and satisfy the Bellman expectation equations that come from , and policy evaluation is a linear solve. .
- The Bellman optimality operator is a γ-contraction, so value iteration converges geometrically to the unique . .
- LLM generation is an MDP with state = prompt + tokens, action = next token, deterministic transitions, and a terminal reward. Treating the whole completion as one action makes it a contextual bandit.
해 볼 것:
- p = 0: 미끄러지지 않으면 복도로 곧장 간다. 7 step이면 도착한다.
- p를 0.1 이상으로: 복도를 지나는 동안 매 step 확률로 함정에 빠진다. 위쪽 우회로(11 step)가 더 큰 가치를 갖게 되고 화살표가 뒤집힌다. 이동 확률이 바뀌었을 뿐인데 최적 행동이 바뀐다.
- p = 0.06에서 γ를 0.95 → 0.9로: 복도의 사고 확률은 작고, 우회로의 추가 4 step은 만큼 할인된다. 참을성이 줄면 위험한 지름길이 다시 이긴다. 반대로 γ = 0.99면 p = 0.04에서도 돌아간다. 할인율은 “얼마나 참을성이 있는가”다.
- 이동 보상 c를 −0.15로: 오래 걷는 비용이 커져 다시 복도로 서두른다. −0.2까지 내리면 왼쪽 아래 몇 칸의 화살표가 함정 쪽을 가리킨다. 끝없이 비용을 내느니 −1을 받고 끝내는 편이 낫다는 계산이다. 보상을 조금 잘못 설계하면 의도하지 않은 행동이 최적이 된다는 첫 예다(Track V의 reward hacking).
- residual 그래프: 매 sweep 오차가 최소한 γ배씩 줄어든다. 탐욕 정책은 V가 수렴하기 훨씬 전에 고정된다.
직접 구현하기
그림과 같은 지도에서 전이 확률 텐서 를 만들고 가치 반복과 정책 평가를 한다. 정책 평가는 선형 풀이와 반복 backup 두 방법으로 해서 같은 값이 나오는지 본다. 마지막으로 “미끄러짐이 없다고 믿고 만든 정책”을 실제(미끄러지는) 환경에서 평가해 최적 가치와 비교한다.
import numpy as np
MAP = ["........",
".######.",
"S......+",
".------.",
"........"]
H, W = len(MAP), len(MAP[0])
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)] # ↑ → ↓ ←
ARROW = "↑→↓←"
def build(slip=0.2, step=-0.02):
"""P[s, a, s'] 전이확률, R[s, a] 기대 보상"""
S = H * W
P = np.zeros((S, 4, S)); R = np.zeros((S, 4))
for i in range(H):
for j in range(W):
s = i * W + j
if MAP[i][j] in "#+-": # 벽·종단: 흡수 상태, 보상 0
P[s, :, s] = 1.0
continue
for a in range(4):
# 의도한 방향 1-slip, 양옆으로 slip/2씩
for d, p in [(a, 1 - slip), ((a + 1) % 4, slip / 2), ((a + 3) % 4, slip / 2)]:
ni, nj = i + MOVES[d][0], j + MOVES[d][1]
if not (0 <= ni < H and 0 <= nj < W) or MAP[ni][nj] == "#":
ni, nj = i, j # 벽·경계에 부딪히면 제자리
P[s, a, ni * W + nj] += p
R[s, a] += p * (step + {"+": 1.0, "-": -1.0}.get(MAP[ni][nj], 0.0))
return P, R
def value_iteration(P, R, gamma, tol=1e-8):
V = np.zeros(P.shape[0]); hist = []
while True:
Q = R + gamma * P @ V # (S, A): Bellman 최적 backup
V_new = Q.max(axis=1)
hist.append(np.abs(V_new - V).max())
V = V_new
if hist[-1] < tol:
return V, Q.argmax(axis=1), np.array(hist)
def show(V, pi):
for i in range(H):
cells = []
for j in range(W):
s, c = i * W + j, MAP[i][j]
if c == "#": cells.append(" ### ")
elif c in "+-": cells.append(f" {c}1 ")
elif V is None: cells.append(f" {ARROW[pi[s]]} ")
else: cells.append(f"{V[s]:+.2f}{ARROW[pi[s]]}")
print(" ".join(cells))
gamma = 0.95
P, R = build(slip=0.2)
V, pi, hist = value_iteration(P, R, gamma)
print(f"slip=0.2, γ={gamma}: {len(hist)} sweep 후 수렴. V*와 탐욕 정책:")
show(V, pi)
print(f"\nresidual: k=1 {hist[0]:.2e} → k=20 {hist[19]:.2e} → k=40 {hist[39]:.2e}")
print(f"연속 sweep의 residual 비율 최댓값 = {(hist[1:] / hist[:-1]).max():.3f} (≤ γ: 수축)")이제 정책 평가다. 를 직접 풀고, Bellman 기대 backup을 반복한 결과와 비교한다.
def policy_eval_exact(P, R, pi, gamma):
S = P.shape[0]
P_pi = P[np.arange(S), pi] # (S, S'): 정책이 고른 행동의 전이
r_pi = R[np.arange(S), pi]
return np.linalg.solve(np.eye(S) - gamma * P_pi, r_pi)
def policy_eval_iter(P, R, pi, gamma, n=500):
S = P.shape[0]; V = np.zeros(S)
for _ in range(n): # V ← r_π + γ P_π V
V = R[np.arange(S), pi] + gamma * P[np.arange(S), pi] @ V
return V
P0, R0 = build(slip=0.0) # "미끄러지지 않는다"는 잘못된 모델
_, pi0, _ = value_iteration(P0, R0, gamma)
print("slip=0 모델로 계획한 정책 (복도를 곧장 지난다):")
show(None, pi0)
s0 = 2 * W # 출발점 S
Ve, Vi = policy_eval_exact(P, R, pi0, gamma), policy_eval_iter(P, R, pi0, gamma)
print(f"\n실제 환경(slip=0.2)에서 그 정책의 V^π(S): 선형 풀이 {Ve[s0]:+.4f}, 반복 {Vi[s0]:+.4f}")
print(f"실제 환경의 최적 가치 V*(S): {V[s0]:+.4f}")복도 정책의 실제 가치는 음수다. 함정에 빠질 확률이 +1에 도착할 확률을 상쇄하고도 남는다. 모델이 틀리면 그 모델로 만든 최적 정책은 실제로는 나쁠 수 있다. 이것이 다음 레슨에서 모델 없이(model-free) 경험으로부터 직접 배우는 방법으로 넘어가는 이유 중 하나다.
γ = 0.99일 때 미래 보상의 가중치가 대략 1/e로 줄어드는 시점, 즉 '유효 지평'은 몇 step 정도인가?
이므로 에서 가 된다. Atari류 과제에서 가 표준인 이유가 대략 수십~수백 step 앞을 보면 되는 과제가 많기 때문이다. LLM은 응답 길이가 수천 토큰이고 보상이 끝에만 있으므로 을 쓴다. 에피소드가 반드시 끝나기 때문에 합이 발산하지 않는다.
LLM을 MDP로 보기
이제 같은 기호에 LLM을 올린다. 프롬프트 를 받아 완성문 을 생성하는 과정은 다음 MDP다.
| RL | LLM 생성 |
|---|---|
| 초기 상태 | 프롬프트 (프롬프트 데이터셋에서 샘플) |
| 상태 | : 프롬프트 + 지금까지 생성한 토큰 |
| 행동 | 다음 토큰 (어휘 크기 수만~수십만) |
| 전이 | 결정적: , 그냥 이어 붙이기 |
| 정책 | 언어 모델의 다음 토큰 분포 |
| 보상 | (), 마지막에만 (보상모델 또는 검증기) |
| 할인율 | |
| 에피소드 | 완성문 하나. EOS 또는 최대 길이에서 끝난다 |
몇 가지가 고전 RL과 크게 다르다.
- 상태가 역사 전체 이므로 마르코프 성질이 공짜로 성립한다. 대신 상태 공간은 천문학적으로 크고, 같은 상태를 두 번 방문하는 일이 거의 없다. 표(table)로 가치를 저장하는 방법은 불가능하고 함수 근사가 필수다.
- 전이가 결정적이고 알려져 있다. 환경의 불확실성은 없고, 모든 무작위성은 정책의 샘플링에서 나온다.
- 보상이 희소하고 끝에만 있다. 그래서 , 중간 보상 0일 때 가치함수는 아주 깔끔한 뜻을 갖는다. 는 “이 prefix에서 이어 쓰면 기대 보상이 얼마인가”, 0/1 검증기라면 이 prefix에서 이어 썼을 때 정답에 도달할 확률 이다. 그리고 전이가 결정적이라
토큰 하나의 advantage는 “그 토큰이 성공 확률을 얼마나 바꿨는가”다. 풀이 중간의 결정적인 한 줄이 큰 advantage를 갖고, 기계적인 토큰은 0 근처의 advantage를 갖는 것이 이상적인 credit assignment다. 문제는 를 모른다는 것이고, Track IV 나머지가 그것을 추정하거나 피하는 방법들이다.
Bandit 관점. 완성문 전체를 하나의 행동으로 볼 수도 있다. 정책은 시퀀스 확률
이고, 문맥 를 보고 행동 를 하나 고른 뒤 보상 를 받으면 끝나는 contextual bandit 이 된다. 시간 구조가 사라지고 credit assignment는 “완성문 전체가 좋았다/나빴다”로 뭉뚱그려진다. 놀랍게도 LLM RL의 상당 부분이 이 관점에서 잘 작동한다. REINFORCE, RLOO, GRPO는 모두 완성문 하나에 advantage 하나를 주고 그 값을 모든 토큰에 똑같이 나눠 준다. 반면 RLHF용 PPO는 토큰 단위 가치함수를 학습해 토큰마다 다른 advantage를 준다(토큰 MDP 관점). 이 둘의 차이가 Track IV 4–5강과 Track V 전체를 관통한다.
γ = 1, 중간 보상 0, 마지막에 정답이면 1 아니면 0을 주는 검증기 보상으로 LLM을 학습한다. 이때 V^π(s_t)는 무엇인가?
. 지금까지 받은 보상은 항상 0이므로 정보가 없고, 가치함수는 순전히 미래에 대한 예측이다. 이 확률을 토큰마다 정확히 예측하는 critic을 학습하기가 어렵다는 것이 GRPO류 방법이 critic을 버리는 이유 중 하나다.
정리
- MDP는 와 . 마르코프 성질은 상태를 어떻게 정의하느냐의 문제다.
- 목표는 기대 return . 가 유효 지평이다.
- , 는 에서 나온 Bellman 기대 방정식을 만족하고, 정책 평가는 선형 풀이다. .
- Bellman 최적 연산자는 γ-수축이라 가치 반복은 유일한 로 기하급수적으로 수렴한다. .
- LLM 생성은 상태 = prompt + 토큰, 행동 = 다음 토큰, 결정적 전이, , 종단 보상인 MDP다. 완성문 전체를 행동 하나로 보면 contextual bandit이다.
더 읽을거리Further reading
- Sutton & Barto, Reinforcement Learning: An Introduction, 2nd ed. (MIT Press, 2018) Ch. 3–4 — MDP, 가치함수, Bellman 방정식, 동적계획법의 표준 교과서. 무료 PDF.The standard textbook for MDPs, value functions, the Bellman equation and dynamic programming. Free PDF.
- OpenAI Spinning Up, Part 1: Key Concepts in RL — 이 트랙의 표기(r_t, G, V^π, Q^π)를 가장 짧게 정리한 글.The shortest summary of the notation this track uses (r_t, G, V^π, Q^π).
- Sergey Levine, CS 285: Deep Reinforcement Learning (UC Berkeley) — Lecture 2–4가 MDP, 가치함수, RL 알고리즘의 분류를 다룬다.Lectures 2–4 cover MDPs, value functions and the taxonomy of RL algorithms.
- Puterman, Markov Decision Processes: Discrete Stochastic Dynamic Programming (Wiley, 1994) — 수축 사상과 가치 반복 수렴 증명의 고전적 출처.The classic source for the contraction mapping and the convergence proof of value iteration.
- Nathan Lambert, Reinforcement Learning from Human Feedback (rlhfbook.com) — LLM 생성을 RL 문제로 놓는 방식과 그 한계를 정리한 책. Track V가 따라간다.A book on how LLM generation is cast as an RL problem and where that framing breaks down. Track V follows it.
- Ahmadian et al., Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs (ACL 2024) — 완성문 전체를 하나의 행동으로 보는 bandit 관점을 옹호한다.Argues for the bandit view, where the whole completion is a single action.