1. 程式人生 > 實用技巧 >第三部分:策略優化介紹

第三部分:策略優化介紹

第三部分:策略優化介紹

Table of Contents

在這個部分,我們會討論策略優化演算法的數學基礎,同時提供樣例程式碼。我們會包括策略優化的以下三個部分

  • 最簡單的等式 描述了策略表現對於策略引數的梯度
  • 一個讓我們可以 捨棄無用項 的公式
  • 一個讓我們可以 新增有用引數 的公式

最後,我們會把結果放在一起,然後描述策略梯度更有優勢的版本: 我們在Vanilla Policy Gradient中使用的版本。

最簡單的策略梯度求導

我們考慮一種基於隨機引數的策略:。我們的目的是最小化期望回報。為了計算導數,我們假定屬於無衰減回報,但是對於衰減回報來說基本上是一樣的。

We would like to optimize the policy by gradient ascent, eg 我們想要通過梯度下降來優化策略,例如

策略效能的梯度,通常被稱為策略梯度

,優化策略的演算法通常被稱為策略演算法。(比如說 Vanilla Policy Gradient 和 TRPO。PPO 也被稱為策略梯度演算法,儘管這樣不是很準確。)

To actually use this algorithm, we need an expression for the policy gradient which we can numerically compute. This involves two steps: 1) deriving the analytical gradient of policy performance, which turns out to have the form of an expected value, and then 2) forming a sample estimate of that expected value, which can be computed with data from a finite number of agent-environment interaction steps.

In this subsection, we’ll find the simplest form of that expression. In later subsections, we’ll show how to improve on the simplest form to get the version we actually use in standard policy gradient implementations.

We’ll begin by laying out a few facts which are useful for deriving the analytical gradient.

1. Probability of a Trajectory.The probability of a trajectorygiven that actions come fromis

2. The Log-Derivative Trick.The log-derivative trick is based on a simple rule from calculus: the derivative ofwith respect tois. When rearranged and combined with chain rule, we get:

3. Log-Probability of a Trajectory.The log-prob of a trajectory is just

4. Gradients of Environment Functions.The environment has no dependence on, so gradients of,, andare zero.

5. Grad-Log-Prob of a Trajectory.The gradient of the log-prob of a trajectory is thus

Putting it all together, we derive the following:

Derivation for Basic Policy Gradient

This is an expectation, which means that we can estimate it with a sample mean. If we collect a set of trajectorieswhere each trajectory is obtained by letting the agent act in the environment using the policy, the policy gradient can be estimated with

whereis the number of trajectories in(here,).

This last expression is the simplest version of the computable expression we desired. Assuming that we have represented our policy in a way which allows us to calculate, and if we are able to run the policy in the environment to collect the trajectory dataset, we can compute the policy gradient and take an update step.

Implementing the Simplest Policy Gradient

We give a short Tensorflow implementation of this simple version of the policy gradient algorithm inspinup/examples/pg_math/1_simple_pg.py. (It can also be viewedon github.) It is only 122 lines long, so we highly recommend reading through it in depth. While we won’t go through the entirety of the code here, we’ll highlight and explain a few important pieces.

1. Making the Policy Network.

25
26
27
28
29
30
# make core of policy network
obs_ph = tf.placeholder(shape=(None, obs_dim), dtype=tf.float32)
logits = mlp(obs_ph, sizes=hidden_sizes+[n_acts])

# make action selection op (outputs int actions, sampled from policy)
actions = tf.squeeze(tf.multinomial(logits=logits,num_samples=1), axis=1)

This block builds a feedforward neural network categorical policy. (See theStochastic Policiessection in Part 1 for a refresher.) Thelogitstensor can be used to construct log-probabilities and probabilities for actions, and theactionstensor samples actions based on the probabilities implied bylogits.

2. Making the Loss Function.

32
33
34
35
36
37
# make loss function whose gradient, for the right data, is policy gradient
weights_ph = tf.placeholder(shape=(None,), dtype=tf.float32)
act_ph = tf.placeholder(shape=(None,), dtype=tf.int32)
action_masks = tf.one_hot(act_ph, n_acts)
log_probs = tf.reduce_sum(action_masks * tf.nn.log_softmax(logits), axis=1)
loss = -tf.reduce_mean(weights_ph * log_probs)

In this block, we build a “loss” function for the policy gradient algorithm. When the right data is plugged in, the gradient of this loss is equal to the policy gradient. The right data means a set of (state, action, weight) tuples collected while acting according to the current policy, where the weight for a state-action pair is the return from the episode to which it belongs. (Although as we will show in later subsections, there are other values you can plug in for the weight which also work correctly.)

You Should Know

Even though we describe this as a loss function, it isnota loss function in the typical sense from supervised learning. There are two main differences from standard loss functions.

1. The data distribution depends on the parameters.A loss function is usually defined on a fixed data distribution which is independent of the parameters we aim to optimize. Not so here, where the data must be sampled on the most recent policy.

2. It doesn’t measure performance.A loss function usually evaluates the performance metric that we care about. Here, we care about expected return,, but our “loss” function does not approximate this at all, even in expectation. This “loss” function is only useful to us because, when evaluated at the current parameters, with data generated by the current parameters, it has the negative gradient of performance.

But after that first step of gradient descent, there is no more connection to performance. This means that minimizing this “loss” function, for a given batch of data, hasnoguarantee whatsoever of improving expected return. You can send this loss toand policy performance could crater; in fact, it usually will. Sometimes a deep RL researcher might describe this outcome as the policy “overfitting” to a batch of data. This is descriptive, but should not be taken literally because it does not refer to generalization error.

We raise this point because it is common for ML practitioners to interpret a loss function as a useful signal during training—”if the loss goes down, all is well.” In policy gradients, this intuition is wrong, and you should only care about average return. The loss function means nothing.

You Should Know

The approach used here to make thelog_probstensor—creating an action mask, and using it to select out particular log probabilities—onlyworks for categorical policies. It does not work in general.

3. Running One Epoch of Training.

 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
    # for training policy
    def train_one_epoch():
        # make some empty lists for logging.
        batch_obs = []          # for observations
        batch_acts = []         # for actions
        batch_weights = []      # for R(tau) weighting in policy gradient
        batch_rets = []         # for measuring episode returns
        batch_lens = []         # for measuring episode lengths

        # reset episode-specific variables
        obs = env.reset()       # first obs comes from starting distribution
        done = False            # signal from environment that episode is over
        ep_rews = []            # list for rewards accrued throughout ep

        # render first episode of each epoch
        finished_rendering_this_epoch = False

        # collect experience by acting in the environment with current policy
        while True:

            # rendering
            if not(finished_rendering_this_epoch):
                env.render()

            # save obs
            batch_obs.append(obs.copy())

            # act in the environment
            act = sess.run(actions, {obs_ph: obs.reshape(1,-1)})[0]
            obs, rew, done, _ = env.step(act)

            # save action, reward
            batch_acts.append(act)
            ep_rews.append(rew)

            if done:
                # if episode is over, record info about episode
                ep_ret, ep_len = sum(ep_rews), len(ep_rews)
                batch_rets.append(ep_ret)
                batch_lens.append(ep_len)

                # the weight for each logprob(a|s) is R(tau)
                batch_weights += [ep_ret] * ep_len

                # reset episode-specific variables
                obs, done, ep_rews = env.reset(), False, []

                # won't render again this epoch
                finished_rendering_this_epoch = True

                # end experience loop if we have enough of it
                if len(batch_obs) > batch_size:
                    break

        # take a single policy gradient update step
        batch_loss, _ = sess.run([loss, train_op],
                                 feed_dict={
                                    obs_ph: np.array(batch_obs),
                                    act_ph: np.array(batch_acts),
                                    weights_ph: np.array(batch_weights)
                                 })
        return batch_loss, batch_rets, batch_lens

Thetrain_one_epoch()function runs one “epoch” of policy gradient, which we define to be

  1. the experience collection step (L62-97), where the agent acts for some number of episodes in the environment using the most recent policy, followed by
  2. a single policy gradient update step (L99-105).

The main loop of the algorithm just repeatedly callstrain_one_epoch().

Expected Grad-Log-Prob Lemma

In this subsection, we will derive an intermediate result which is extensively used throughout the theory of policy gradients. We will call it the Expected Grad-Log-Prob (EGLP) lemma.[1]

EGLP Lemma.Suppose thatis a parameterized probability distribution over a random variable,. Then:

Proof

Recall that all probability distributions arenormalized:

Take the gradient of both sides of the normalization condition:

Use the log derivative trick to get:

[1] The author of this article is not aware of this lemma being given a standard name anywhere in the literature. But given how often it comes up, it seems pretty worthwhile to give it some kind of name for ease of reference.

Don’t Let the Past Distract You

Examine our most recent expression for the policy gradient:

Taking a step with this gradient pushes up the log-probabilities of each action in proportion to, the sum ofall rewards ever obtained. But this doesn’t make much sense.

Agents should really only reinforce actions on the basis of theirconsequences. Rewards obtained before taking an action have no bearing on how good that action was: only rewards that comeafter.

It turns out that this intuition shows up in the math, and we can show that the policy gradient can also be expressed by

In this form, actions are only reinforced based on rewards obtained after they are taken.

We’ll call this form the “reward-to-go policy gradient,” because the sum of rewards after a point in a trajectory,

is called thereward-to-gofrom that point, and this policy gradient expression depends on the reward-to-go from state-action pairs.

You Should Know

But how is this better?A key problem with policy gradients is how many sample trajectories are needed to get a low-variance sample estimate for them. The formula we started with included terms for reinforcing actions proportional to past rewards, all of which had zero mean, but nonzero variance: as a result, they would just add noise to sample estimates of the policy gradient. By removing them, we reduce the number of sample trajectories needed.

An (optional) proof of this claim can be foundhere, and it ultimately depends on the EGLP lemma.

Implementing Reward-to-Go Policy Gradient

We give a short Tensorflow implementation of the reward-to-go policy gradient inspinup/examples/pg_math/2_rtg_pg.py. (It can also be viewedon github.)

The only thing that has changed from1_simple_pg.pyis that we now use different weights in the loss function. The code modification is very slight: we add a new function, and change two other lines. The new function is:

12
13
14
15
16
17
def reward_to_go(rews):
    n = len(rews)
    rtgs = np.zeros_like(rews)
    for i in reversed(range(n)):
        rtgs[i] = rews[i] + (rtgs[i+1] if i+1 < n else 0)
    return rtgs

And then we tweak the old L86-87 from:

86
87
                # the weight for each logprob(a|s) is R(tau)
                batch_weights += [ep_ret] * ep_len

to:

93
94
                # the weight for each logprob(a_t|s_t) is reward-to-go from t
                batch_weights += list(reward_to_go(ep_rews))

Baselines in Policy Gradients

An immediate consequence of the EGLP lemma is that for any functionwhich only depends on state,

This allows us to add or subtract any number of terms like this from our expression for the policy gradient, without changing it in expectation:

Any functionused in this way is called abaseline.

The most common choice of baseline is theon-policy value function. Recall that this is the average return an agent gets if it starts in stateand then acts according to policyfor the rest of its life.

Empirically, the choicehas the desirable effect of reducing variance in the sample estimate for the policy gradient. This results in faster and more stable policy learning. It is also appealing from a conceptual angle: it encodes the intuition that if an agent gets what it expected, it should “feel” neutral about it.

You Should Know

In practice,cannot be computed exactly, so it has to be approximated. This is usually done with a neural network,, which is updated concurrently with the policy (so that the value network always approximates the value function of the most recent policy).

The simplest method for learning, used in most implementations of policy optimization algorithms (including VPG, TRPO, PPO, and A2C), is to minimize a mean-squared-error objective:

whereis the policy at epoch. This is done with one or more steps of gradient descent, starting from the previous value parameters.

Other Forms of the Policy Gradient

What we have seen so far is that the policy gradient has the general form

wherecould be any of

or

or

All of these choices lead to the same expected value for the policy gradient, despite having different variances. It turns out that there are two more valid choices of weightswhich are important to know.

1. On-Policy Action-Value Function.The choice

is also valid. Seethis pagefor an (optional) proof of this claim.

2. The Advantage Function.Recall that theadvantage of an action, defined by, describes how much better or worse it is than other actions on average (relative to the current policy). This choice,

is also valid. The proof is that it’s equivalent to usingand then using a value function baseline, which we are always free to do.

You Should Know

The formulation of policy gradients with advantage functions is extremely common, and there are many different ways of estimating the advantage function used by different algorithms.

You Should Know

For a more detailed treatment of this topic, you should read the paper onGeneralized Advantage Estimation(GAE), which goes into depth about different choices ofin the background sections.

That paper then goes on to describe GAE, a method for approximating the advantage function in policy optimization algorithms which enjoys widespread use. For instance, Spinning Up’s implementations of VPG, TRPO, and PPO make use of it. As a result, we strongly advise you to study it.

Recap

In this chapter, we described the basic theory of policy gradient methods and connected some of the early results to code examples. The interested student should continue from here by studying how the later results (value function baselines and the advantage formulation of policy gradients) translate into Spinning Up’s implementation ofVanilla Policy Gradient.