Skip to content
English

Switch theme

Deep Learning

Reinforcement Learning Basics: MDPs, Q-Learning, DQN, Policy Gradients, PPO and AlphaZero

Intermediate 40 min For: Researchers

Key takeaways

  • ▸Reinforcement learning studies how an agent improves its behaviour by interacting with an environment and receiving reward signals. The problem is usually formalised as a Markov decision process (MDP) whose goal is to maximise the discounted return Gₜ = rₜ + γrₜ₊₁ + γ²rₜ₊₂ + …; value functions satisfy the Bellman equations, the starting point of almost every algorithm.
  • ▸Q-learning (Watkins and Dayan, 1992) needs no model of the environment and converges to the optimal action values with probability 1 as long as every action is repeatedly sampled in every state. In this lesson's FrozenLake example, after 20,000 episodes the greedy Q-learning policy succeeds 0.737 of the time, the same as the optimal policy found by value iteration with the model known.
  • ▸DQN (Mnih et al., 2013, 2015) approximates the Q-function with a convolutional network and stabilises training with experience replay and a target network. Using only pixels and the score as input, it reached a level comparable to a professional human games tester across 49 Atari games, with the same algorithm, network architecture and hyperparameters for every game.
  • ▸Policy-gradient methods optimise the policy directly. PPO (Schulman et al., 2017) clips the probability ratio between the new and old policies to [1 − ε, 1 + ε], so the same batch of data can safely be used for several epochs; in the paper's continuous-control experiments, ε = 0.2 gives an average normalised score of 0.82, against −0.39 with neither clipping nor a penalty. In this lesson's example PPO reaches the maximum score of 500 on CartPole with all 3 seeds, while REINFORCE with the same 100,000 steps reaches only 178–291.
  • ▸RL also underpins LLM post-training: InstructGPT (Ouyang et al., 2022) trains a reward model from human preferences and then fine-tunes with PPO, and outputs from the 1.3B-parameter model are preferred to those of the 175B-parameter GPT-3; GRPO, proposed in DeepSeekMath, drops the value network and estimates the baseline from the scores of a group of answers to the same question.

Overview: reinforcement learning (RL) studies how an agent gradually improves its behaviour through interaction with an environment, guided by reward signals. It differs from supervised learning in two ways: there are no correct answers, only after-the-fact judgements of how good an outcome was, and the data are produced by the agent's own decisions. This lesson first sets out the basic concepts of Markov decision processes, returns, value functions and the Bellman equations, then follows two lines of core algorithms: value-based methods (value iteration, temporal-difference learning, Q-learning, DQN) and policy-based methods (REINFORCE, actor-critic, TRPO, PPO). It then covers continuous control, offline RL, and self-play and tree search in the AlphaGo family, and finally explains how RL connects to LLM post-training (RLHF, GRPO). All experimental figures come from the runnable example at the end.

This lesson belongs to the Reinforcement Learning Basics unit. Its prerequisites are Probability and Information Theory (expectations, conditional probability) and Training Deep Networks (optimisers and gradient clipping). It leads on to RLHF in How LLMs Learn and to Reasoning Models. Related algorithm cards: Q-learning, DQN, policy gradient, actor-critic and A3C, TRPO, PPO, DDPG/TD3, SAC, CQL, Decision Transformer, AlphaGo/AlphaZero, MuZero, RLHF and GRPO.

The problem: agents, environments and Markov decision processes

At each time step t the agent observes a state sₜ and chooses an action aₜ according to its policy π; the environment returns a reward rₜ and moves to the next state sₜ₊₁. This interaction is usually formalised as a Markov decision process (MDP) with five elements:

Element Meaning FrozenLake example
State set S Situations the environment can be in The 16 cells of a 4×4 frozen lake
Action set A Actions available to the agent Up, down, left, right
Transition probabilities P(s′ | s, a) Probability of reaching each state after an action Slippery ice: the agent moves in the intended direction with probability 1/3 and in each perpendicular direction with probability 1/3
Reward function R Scalar feedback at each step 1 for reaching the goal, 0 otherwise
Discount factor γ Weight of future rewards, 0 ≤ γ ≤ 1 0.99

“Markov” means the next state depends only on the current state and action, not on earlier history. A policy π(a | s) gives the probability of each action in each state; a deterministic policy gives a single action.

Returns, value functions and the Bellman equations

The agent's goal is to maximise the return, the discounted sum of rewards from the current time onwards:

Gₜ = rₜ + γ·rₜ₊₁ + γ²·rₜ₊₂ + … = rₜ + γ·Gₜ₊₁

With γ < 1 distant rewards count for less, and the return of an infinitely long sequence stays bounded. In the example, with rewards (0, 0, 0, 1) and γ = 0.9, the returns at successive times are 0.729, 0.81, 0.9 and 1.0: the earlier the time, the further from the reward and the smaller the return.

The state value Vπ(s) is the expected return starting from state s and following policy π; the action value Qπ(s, a) is the expected return after first taking action a in s and then following π; their difference Aπ(s, a) = Qπ(s, a) − Vπ(s) is the advantage, how much better action a is than the average in that state. The recursive form of the return gives the Bellman equation:

Vπ(s) = Σₐ π(a | s) · Σₛ′ P(s′ | s, a) · [ R(s, a, s′) + γ·Vπ(s′) ]

The optimal value function satisfies the Bellman optimality equation, which replaces the average over the policy with a maximum:

Q*(s, a) = Σₛ′ P(s′ | s, a) · [ R(s, a, s′) + γ·maxₐ′ Q*(s′, a′) ]

Once Q* is known, choosing the action with the largest Q* in each state is an optimal policy. The algorithms below can all be seen as different ways of solving or approximating these two equations (Sutton and Barto, 2018, Chapters 3–4).

Known model: dynamic programming and value iteration

If the transition probabilities and reward function are known, the problem can be solved directly by dynamic programming. Value iteration repeatedly applies the Bellman optimality equation to every state until the values stop changing. The example runs value iteration on Gymnasium's slippery 4×4 FrozenLake: it converges after 438 sweeps (largest change below 10⁻⁸), with an optimal start-state value of 0.542; running the resulting policy for 10,000 episodes reaches the goal 0.737 of the time. Because the ice is slippery, even the optimal policy cannot guarantee success.

In real problems the environment model is usually unknown (game internals, robot dynamics) or there are too many states to enumerate. This calls for model-free methods that learn from interaction data, and for neural networks that approximate value functions or policies.

Model-free learning: temporal differences and Q-learning

Without the transition probabilities, values can be estimated from experienced samples. Monte Carlo methods wait until an episode ends and use the actual return Gₜ as the target; temporal-difference (TD) learning (Sutton, 1988) looks only one step ahead and uses rₜ + γ·V(sₜ₊₁) as the target, updating an estimate from an estimate (bootstrapping) without waiting for the episode to end. The two trade off bias against variance: the Monte Carlo target is unbiased but has high variance, while the TD target has lower variance but depends on how accurate the current estimate is.

Q-learning (Watkins, 1989; Watkins and Dayan, 1992) applies the TD idea to the Bellman optimality equation. After each transition (s, a, r, s′) it makes one update:

Q(s, a) ← Q(s, a) + α · [ r + γ·maxₐ′ Q(s′, a′) − Q(s, a) ]

The bracketed term is the TD error and α is the learning rate. Watkins and Dayan proved that Q-learning converges to the optimal action values with probability 1 as long as every action is repeatedly sampled in every state and the action values are represented discretely in a table. To ensure exploration, an ε-greedy policy is common: with probability ε choose a random action, otherwise the action with the largest current Q-value, and decay ε during training. Because the update uses maxₐ′ Q(s′, a′) regardless of the exploratory action actually taken next, Q-learning is an off-policy method; using the Q-value of the next action actually taken gives the on-policy SARSA (Sutton and Barto, 2018, Chapter 6).

The example trains tabular Q-learning on the same FrozenLake for 20,000 episodes (α = 0.1, ε decaying exponentially from 1 to 0.05), without access to the transition probabilities. After training the largest Q-value at the start state is 0.504 (the exact value from value iteration is 0.542), and the greedy policy also succeeds 0.737 of the time; in 10 of the 11 non-terminal states it chooses the same action as value iteration.

Deep Q-networks (DQN)

When the state space is large, as with game screens, a table per state is impossible and a neural network Q(s, a; θ) must approximate the action values. Naively combining Q-learning with a neural network is often unstable. The DQN of Mnih et al. (2013) reads raw pixels with a convolutional network that outputs a Q-value per action, and introduces two key techniques:

  1. Experience replay: transitions (s, a, r, s′) are stored in a replay buffer (the most recent 1 million frames in the paper) and training samples random minibatches from it, breaking the correlation between consecutive samples and letting each experience be used many times;
  2. Target network: the 2015 Nature version computes r + γ·maxₐ′ Q(s′, a′; θ⁻) with a target network whose parameters are copied periodically from the online network, so the target does not move with every update (described in van Hasselt et al., 2015).

The 2013 paper tested 7 Atari games, outperforming all previous approaches on 6 and a human expert on 3; ε was annealed linearly from 1 to 0.1 over the first million frames, and in most games the agent chose an action every 4 frames. The 2015 Nature paper extended the evaluation to 49 games using only pixels and the score as input, with the same algorithm, network architecture and hyperparameters for every game, reaching a level comparable to a professional human games tester.

Many refinements followed. Double DQN (van Hasselt et al., 2015) showed that the max in Q-learning systematically overestimates action values and instead selects the action with the online network while evaluating it with the target network, reducing overestimation and improving scores. Prioritized experience replay (Schaul et al., 2015) samples transitions in proportion to their TD error and beats uniform-replay DQN on 41 of 49 games.

Policy gradients and actor-critic

Value-based methods learn Q first and derive a policy from it, which makes continuous actions awkward. Policy-gradient methods parameterise the policy directly as πθ(a | s) and move the parameters along the gradient of the expected return J(θ). The log-derivative trick gives:

∇J(θ) = E[ Σₜ ∇log πθ(aₜ | sₜ) · Gₜ ]

Intuitively: raise the probability of actions that appear in high-return trajectories and lower it for low-return ones. This is the REINFORCE algorithm (Williams, 1992). Its weakness is high variance. Subtracting a baseline b(sₜ) that depends only on the state (usually a learned V(sₜ)) from Gₜ leaves the expected gradient unchanged but reduces its variance substantially; Gₜ − V(sₜ) is then an estimate of the advantage (Spinning Up, Part 3).

Methods that learn a policy (the actor) and a value function (the critic) together are called actor-critic methods. Mnih et al. (2016) proposed A3C, in which several parallel actor-learners update shared parameters asynchronously; the paper reports that parallelism stabilises training, and its best variant surpassed the state of the art on Atari while training for half the time on a single multi-core CPU. Generalized advantage estimation (GAE) (Schulman et al., 2015) weights multi-step TD errors exponentially with a parameter λ, trading bias against variance continuously: λ = 0 is one-step TD and λ = 1 is the Monte Carlo return.

TRPO and PPO

A central difficulty in policy gradients is the step size: an update that goes too far can make the policy collapse suddenly, and because the policy generates its own data, recovery is hard. TRPO (Schulman et al., 2015) starts from a procedure with guaranteed monotonic improvement and constrains the KL divergence between the old and new policies to a small region (the trust region) at each update. In experiments it improves steadily with little hyperparameter tuning, but each update approximately solves a constrained optimisation problem with the conjugate gradient method, which makes it complex to implement.

PPO (Schulman et al., 2017) approximates the same goal with first-order methods. Writing the probability ratio of an action under the new and old policies as ratio = πθ(a | s) / πθ_old(a | s), PPO maximises the clipped surrogate objective:

L = E[ min( ratio · Â, clip(ratio, 1 − ε, 1 + ε) · Â ) ]

where  is an advantage estimate (usually from GAE) and ε is typically 0.2. Taking the minimum makes the objective a lower bound on the unclipped one: when an update would push the ratio outside [1 − ε, 1 + ε] in the direction that looks better, the objective stops increasing and there is no gradient pushing further. The example computes the clipped objective with ε = 0.2: with advantage +1, ratios 0.5, 0.8, 1.0, 1.2 and 1.5 give 0.5, 0.8, 1.0, 1.2 and 1.2; with advantage −1 they give −0.8, −0.8, −1.0, −1.2 and −1.5.

This constraint lets PPO run several epochs of minibatch updates on the same batch. The paper compares surrogate objectives on 7 MuJoCo continuous-control tasks (3 random seeds per setting, 21 runs in total): with neither clipping nor a penalty the average normalised score is −0.39; with ε = 0.1, 0.2 and 0.3 it is 0.76, 0.82 and 0.70; the best adaptive KL penalty scores 0.74 and the best fixed KL penalty 0.72, so clipping with ε = 0.2 scores highest.

The example compares REINFORCE (with a value baseline, one update per batch of 2,048 steps) and PPO (also 2,048 steps per batch, GAE λ = 0.95, 10 epochs per batch with minibatches of 64) on Gymnasium's CartPole-v1, with identical networks, 100,000 training steps and 3 random seeds each. CartPole gives 1 point for every step the pole stays up, and an episode lasts at most 500 steps. The results:

Algorithm Mean return of last 20 episodes (seeds 0 / 1 / 2) Step at which the 20-episode mean first reaches 475
REINFORCE (with baseline) 178.0 / 290.8 / 204.6 Not reached within 100,000 steps
PPO (ε = 0.2) 500.0 / 500.0 / 500.0 46,296 / 45,191 / 35,285

PPO is far more sample-efficient, mainly because each batch is safely reused for several epochs. Practical implementations involve many further details that affect results, such as advantage normalisation, gradient clipping, learning-rate annealing and value-function clipping; see the ICLR blog post “The 37 Implementation Details of PPO” and CleanRL's single-file implementation.

Continuous control and offline RL

In tasks such as robotics the actions are continuous, so a maximum over all actions is not available. DDPG (Lillicrap et al., 2015) combines DQN's experience replay and target networks with the deterministic policy gradient, and solves more than 20 simulated physics tasks with the same algorithm, network architecture and hyperparameters. TD3 (Fujimoto et al., 2018) shows that value overestimation also occurs in actor-critic methods and mitigates it by taking the minimum of two critics and delaying policy updates. SAC (Haarnoja et al., 2018) belongs to the maximum-entropy RL framework: the policy maximises its own entropy as well as the return, which encourages exploration and improves stability.

Offline RL trains only on a fixed historical dataset without further interaction, which suits settings where interaction is expensive or risky. The main difficulty is that the distribution shift between the dataset and the learned policy leads to overestimated values. CQL (Kumar et al., 2020) adds a regulariser to the Bellman error so that it learns a conservative Q-function whose estimate of the policy's value is a lower bound on the true value. Decision Transformer (Chen et al., 2021) takes a completely different approach and casts RL as conditional sequence modelling: conditioned on the desired return, past states and actions, a causal Transformer generates actions autoregressively, matching or exceeding state-of-the-art model-free offline RL baselines on Atari, OpenAI Gym and Key-to-Door tasks.

Planning and self-play: AlphaGo, AlphaZero and MuZero

The rules of board games are fully known, so learning can be combined with search. AlphaGo (Silver et al., 2016) uses a policy network to choose moves and a value network to evaluate positions; both are first trained by supervised learning on human expert games, then by self-play reinforcement learning, and combined with Monte Carlo tree search (MCTS). AlphaGo won 99.8% of its games against other Go programs and beat the European Go champion 5–0, the first time a computer program defeated a human professional on a full-sized board.

AlphaGo Zero (Silver et al., 2017) uses no human data at all: a neural network learns to predict MCTS's own move choices and the winners of its games, a stronger network makes the search stronger and the self-play data better, and the cycle repeats. Starting from random play, AlphaGo Zero beat the champion-defeating AlphaGo 100–0. AlphaZero (Silver et al., 2017) generalises the same algorithm to chess and shogi with no domain knowledge beyond the rules, reaching superhuman play in all three games within 24 hours and convincingly defeating a world-champion program in each. MuZero (Schrittwieser et al., 2019) removes the need for the rules: it learns a model that predicts only the quantities most relevant to planning (reward, policy and value) and searches with that model, setting a new state of the art on 57 Atari games while matching AlphaZero's superhuman performance in Go, chess and shogi.

Connection to LLMs: RLHF and reasoning models

If a language model is treated as a policy and each generated token as an action, RL can optimise properties that are hard to express as supervised targets. InstructGPT (Ouyang et al., 2022) first fine-tunes on human demonstrations, then trains a reward model from human rankings of several answers, and finally optimises the policy with PPO, using a KL penalty to keep it from drifting too far from the supervised model. On its prompt distribution, outputs from the 1.3B-parameter InstructGPT were preferred to those of the 175B-parameter GPT-3. GRPO, proposed in DeepSeekMath (Shao et al., 2024), drops PPO's value network (the critic), samples a group of answers to the same question and uses the group's scores as the baseline for the advantage, substantially reducing training resources. The full RLHF pipeline is covered in How LLMs Learn, and the use of GRPO in reasoning models such as DeepSeek-R1, together with RL from verifiable rewards, in Reasoning Models.

Runnable example

The code below was run with PyTorch 2.15 (CPU) and Gymnasium 1.4 with OMP_NUM_THREADS=3, and its output matches the figures above. The whole script takes about 3 minutes, mostly in the CartPole part. With a different thread count the order of floating-point accumulation changes, so training figures may differ slightly.

import numpy as np, torch, torch.nn as nn, gymnasium as gym, time
torch.manual_seed(0); np.random.seed(0); torch.set_num_threads(3)

# 1) Discounted return
r=[0,0,0,1]; g=0.9
G=[sum(g**k*r[t+k] for k in range(len(r)-t)) for t in range(len(r))]
print('Discounted returns G_t:', [round(x,3) for x in G])

# 2) FrozenLake 4x4 (slippery): value iteration
env=gym.make('FrozenLake-v1', is_slippery=True); P=env.unwrapped.P; nS,nA=16,4; gamma=0.99
V=np.zeros(nS); it=0
while True:
    it+=1
    Q=np.array([[sum(p*(rw+gamma*V[s2]*(not d)) for p,s2,rw,d in P[s][a]) for a in range(nA)] for s in range(nS)])
    V2=Q.max(1)
    if np.abs(V2-V).max()<1e-8: V=V2; break
    V=V2
pi_vi=Q.argmax(1)
print(f'Value iteration converged in {it} sweeps, start-state value V(s0) = {V[0]:.3f}')
def evaluate(pi,n=10000,seed=1):
    e=gym.make('FrozenLake-v1', is_slippery=True); w=0
    for i in range(n):
        s,_=e.reset(seed=seed+i); done=False
        while not done:
            s,rw,term,trunc,_=e.step(int(pi[s])); done=term or trunc
        w+=rw
    return w/n
print(f'Value-iteration policy success rate {evaluate(pi_vi):.3f}')

# 3) Tabular Q-learning (epsilon-greedy, model-free)
Qt=np.zeros((nS,nA)); alpha=0.1; rng=np.random.default_rng(0); eps=1.0
e=gym.make('FrozenLake-v1', is_slippery=True)
for ep in range(20000):
    s,_=e.reset(seed=int(rng.integers(1e9))); done=False
    while not done:
        a=int(rng.integers(nA)) if rng.random()<eps else int(rng.choice(np.flatnonzero(Qt[s]==Qt[s].max())))
        s2,rw,term,trunc,_=e.step(a); done=term or trunc
        target=rw+(0 if term else gamma*Qt[s2].max())
        Qt[s,a]+=alpha*(target-Qt[s,a]); s=s2
    eps=max(0.05, eps*0.9997)
print(f'Q-learning after 20000 episodes: max Q(s0) {Qt[0].max():.3f}, greedy-policy success rate {evaluate(Qt.argmax(1)):.3f}, states matching the value-iteration policy {(Qt.argmax(1)==pi_vi)[[0,1,2,3,4,6,8,9,10,13,14]].sum()}/11')

# 4) PPO clipped objective for positive and negative advantages
eps_c=0.2
for A in (1.0,-1.0):
    vals=[]
    for ratio in (0.5,0.8,1.0,1.2,1.5):
        vals.append(round(min(ratio*A, float(np.clip(ratio,1-eps_c,1+eps_c))*A),2))
    print(f'A={A:+.0f}: clipped objective at ratio=0.5/0.8/1.0/1.2/1.5', vals)

# 5) CartPole: REINFORCE (with baseline) vs PPO, 100k steps each
def mlp(o): return nn.Sequential(nn.Linear(4,64),nn.Tanh(),nn.Linear(64,64),nn.Tanh(),nn.Linear(64,o))
def run(algo, steps=100_000, seed=0):
    torch.manual_seed(seed); env=gym.make('CartPole-v1'); pi=mlp(2); vf=mlp(1)
    opt=torch.optim.Adam(list(pi.parameters())+list(vf.parameters()), lr=3e-4 if algo=='ppo' else 1e-3)
    obs,_=env.reset(seed=seed); t=0; ep_ret=0; rets=[]; first475=None
    while t<steps:
        O,A,R,D,LP=[],[],[],[],[]
        for _ in range(2048):
            o=torch.tensor(obs,dtype=torch.float32)
            with torch.no_grad(): dist=torch.distributions.Categorical(logits=pi(o))
            a=dist.sample(); obs,rw,term,trunc,_=env.step(int(a)); t+=1; ep_ret+=rw
            O.append(o);A.append(a);R.append(rw);D.append(term);LP.append(dist.log_prob(a))
            if term or trunc:
                rets.append(ep_ret); ep_ret=0; obs,_=env.reset()
                if first475 is None and len(rets)>=20 and np.mean(rets[-20:])>=475: first475=t
                D[-1]=True if (term or trunc) else D[-1]
        O=torch.stack(O);A=torch.stack(A);LP=torch.stack(LP);R=torch.tensor(R);Dn=torch.tensor(D,dtype=torch.float32)
        with torch.no_grad():
            V=vf(O).squeeze(-1); nv=vf(torch.tensor(obs,dtype=torch.float32)).squeeze()
        # GAE(lambda=0.95); REINFORCE uses Monte Carlo returns (lambda=1)
        lam=0.95 if algo=='ppo' else 1.0; adv=torch.zeros(len(R)); last=0
        for i in reversed(range(len(R))):
            nxt=nv if i==len(R)-1 else V[i+1]
            delta=R[i]+0.99*nxt*(1-Dn[i])-V[i]; last=delta+0.99*lam*(1-Dn[i])*last; adv[i]=last
        ret=adv+V
        if algo=='ppo':
            for _ in range(10):
                for idx in torch.randperm(len(R)).split(64):
                    a_=(adv[idx]-adv[idx].mean())/(adv[idx].std()+1e-8)
                    nlp=torch.distributions.Categorical(logits=pi(O[idx])).log_prob(A[idx])
                    ratio=(nlp-LP[idx]).exp()
                    l=-torch.min(ratio*a_, ratio.clamp(0.8,1.2)*a_).mean()+0.5*((vf(O[idx]).squeeze(-1)-ret[idx])**2).mean()
                    opt.zero_grad(); l.backward(); nn.utils.clip_grad_norm_(list(pi.parameters())+list(vf.parameters()),0.5); opt.step()
        else:
            a_=(adv-adv.mean())/(adv.std()+1e-8)
            nlp=torch.distributions.Categorical(logits=pi(O)).log_prob(A)
            l=-(nlp*a_).mean()+0.5*((vf(O).squeeze(-1)-ret)**2).mean()
            opt.zero_grad(); l.backward(); opt.step()
    return np.mean(rets[-20:]), first475
for algo in ('reinforce','ppo'):
    res=[]
    for seed in (0,1,2):
        t0=time.time(); m,f=run(algo,seed=seed); res.append((round(m,1),f))
    print(f'{algo}: mean return of last 20 episodes and first step reaching 475, 3 seeds', [(float(a),b) for a,b in res])

Output:

Discounted returns G_t: [0.729, 0.81, 0.9, 1.0]
Value iteration converged in 438 sweeps, start-state value V(s0) = 0.542
Value-iteration policy success rate 0.737
Q-learning after 20000 episodes: max Q(s0) 0.504, greedy-policy success rate 0.737, states matching the value-iteration policy 10/11
A=+1: clipped objective at ratio=0.5/0.8/1.0/1.2/1.5 [0.5, 0.8, 1.0, 1.2, 1.2]
A=-1: clipped objective at ratio=0.5/0.8/1.0/1.2/1.5 [-0.8, -0.8, -1.0, -1.2, -1.5]
reinforce: mean return of last 20 episodes and first step reaching 475, 3 seeds [(178.0, None), (290.8, None), (204.6, None)]
ppo: mean return of last 20 episodes and first step reaching 475, 3 seeds [(500.0, 46296), (500.0, 45191), (500.0, 35285)]

Exercises

  1. Unit project: on Gymnasium's CartPole, implement in turn tabular Q-learning with a discretised state (binning the continuous state), DQN (following the PyTorch DQN tutorial) and PPO, record the number of environment steps each needs to reach a mean return of 475, and compare sample efficiency.
  2. Make the example's FrozenLake non-slippery (is_slippery=False), rerun value iteration and Q-learning, and explain why the optimal success rate becomes 1; then set γ to 0.9 and 0.5 and observe how the start-state value and the policy change.
  3. In the example's PPO, set the clipping coefficient to 0.1, 0.3 and effectively no clipping (a very large ε), run 3 seeds for each, and compare with the trends in Table 1 of the PPO paper.
  4. Read CleanRL's PPO implementation and, using “The 37 Implementation Details of PPO”, list the details missing from the example code; add two of them and compare the learning curves.

Suggested reading order

Start with Chapters 3, 4 and 6 of Sutton and Barto's Reinforcement Learning: An Introduction (MDPs, dynamic programming, temporal differences), then read Part 1 and Part 3 of Spinning Up for the derivation of policy gradients. For deep RL, read the original papers in the order DQN (2013), Double DQN, A3C, TRPO, GAE, PPO, and practise with the Hugging Face Deep RL Course. For a full course, choose UC Berkeley CS285 or David Silver's RL course; for a survey, read Lilian Weng's Policy Gradient Algorithms. Then move on to RLHF in How LLMs Learn and to Reasoning Models.

FAQ

How does reinforcement learning differ from supervised learning?

In supervised learning every example has a correct answer and the loss tells the model directly what to output. In reinforcement learning there is only a reward signal: it says how good an outcome was but not which action the agent should have taken, and the reward may arrive many steps later (the credit-assignment problem). The data are also generated by the agent's own behaviour, so the data distribution shifts as the policy changes, and the agent must balance exploring new actions against exploiting actions known to be good.

What is the difference between on-policy and off-policy methods?

On-policy methods update the current policy only with data generated by that policy, as in REINFORCE, A2C and PPO; most old data are discarded after an update. Off-policy methods can learn from data generated by other policies, including older ones, as in Q-learning, DQN, DDPG, TD3 and SAC. They can therefore use experience replay and are usually more sample-efficient, but stable training is harder to guarantee.

Why does PPO clip the probability ratio?

The policy-gradient surrogate objective is only reliable when the new and old policies are close. PPO uses min(ratio × advantage, clipped ratio × advantage) as its objective: with a positive advantage the objective stops increasing once the ratio exceeds 1 + ε, and with a negative advantage it stops decreasing once the ratio falls below 1 − ε, so there is no gradient pushing the policy further away. In this lesson's example with ε = 0.2, a ratio of 1.5 with advantage +1 is clipped to 1.2, and a ratio of 0.5 with advantage −1 is clipped to −0.8. This lets the same batch be used for 10 epochs without the policy moving too far in one step.

How do AlphaGo, AlphaGo Zero, AlphaZero and MuZero differ?

AlphaGo (2016) first trained its policy network on human expert games, then improved it by self-play reinforcement learning, combined with Monte Carlo tree search, and beat the European Go champion 5–0. AlphaGo Zero (2017) used no human data at all, learning by self-play from the rules alone, and beat the earlier AlphaGo 100–0. AlphaZero (2017) generalised the same algorithm to chess and shogi, reaching superhuman play in all three games within 24 hours. MuZero (2019) does not even need the rules: it learns a model that predicts reward, policy and value and searches with it, setting a new state of the art on 57 Atari games.

Do I need reinforcement learning to study LLMs?

To understand RLHF, DPO and how reasoning models are trained, the basic concepts of RL are necessary: policies, rewards, advantages, KL constraints and PPO's clipped objective all appear directly in these methods. Application developers can skip it for now; anyone working on post-training or alignment should learn this lesson first and then move on to the alignment and reasoning-model lessons.

Sources & further reading

  1. Sutton, Barto (2018), Reinforcement Learning: An Introduction (2nd edition, free full text from the authors)
  2. Sutton (1988), Learning to Predict by the Methods of Temporal Differences, Machine Learning
  3. Watkins, Dayan (1992), Q-learning, Machine Learning
  4. Williams (1992), Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning, Machine Learning
  5. Mnih et al. (2013), Playing Atari with Deep Reinforcement Learning
  6. Mnih et al. (2015), Human-level Control through Deep Reinforcement Learning, Nature
  7. van Hasselt, Guez, Silver (2015), Deep Reinforcement Learning with Double Q-learning
  8. Schaul et al. (2015), Prioritized Experience Replay
  9. Mnih et al. (2016), Asynchronous Methods for Deep Reinforcement Learning
  10. Schulman et al. (2015), Trust Region Policy Optimization
  11. Schulman et al. (2015), High-Dimensional Continuous Control Using Generalized Advantage Estimation
  12. Schulman et al. (2017), Proximal Policy Optimization Algorithms
  13. Lillicrap et al. (2015), Continuous Control with Deep Reinforcement Learning
  14. Fujimoto, van Hoof, Meger (2018), Addressing Function Approximation Error in Actor-Critic Methods
  15. Haarnoja et al. (2018), Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor
  16. Kumar et al. (2020), Conservative Q-Learning for Offline Reinforcement Learning
  17. Chen et al. (2021), Decision Transformer: Reinforcement Learning via Sequence Modeling
  18. Silver et al. (2016), Mastering the Game of Go with Deep Neural Networks and Tree Search, Nature
  19. Silver et al. (2017), Mastering the Game of Go without Human Knowledge, Nature
  20. Silver et al. (2017), Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm
  21. Schrittwieser et al. (2019), Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model
  22. Ouyang et al. (2022), Training Language Models to Follow Instructions with Human Feedback
  23. Shao et al. (2024), DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models
  24. OpenAI Spinning Up: Part 1: Key Concepts in RL
  25. OpenAI Spinning Up: Part 3: Intro to Policy Optimization
  26. OpenAI Spinning Up: Proximal Policy Optimization
  27. Gymnasium documentation: Frozen Lake
  28. Gymnasium documentation: Cart Pole
  29. CleanRL documentation: Proximal Policy Gradient (PPO)
  30. Huang et al. (2022), The 37 Implementation Details of Proximal Policy Optimization, ICLR Blog Track
  31. PyTorch tutorial: Reinforcement Learning (DQN) Tutorial
  32. Hugging Face Deep Reinforcement Learning Course
  33. Lilian Weng: Policy Gradient Algorithms

Part of these paths

Data updated: Learn AI curriculum · Lesson news(UTC+8)