CS 285, Lecture 6, Actor-Critic Algorithms
CS 285 Deep Reinforcement Learning, Sergey Levine, Lecture 6, Actor-Critic Algorithms notes.
# Recap: Policy Gradients
REINFORCE algorithm:
- Sample from (run the policy)
- , where the "reward to go" is
# Improving the Policy Gradient
The policy gradient estimate relies on a sample estimate of the return:
The "reward to go" is an estimate of expected return if we take action in state .
A single sample estimate has high var, so generate many samples and calc the exp of reward to go with a lower var.
Can we get a better estimate? The ideal is the true expected reward-to-go, :
If we can replace with true Q function, the var of policy gradient would be much lower:
# Subtract the Baseline
Previously, we subtract the average reward as baseline. Now, if we have true expected reward-to-go:
Then rewrite policy gradient w/ true to subtract baseline:
Baseline depending on actions would lead to bias, so instead depend on state, using average reward over all actions for the state :
Choose value function as the baseline:
where the advantage function is defined as:
If take the actions better than avg in the state, then increase the prob. If take the actions worse than avg in the state, then decrease the prob.
# State & state-action value function (Q function)
Total expected reward starting from , taking action , and following policy :
We add the superscript to emphasize function depends on . Every policy has a different function.
The value function is the expected value of values over all actions in state under policy . Or, the total reward starting from and following policy :
The advantage function represents how much better the action is compared to the avg performance of policy in state :
Conventionally, policy gradient uses a Monte Carlo estimate of the advantage, is calculated by using 1 sample in the remainder of current traj, summing up rewards in the traj, and subtracting a baseline.
This is an unbiased single sample estimate with high var, but we now replace it with lower var approximate advantage function.
In practice, we don't have the correct value of advantage, but can only estimate it. The better estimate of advanatage, the lower var is. If the advantage is incorrect, policy gradients can be biased. Usually, we trade large var reduction for slight increase in bias from value function.
Now, in the 2nd step (green box), when we "fit a model to estimate return", we fit , or .
# Policy Evaluation
The policy is held fixed while we estimate the return it induces from each state. This step is called policy evaluation because it evaluates the current policy rather than improving it.
# Value function fitting
Among , or , which should we fit to?
Because and are not RVs, can rewrite the as current reward (exact, not random) expected value of future rewards:
Assuming for , the actual state in current traj is representative of the average state. For the next time step, approximate the distr of states with a single-sample estimator:
The advantage function is approximated as current reward next value current value:
We do the approximation b/c only depends on state, whereas and depend on both state and action. Function approximator is easier to learn due to fewer samples.
So, fit .
# Monte Carlo Policy Evaluation
Policy evaluation: calc , the value of policy at every state.
The RL objective can be written as:
To perform policy evaluation, use Monte Carlo policy evaluation. Like policy gradients, run policy many times, sum rewards obtained along the generated trajectories, use it as unbiased but high-var single sample estimate of the policy's total reward.
single sample estimate:
Ideally, want to sum over all possible trajectories. Unfortunately, need to reset to in model-free setting and run multiple trials starting from that state (can't do this unless in a simulator). But usually we only assume we can run multiple trials from the initial-state distribution.
multi-sample estimate (but can’t reset the world):
# Monte Carlo evaluation with function approximation
Function approximator can generalize: it understands that similar states visited in different trajectories take similar values:
training data: , where
supervised regression (over all samples, minimize the MSE btw value function's prediction and the single-sample Monte-Carlo estimate of value at the state):
# Bootstrapped estimate
ideal target can be approximated by current reward next value:
Using previously fitted value function, get the bootstrapped estimate:
training data becomes:
Then do supervised regression like before.
Compared with single sample estimator, bootstrapped estimate has lower var, but higher bias b/c may be incorrect.
# Estimating : Monte Carlo vs. Bootstrap
Monte Carlo (supervise with roll-out's summed rewards):
Bootstrapped (supervise using reward next value estimate):
# Actor-Critic algorithm
actor: policy
critic: value function
# Aside: discount factor
Bootstrap rule in infinite horizon
if , can get infinitely large.
better to get rewards sooner than later w/ disount factor ( works well):
Mathematically, say there is an MDP of 4 states with transition probability :
By modifying the MDP to introduce the death state (never leaves once enter) w/ reward and prob , the MDP becomes:
with critic, the policy gradient uses the bootstrapped advantage (TD error):
Monte Carlo policy gradients:
# Batch actor-critic algorithm (with discount)
In episodic batch setting, we collect a batch of trajectories, each trajectory runs to the end, use the batch to eval gradient and update policy.
- sample from
- fit to sampled reward sums
- evaluate
- evaluate
- update
need to train 2 NN's: actor and critic .
can be Monte Carlo or Bootstrapped. With discount factor , the bootstrapped estimate is
The MSE loss is same as before:
# Online actor-critic algorithm (with discount)
The update equations are the same as in batch actor-critic; the difference is the update schedule. Batch actor-critic freezes the policy while collecting many transitions, averages their gradients, and then updates. Online actor-critic updates the actor and critic immediately after each transition, so the policy can change during an episode.
- take action , get
- update using target
- evaluate
- evaluate
- update
collect transitions for bootstrapped estimate of .
# Architecture Design
2 networks to learn value and policy:
1 maps from to
1 maps from to
+: simple & stable
-: no shared features btw actor & critic
or shared network design:
map from to 2 heads: and
+: can be more efficient due to shared internal representations
-: harder to train, unstable b/c of different gradients, need more hyperparameter tuning
# Online actor-critic in practice: w/ multi-threading
synchronized parallel actor-critic
batch size = # of worker threads, e.g., 32
step 1: multiple simulators use diff random seeds, choose an action, generate diff transitions
step 2 & 4: update using data from all threads
step 5: update 1 policy
faster: asynchronous parallel actor-critic
each thread runs at diff speed
as soon as get 32 transitions, update policy
problem: the transitions may be collected by diff actors
this creates policy lag, a small off-policy mismatch: workers may collect transitions using stale policy parameters, while the updates are applied to the latest policy
in practice, the async method leads to perf gain that outweighs bias incurred from using slightly older actors.
# Eligibility trace & n-step return
for critic training, the 1-step bootstrapped target is:
+: lower variance than Monte Carlo target
-: higher bias if value is wrong (always is)
Monte-Carlo target:
+: no bias
-: higher variance (b/c single-sample estimate)
want to combine these 2, to control bias-variance tradeoff
higher var when far in the future
lower var when closer to the present
estimating using n-step return: sum up rewards of a single-sample estimator until some time step , then cut off before var gets too big, and replace the remainder with a value function estimate:
the larger is, the lower the bias (smaller 2nd term), the higher the var (larger 1st term)
sweet spot is an intermediate value btw and
less variance than MC, lower bias than 1-step bootstrap
# Generalized advantage estimation
While -step return helps, we still face the question: which should we choose? Ideally, we want a method that combines all possible -step estimators to get the best of both worlds (low bias and low variance).
# Core Definitions
Generalized Advantage Estimation (GAE) is defined by three core mathematical components:
The -step Advantage ():
The difference between our -step sampled return and our current baseline:- Intuition: It balances "reality" (actual rewards collected for steps) with our "belief" (the Critic’s estimate of the future from step onwards).
Weighted Combination of Estimators:
Instead of picking one , take a weighted average of all -step advantages. To ensure the weights sum to 1 while favoring shorter (lower variance) horizons, use an exponential decay:- Intuition: This is a "blending" strategy. acts as a secondary discount factor that decides how much we trust our multi-step reward samples versus our single-step TD estimates.
The TD error (temporal difference error) :
the one-step "surprise" — the difference between the bootstrapped target and the current value estimate:This is exactly the 1-step advantage estimate used in the actor-critic algorithms above.
# The Telescoping Derivation
The -step advantage can be rewritten as a discounted sum of TD errors. When we expand the sum , the intermediate value function terms cancel out due to the telescoping property:
- The ( and ) cancel.
- The ( and ) cancel.
- The are left behind, which exactly match the definition of the -step advantage:
# Final Form and Implementation
Substituting the telescoping sum into the weighted average definition simplifies the entire estimator into a single discounted sum of TD errors:
In practice, this is implemented using a recursive structure that "mixes" rewards and value estimates at every step:
Or, implement this recursively (backwards from the end of an episode):
This recursive view shows the specific choice at each step:
- : Trust the Critic's immediate prediction (Lower variance).
- : Trust the actual reward and the subsequent trajectory (Lower bias).
controls the bias-variance tradeoff: smaller cuts earlier and reduces variance, while a larger moves closer to an unbiased Monte Carlo estimate.
# Review so far
Algorithms
- Policy gradients: observe what is good vs. bad, then do more of good stuff
- Actor-critic: learn to estimate what is good vs. bad, then do more of the good stuff
i.e. get a better policy gradient by using neural network to estimate value function
How to estimate value (policy evaluation):
- Supervised learning directly on observed sum of future rewards
- Supervised learning on current reward + value estimate of next state
- Hybrid: Supervised learning on sum of next rewards + value of state after that
# Off-policy actor critic
replay buffer stores all previously seen transitions.
implementation: FIFO ring buffer
- take action , get , store in
- sample a batch from buffer
- update using targets to each
- evaluate
- evaluate
- update
use older transitions from the same but old actor
collect transitions, store in replay buffer, sample a batch w/ size (e.g., 32 transitions) from the replay buffer
transitions in replay buffer did not come from latest policy need to modify the classical online value-based actor-critic algorithm
2 problems:
- In step 3, the actions in the transitions from replay buffer were taken by older actors, which would not give value of the latest actor. Formally, did not come from the latest policy , but from an older policy. Thus, was not the results of taking an action with the latest actor.
- In step 5, because did not come from the latest , cannot compute off-policy policy gradient this way. Previously, use importance sampling.
# Problem 1 fix the value function
value function: expected return if start in state and follow the policy
function: expected return if start in state , take action , then follow policy
Keep the stored action paired with the reward and next state it produced. Learn rather than : take the stored action first, then follow the current policy .
So step 3 should be: update using targets for each
then regress against MSE:
We want to learn , but how do we get the target value?
Because , we can replace with and use the target value
where is a fresh action sampled from the current policy at the replay-buffer next state, not an action stored in the replay buffer.
# Problem 2 fix the policy update
For the actor update, do not replace the action stored in the replay buffer. Instead, sample a separate fresh action from the current policy at the replay-buffer state . Step 5 becomes:
Instead of using advantage , use directly in the equation.
Higher var b/c there is no baseline, but OK b/c sampling does not require the simulator; we only need extra forward passes through the policy network. In practice this trades lower bias from the action mismatch for higher variance, and the larger replay buffer batch size can offset some of that variance. Also, after switching to , we can drop step 4.
# Another small problem
did not come from state marginal of latest policy , but from an old policy. Unfortunately, we can't do anything and this is a source of bias. It's acceptable b/c we want the optimal policy on , but we get optimal policy on a broader distr. The replay buffer contains many samples from the latest policy, and also many samples from older policies. The states from latest policy are not missed, but the trained policy is also good at other not so probable states.
# Some implementation details
In step 4, do reparameterization trick to better estimate the gradient (for Gaussian policy)
there are better way to fit Q function (more on this in next two lectures)
e.g., Q learning with deterministic actor