← All notes

Note · Machine Learning

Reinforcement Learning

Training via exploration

The Networks

There are two networks required for PPO training.

The “Policy Network”, which we’ll denote with the function π(⋅)\pi(\cdot), is a mapping from the state space to a distribution over actions.

Mathematically, π:s→a\pi: \pmb s \to \pmb a where s∈Rs\pmb s \in \mathbb R^s and a∈Ra\pmb a \in \mathbb R^a where ss is the dimension of the state space and aa is the dimension of the action space. Note that since π(⋅)\pi(\cdot) maps to the state space, ai≥0a_i \geq 0 for all ii and ∑i=1pai=1\sum_{i=1}^p a_i = 1.

The “Value Network”, which we’ll denote with the function V(⋅)V(\cdot), is a mapping from the state space to “rewards” over the action space.

Concisely, V:s→rV: \pmb s \to r where s\pmb s is the same as defined before and r∈Rr \in R. Notice that unlike π\pi, VV is scalar valued. It’s a measure of the desirability of the given state.

Simulated Environment

Information about π(⋅)\pi(\cdot) and V(⋅)V(\cdot) needs to be revealed somehow. In reinforcement learning, this information comes from the “environment” which we’ll represent with the function E(⋅)E(\cdot). The environment is responsible for knowing how to 1) generate an initial state 2) update the state based on an action 3) provide an award associated with an action 4) know when the game is over.

A classic environment where reinforcement learning can be used is the “cart pole” simulation (also known as an inverted pendulum to physicists). The game is simple; there is a pole on a cart and the objective is the keep the pole in the air. We’ll do this experiment in a 2-D world where the cart can either be moved left or right (p=2p=2). Although there are only 2 directions our cart can move, we’ll need to choose a single direction to move the cart at each point in time. We’ll call our choice c∈{0,1}c \in \{0,1\} where 00 represents moving left and 11 represent moving right.

The state of the cart pole system can be summarized by a vector of 4 values: position of the cart, velocity of the cart, angle of the pole, and rotation of the pole (s=4s=4).

Now that we know the parts of our system we can describe E(⋅)E(\cdot) as being a list-valued function E(st,ct)=[st+1,rt,dt+1]E(\pmb s_t, c_t) = [\pmb s_{t+1}, r_t, d_{t+1}]. Here, rtr_t is known as the “reward” which is the reward associated with the action (choice) ctc_t. The element, dt+1d_{t+1}, is an indicator variable for if the game is over.

In the cart pole scenario, once the pole has fallen over the game is over. When training a netork, nothing after this point should be learned because no action has an effect on the end result from this point onward.

The Goal

We’ve been introduced to our three main components of reinforcement learning: the policy π(⋅)\pi(\cdot), The value V(⋅)V(\cdot), and the environment E(⋅)E(\cdot). Though E(⋅)E(\cdot) must be known before training time, nothing is known about π(⋅)\pi(\cdot) and V(⋅)V(\cdot) so we initialize networks π^(⋅)\hat \pi(\cdot) and V^(⋅)\hat V(\cdot). The initial versions of this network we’ll denote π^0(⋅)\hat \pi^0(\cdot) and V^0(⋅)\hat V^0(\cdot) where the superscript 00 indicates that no training has taken place. If all goes well, as more training takes place π^(⋅)\hat \pi(\cdot) and V^(⋅)\hat V(\cdot) will converge to π(⋅)\pi(\cdot) and V(⋅)V(\cdot) respectively. That is to say, as long as our networks have a good architecture then lim⁡n→∞π^n=π\lim\limits_{n \to \infty} \hat \pi^n = \pi and lim⁡n→∞V^n=V\lim\limits_{n \to \infty} \hat V^n = V.

Learing Via Simulation

Though π^\hat \pi and V^\hat V start off no better than random number generators, through interacting with E(⋅)E(\cdot) they’ll become more like π\pi and VV. First, we run a full simulation to see how we’re doing.

Generating an experience

We start off with some initial state s0\pmb s_0 (from our environment) and we want to let our network choose what to do given this state. Therefore we compute a0=π^0(s0)\pmb a_0 = \hat \pi^0(\pmb s_0) where a0\pmb a_0 is a distribution of choices over our discrete action space. We sample from a0\pmb a_0 by treating it as a discrete distribution where the probability of selecting each action is given by aia_i.

After sampling the action, we’ll have scalar c0∈{1,2,⋯ ,a}c_0 \in \{1,2,\cdots, a\} which is our network’s response to s0\pmb s_0.

It is key to note that since we are sampling from our distribution, there is an element of randomness in our model’s deciding which path to take.

We now compute E(st,ct)=[st+1,rt,dt+1]E(\pmb s_t, c_t) = [\pmb s_{t+1}, r_t, d_{t+1}]. We now have reward rtr_t associated with action ctc_t given under at\pmb a_t which was generated by π^0(⋅)\hat \pi^0(\cdot).

Given the new st+1s_{t+1} and assuming dt+1≠1d_{t+1} \neq 1 we repeat the process some TT times.

In pseudocode we have:

s = E.start();

game_over = False;
steps = 0;
experience = set();

while (not game_over and steps < T) {
     c, pmf = policy(s);

     next_s, r, game_over = E(s, c);

     steps += 1;
     experience.add(s, c, r, pmf);

     s = next_s;
};

Correcting rewards

Though each action has a reward associated with it, some actions with lower initial rewards by lead to higher rewards in the future.

Therefore the rewards with each action aren’t actually the raw rewards that we’ve collected. We update these rewards with information about future rewards via:

r~t=∑i=tTγi−tri\begin{align*} \tilde r_{t} = \sum_{i=t}^T \gamma^{i-t} r_{i} \tag{adjusted reward} \end{align*}

Where 0<γ<10 < \gamma < 1 and called the “discount rate” or “patience factor”. A reward today is worth more than a reward tomorrow. If γ=1\gamma = 1 then a reward tomorrow is just as good as reward today and if γ=0\gamma = 0 then a reward tomorrow is worth nothing today.

Now that the rewards have been updated to more reasonable measurements, our network is ready to learn from its experience.

Learning

Now we’ll use our set of experiences, call it ee, to learn. This set looks like this e0={(s0,c0,r0,a0),(s1,c1,r1,a1),…,(sT,cT,rT,aT)}e^0 = \{(\pmb s_0, c_0, r_0, \pmb a_0), (\pmb s_1, c_1, r_1, \pmb a_1), \dots, (\pmb s_T, c_T, r_T, \pmb a_T)\}. We’ll sample from these experiences to learn.

There’s two losses that will make up the total loss: value loss and policy loss

Value Loss

Value loss is a straightforward intuitive calculation. It’s the mean squared error (MSE) between the predicted rewards by the value network and the returns obtained from experience.

ValueLoss=MSE(r^,r~)\text{ValueLoss} = MSE(\hat {\pmb r}, \tilde {\pmb r})

Where r^=V(s)\hat {\pmb r} = V(\pmb s) and r~\tilde {\pmb r} is the adjusted reward.

Policy Loss

Policy loss is bit more involved. The equation is

PolicyLoss=−Mean(min⁡[π′(a∣s)π(a∣s)A^,clip(π′(a∣s)π(a∣s),1−ϵ,1+ϵ)A^] )\begin{align*} \text{PolicyLoss} = -&\text{Mean}\left(\min\left[\frac{\pi'(a|\pmb s)}{\pi(a|\pmb s)}\hat A, \text{clip}\left(\frac{\pi'(a|\pmb s)}{\pi(a|\pmb s)}, 1- \epsilon, 1 + \epsilon \right)\hat A \right]\ \right) \end{align*}

Where π′\pi' is what would happen if we accepted the random walk as the new policy and π\pi is the current (old) policy. clip(⋅)\text{clip}(\cdot) is a function that uses ϵ\epsilon to determine how large of a step we’re comfortable iwth making in the optimization space. Finally A^\hat A is defined as

A^=r~−r^=V′(a∣s)−V(a∣s)=Vnew(a∣s)−Vcurrent(a∣s)=rexperience−rpredicted\begin{align*} \hat A &= \tilde{r} - \hat{r} \\ &= V'(a |\pmb s) - V(a | \pmb s) \\ &= V_{\text{new}}(a | \pmb s) - V_{\text{current}}(a | \pmb s) \\ &= r_{\text{experience}} - r_{\text{predicted}} \end{align*}

And is referred to as “advantage”. Advantage is positive when tilting the distribution toward the explored route would increase rewards compared to the decision under the current policy. Since capitalizing on advantage is good, that’s why PolicyLoss has a negative sign on the outside of mean.

The term π′/π\pi'/\pi is called the “policy ratio” which determines how much the network follows the advantage signal. When π′/π>1\pi'/\pi > 1 then the advatange signal is amplified. This is desirable because as an action’s relative weighting increases, the importance of accurately gauging the reward associated with that action also increases which is precisely what this policy ratio reflects.

The policy ratio will be 11 before updating the function π\pi because initially we have π′ (0)/π′ (0)\pi^{\prime\ (0)}/\pi^{\prime\ (0)} however after backpropping on the the total loss (which is equal to ValueLoss+PolicyLoss\text{ValueLoss} + \text{PolicyLoss}) we’ll be computing the π′ (1)/π′ (0)\pi^{\prime\ (1)}/\pi^{\prime\ (0)} after sampling the next batch from memories. We continually update π′ (i)→π′ (i+1)\pi^{\prime\ (i)} \to \pi^{\prime\ (i+1)} by sampling new batches from the given set of memories until we decide to get a obtain a new set of memories.

The minimum loss term is chosen from the two policy terms for optimization stability.

In pseudo code this training process looks like

function learn_from_memory(policy, value, memories) {
    for (number_of_epochs) {
        for mem in memories {
            s, c, r, pmf = mem;

            hat_r = value(s);
            value_loss = MSE(hat_r, r);


            proba_c = policy(s).at(c);
            old_proba_c = pmf.at(c);
            change = proba_c / old_proba_c;

            adv = r - hat_r;

            policy_loss = min([
                change * adv,
                clip(change, 1-eps, 1+eps) * adv
            ]);

            tot_loss = value_loss + policy_loss;

            back_prop_step(tot_loss);
        };
    };
};

When this point is reached, we repeat the process outlined except now we have π^1\hat \pi^1 where 11 denotes that the model has learned from one set of memories. Each successive set of memories should be more advanced than the previous. After enough training, if the architecture is good π^→π\hat \pi \to \pi and V^→V\hat V \to V and our model now understands the game it’s playing.