CS 285, Lecture 5, Policy Gradients
CS 285 Deep Reinforcement Learning, Sergey Levine, Lecture 5, Policy Gradients notes.
# The goal of RL
Let , then
The RL objective is the expectation under the trajectory distribution:
can push sum out of expectation
finite horizon case:
infinite horizon case:
this lecture focuses on finite horizon version.
In model-free RL, do not assume we know transition probability and initial state probability . Instead, we assume can interact with the real world, and samples from these distributions.
# Evaluate the objective
Let
run our policy N times and collect N sampled trajectories ( means time step in the -th sample):
where is the sum over samples from .
# Direct policy differentiation
Let
use a convenient identity:
we want to optimize using its gradient:
recall that
take from both sides,
As and are independent of ,
Now everything inside the expectation is known, as we know policy and can evaluate reward for samples. The unknown terms, like initial prob and transition prob, only occur in the .
# Evaluate policy gradient
recall:
and we just got:
Run the policy, sum up the rewards to determine if a trajectory is good or bad, then multiply by the sum of 's:
REINFORCE algorithm (a loop):
- sample from (run the policy)
- sum up rewards along each sample trajectory, then calc policy gradient:
- 1 step of gradient descent/ascent:
Problem: won't work well in practice.
# Understanding Policy Gradient
# Comparison to maximum likelihood
policy gradient runs own policy, can give good or bad actions:
maximum likelihood:
ML gradient increases prob of all actions, whereas policy gradient may increase or decrease. High reward trajectory increases log probability, and low reward trajectory decreases log probability.
# Example: Gaussian policies
example: . Neural network predicts the mean, and covariance could be learned or fixed. Train the neural network :
iteration 2000: humanoid can walk!
# Intuition of Policy Gradients
Gradient of policy gradients in full form:
Simply put, let , then:
In comparison, the gradient for maximum likelihood is:
Intuitively, good trajectory is made more likely and bad trajectory is made less likely. This simply formalizes the notion of "trial and error".
# Partial observability
So far, we have not actually used Markov property for states. For partial observations, can use policy gradient in partially observed MDPs without modification.
# Problem: policy gradient has high variance
For finite sample size, adding constant to sample rewards could yield high variance and influence policy gradients in different degrees.
Example: if the two "good" samples have , their gradients don't matter.
# Reduce Variance
Causality (always true): policy at time cannot affect reward at time if .
past rewards are independent of present decision.
not the same as Markov property (not always true): future state is independent of past state given the present.
After removing past rewards, the estimator stays unbiased, but with lower variance (smaller number of terms).
This quantity is sometimes called "reward to go" (without rewards in the past):
where the means single sample estimator, and means state-value function.
# Baselines
increase the rewards for the trajectory better than average, and decrease if worse than average.
Why are we allowed to do that?
For any , subtracting would make the estimator unbiased.
The 2nd equal sign comes from a convenient identity:
Subtracting a baseline is unbiased in expectation and reduces the variance.
Average reward is not the best baseline, but it's pretty good.
# Find the best baseline
The variance:
Let , and cross out as not dependent on :
So, optimal baseline: expected reward weighted by param gradient magnitude.
Baseline depends on the gradient of the param.
In practice, we don't calc the optimal baseline for every dim, and just use the expected reward.
# Summary
In summary, to eliminate the high var of policy gradient, we can exploit causality as future does not affect the past, subtract baseline as it renders the estimator unbiased. We could use optimal baseline, but usually just use the expected reward as baseline.
# Problem: Policy gradient is on-policy
# Why is policy gradient on-policy?
As 1st step of REINFORCE algo, the red part means policy gradients have to sample from , even though NN changes only a little bit with each gradient step. But on-policy learning can be extremely inefficient!
on-policy: each update step requires fresh samples from own current policy.
When generating samples is very cheap, policy gradient can be a great choice, b/c it's simple to implement and work fairly well.
# Importance sampling
a general technique to evaluate an expectation from one distribution when only given samples from another distribution.
importance sampling:
For off policy, we have samples from some instead of :
the unknown initial prob and transition prob cancel out. Luckily, we know the policy prob and can evaluate the importance weight.
We have samples from a diff policy , and want to estimate the value of some new parameters :
where is the only bit that depends on .
Use the convenient identity ,
If estimate locally at :
This accords with our prev deduction of policy gradient.
# The off-policy policy gradient
When ,
Since , we can expand:
By causality (future actions don't affect current weights):
The crossing can be done b/c if we ignore this, we get a policy iteration algorithm (more on this in a later lecture).
# A first-order approximation for IS (preview)
To avoid the exponential and high variance, let's write the objective a bit differently.
on-policy policy gradient, sample by rolling out policy:
off-policy policy gradient, sample from state-action marginal at :
ignore state marginal prob when is not too different from , but keep state-action conditional prob.
TODO: We'll see why this is reasonable later in the course.
# Implementing Policy Gradients
# Policy gradient with automatic differentiation
Have to calc policy gradient explicitly for every param in the NN, but pretty inefficient.
How can we compute policy gradients with automatic differentiation? We need a graph such that its gradient is the policy gradient!
maximum likelihood:
Just implement "pseudo-loss" as a weighted maximum likelihood:
would be cross entropy for discrete distribution or squared error for Gaussian.
# Pseudocode example (with discrete actions)
Maximum likelihood:
# Given:
# actions - (N*T) x Da tensor of actions
# states - (N*T) x Ds tensor of states
# Build the graph:
logits = policy.predictions(states) # This should return (N*T) x Da tensor of action logits
negative_likelihoods = tf.nn.softmax_cross_entropy_with_logits(labels=actions, logits=logits)
loss = tf.reduce_mean(negative_likelihoods)
gradients = loss.gradients(loss, variables)
2
3
4
5
6
7
8
Policy gradient:
# Given:
# actions - (N*T) x Da tensor of actions
# states - (N*T) x Ds tensor of states
# q_values - (N*T) x 1 tensor of estimated state-action values
# Build the graph:
logits = policy.predictions(states) # This should return (N*T) x Da tensor of action logits
negative_likelihoods = tf.nn.softmax_cross_entropy_with_logits(labels=actions, logits=logits)
weighted_negative_likelihoods = tf.multiply(negative_likelihoods, q_values)
loss = tf.reduce_mean(weighted_negative_likelihoods)
gradients = loss.gradients(loss, variables)
2
3
4
5
6
7
8
9
10
q_values refer to .
# Policy gradient in practice
- Remember that policy gradient has high variance (soln: causality, baseline)
- B/c gradients are quite noisy, need larger batches (at least 1k)
- Tweaking learning rates is very hard
- Adaptive step size rules like ADAM can be an OK starting point
- will talk about policy gradient-specific learning rate adjustment methods
# Review
- Policy gradient is on-policy
- Can derive off-policy variant
- Use importance sampling
- Exponential scaling in T
- Can ignore state portion (approximation)
- Can implement with automatic differentiation - need to know what to backpropagate
- Practical considerations: batch size, learning rates, optimizers
# Advanced Policy Gradients
# Numerical issue
Policy gradient has numerical issue especially in continuous action space.
Near Gaussian mode, arrow does not point towards the optimal. As approaches the optimum, its gradient gets larger. After gradient is normalized, the portion dominates whereas the portion is too small. So if using 1st order methods, will spend a long time to reach optimum due to poor conditioning.
Essentially the same problem as this:
# Covariant/natural policy gradient
Different params affect the policy in different degrees. Some params change the policy a lot (want smaller lr), some don't change the policy much (want larger lr).
constrained optimization for 1st order gradient descent, where the constraint controls how far we can go:
ball is in space, but want to reparametrize s.t. steps are of equal size in policy space rather than param space.
rescale the gradient:
using parameterization-independent divergence measure, usually KL divergence:
The KL divergence can be approximated as:
where is the Fisher-information matrix, and can estimate with samples:
Now the params are updated as:
where is the Lagrange multiplier, and we add to param update.
natural gradient: pick
TRPO (trust region policy optimization): pick , then derive
using conjugate gradient, can solve for optimal while solving .
# Next time
- Introduce value functions and Q-function
- Later in the class: more on natural gradient and automatic step size adjustment
# Policy gradients suggested readings
- Classic papers
[x] Williams (1992). Simple statistical gradient-following algorithms for connectionist reinforcement learning: introduces REINFORCE algorithm
[] Baxter & Bartlett (2001). Infinite-horizon policy-gradient estimation: temporally decomposed policy gradient (not the first paper on this! see actor-critic section later)
[] Peters & Schaal (2008). Reinforcement learning of motor skills with policy gradients: very accessible overview of optimal baselines and natural gradient - Deep reinforcement learning policy gradient papers
[] Levine & Koltun (2013). Guided policy search: deep RL with importance sampled policy gradient (unrelated to later discussion of guided policy search)
[] Schulman, L., Moritz, Jordan, Abbeel (2015). Trust region policy optimization: deep RL with natural policy gradient and adaptive step size
[] Schulman, Wolski, Dhariwal, Radford, Klimov (2017). Proximal policy optimization algorithms: deep RL with importance sampled policy gradient