Most papers using reinforcement learning these days use the policy gradient class of learning. In this post, I will cover a basic tutorial of policy gradient, uncover some confusion on using baseline and regularization and give some suggestion for debugging these learning algorithms that I have found useful in the past.
Policy gradient methods is a class of reinforcement learning algorithm that optimize the reinforcement learning (RL) objective by performing gradient descent on the policy parameters. As opposed to value function based methods (SARSA, Q-learning), the central object of study in policy gradient methods is a policy function , which denotes a probability distribution over actions given a state. are the parameters of this policy. Assuming we are optimizing using stochastic gradient methods our updates are given by:
The objective can be expected total discounted reward, expected average reward or something else. We will stick to total discounted reward for this discussion. The aim now is to express in a form that is easier to work with. This is done using the policy gradient theorem.
Policy Gradient Theorem
Let be our MDP where are the state space, action space, reward function and transition probability respectively. is the discounting factor and is an initial state distribution.
The expected total discounted reward can be expressed as:
See my previous post if you don’t know what function is. Using above equation we have . Policy gradient theorem (Sutton et al. 1999) computes by repeatedly applying the Bellman self consistency theorem. It really is just that.
using we get:
so now we have an expression for in terms of itself. Writing it down together we have:
we will change the notation as giving us:
unfolding this equation gives us (verify it for yourself):
where is the probability of being in state after time when starting in state and taking actions according to the policy . Note that our setup does not include multiple agents, policies dependent upon time or non-Markovian policies.
Discounted unnormalized visitation probability: The term appears fairly often in RL theory so it is given a notation of . Essentially this value is high for a state if it is likely to be visited by an agent sampling actions according to the policy and starting in state . This term is called “discounted unnormalized visitation probability”. It is “visitation probability” since it is higher for state which are likely to be visited. It is discounted cause probability terms are discounted with factor and it is unnormalized cause it may not sum to 1. In fact for infinite horizon:
and for finite horizon with we have:
so in either case the sum of is equal to the time horizon (for episodic undiscounted case) or effective time horizon (for unending discounted case).
using the notation we have:
and which gives us:
or using the notation of Kakade and Langford 2002, we define which allows us to express the gradient as:
Another way to express objective: Using the notation of visitation distribution, allows us to express the expected total discounted reward objective in a form that gives another interpretation to the policy gradient theorem. Observe that:
(linearity of expectation)
reward where is the state in which the agent is at time and is the action taken at that time. Therefore:
Plugging it in we get:
Rearranging the terms we get:
and then using the notation of we get:
Compare this with the gradient of the objective:
It appears as if we don’t take gradient over the term and it comes with the price of replacing with . It also allows us to derive a corollary for derivative of visitation distribution. Derivative of visitation distribution has been studied in other context, not using this corollary, which I will probably cover in a future blog.
Proof: (from policy gradient theorem).
(from alternative expression for ).
comparing the two equations and rearranging gives the result.
The REINFORCE algorithm
REINFORCE algorithm (Williams 1992) comes directly from approximating the gradient given by the policy gradient objective. Firstly, we will review sampling for the wider audience.
Brief Summary on Sampling: Given an expectation of a function with respect to probability distribution over , we can approximate the expectation by drawing samples and using empirical mean given by as our approximation. From the law of large number this approximation will converge to as . The estimate is called unbiased since its mean is the quantity we are approximating i.e. . . Note that if our samples were from another distribution then our estimate may not be unbiased. Another quantity of interest for an estimate is its variance given by , which measures how far can the estimate deviate on expectation from the mean. For the above estimate, we have . Thus, as we collect more samples our estimate deviates less from the mean and if the variance is low then even fewer samples can help us get accurate estimate.
Vanilla REINFORCE: A quick look at the policy gradient tells us that we can never compute it exactly except for tiny MDP. We therefore want to approximate the gradient of given by policy gradient objective and we will do it using sampling. We show below how to do it,
Let’s say we sample a rollout using the policy . A rollout is generated by starting from a sampled state and then taking actions in the current state using the policy and receiving reward. Then note that . Then using the sampling approach described above,
Note that we only use a single sample here () for approximation!
After this approximation we have,
If we knew perfectly for every state and action then we can compute the above objective perfectly provided the number of actions are not prohibitively large. However, in general we do not have these conditions therefore we want to get ride of the second summation as well.
Unfortunately, the summation is not written in the form of an expectation i.e. for some probability distribution . Therefore we cannot apply the sampling approach. To solve this, we will use calculus 101 to express it in an expectation format by using . Thus,
We already have samples from which are nothing but the action . Using it as a sample gives us:
We are still left with estimating to complete our algorithm. Turns out, we can approximate even this by sampling. By definition, is an expectation of total discounted reward collected by a rollout sampled using our policy. For , the value is an unbiased sample estimating (convince yourself that this is true). This gives us
After these approximations, we are ready to state the vanilla REINFORCE algorithm:
The REINFORCE Algorithm
- Initialize the parameters randomly.
- Generate rollout using the current policy
- Do gradient ascent:
Keep the Samples Unbiased. Throw away Rollouts after Update.
Our entire derivation approximating the value of relies on a single rollout that is generated using the policy . If the rollout was generated using another policy then our assumptions will not be valid anymore. This is true, if we keep old rollouts and update the policy. Then those rollouts are no longer unbiased sample of the current policy and hence do not estimate the objective above. Therefore, we cannot keep those samples after update. This is unlike Q-learning where experiences are stored in huge replay memory. Since our derivation relies on samples coming from the current policy, therefore REINFORCE is an example of on-policy reinforcement learning approach. It seems kind of wasteful and inefficient to throw away old samples after updating the parameter. A common tactic is therefore to collect several rollouts in parallel using large number of threads. We will talk about this in another blog.
Problem with REINFORCE:
REINFORCE is not a very good learning algorithm for anything interesting. Few main issues with it are:
- No Exogenous Randomization: REINFORCE uses the same policy for exploration as the one being optimized. There is no way to control the flow of exploration or way to add exogenous randomization. This can hinder exploration since the policy can get stuck in specific regions and may not be able to explore outside.
- Variance: We used a single rollout above to make several approximations. This can affect the variance of our estimate of the gradient. Having high-variance estimate can prohibit learning.
- Degenerate Solutions: REINFORCE can get stuck in degenerate solutions where the policy can suddenly become deterministic while being far from optimal. Once the policy is deterministic, the updates stop since our estimated gradient:
becomes 0. This effectively kills the learning and it has to be restarted. This situation is frequently encountered in practice and we will call it the entropy-collapse issue. Q-learning does not suffer from this degeneracy.
Next we will discuss some solutions to above problem and discuss few methods for debugging.
No Exogenous Randomization
REINFORCE’s inability to separate the exploration policy from the policy being optimized is one of its biggest weakness. There are atleast two different ways in which this has been addressed. The first approach uses a warm start to initialize the policy using behaviour cloning or imitation learning. This also makes sense from deployment point of view where we have to place our agent in the real world in order to perform reinforcement learning and thus don’t want the start policy to be randomly initialized (imagine asking users to chat with a randomly intialized conversation model!). One can naively hope that warm start will enable the policy to explore in the right region of the problem.
The other approach is to use a separate exploration policy and unbias the gradients by using importance weights. However this approach may not be suitable if the policy has close to 0 mass on actions which are chosen by the exploration policy.
Another line of research involves designing intrinsic reward function (pseudo-counts, prediction error, variance of ensemble) to incentivize the policy to eventually learn to explore the desired state space. However, these approaches generally range from having theoretical guarantees in tabular MDPs (e.g., MBIE-EB count based exploration) to having no theoretical guarantee at all (e.g., prediction error).
Reducing Variance through Control Variate
We made a remark earlier pertaining to the variance of the estimate of the gradient for the REINFORCE algorithm. Let’s make it more formalized:
Given a rollout, generated by a policy , we approximate the derivative of expected total discounted reward using:
This estimate is unbiased i.e. and its variance is given by:
. This variance can be high due to the value of . Therefore, we want to modify the estimate, keeping it unbiased but reducing the variance. In statistics, one way to do this is to use control-variate.
Control-Variate: Let be an estimate of a quantity with mean , we define a control variable with mean and define a new estimate given by . This new estimate is still unbiased as . The variance is given by:
which can be made smaller than by optimizing the choice of and .
Reinforce Baseline: We need to define a control variable to reduce variance.
We define it as: , where is a function called the baseline. We can observe that as,
We will further set the value of , giving us our new estimate as:
, where .
Proof of Variance Reduction(*): We still haven’t chosen a baseline function and we set the value of without justification. Overall we still haven’t shown that variance gets reduced. I will provide a proof that gives a choice of the baseline function and proves variance reduction. For simplicity, we will consider a single step case (i.e. . We have,
which can be simplified to
setting it to 0 gives the optimal baseline as .
If one makes an independency assumption between and then we get
One can do a similar analysis for multi-step reinforcement learning and derive the optimal policy. While the optimal policy has been known for many years, all empirical application of REINFORCE or its derivative (in which I count actor-critic methods) use an approximated baseline given by the state-value function . I am not familiar with any literature where they prove (or disprove) if the approximate baseline actually does reduces the variance. However, in the empirical RL circle the variance reduction due to the approximated baseline is often taken as granted.
Importance of Regularization
REINFORCE can get stuck in degenerate solutions as pointed out before. To avoid this degeneracy, a common tactic of regularizing the objective with the entropy of the policy or KL-divergence from a reference policy is adopted. We will focus on the former method here. The entropy regularized objective is given below:
where is a hyperparameter controlling the effect of the regularization. If one computes the derivative of the new objective one gets:
Most researchers however use biased gradients given below:
Entropy regularized objective will no longer follow our classic Bellman optimality conditions and the optimal policy no longer remains deterministic. An easy verification of this is to set and observe that the optimal solution of will be to remain uniformly random everywhere (assuming the reward function is bounded).
Evaluating Training Progress
When training a classifier for a task like ImageNet, one generally monitors the training error and the error on a held out tune set. The decrease in training error tells that your model has sufficient capacity and an increase in tune set indicates potential overfitting. Consider, the approximated gradient of the objective for REINFORCE:
the standard way to program this using pytorch or tensorflow is to define the loss variable:
when doing gradient descent on this variable we get the same gradient as the approximation gives us. This does not make the real loss function, in fact it is not the loss for the REINFORCE algorithm at all but using it gives us the real gradients therefore we will call it the substitute loss.
Monitoring the substitute loss is not the same as monitoring the actual training loss when doing supervised learning. To begin with, notice that the substitute loss is positive when the agent receives only positive reward and it is negative when the agent only receives negative rewards. This is counterintuitive as one ideally associates high loss with low return. So why is this so?
This happens cause when all the rewards are positive then the loss is positive and the only way the agent can reduce it is by pushing the term towards 0 which means increasing the probability of actions which generate positive reward (which is what we want). Similarly, when all rewards are negative then the loss is negative and the only way the agent can make it more negative is by decreasing the probability of these actions until the term tends towards negative infinity. This will eventually lead to these actions not being sampled anymore.
Thus, instead of monitoring the substitute loss, one can monitor two things: (i) the total reward received by the agent which also represents an unbiased estimate of the actual objective and (ii) the entropy of the policy. Ideally the total reward achieved by the agent should increase and the entropy of the policy should decrease. Any stagnation means the learning is not happening effectively.
Major Failure Case for Policy Gradient
Policy gradient methods have no guarantees in theory or practice. A simple example which can be used to demonstrate this is from John Langford. There are states and two actions and the agent always starts in state . At each state (, an action takes you to and the other actions takes you back to . The action mappings are randomly assigned to each state but the MDP is deterministic. Every state has a reward of 0 except which has a reward of 1. The game ends when the agent reaches the state .
With a close to 1 probability, any rollout will fail to reach the destination state where it earns a reward and therefore will not cause any meaningful learning when using on-policy policy gradient methods. It will require exponentially many samples for it to reach the state and therefore on-policy policy gradient with a randomly initialized policy is not what is called a PAC RL algorithm, which is an important theoretical guarantee.
Despite its flaws policy gradient methods are used widely for all sort of AI applications. One reason behind its widespread use is their remarkable similary to supervised learning with which most empiricists are widely familiar. Thus, one can train their favourite dialogue model using REINFORCE by simply multiplifying the log probabilities with a value term. Further, variants of policy gradient methods like PPO perform much better and are reasonable baselines. However, it could also be the case that most people don’t care about guarantees as long as they can solve their favourite childhood game and as a field we must guard against this trend as we move towards more serious applications of these algorithms.