Main Content

Proximal Policy Optimization (PPO) Agent

Proximal policy optimization (PPO) is an on-policy, policy gradient reinforcement learning method for environments with a discrete, continuous or hybrid action space. It directly estimates a stochastic policy and uses a value function critic to estimate the value of the policy. This algorithm alternates between sampling data through environmental interaction and optimizing a clipped surrogate objective function using stochastic gradient descent. The clipped surrogate objective function improves training stability by limiting the size of the policy change at each step [1].

For continuous action spaces and with custom networks, this agent does not automatically enforce the constraints set by the action specification. In this case, you must enforce action space constraints within the environment. The default agent for continuous action spaces automatically enforces constraints on the action.

PPO is a simplified version of TRPO. Specifically, PPO has less hyperparameters and therefore is easier to tune, and less computationally expensive than TRPO. For more information on TRPO agents, see Trust Region Policy Optimization (TRPO) Agent. For more information on the different types of reinforcement learning agents, see Reinforcement Learning Agents.

In Reinforcement Learning Toolbox™, a proximal policy optimization agent is implemented by an rlPPOAgent object.

Proximal policy optimization agents can be trained in environments with the following observation and action spaces.

Observation SpaceAction Space
Discrete, continuous, or hybrid.Discrete, continuous, or hybrid.

Proximal policy optimization agents use the following actor and critics. In the most general case, for hybrid action spaces, the action A has a discrete part Ad and a continuous part Ac.

CriticActor

Value function critic V(S), which you create using rlValueFunction

Stochastic policy actor π(A|S), which you create using rlDiscreteCategoricalActor (for discrete action spaces), rlContinuousGaussianActor (for continuous action spaces) or rlHybridStochasticActor for hybrid action spaces

During training, a Proximal policy optimization 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.

Note

The UseExplorationPolicy option affects only simulation and deployment; it does not affect training. When you train an agent using train, the agent always uses its exploration policy independently of the value of this property.

Actor and Critic Used by the PPO Agent

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

  • Stochastic 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 — A vector containing the probability of taking each discrete action. The sum of these probabilities across all actions is 1.

    • Continuous action space — Two vectors containing the means and standard deviations, respectively, of the Gaussian distribution for each continuous action.

    • Hybrid action space — A vector of probabilities for each discrete action, and two vectors representing mean and standard deviation for each continuous action.

    The agent samples these probability distributions to obtain the action vector.

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

During training, the actor tunes the parameter values in θ to improve the policy. Similarly, during training, the critic tunes the parameter values in ϕ to improve its value function estimation. After training, the parameters remain at their tuned values in the actor and critic internal to the trained agent.

For more information on actors and critics, see Create Actors, Critics, and Policy Objects.

PPO Agent Creation

You can create and train proximal policy optimization 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 PPO agent with default actor and critic based on the observation and action specifications from the environment. To do so, perform the following steps.

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

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

  3. If needed, specify the number of neurons in each learnable layer of the default network or whether to use an LSTM layer. To do so, create an agent initialization option object using rlAgentInitializationOptions.

  4. Specify agent options using an rlPPOAgentOptions object. Alternatively, you can skip this step and modify the agent options later using dot notation.

  5. Create the agent using rlPPOAgent.

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.

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

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

  3. Create an approximation model for your actor. For continuous action spaces, this model must be a neural network object. For discrete action spaces, you also have the option of using a custom basis function with initial parameter values.

  4. Create a stochastic actor using rlContinuousGaussianActor (for continuous action spaces), rlDiscreteCategoricalActor (for discrete action spaces), or rlHybridStochasticActor (for hybrid action spaces). Use the model you created in the previous step as a first input argument.

  5. Create an approximation model for your critic using either a custom basis function with initial parameter values or a neural network object.

  6. Create a critic using rlValueFunction. Use the model you created in the previous step as a first input argument.

  7. If needed, specify agent options using an rlPPOAgentOptions object. Alternatively, you can skip this step and modify the agent options later using dot notation.

  8. Create the agent using rlPPOAgent.

PPO agents support actors and critics that use recurrent deep neural networks as function approximators.

For more information on creating actors and critics for function approximation, see Create Actors, Critics, and Policy Objects.

PPO Agent Initialization

When you create a PPO agent, the actor and critic initialize as follows.

  • The actor π(A|S;θ) uses random parameter values in θ.

  • The critic V(S;ϕ) uses parameter values in ϕ.

The agent uses this initial actor and critic parameters at the beginning of the first training session. For each subsequent training session, the actor and critic retain the parameters from the previous session.

PPO Training Algorithm

Proximal policy optimization agents use the following training algorithm. To configure the training algorithm, specify options using an rlPPOAgentOptions object.

  1. Generate E experiences (possibly running multiple episodes) by following the current policy. Specifically:

    1. At the beginning of each episode, get the initial observation from the environment.

    2. For the current observation S, select the action A using the policy in π(A|S;θ).

    3. Execute action A. Observe the reward R and the next observation S'.

    4. Store the experience (S,A,R,S').

    To specify E use the LearningFrequency option.

  2. Divide the E experiences into sequences each having N experiences, numbered from ts to 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 SN is the terminal state.

  3. For each step t = ts, ts+1, …, ts+N-1, of each sequence, compute the return and advantage function using the method specified by the AdvantageEstimateMethod option.

    • Finite Horizon (AdvantageEstimateMethod = "finite-horizon") — Compute the return Gt, which is the sum of the reward for that step and the discounted future reward [2].

      Gt=k=t+1ts+N(γkt1Rk)+bγts+NtV(Sts+N;ϕ)

      Here, b is 0 if Sts+N is a terminal state and 1 otherwise. That is, if Sts+N is not a terminal state, the discounted future reward includes the discounted state value function, computed using the critic approximator V.

      Compute the advantage function Dt.

      Dt=GtV(St;ϕ)

    • Generalized Advantage Estimator (AdvantageEstimateMethod = "gae") — Compute the advantage function Dt, which is the discounted sum of temporal difference errors [3].

      Dt=k=tts+N1(γλ)ktδkδk=Rk+1+bγV(Sk+1;ϕ)V(Sk;ϕ)

      Here, b is 0 if Sts+N is a terminal state and 1 otherwise. λ is a smoothing factor specified using the GAEFactor option.

      Compute the return Gt.

      Gt=Dt+V(St;ϕ)

    To specify the discount factor γ for either method, use the DiscountFactor option.

  4. Perform the following two operations for NumEpoch times:

    1. Using all the collected experiences, create a maximum of B different mini-batches. To specify B, use the MaxMiniBatchPerEpoch option. Each mini-batch contains M different (typically nonconsecutive) experiences (Si,Ai,Ri,S'i) that are randomly sampled from the experience buffer (each experience can only be part of one mini-batch). To specify M, use the MiniBatchSize option.

      If the agent contains recurrent neural networks, each mini-batch contains M different sequences. Each sequence contains K consecutive experiences (starting from a randomly sampled experience). To specify K, use the SequenceLength option.

    2. For each (randomly selected) mini-batch, perform the learning operations described in Mini-Batch Learning Operations.

Mini-Batch Learning Operations

Operations performed for each mini-batch.

  1. Update the critic parameters by minimizing the loss Lcritic across all sampled mini-batch data.

    Lcritic(ϕ)=12Mi=1M(GiV(Si;ϕ))2

  2. Normalize the advantage values Di based on recent unnormalized advantage values.

    • If the NormalizedAdvantageMethod option is "none", do not normalize the advantage values.

      D^iDi

    • If the NormalizedAdvantageMethod option is "current", normalize the advantage values based on the unnormalized advantages in the current mini-batch.

      D^iDimean(D1,D2,,DM)std(D1,D2,,DM)

    • 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.

      D^iDimean(D1,D2,,DN)std(D1,D2,,DN)

  3. Update the actor parameters by minimizing the actor loss function Lactor across all sampled mini-batch data.

    Lactor(θ)=1Mi=1M(min(ri(θ)D^i,ci(θ)D^i)wi(θ,Si))ri(θ)=π(Ai|Si;θ)π(Ai|Si;θold)ci(θ)=max(min(ri(θ),1+ε),1ε)

    Here:

    • Di and Gi are the advantage function and return value for the ith element of the mini-batch, respectively.

    • i(θ,Si) is the entropy loss and w is the entropy loss weight factor, specified using the EntropyLossWeight option. For more information on entropy loss, see Entropy Loss.

    • π(Ai|Si;θ) indicates one of the following quantities:

      • For a discrete action space — The probability of taking the discrete action Ai, given observation Si, and parameters θ.

      • For a continuous action space — The value of the joint probability density function of the action, calculated for the action vector Ai and the observation Si, given parameters θ:

        π(Ai|S;θ)=j=1Nfj(Aj,i|Si;θ)

        Here, fj is the probability density function for the dimension j of the action vector, and Ai,j is the jth element of Ai, which has dimension N.

      • For a Hybrid action space — The value of the joint probability density function of both the discrete and continuous actions, calculated for the action vector Ai and the observation Si, given parameters θ:

        π(Ai|Si;θ)=p(Aid|Si;θ)j=1NCfj,i(Aj,ic|Si;θ)

        Here, p(Adi| Si;θ) is the probability of taking the discrete action Adi, given observation Si and parameters θ, fj,i is the probability density function for the dimension j of the continuous part of the action vector Aci, and Acj,i is the jth element of Aci, which has dimension NC.

    • π(Ai|Si;θold) is the same as π(Ai|Si;θold), except that the previous policy parameters θold from before the current learning epoch are used instead of the current parameters θ.

    • ε is the clip factor specified using the ClipFactor option.

Entropy Loss

To promote agent exploration, you can subtract an entropy loss term wi(θ,Si) from the actor loss function, where w is the entropy loss weight and i(θ,Si) is the entropy.

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 more information on entropy weights, see the EntropyLossWeight property in rlPPOAgentOptions.

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.

i(θ,Si)=id(θ,Si)=k=1Pπ(Ak|Si;θ)lnπ(Ak|Si;θ)

Here:

  • P is the number of possible discrete actions.

  • π(Ak|Si;θ) is the probability of taking action Ak when in state Si following the current policy.

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.

i(θ,Si)=ic(θ,Si)=12k=1NCln(2πeσk,i2)

Here:

  • NC is the dimension of the continuous part of the action vector.

  • σk,i is the standard deviation for action k when in state Si following the current policy.

For an hybrid action space, the entropy is a two-element column vector containing both the discrete and a continuous entropy values, respectively.

i(θ,Si)=[id(θ,Si)ic(θ,Si)]

In this case, the entropy weight is a row vector containing weights for the discrete and continuous entropy values, respectively.

References

[1] Schulman, John, Filip Wolski, Prafulla Dhariwal, Alec Radford, and Oleg Klimov. “Proximal Policy Optimization Algorithms.” arXiv, August 28, 2017. https://doi.org/10.48550/arXiv.1707.06347.

[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, June 16, 2016. https://doi.org/10.48550/arXiv.1602.01783.

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

See Also

Objects

Topics