Lazy loaded image3.2 Reinforcement Learning

3.2 Foundation of Reinforcement Learning (RL)

This section primarily references "Hands-On Reinforcement Learning". Readers can refer to the Chinese edition for a more detailed introduction to reinforcement learning. Here, we offer a concise yet comprehensive overview aimed at building a solid foundation. This foundational knowledge will make it easier to understand and explore reinforcement learning in large language models later on.

3.2.1 Problem, Process, and Uniqueness

The Problem Addressed by Reinforcement Learning

In machine learning, there is a class of tasks analogous to real-life decision-making situations—sequential decision-making tasks. Unlike simple prediction tasks (e.g., forecasting/regression or classification), these tasks involve making a series of decisions that can influence future outcomes. Reinforcement Learning (RL) is the branch of machine learning that tackles these sequential decision-making problems. While traditional prediction models merely produce outputs (or signals) for given inputs, RL agents learn how their actions affect the environment and, consequently, how to optimize for long-term cumulative rewards.
Reinforcement Learning (RL) can be understood as a method by which an agent learns an optimal strategy through interactions with its environment. It does so via trial-and-error exploration and a reward mechanism, guiding the agent to action in different states in order to maximize long-term rewards.
Typical RL Applications: Control problems (e.g., robotics), Gaming (e.g., playing board games or video games), Resource allocation and optimization, Financial risk control, Recommendation systems, etc.

The Reinforcement Learning Process

Reinforcement learning is a computational approach in which an agent learns by interacting with an environment to achieve a goal. One interaction cycle is as follows:
  1. Observation: Observe the current state of the environment.
  1. Decide and act: The agent selects an action based on its current policy or strategy and then acts.
  1. Receive feedback: After the action, the environment provides a reward signal and transitions to a new state.
This cycle repeats until a terminal state is reached or the process is halted. The agent’s objective is to maximize the expected cumulative reward across multiple interactions. Unlike the "model" in supervised learning, the agent in RL not only perceives environmental information but also directly alters the environment through its decisions, rather than merely producing predictions. In classical RL, agents are often implemented with relatively simple neural networks (MLPs, RNNs, or CNNs), which contrasts with current LLM-based agents.
notion image
The specific interaction between the agent and the environment is illustrated above.
  1. In each iteration, the agent observes the current state of the environment and computes an action.
  1. The action is applied to the environment, which then generates an immediate reward signal and transitions to a new state.
  1. The agent perceives the new state in the next iteration, repeating the process until a terminal state is reached.
Throughout this process, the agent learns with the ultimate goal of finding a policya strategy that selects the best action based on the currently observed environment state and reward feedback.

The Uniqueness of Reinforcement Learning

Comparison with Supervised Learning Objectives: In supervised learning, the goal is to find an optimal model that minimizes a loss function over a given dataset drawn from some distribution. Formally:
In reinforcement learning, the objective is to find a policy that maximizes the expected reward under the policy’s occupancy measure (i.e., the distribution of state-action pairs induced by that policy). Formally:
Key Observations
  • Both supervised and reinforcement learning optimize the expectation of some score (loss or reward) over a distribution of data.
  • In supervised learning, we fix the data distribution and optimize the model’s parameters.
  • In reinforcement learning, the data distribution is adjusted by optimizing the policy (which could be parameterized by a model as well) because a new policy changes what data (state-action pairs) will be encountered.
Thus, supervised learning aims to minimize error on a fixed distribution of labeled data, whereas reinforcement learning aims to iteratively improve a policy so that the induced distribution of states and actions yields the maximum expected reward.
📌
Other Differences Between Reinforcement Learning and Supervised Learning
  • Agent vs. Model
    • Supervised Learning: Uses a model that predicts an output given an input (features), without directly affecting its environment (data distribution).
    • Reinforcement Learning: Uses an agent, which not only perceives the environment but also influences the environment (data distribution) through its actions.
  • Data Types and Sources
    • Supervised Learning: Relies on a labeled dataset where each data sample has an explicit label (target value).
    • Reinforcement Learning: Generates data through ongoing interaction with the environment. The agent’s actions lead to rewards (or penalties), which serve as feedback instead of explicit labels.
  • Learning Methods
    • Supervised Learning: Typically trains once (via multiple epochs maybe) on a static dataset, optimizing a loss function.
    • Reinforcement Learning: Engages in a continuous, dynamic learning process in which the policy is updated constantly based on new interactions in the environment.
  • Feedback Mechanisms
    • Supervised Learning: Every training example has an explicit label for error computation.
    • Reinforcement Learning: Rewards are often delayed, and not every action has immediate feedback.
In summary, while both supervised and reinforcement learning involve optimizing an expectation over a distribution, their fundamental difference lies in how the distribution of data is treated: fixed in supervised learning vs. continuously shaped by the agent’s actions in reinforcement learning.
<ins/>

3.2.2 Markov Process

Markov Process

  1. Stochastic Processes: A stochastic process studies how random phenomena evolve over time. Let denote the state of a system at time . The probability of transitioning to the next state given the entire history can be written as:
  1. Markov Property: A random process has the Markov property if the next state depends only on the current state. Formally:
    1. In other words, knowing the current state is sufficient to predict the next state
  1. Markov Process (Markov Chain): A Markov process is a stochastic process that satisfies the Markov property. It is often defined as a tuple , where:
    1. is a finite set of possible states.
    2. is the state transition matrix:
    3. where the entry represents the probability of moving from state to state :
      Each row of sums to 1 because, from any given state, the probabilities of moving to all possible next states must add up to 1.
      notion image
      Sampling from a Markov chain means starting from some initial state and using the transition probabilities to generate a sequence (episode) of states over time, such as .

Markov Reward Process

  1. Markov Reward Process: A Markov Reward Process is a Markov process augmented with a reward function and a discount factor . Formally, it is defined by the tuple , where:
    1. is a finite set of states.
    2. is the state-transition matrix, with .
    3. gives the expected reward for transitioning into state .
    4. (ranging from 0 to 1) is the discount factor, reflecting the idea that future rewards may be uncertain or less valuable than immediate ones.
  1. Return: When starting from a specific state at time , the return is the sum of all (discounted) rewards until reaching a terminal state:
    1. Here, is the reward received upon transitioning into the state at time , is the discount factor, and the series continues until the process terminates (or indefinitely if it never does).
  1. Value Function: The value of a state , denoted , is the expected return when starting in that state:
    1. Because we are in a Markov Reward Process, this expectation can be broken down using the Bellman equation:
      where is the immediate reward for entering , and is the probability of moving from to .
      For a finite state space , we can write (the values of all states) as a column vector, as another column vector of immediate rewards, and as the transition matrix. Then in matrix form, the Bellman equation becomes:
      This closed-form solution has computational complexity for states, so it is feasible only for small-scale problems. For larger MRPs, methods like dynamic programming, Monte Carlo, and temporal-difference learning are used to estimate . These techniques will be introduced in later sections.

Markov Decision Process

  1. Markov Decision Process (MDP): Markov Decision Process extends a Markov Reward Process by including an action chosen by an agent. Formally, an MDP is described by the tuple , where:
    1. is the set of states.
    2. is the set of possible actions.
    3. is the state-transition function, which gives the probability of transitioning to state after taking action at state .
    4. is the reward function, giving the expected reward when action is taken at state . If depends only on , it reduces to the MRP case.
    5. is the discount factor ().
    6. Unlike the spontaneous transitions in a Markov Reward Process, an MDP features agent actions that influence how the state evolves. The following figure illustrates how the agent observes the current state , chooses an action , and then the environment transitions to a new state while providing a reward .
      notion image
  1. Policy: A policy determines how the agent chooses actions. Formally, is the probability of selecting action in state . A policy can be:
    1. Deterministic: always choose a specific action in each state.
    2. Stochastic: provide a probability distribution over actions for each state.
    3. Because of the Markov property, depends only on the current state, not on prior history.
  1. State-Value Function: In an MDP, the value of a state under a policy , denoted , is the expected return (sum of discounted future rewards) when starting from and following . Formally:
    1. Here, is the total discounted reward from time onward.
  1. Action-Value Function: Because actions explicitly influence transitions in an MDP, we also define the action-value function . It is the expected return when the agent starts from state , takes action , and then continues following policy :
    1. The relationship between and is:
      And:
      These equations show how a policy affects the expected return and reward in an MDP.

3.2.3 Bellman Expectation Equations

Bellman Expectation Equations

We previously introduced value functions and for a policy . The Bellman Expectation Equations for these functions explicitly show how to compute their values in terms of expected returns:
  1. State-Value Function
  1. Action-Value Function
Practical Significance
  • The Bellman Expectation Equations let you evaluate any policy in an MDP by relating current value estimates to expected future returns.
  • For large state-action spaces, exact matrix-based solutions become impractical, so algorithms such as dynamic programming, Monte Carlo methods, or temporal-difference learning approximate and .
  • Even so, the underlying idea always stems from these Bellman equations—understanding them is fundamental in reinforcement learning.

Converting an MDP + Policy into an MRP

A Markov Decision Process (MDP) is defined by . When you fix a policy (i.e., you specify the probability of choosing each action at each state ), you effectively create a Markov Reward Process (MRP) out of that MDP with the marginalization technique:
  • The reward for being in state under policy becomes
  • The transition probability from to under is
As shown above, once you fix a policy in an MDP, you can combine that policy’s action probabilities with the MDP’s transitions and rewards to form a single-state transition structure—effectively turning the MDP into an MRP . From there, you can use MRP methods (like the closed-form approach for small state spaces) to compute the value function . This value function will match exactly what you would have obtained had you computed values directly in the MDP under the same policy. Thus, an MDP with a fixed policy is equivalent to the resulting MRP.

Optimal Policies

In many Reinforcement Learning (RL) problems, we want to find a policy that maximizes the agent’s expected return (cumulative reward). This leads us to the concept of an optimal policy.
  1. Defining an Optimal Policy
    1. We say a policy is better than or equal to another policy (denoted ) if its expected return is at least as high for every state :
    2. In a finite MDP (with limited states and actions), there is at least one policy that is not worse than any other policy. Such a is called an optimal policy. There may be multiple optimal policies; we denote them all just as .
  1. Optimal Value Functions
    1. All optimal policies share the same optimal state-value function, denoted:
      They also share the optimal action-value function:
  1. Relationship Between and :
    1. The relationship between the optimal state-value function and optimal action-value function is the same as we saw for general (non-optimal) policies.
      We consider the best possible actions at each step, which yield the highest state value:

Bellman Optimality Equation

Bringing these relationships together, we obtain the Bellman optimality equation for and :
This can be read as: the optimal value of state is the maximum over all possible actions of its immediate reward plus the weighted discounted value of the next state.
<ins/>

3.2.4 Monte Carlo Methods

A Monte Carlo (MC) method is a numerical technique based on repeated random sampling. The idea is to approximate some quantity of interest—in this case, the value of states under a certain policy—by averaging the outcomes from many sample episodes.

Estimating the Area of a Circle

A simple, classic illustration is estimating the area of a circle by randomly placing points inside a square and counting how many of them land inside the circle. The ratio of points in the circle to points in the square approximates the ratio of the circle’s area to the square’s area. The more points we sample, the closer our estimate is to the true area.
notion image

Estimating a Policy’s State-Value Function

In a Markov Decision Process (MDP), the value of state under policy is its expected return. We can approximate this by running the policy many times, generating multiple episodes (state-action-reward sequences), then computing the returns and averaging them.
Formally, if we gather many returns for a state , the Monte Carlo estimate of is just the average of those returns:
where is the number of returns we collected for state , and is one of those returns.
First-Visit vs. Every-Visit MC
  • First-visit MC only updates the state value for the first time each state is encountered in an episode.
  • Every-visit MC updates the value estimate for every occurrence of a state in an episode.
Either method works, and both converge to the correct value as you sample enough episodes (by the law of large numbers).

Monte Carlo Value Estimation

  1. Sampling Trajectories: Use policy to sample multiple trajectories. Each trajectory has the form:
  1. Trajectory Processing and State Information Update: For each state at time step in every trajectory:
    1. Update the state’s counter:
    2. Update the state’s total return:
  1. State Value Estimation:
    1. The value of each state is estimated as the average return:
    2. By the Law of Large Numbers, as ,
  1. Incremental Update (Optional): Use this to substitute step 3 if you want to save some memory. For each state and its corresponding return :
    1. Update the counter:
    2. Update the value incrementally:
Code Example
Here’s a Monte Carlo function that processes episodes, each represented as a list of tuples. It goes backwards through each episode, computes the return incrementally, and updates the value function using the incremental formula shown above:
  • episodes: A list of sampled trajectories (each a list of tuples).
  • V: A dictionary (or array) for the estimated value of each state.
  • N: A dictionary (or array) counting how many times each state has appeared.
  • gamma: The discount factor.
Observing the Result: When you run this method with enough episodes, the Monte Carlo estimates of state values tend to match very closely with values computed by an analytical solution (if one is available). If you lower the number of sampled episodes, you can see higher variance in your estimates.

3.2.5 Dynamic Programming

Dynamic programming (DP) offers a systematic way to solve certain Reinforcement Learning (RL) problems, assuming we have complete knowledge of the Markov Decision Process (MDP)—i.e., we know the transition probabilities and the reward function . The DP-based RL methods most commonly discussed are policy iteration and value iteration.
In practice, DP methods often require large computational resources, and they rely on having a “white-box” environment (full knowledge of transitions and rewards). This limits their direct applicability to many real-world scenarios. However, they remain important for theoretical understanding and for smaller or simulated problems where a model of the environment is readily available.

Policy Iteration

Policy iteration consists of two alternating steps: policy evaluation and policy improvement. The goal is to find the optimal policy that maximizes returns.
  1. Policy Evaluation
    1. Given a policy , we compute its state-value function with the Bellman expectation equation:
      In practice, we can generalize the Bellman expectation equation as below, where we compute the next iteration's state value function based on the current iteration's state values. Pick an initial guess , then iteratively update:
      We stop when changes between successive updates fall below a small threshold .
  1. Policy Improvement
    1. Once we have , we can derive a better policy by choosing, at each state , the action that maximizes the action-value (Q-value):
      Hence, the improved policy is given by:
      If this new policy is identical to , the algorithm has converged; otherwise, replace with and repeat.
🌟
Policy Iteration Algorithm
  • Randomly initialize policy and value function
  • while : (Policy Evaluation Loop)
    • For each state :
    • End For
  • End While
  • For each state
  • End For
  • If , then terminate and return and ; else return to Policy Evaluation Loop.
  • Overall workflow:
  • Policy Iteration Code: here, we adopt the Cliff Walking environment for demonstration
    • Cliff Walking is a classic reinforcement learning environment where an agent must start from the bottom-left of a 4×12 grid and reach the bottom-right goal while avoiding a cliff.
    • The agent can move up, down, left, or right. Hitting a wall keeps the agent in place; otherwise, it moves to the next state. Falling into the cliff or reaching the goal ends the episode and resets the agent to the start.
    • Each step gives a reward of -1, while falling into the cliff gives -100.
    • notion image
We'll see the outputs:

Value Iteration

Instead of performing full policy evaluation in each iteration, value iteration merges policy evaluation and improvement into a single process. It relies on the Bellman optimality equation:
In value iteration, we iterate:
Once is small enough (below ), we can derive a greedy policy from :
Hence, value iteration often converges faster because it avoids the repeated, full evaluations of policy iteration.
🌟
Value Iteration Algorithm
  • Randomly initialize
  • While do:
    • for each state :
  • end while
  • Return a deterministic policy
  • Overall Workflow:
For the implementation, we can just replace the PolicyIteration class with the below ValueIteration class.
<ins/>

3.2.6 Temporal-Difference Methods

In most real-world scenarios, the agent does not have direct access to the environment’s reward function or state-transition model. Hence, unlike Dynamic Programming (which requires full knowledge of the Markov Decision Process), practical reinforcement learning (RL) relies on model-free methods that learn purely from sampled interactions.
This is analogous to how, in supervised learning, one rarely has the explicit distribution formula for the data. Instead, we estimate parameters based on sampled data points. In RL, we similarly update our policies based on experience sampled through agent–environment interactions.
Temporal-Difference (TD) methods combine ideas from Monte Carlo (MC) and Dynamic Programming (DP):
  • MC-style sampling: They learn from actual sampled returns, without needing the environment’s transition probabilities.
  • Dynamic Programming: They use estimates of future returns (via the Bellman equation concept) to update the current value.
Where Monte Carlo waits until an entire episode finishes to compute the actual returns , TD updates the value function after each time step, using
The difference
is called the TD error, and is the step size.
TD methods update the value of the current state using an estimate of the value of the next state , rather than waiting for the actual return (like in Monte Carlo). This introduces bias into the update.

On-Policy vs. Off-Policy Learning

An important distinction in RL is whether an algorithm learns from data that comes from its current policy (on-policy) or from a different policy (off-policy):
  • On-policy: The agent updates its estimates using the same policy it uses to generate data (e.g., SARSA).
    • The data efficiency is low, and the old data cannot be used after the policy is updated. New data is acquired through interaction with the environment using the updated policy.
  • Off-policy: The agent can learn an optimal policy while following a different behavior policy for exploration (e.g., Q-learning).
    • It can reuse data generated by the behavior policy, and is efficient.

SARSA (On-Policy TD)

SARSA learns an action-value function by directly using the next action selected by the current (often ) policy in its update. Its core update rule is:
In the algorithm:
  • With probability , the agent chooses the best action — the one that maximizes the estimated action-value .
  • With probability , the agent chooses a random action from the action space , including the best action, encouraging exploration.
We can prove its summation of 1:
💡
Sarsa Algorithm
  • Initialize
  • for episode do:
    • Obtain initial state
    • Choose action from state using an policy derived from
    • for timestep do:
      • Observe reward , next state
      • Choose action from state using an policy derived from
    • end for
  • end for
  • SARSA Code
Then you will see outputs like:
notion image
Looks like the Sarsa algorithm adopts a strategy that is relatively far away from the cliff to reach its target.

Multi-Step TD (e.g., n-Step SARSA)

There is a continuum between Monte Carlo (which is unbiased and high-variance because it uses returns from the entire episode and accumulates multi-step uncertainty) and one-step TD/Sarsa (which is biased and low-variance because it estimates the value for the next state). Multi-step TD methods use several steps of sampled rewards, offering a balance of bias and variance. The n-step SARSA uses
Such methods can improve learning speed because of lower bias, though they introduce additional hyperparameters of step n.
Then you will see outputs like:
notion image
We found that the strategy obtained by the multi-step Sarsa algorithm at this time will walk the farthest from the cliff to ensure maximum safety.

Q-Learning (Off-Policy TD)

Q-Learning aims to learn the optimal action-value function regardless of which actions are taken for exploration. Its core update rule is:
Here, we use for the next state, which corresponds to the Bellman optimality equation. Because the target policy still uses for exploratory interaction with the environment, Q-learning still converges to an optimal policy under certain conditions, although the behavior policy is purely greedy.
💡
Q-Learning Algorithm
  • Initialize
  • for episode do:
    • Obtain initial state
    • for timestep do:
      • Select action in state using an policy derived from
      • Observe reward , and next state
    • end for
  • end for
  • Q-Learning Code
You will see outputs:
notion image
After printing out the behavior of the target strategy, we found that it is more inclined to walk on the edge of the cliff, which is better than the more conservative strategy obtained by the Sarsa algorithm. But we can also see that Sarsa receives a higher expected return than Q-learning. This is because the Q-learning algorithm may fall into the cliff when it walks along it, while Sarsa's relatively conservative route makes it almost impossible for the agent to fall into the cliff.
<ins/>

3.2.7 Types of Reinforcement Learning

Several important concepts in reinforcement learning include: Online & Offline, On-Policy & Off-Policy, Model-based & Model-free, and Value-based & Policy-based.
  • Based on Data Source:
    • Online: The agent interacts with the environment while collecting trajectory samples and learns the policy simultaneously.
    • Offline: The trajectory samples used for learning are collected beforehand and provided to the agent as an offline dataset. The learning process does not involve interaction with the environment.
  • Based on Behavior Policy and Target Policy
    • On-Policy: The behavior policy (used to collect samples) and the target policy (used to update) are the same policy. For example, in SARSA, the update uses five-tuple data sampled using : ; so the behavior and target policies are both
    • Off-Policy: The behavior policy (used to collect samples) and the target policy (used to update) are not the same. For example, in Q-learning, the update uses four-tuples data , and is obtained via , rather than sampled from the behavior policy. So here, the behavior policy is and the target policy is purely greedy.
      • notion image
  • Based on if we have access to the Environment Model
    • Model-based: The dynamics of the environment are known or learned in the form of a transition model and reward function. Using planning (e.g., dynamic programming or tree search), an optimal policy can be computed without real interaction with the environment.
    • Model-free: The environment dynamics are unknown. The agent learns the policy through direct interaction with the environment and does not require learning a transition model.
  • Based on How the Policy is Learned
    • Value-based: The agent first learns a value function, then derives a policy from it. There is no explicit policy during learning.
    • Policy-based: The agent explicitly learns a target policy directly.
🎓
Here we present a table to compare different methods in terms of these RL types. Some algorithms will be introduced later, and we will put them here for a complete comparison.
Algorithm
Model(Environment)
Data Source
Policy
State Spase
Deep Learning
Base
Policy Iteration (DP)
✅(Known)
Finite & discrete
Value-based
Value Iteration (DP)
✅(Known)
Finite & discrete
Value-based
Sarsa/Multi-Step Sarsa (TD)
Online
On-policy
Finite & discrete
Value-based
Q-Learning (TD)
Online
Off-policy
Finite & discrete
Value-based
Dyna-Q
✅(Learned)
Half Online + Half Offline
Off-policy
Finite & discrete
Value-based
DQN Double DQN /Dueling DQN
✅(Learned)
Half Online + Half Offline
Off-policy
Coninuous
Value-based
REINFORCE (Policy Gradient)
Online
On-policy
Coninuous
Policy-based
Actor-Critic (Policy Gradient)
Online
On-policy
Coninuous
Policy-based+ Value Prediction
TRPO (Policy Gradient +Trust Region)
Online
On-policy
Coninuous
Policy-based+ Value Prediction
PPO(Policy Gradient +Clipping)
Online
On-policy
Coninuous
Policy-based+ Value Prediction
<ins/>

3.2.8 Deep Q-Network

Deep Q-Network (DQN)

Standard Q-learning uses a table to store for all discrete state-action pairs. This becomes infeasible when states or actions are large or continuous (e.g., images). Based on Q-learning, Deep Q-Network (DQN) addresses this by parameterizing Q-values with a neural network .
Recall that the Q-learning update rule is adapted as follows:
The goal of DQN is to align the output of the Q-network with the Temporal Difference (TD) target. This is achieved by minimizing the Mean Squared Error (MSE) loss:
In other words, we train a deep learning network, which takes state and action as input, and predict the action-value function , and use the MSE loss to train the network.
Like Q-learning, DQN is an Off-Policy algorithm. Additionally, DQN incorporates two key improvements:
  1. Replay Buffer: In standard supervised learning, each training sample is used multiple times. However, in vanilla Q-learning, each sample updates the Q-value only once. DQN introduces a Replay Buffer (typically a fixed-size FIFO buffer with sampling strategies like random or prioritized sampling) to store transition samples. During training, batches are sampled from this buffer (like the offline method). The advantage include:
    1. Independence Assumption: Sequential MDP samples are correlated, violating the i.i.d. assumption critical for neural network training. The Replay Buffer breaks temporal correlations.
    2. Improved Sample Efficiency: Each sample can be reused multiple times, suitable for gradient-based learning in deep networks.
  1. Target Network: The TD target depends on the same Q-network , leading to instability as the target shifts during training (a "chasing moving target" problem). To mitigate this, DQN employs a separate Target Network , initialized identically to the main Q-network. The target network’s parameters are periodically synchronized with (e.g., every fixed number of steps), stabilizing training. The loss function is formulated as:
💡
DQN algorithm
  • Initialize the Q-network with random network parameters
  • Copy the parameters to initialize the target network
  • Initialize the experience replay buffer
  • for episode/epoch do:
    • Get the initial state
    • for timestep do:
      • Select action using policy based on current Q-network
      • Execute action , receive reward , and observe the new state
      • Store the transition in the replay buffer
      • If there is enough data in , sample transitions from
      • For each sample, use the target network to compute
      • Minimize the target loss to update the current network
      • Update the target network every C iteration.
    • end for
  • end for
  • DQN Code
    • You may have to downgrade the numpy lib if you run this code on the Colab: pip install numpy==1.26.4
You will see outputs like this (the right plot is the moving average on the left plot):
notion image
notion image
Visualization:

Double DQN

A well-known shortcoming of standard DQN is an overestimation of the Q value. In standard DQN, the action selection at state and the Q-value calculation both come from the same target network , potentially amplifying error.
Double DQN separates the action selection and action evaluation:
  • Action selection: uses the current network for action selection.
  • Value calculation: uses the target network .
  • Formula
Because the second term is evaluated by a different set of parameters, Double DQN reduces the overestimation problem that can occur in vanilla DQN.
💡
Double DQN algorithm
  • Initialize the Q-network with random network parameters
  • Copy the parameters to initialize the target network
  • Initialize the experience replay buffer
  • for episode do:
    • Get the initial state
    • for timestep do:
      • Select action using policy based on current Q-network
      • Execute action , receive reward , and observe the new state
      • Store the transition in the replay buffer
      • If there is enough data in , sample transitions from
      • for each sample (The only difference to vanilla DQN):
        • Compute next action using current network:
        • Compute target Q-value using target network:
      • Minimize the target loss to update the current network
      • Update the target network every C iteration.
    • end for
  • end for
  • Double DQN Code: Just replace the DQN class to the new one
  • Results
Click here to see more code and results of Double DQN on Pendulum-v1.

Dueling DQN

In many states, selecting any action yields similar outcomes—only the state’s overall “value” matters. Dueling DQN decomposes into two parts:
  • A state value function .
  • An advantage function , capturing how much better or worse an action is compared to the average at that state. In the same state, the sum of the advantage values of all actions is 0
The following figure shows the difference between a single-stream Q-network (top) and the dueling Q-network (bottom). The dueling network has two streams to separately estimate state-value and the advantage-value for each action; the green output module adds the state-value and the advantage function to get the state-action-value Q. Both networks output Q-values for each action.
notion image
Formally,
However, and are not uniquely determined; Dueling DQN typically forces their average or max to be zero to ensure stable learning. A common variant is:
  • Advantages of Dueling DQN
    • By explicitly modeling , the network more rapidly learns which states are good or bad overall—without waiting to see how each action plays out.
    • This can be helpful when there are many actions or when most actions have similar outcomes in certain states.
    • Since Dueling DQN is an improvement only for the action-value estimation network, it does not conflict with Double DQN. In fact, it is common and effective to combine Dueling DQN with Double DQN.
  • Dueling DQN Code: just replace the DQN class with below code and set lr = 2e-2
  • Visualization
Click here to see more code and results of Dueling DQN on Pendulum-v1.
<ins/>

3.2.9 Policy Gradient Algorithm

From Q-learning to Deep Q-Networks (DQN), these are value-based methods. The model learns an action-value function to estimate the expected return (cumulative future reward) given a state and action . The final policy is derived by selecting the action that yields the maximum return: .
Policy gradient methods, on the other hand, are policy-based approaches. The policy is directly parameterized and modeled using a neural network, which takes the state as input and outputs a probability distribution over actions (i.e., a stochastic policy). The objective function for policy learning is to maximize the expected return from the initial state under the current policy:
The gradient of the objective function with respect to the parameters is computed, and gradient ascent is used to maximize the objective function, yielding the optimal policy:
Here, represents the state visitation distribution. Note that the in the last line actually indicates . From the derived policy gradient, it is evident that policy gradient algorithms are on-policy algorithms, as the data used to update the policy is sampled from the policy itself.
💡
A more intuitive way to understand the policy gradient formula: in each state, the algorithm looks at how good each possible action is (using the Q-values) and adjusts the policy to make better actions more likely and worse actions less likely. The gradient term tells us how to change the policy, and the Q-value acts like a weight — the higher the Q-value, the more strongly we push the policy toward choosing that action. In this way, the Q-value function serves as a guide, showing the policy which actions are worth favoring during learning.

REINFORCE algorithm

In policy gradient methods, the Q-value function is required, and there are multiple ways to estimate it. The REINFORCE algorithm employs the Monte Carlo (MC) method, as previously discussed, to estimate the Q-value:
💡
REINFORCE algorithm
  • Initialize the policy parameters
  • for episode do:
    • Use the current policy to sample a trajectory
    • Compute the return from each time step to the end of the trajectory: , denoted as
    • Update :
  • End for
  • REINFORCE Code
  • Results
notion image
notion image
The performance of the REINFORCE algorithm also fluctuates to a certain extent, mainly because the return value of each sampling trajectory fluctuates greatly during training, which is also the main shortcomings of the REINFORCE algorithm.
<ins/>

3.2.10 Actor-Critic Algorithm

notion image
  • Motivation
    • Value-based methods: Value-based methods, like DQN (or its variants), learn only a value function (like a critic), which estimates the action-value function . Actions are selected using an policy derived from the function.
    • Policy-based methods: Policy-based methods, like REINFORCE, learn only a policy function (like an actor), which directly parameterizes the policy . These methods use Monte Carlo (MC) to estimate returns for updating the policy.
    • A natural question: Can we learn both at once? The answer is Actor‑Critic, which combines a parameterized policy model (actor) with a learned value function model (critic). The critic provides bootstrapped estimates (i.e., using Temporal Difference learning) to reduce the variance of the policy gradient estimates. Although the critic is learned, these algorithms are still fundamentally policy-based, because the primary objective is to optimize the policy through gradient ascent.
      • Note that the bootstrapping used in the Temporal-Difference learning is not like the one in machine learning, below is a comparison table to clarify this concept.
        Aspect
        Bootstrapping in Reinforcement Learning
        Bootstrapping in Statistics / Traditional ML
        What
        Using the model’s own estimates to update targets without sampling a complete episode (e.g., TD learning)
        Resampling from data to create multiple sub-datasets for estimation and combine their predictions to enhance performance
        Why
        Accelerate learning, reduce variance
        Estimate generalization error, stabilize learning, quantify uncertainty
        Uses multiple data subsets?
        No
        Yes
        Combines multiple models?
        No
        Yes
        Used in Actor-Critic?
        Yes (the Critic uses TD bootstrapping)
        No (unrelated to Actor-Critic)
  • The Basic Idea
    • Recall the policy gradient formula:
    • In a pure policy-based method like REINFORCE, we estimate via Monte Carlo, which can suffer from high variance.
    • Actor‑Critic replaces this Monte Carlo estimate with a learned value function (critic). The actor (the policy network) interacts with the environment, while the critic (the value network) evaluates how good the actor’s chosen actions are.
  • Generalized Policy Gradient
    • You can express the policy gradient more generally as:
      where could be:
      1. Total return of the trajectory: . This uses the total discounted return of the entire trajectory to update the policy at each time step . The drawback is that it assigns the same return value to every state-action pair in the trajectory. Additionally, it requires the full episode to be completed before updates can be made.
      1. Returns after action : . This is the Monte Carlo estimate used in the REINFORCE method. While unbiased, MC methods suffer from high variance due to the accumulated uncertainty of state transitions and rewards.
      1. Baseline-adjusted variant: . Introducing a baseline reduces variance. A common choice is the value function .
        1. notion image
          💡
          Why does subtracting a baseline reduce variance?
          • With the baseline, the policy gradient becomes:
          • However, the baseline function is only a function of the state and is independent of the action, so subtracting it doesn’t affect the expected value of the policy gradient. That is, the expected policy gradient remains unchanged:
            • Now we prove that the second term equals 0:
          • Without changing the expected policy gradient, the role of the baseline is to serve as a reference value, used to reduce the background "noise" in the reward that does not depend on the current action selection. By subtracting an appropriate baseline, the scores for different actions become more focused and stable, which reduces variance.
          • Intuitively: If no baseline is subtracted, the reward received after taking an action may vary significantly due to the randomness of the environment. Subtracting a suitable baseline makes the relative quality of different actions clearer, reducing randomness and lowering the variance of the policy gradient.
      1. Action-value function: . In the general form, Actor-Critic uses the action-value function to estimate . However, in practical implementations, we rarely estimate full Q-function directly due to its high variance or instability.
      1. Advantage function: . The advantage function subtracts the state-value function from the action-value function , measuring how much better the current action is compared to the average
        1. Similar to baseline-adjusted method, the advantage function reduces the variance, which makes the training more stable.
      1. Temporal difference (TD) residual: . Using the advantage function requires learning both and networks, doubling estimation error. In practice, TD-based approximations of the advantage function are used.
        1. 💡
          Why Can We Use the Temporal Difference of the Value Function to Approximate the Advantage Function?
          Let’s revisit the Markov Decision Process (MDP) we discussed earlier. We know that the action-value function and the state-value function are directly related through the following equation:
          The action-value of taking action in state equals the immediate reward plus the discounted expected value of the next state, averaged over all possible transitions. However, in many cases, the state transition is deterministic — that is, the next state after taking action in state is fixed. So we can write:
          When the state transition is deterministic, the formula above is an unbiased estimation. Even if transitions are stochastic or uncertain, which leads the formula to biased estimation, this expression still serves as a reasonable approximation of the true Q-value. Therefore, using the expression , we can define an advantage function based on the temporal difference of :
  • Loss Function
    • After obtaining the policy gradient for Actor-Critic, we can update the Actor based on the policy gradient, and update the Critic using the TD-error update method as previously discussed. The MSE loss for the critic is as follows:
      So we have , here we consider the as a constant so we don't calculate gradients for it. This is the idea of the semi-gradient method.
💡
Actor-Critic algorithm:
  • Initialize policy network parameters and value network parameters
  • for episode do:
    • Use the current policy to sample a trajectory
    • For each step, compute:
    • Update the critic-network parameters:
    • Update the actor-network parameters:
  • end for
  • Actor-Critic Code
  • Results
notion image
notion image
Based on the experimental results, we can find that the Actor-Critic algorithm can quickly converge to the optimal strategy, and the training process is very stable. The jittering has been significantly improved compared to the REINFORCE algorithm, which shows that the introduction of the value function reduces the variance.
<ins/>

3.2.11 PPO Algorithm

Before discussing the Proximal Policy Optimization (PPO) algorithm, we need to talk about its predecessor: the Trust Region Policy Optimization (TRPO) algorithm.

TRPO Algorithm

Trust Region Policy Optimization: The previously mentioned policy gradient and Actor-Critic algorithms update policy parameters in the direction of the policy gradient. This leads to a problem: since the policy network is typically a deep neural network model, large update steps may cause drastic changes in the policy, leading to instability in training performance. Therefore, TRPO proposes finding a Trust Region, updating the policy only within this region to ensure safe and stable updates.
notion image
TRPO derivation and approximation are complex (involving KKT optimization, Hessian matrix, Conjugate gradient method, and Line search), most of which are unnecessary compared to PPO, and there is no need to dig too deep (unless you just want to learn its mathematics). For simplicity, we focus here on the TRPO optimization objective:
This surrogate objective incorporates importance sampling, allowing the evaluation of the new policy’s advantage using data collected under the old policy. The KL constraint ensures policy updates stay within a trust region, maintaining stability during learning.
Overall, the objective is to use the advantage function to guide policy optimization—favoring actions that lead to higher expected returns—while constraining the policy update to remain close to the previous policy. This closeness is measured using the KL divergence, which quantifies the "distance" between the new and old policies. By keeping this divergence under a predefined threshold, TRPO ensures more stable and reliable learning updates.

PPO Algorithm

PPO simplifies TRPO's optimization objective by directly clipping the range of policy updates, keeping the updates within a relatively safe range. PPO has two versions: PPO-penalty and PPO-clip. The commonly used PPO-clip optimization objective is as follows:
Where is the policy from the Actor, and is the advantage function computed by the Critic. To understand why PPO ends up in this form, let’s first look at the TRPO version:
PPO modifies this objective by clipping the probability ratio to avoid large policy updates, leading to the commonly used PPO-clip objective. This objective allows us to drop the KL divergence constraint. The advantage function calculated by the Critic guides the direction of policy optimization for the Actor.
  • If the advantage function value is positive, it indicates the action is better than average in that state, so maximizing the equation increases the probability of selecting that action.
  • If the advantage function is negative, it means the action is worse than average, so maximizing the equation will decrease the probability of selecting that action.
 
The overall improvements of PPO (some are inherited from TRPO):
  • Importance Sampling: From the simplified formula above, we can see that PPO is an on-policy algorithm, meaning the policy used for sampling and the policy being updated are the same (both come from ). However, a problem with this is low sample efficiency, so PPO uses importance sampling techniques, which allow it to reuse data generated from the previous policy .
    • 📌
      Importance Sampling
      1. To estimate the expectation of a function under the target distribution :
      1. Suppose there is a proposal distribution , and , as long as , the expectation can be rewritten as:
  • Policy Clipping: PPO is essentially an improvement based on the TRPO algorithm. TRPO introduces a KL divergence constraint between the current policy and the previous policy to ensure that the updated policy doesn't deviate too much from the previous one. In other words, the step size of the policy update is adjusted based on the KL divergence. However, TRPO uses complex mathematical methods to estimate the KL divergence.
    • In contrast, PPO simplifies this by using a fixed policy clipping operation — the "clip" — which restricts the update ratio of the policy within a range of . PPO-Clip essentially sets a “safe range” to ensure that the policy update doesn't deviate too much. Each time the policy is updated, PPO calculates the difference between the new and old policy. If the difference is too large, PPO will “clip” it back into a reasonable range.
      notion image
  • GAE Estimation: PPO uses Generalized Advantage Estimation (GAE). Traditional advantage function estimation is usually based on either the one-step/multi-step TD error (Temporal Difference Error), or Monte Carlo methods for computing returns. GAE is designed to reduce the variance in policy gradient methods while maintaining low bias, thereby improving sample efficiency and convergence speed of the algorithm.
    • Based on the idea of multi-step temporal difference, we have:
      The first step is the advantage estimation used in Actor-Critic, but it only uses one-step estimation. Although it has low variance, its estimation accuracy is not as good as multi-step temporal difference estimation. GAE (Generalized Advantage Estimation) performs an exponentially weighted average over these multi-step advantage estimates:
      The parameter is a hyperparameter introduced in GAE (Generalized Advantage Estimation). When , GAE degrades back to one-step TD errors :
      When , it becomes the infinite-step TD (Monte Carlo-style advantage):
  • Advantages of PPO: Stable, easy to implement, suitable for high-dimensional problems, balances exploration and exploitation, no need for complex constraints or second-order optimization, etc.
📌
Prev
3.1 Supervised Fine-Tuning (SFT)
Next
3.3 RLHF: Reinforcement Learning from Human Feedback
Loading...
Article List
LLM Learning Roadmap
✨ Awesome-Anything
🖼️ Digital Image Processing
🍃 LLM Components
🌱 LLM Pre-training
☘️ LLM Post-Training
🍀 LLM Popular Models
🪴 LLM Applications
🌿 LLM Optimization
🌾 LLM Compression
🌵 LLM Hands-on Practice
🌴 LLM Must-read Papers
🌳 LLM Q&A
🐝 VLM Image Encoders
📝 MISC.