## Trust Region Policy Optimization (TRPO) Agents

Trust Region Policy Optimization (TRPO) is a model-free, online, on-policy, policy gradient reinforcement learning algorithm. TRPO alternates between sampling data through environmental interaction and updating the policy parameters by solving a constrained optimization problem. The KL-divergence between the old policy and the new policy is used as a constraint during optimization. As a result, this algorithm prevents significant performance drops compared to standard policy gradient methods by keeping the updated policy within a trust region close to the current policy [1].

**Note**

TRPO agents do not support recurrent networks.

PPO is a simplified version of TRPO. TRPO is more computationally expensive than PPO, but TRPO tends to be more robust than PPO if the environment dynamics are deterministic and the observation space is low-dimensional. For more information on PPO agents, see Proximal Policy Optimization (PPO) Agents.

For more information on the different types of reinforcement learning agents, see Reinforcement Learning Agents.

TRPO agents can be trained in environments with the following observation and action spaces.

Observation Space | Action Space |
---|---|

Discrete or continuous | Discrete or continuous |

TRPO agents use the following actor and critic.

Critic | Actor |
---|---|

Value function critic | Stochastic policy actor |

During training, a TRPO agent:

Estimates probabilities of taking each action in the action space and randomly selects actions based on the probability distribution.

Interacts with the environment for multiple steps using the current policy before using mini-batches to update the actor and critic properties over multiple epochs.

If the `UseExplorationPolicy`

option of the agent is set to
`false`

the action with maximum likelihood is always used in `sim`

and `generatePolicyFunction`

. As a result, the simulated agent and generated policy
behave deterministically.

If the `UseExplorationPolicy`

is set to `true`

the
agent selects its actions by sampling its probability distribution. As a result the policy is
stochastic and the agent explores its observation space.

This option affects only simulation and deployment; it does not affect training.

### Actor and Critic Function Approximators

To estimate the policy and value function, a TRPO agent maintains two function approximators.

Actor

*π*(*A*|*S*;*θ*) — The actor, with parameters*θ*, outputs the conditional probability of taking each action*A*when in state*S*as one of the following:Discrete action space — The probability of taking each discrete action. The sum of these probabilities across all actions is 1.

Continuous action space — The mean and standard deviation of the Gaussian probability distribution for each continuous action.

Critic

*V*(*S*;*ϕ*) — The critic, with parameters*ϕ*, takes observation*S*and returns the corresponding expectation of the discounted long-term reward.

For more information on creating actors and critics for function approximation, see Create Policies and Value Functions.

During training, the agent tunes the parameter values in *θ*. After
training, the parameters remain at their tuned value and the trained actor function
approximator is stored in
*π*(*A*|*S*).

### Agent Creation

You can create and train TRPO agents at the MATLAB^{®} command line or using the Reinforcement Learning Designer app. For
more information on creating agents using Reinforcement Learning Designer, see
Create Agents Using Reinforcement Learning Designer.

At the command line, you can create a TRPO agent with default actor and critic based on the observation and action specifications from the environment. To do so, perform the following steps.

Create observation specifications for your environment. If you already have an environment interface object, you can obtain these specifications using

`getObservationInfo`

.Create action specifications for your environment. If you already have an environment interface object, you can obtain these specifications using

`getActionInfo`

.If needed, specify the number of neurons in each learnable layer. To do so, create an agent initialization options object using

`rlAgentInitializationOptions`

.Specify agent options using an

`rlTRPOAgentOptions`

object.Create the agent using an

`rlTRPOAgent`

object.

Alternatively, you can create actor and critic and use these objects to create your agent. In this case, ensure that the input and output dimensions of the actor and critic match the corresponding action and observation specifications of the environment.

Create an actor using

`rlDiscreteCategoricalActor`

object (for discrete action spaces) or`rlContinuousGaussianActor`

object (for continuous action spaces).Create a critic using an

`rlValueFunction`

object.If needed, specify agent options using an

`rlTRPOAgentOptions`

object.Create the agent using the

`rlTRPOAgent`

function.

TRPO agents do not support actors and critics that use recurrent deep neural networks as
function approximators. TRPO agents also do not support deep neural networks that use a
`quadraticLayer`

.

For more information on creating actors and critics for function approximation, see Create Policies and Value Functions.

### Trust Region Policy Optimization

Trust region policy optimization finds the actor parameters that minimize the following actor loss function.

$${L}_{actor}\left(\theta \right)=-\frac{1}{M}{\displaystyle \sum _{i=1}^{M}\left(\frac{\pi \left({A}_{i}|{S}_{i};\theta \right)}{\pi \left({A}_{i}|{S}_{i};{\theta}_{old}\right)}{D}_{i}+w{\mathscr{H}}_{i}\left(\theta ,{S}_{i}\right)\right)}$$

Here:

*M*is the mini-batch size.*D*is an advantage function._{i}*π*(_{i}*A*|_{i}*S*;_{i}*θ*) is the probability of taking action*A*following the current policy. This value is a specific value of the probability (discrete action) or of the probability density function (continuous action)._{i}*π*(*A*|_{i}*S*;_{i}*θ*) is the probability of taking action_{old}*A*following the old policy._{i}*w**ℋ*(_{i}*θ*,*S*) is an entropy loss term, where_{i}*w*is the entropy loss weight and*ℋ*(_{i}*θ*,*S*) is the entropy. For more information, see Entropy Loss._{i}

This minimization is subject to the following constraint.

$$\frac{1}{M}{\displaystyle \sum _{i=1}^{M}{D}_{KL}\left({\theta}_{old},\theta ,{S}_{i}\right)}\le \delta $$

Here:

*D*(_{KL}*θ*,_{old}*θ*,*S*) is the Kullback-Leibler (KL) divergence between the old policy_{i}*π*(*A*|*S*;_{i}*θ*) and current policy_{old}*π*(*A*|*S*;_{i}*θ*).*D*measures how much the probability distributions of the old and new policies differ._{KL}*D*is zero when the two distributions are identical._{KL}*δ*is the limit for*D*and controls how much the new policy can deviate from the old policy._{KL}

For agents with discrete action spaces, *D _{KL}* is
computed as follows, where

*P*is the number of actions.

$${D}_{KL}\left({\theta}_{old},\theta ,{S}_{i}\right)={\displaystyle \sum _{k=1}^{P}\pi \left({A}_{k}|{S}_{i};{\theta}_{old}\right)}\mathrm{ln}\left(\frac{\pi \left({A}_{k}|{S}_{i};{\theta}_{old}\right)}{\pi \left({A}_{k}|{S}_{i};\theta \right)}\right)$$

For agents with continuous action spaces, *D _{KL}*
is computed as follows.

$${D}_{KL}\left({\theta}_{old},\theta ,{S}_{i}\right)=\frac{1}{P}{\displaystyle \sum _{k=1}^{P}\left(\mathrm{ln}\left({\sigma}_{\theta ,k}\right)-\mathrm{ln}\left({\sigma}_{\theta old,k}\right)+\frac{{\sigma}_{\theta old,k}^{2}+{\left({\mu}_{\theta old,k}-{\mu}_{\theta ,k}\right)}^{2}}{2{\sigma}_{\theta ,k}^{2}}-0.5\right)}$$

Here:

*μ*and_{θ,k}*σ*are the mean and standard deviation for the_{θ,k}*k*th action output by the current actor policy*π*(*A*|_{k}*S*;_{i}*θ*).*μ*and_{θold,k}*σ*are the mean and standard deviation for the_{θold,k}*k*th action output by the old policy*π*(*A*|_{k}*S*;_{i}*θ*)._{old}

To approximate this optimization problem, the TRPO agent uses a linear approximation of
*L _{actor}*(

*θ*) and a quadratic approximation of

*D*(

_{KL}*θ*,

_{old}*θ*,

*S*). The approximations are computed by taking the Taylor series expansion around

_{i}*θ*.

$$\begin{array}{l}\underset{\theta}{\mathrm{min}}{L}_{actor}\left(\theta \right)\approx {g\left(\theta -{\theta}_{old}\right)={\nabla}_{\theta}{L}_{actor}\left(\theta \right)|}_{\theta ={\theta}_{old}}\cdot \left(\theta -{\theta}_{old}\right)\\ subject\text{\hspace{0.17em}}to\text{\hspace{1em}}\frac{1}{2}{\left({\theta}_{old}-\theta \right)}^{T}H\left({\theta}_{old}-\theta \right)\le \delta \\ where\text{\hspace{1em}}H={\nabla}_{\theta}^{2}{\frac{1}{M}{\displaystyle {\sum}_{i=1}^{M}{D}_{KL}\left({\theta}_{old},\theta ,{S}_{i}\right)}|}_{\theta ={\theta}_{old}}\end{array}$$

The analytical solution to this approximate optimization problem is as follows.

$$\theta ={\theta}_{old}+\alpha \sqrt{\frac{2\delta}{{x}^{T}{H}^{-1}x}}x$$

Here,
*x*=*H*^{-1}*g*
and *α* is a coefficient for ensuring that the policy improves and
satisfies the constraint.

### Training Algorithm

TRPO agents use the following training algorithm. To configure the training algorithm,
specify options using an `rlTRPOAgentOptions`

object.

Initialize the actor

*π*(*A*|*S*;*θ*) with random parameter values*θ*.Initialize the critic

*V*(*S*;*ϕ*) with random parameter values*ϕ*.Generate

*N*experiences by following the current policy. The experience sequence is$${S}_{ts},{A}_{ts},{R}_{ts+1},{S}_{ts+1},\dots ,{S}_{ts+N-1},{A}_{ts+N-1},{R}_{ts+N},{S}_{ts+N}$$

Here,

*S*is a state observation,_{t}*A*is an action taken from that state,_{t}*S*is the next state, and_{t+1}*R*is the reward received for moving from_{t+1}*S*to_{t}*S*._{t+1}When in state

*S*, the agent computes the probability of taking each action in the action space using_{t}*π*(*A*|*S*;_{t}*θ*) and randomly selects action*A*based on the probability distribution._{t}*ts*is the starting time step of the current set of*N*experiences. At the beginning of the training episode,*ts*= 1. For each subsequent set of*N*experiences in the same training episode,*ts*←*ts*+*N*.For each experience sequence that does not contain a terminal state,

*N*is equal to the`ExperienceHorizon`

option value. Otherwise,*N*is less than`ExperienceHorizon`

and*S*is the terminal state._{N}For each episode step

*t*=*ts*,*ts*+1, …,*ts*+*N*-1, compute the return and advantage function using the method specified by the`AdvantageEstimateMethod`

option.**Finite Horizon**(`AdvantageEstimateMethod = "finite-horizon"`

) — Compute the return*G*, which is the sum of the reward for that step and the discounted future reward [2]._{t}$${G}_{t}={\displaystyle \sum _{k=t+1}^{ts+N}\left({\gamma}^{k-t-1}{R}_{k}\right)}+b{\gamma}^{ts+N-t}V\left({S}_{ts+N};\varphi \right)$$

Here,

*b*is`0`

if*S*is a terminal state and_{ts+N}`1`

otherwise. That is, if*S*is not a terminal state, the discounted future reward includes the discounted state value function, computed using the critic network_{ts+N}*V*.Compute the advantage function

*D*._{t}$${D}_{t}={G}_{t}-V\left({S}_{t};\varphi \right)$$

**Generalized Advantage Estimator**(`AdvantageEstimateMethod = "gae"`

) — Compute the advantage function*D*, which is the discounted sum of temporal difference errors [3]._{t}$$\begin{array}{c}{D}_{t}={\displaystyle \sum _{k=t}^{ts+N-1}{\left(\gamma \lambda \right)}^{k-t}{\delta}_{k}}\\ {\delta}_{k}={R}_{k+1}+b\gamma V\left({S}_{k+1};\varphi \right)-V\left({S}_{k};\varphi \right)\end{array}$$

Here,

*b*is`0`

if*S*is a terminal state and_{ts+N}`1`

otherwise.*λ*is a smoothing factor specified using the`GAEFactor`

option.Compute the return

*G*._{t}$${G}_{t}={D}_{t}+V\left({S}_{t};\varphi \right)$$

To specify the discount factor

*γ*for either method, use the`DiscountFactor`

option.Learn from mini-batches of experiences over

*K*epochs. To specify*K*, use the`NumEpoch`

option. For each learning epoch:Sample a random mini-batch data set of size

*M*from the current set of experiences. To specify*M*, use the`MiniBatchSize`

option. Each element of the mini-batch data set contains a current experience and the corresponding return and advantage function values.Update the critic parameters by minimizing the loss

*L*across all sampled mini-batch data._{critic}$${L}_{critic}\left(\varphi \right)=\frac{1}{2M}{\displaystyle \sum _{i=1}^{M}{\left({G}_{i}-V\left({S}_{i};\varphi \right)\right)}^{2}}$$

Normalize the advantage values

*D*based on recent unnormalized advantage values._{i}If the

`NormalizedAdvantageMethod`

option is`'none'`

, do not normalize the advantage values.$${\widehat{D}}_{i}\leftarrow {D}_{i}$$

If the

`NormalizedAdvantageMethod`

option is`'current'`

, normalize the advantage values based on the unnormalized advantages in the current mini-batch.$${\widehat{D}}_{i}\leftarrow \frac{{D}_{i}-mean\left({D}_{1},{D}_{2},\dots ,{D}_{M}\right)}{std\left({D}_{1},{D}_{2},\dots ,{D}_{M}\right)}$$

If the

`NormalizedAdvantageMethod`

option is`'moving'`

, normalize the advantage values based on the unnormalized advantages for the*N*most recent advantages, including the current advantage value. To specify the window size*N*, use the`AdvantageNormalizingWindow`

option.$${\widehat{D}}_{i}\leftarrow \frac{{D}_{i}-mean\left({D}_{1},{D}_{2},\dots ,{D}_{N}\right)}{std\left({D}_{1},{D}_{2},\dots ,{D}_{N}\right)}$$

Update the actor parameters by solving the constrained optimization problem.

Compute the policy gradient.

$$g={\nabla}_{\theta}{L}_{actor}\left(\theta \right)={\nabla}_{\theta}-\frac{1}{M}{\displaystyle \sum _{i=1}^{M}\left(\frac{\pi \left({A}_{i}|{S}_{i};\theta \right)}{\pi \left({A}_{i}|{S}_{i};{\theta}_{old}\right)}{\widehat{D}}_{i}+w{\mathscr{H}}_{i}\left(\theta ,{S}_{i}\right)\right)}$$

Apply the conjugate gradient (CG) method to find an approximate solution to the following equation, where

*H*is the Hessian of the KL-divergence between the old and new policies.$$x\approx {H}^{-1}g$$

To configure the termination conditions for the CG algorithm, use the

`NumIterationsConjugateGradient`

and`ConjugateGradientResidualTolerance`

options. To stabilize the numerical computation for the CG algorithm, use the`ConjugateGradientDamping`

option.Using a line search algorithm, find the largest

*α*that satisfies the following constraints.$$\begin{array}{l}\theta ={\theta}_{old}+\alpha \sqrt{\frac{2\delta}{{x}^{T}{H}^{-1}x}}x\\ {L}_{actor}\left(\theta \right)-{L}_{actor}\left({\theta}_{old}\right)<0\\ \frac{1}{M}{\displaystyle \sum _{i=1}^{M}{D}_{KL}\left({\theta}_{old},\theta ,{S}_{i}\right)}\le \delta \\ \alpha \in \left\{1,\frac{1}{2},\frac{1}{{2}^{2}},\dots ,\frac{1}{{2}^{n-1}}\right\}\end{array}$$

Here,

*δ*is the KL-divergence limit, which you set using the`KLDivergenceLimit`

option.*n*is the number of line search iterations, which you set using the`NumIterationsLineSearch`

option.If a valid value of

*α*exists, update the parameters of the actor network to*θ*. If a valid value of*α*does not exist, do not update the actor parameters.

Repeat steps 3 through 5 until the training episode reaches a terminal state.

### Entropy Loss

To promote agent exploration, you can add an entropy loss term
*w**ℋ _{i}*(

*θ*,

*S*) to the actor loss function, where

_{i}*w*is the entropy loss weight and

*ℋ*(

_{i}*θ*,

*S*) is the entropy.

_{i}The entropy value is higher when the agent is more uncertain about which action to take next. Therefore, maximizing the entropy loss term (minimizing the negative entropy loss) increases the agent uncertainty, thus encouraging exploration. To promote additional exploration, which can help the agent move out of local optima, you can specify a larger entropy loss weight.

For a discrete action space, the agent uses the following entropy value. In this case, the actor outputs the probability of taking each possible discrete action.

$${\mathscr{H}}_{i}\left(\theta ,{S}_{i}\right)=-{\displaystyle \sum _{k=1}^{P}\pi \left({A}_{k}|{S}_{i};\theta \right)\mathrm{ln}\pi \left({A}_{k}|{S}_{i};\theta \right)}$$

Here:

*P*is the number of possible discrete actions.*π*(*A*|_{k}*S*;_{i}*θ*) is the probability of taking action*A*when in state_{k}*S*following the current policy._{i}

For a continuous action space, the agent uses the following entropy value. In this case, the actor outputs the mean and standard deviation of the Gaussian distribution for each continuous action.

$${\mathscr{H}}_{i}\left(\theta ,{S}_{i}\right)=\frac{1}{2}{\displaystyle \sum _{k=1}^{C}\mathrm{ln}\left(2\pi \cdot e\cdot {\sigma}_{k,i}^{2}\right)}$$

Here:

*C*is the number of continuous actions output by the actor.*σ*is the standard deviation for action_{k,i}*k*when in state*S*following the current policy._{i}

## References

[1] Schulman, John, Sergey Levine,
Pieter Abbeel, Michael Jordan, and Philipp Moritz. "Trust Region Policy Optimization."
*Proceedings of the 32nd International Conference on Machine
Learning*, pp. 1889-1897. 2015.

[2] Mnih, Volodymyr, Adrià
Puigdomènech Badia, Mehdi Mirza, Alex Graves, Timothy P. Lillicrap, Tim Harley, David
Silver, and Koray Kavukcuoglu. “Asynchronous Methods for Deep Reinforcement
Learning.”* ArXiv:1602.01783 [Cs]*, February 4, 2016. https://arxiv.org/abs/1602.01783.

[3] Schulman, John, Philipp Moritz,
Sergey Levine, Michael Jordan, and Pieter Abbeel. “High-Dimensional Continuous Control Using
Generalized Advantage Estimation.” *ArXiv:1506.02438 [Cs]*, October 20,
2018. https://arxiv.org/abs/1506.02438.