Skip to content
ImagineWorld

Trust Regions

node_idnode-book_deep-reinforcement-learning-hands-on_chapter-16-trust-regions
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num16
chapter_titleTrust Regions
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we will take a look at the approaches used to improve the stability of the stochastic policy gradient method. Some attempts have been made to make the policy improvement more stable, and in this chapter, we will focus on three methods:

  • Proximal policy optimization (PPO)
  • Trust region policy optimization (TRPO)
  • Advantage actor-critic (A2C) using Kronecker-factored trust region (ACKTR).

In addition, we will compare these methods to a relatively new off-policy method called soft actor-critic (SAC), which is the evolution of the deep deterministic policy gradients (DDPG) method described in Chapter 15. To compare them to the A2C baseline, we will use several environments from the so-called “locomotion gym environments” – environments shipped with Farama Gymnasium (using MuJoCo and PyBullet). We also will do a head-to-head comparison between PyBullet and MuJoCo (which we discussed in Chapter 15).

The purpose of the methods that we will look at is to improve the stability of the policy update during training. There is a dilemma: on the one hand, we’d like to train as fast as we can, making large steps during the stochastic gradient descent (SGD) update. On the other hand, a large update of the policy is usually a bad idea. The policy is a very nonlinear thing, so a large update could ruin the policy we’ve just learned.

Things can become even worse in the reinforcement learning (RL) landscape because you can’t recover from making a bad update to the policy by subsequent updates. Instead, the bad policy will provide bad experience samples that we will use in subsequent training steps, which could break our policy completely. Thus, we want to avoid making large updates by all means possible. One of the naïve solutions would be to use a small learning rate to take baby steps during SGD, but this would significantly slow down the convergence.

To break this vicious cycle, several attempts have been made by researchers to estimate the effect that our policy update is going to have in terms of future outcomes. One of the popular approaches is the trust region optimization extension, which constrains the steps taken during the optimization to limit its effect on the policy. The main idea is to prevent a dramatic policy update during the loss optimization by checking the Kullback-Leibler (KL) divergence between the old and the new policy. Of course, this is an informal explanation, but it can help you understand the idea, especially as those methods are quite math-heavy (especially TRPO).

Previous editions of this book used the Roboschool library from OpenAI (https://openai.com/index/roboschool) to illustrate trust region methods. But eventually, OpenAI deprecated Roboschool and stopped its support.

But environments are still available in other sources:

  • PyBullet: The physics simulator we experimented with in the previous chapter, which includes a wide variety of environments that support Gym. PyBullet may be a bit outdated (the latest release was in 2022), but it is still workable with a bit of hacking.
  • Farama Gymnasium MuJoCo environments: MuJoCo is a physics simulator that we discussed in Chapter 15. After it was made open source, MuJoCo was adopted in various products, including Gymnasium, which ships several environments: https://gymnasium.farama.org/environments/mujoco/.

In this chapter, we will explore two problems: HalfCheetah-v4, which models a two-legged creature, and Ant-v4, which has four legs. Their state and action spaces are very similar to the Minitaur environment that we saw in Chapter 15: the state includes characteristics from joints, and the actions are activations of those joints. The goal for each problem is to move as far as possible, minimizing the energy spent. The following figure shows screenshots of the two environments:

Figure 16.1: Screenshots of the cheetah and ant environments

In our experiment, we’ll use PyBullet and MuJoCo to do a comparison of both simulators in terms of speed and training dynamics (however, note that the internal structure of the PyBullet and MuJoCo environments might be different, and so the comparison of training dynamics may not always be reliable). To install the Gymnasium with MuJoCo extensions, you need to run the following command in your Python environment: pip install gymnasium[mujoco]==0.29.0.

To establish the baseline results, we will use the A2C method in a very similar way to the previous chapter. The complete source code is in the Chapter16/01_train_a2c.py and Chapter16/lib/model.py files. There are a few differences between this baseline and the version we used before:

  • 16 parallel environments are used to gather experience during the training.
  • They differ in model structure and the way that we perform exploration.

To illustrate the differences between this baseline and the previously discussed version, let’s look at the model and the agent classes.

The actor and critic are placed in separate networks without sharing weights. They follow the approach used in Chapter 15, with our critic estimating the mean and the variance for the actions. However, now, variance is not a separate head of the base network; it is just a single parameter of the model. This parameter will be adjusted during the training by SGD, but it doesn’t depend on the observation.

The actor network has two hidden layers of 64 neurons, each with tanh nonlinearity (to push the output in the −1…1 range). The variance is modeled as a separate network parameter and is interpreted as a logarithm of the standard deviation:

HID_SIZE = 64
class ModelActor(nn.Module):
def __init__(self, obs_size: int, act_size: int):
super(ModelActor, self).__init__()
self.mu = nn.Sequential(
nn.Linear(obs_size, HID_SIZE),
nn.Tanh(),
nn.Linear(HID_SIZE, HID_SIZE),
nn.Tanh(),
nn.Linear(HID_SIZE, act_size),
nn.Tanh(),
)
self.logstd = nn.Parameter(torch.zeros(act_size))
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.mu(x)

The critic network also has two hidden layers of the same size, with one single output value, which is the estimation of V (s), which is a discounted value of the state:

class ModelCritic(nn.Module):
def __init__(self, obs_size: int):
super(ModelCritic, self).__init__()
self.value = nn.Sequential(
nn.Linear(obs_size, HID_SIZE),
nn.ReLU(),
nn.Linear(HID_SIZE, HID_SIZE),
nn.ReLU(),
nn.Linear(HID_SIZE, 1),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.value(x)

The agent that converts the state into the action also works by simply obtaining the predicted mean from the state and applying the noise with variance, dictated by the current value of the logstd parameter:

class AgentA2C(ptan.agent.BaseAgent):
def __init__(self, net, device: torch.device):
self.net = net
self.device = device
def __call__(self, states: ptan.agent.States, agent_states: ptan.agent.AgentStates):
states_v = ptan.agent.float32_preprocessor(states)
states_v = states_v.to(self.device)
mu_v = self.net(states_v)
mu = mu_v.data.cpu().numpy()
logstd = self.net.logstd.data.cpu().numpy()
rnd = np.random.normal(size=logstd.shape)
actions = mu + np.exp(logstd) * rnd
actions = np.clip(actions, -1, 1)
return actions, agent_states

The training utility 01_train_a2c.py could be started in two different modes: with PyBullet as the physics simulator (without any extra command-line options) or with MuJoCo (if the —mujoco parameter is given).

By default, the HalfCheetah environment is used, which simulates a flat two-legged creature that can jump around on its legs. With -e ant, you can switch to the Ant environment, which is a 3-dimensional 4-legged spider. You can also experiment with other environments shipped with Gymnasium and PyBullet, but this will require tweaking the common.py module.

Results for HalfCheetah on PyBullet are shown in Figure 16.2. Performance on my machine (using the GPU) was about 1,600 frames per second during the training, so 100M training steps took 20 hours in total.

Figure 16.2: The reward during training (left) and test reward (right) for HalfCheetah on PyBullet

The dynamics suggest that the policy could be further improved with more time given to optimization, but for our purpose of method comparison, it should be enough. Of course, if you’re curious and have plenty of time, you can run this for longer and find the point when the policy stops improving. According to research papers, HalfCheetah has a maximum score of around 4,000-5,000.

To use MuJoCo as a physics simulation engine, training has to be started with the —mujoco command-line option. MuJoCo has a performance of 5,100 frames per second, which is 3 times faster than PyBullet, which is really nice. In addition, the training has much better dynamics, so in 90M training steps (which took about 5 hours) the model got a reward of 4,500. Plots for MuJoCo are shown in Figure 16.3:

Figure 16.3: The reward during training (left) and the test reward (right) for HalfCheetah on MuJoCo

The difference could be explained by a more accurate simulation, but could also be attributed to the difference in the observation space and the underlying model differences. PyBullet’s model has 26 parameters provided to the agent as observations, while MuJoCo has only 17, so those models are not identical.

To test our model in the Ant environment, the -e ant command-line option has to be passed to the training process. This model is more complex (due to the 3D nature of the model and more joints being used), so the simulation is slower. On PyBullet, the speed is around 1,400 frames per second. On MuJoCo, the speed is 2,500.

The MuJoCo Ant environment also has an additional check for “healthiness” – if the simulated creature is inclined more than a certain degree, the episode is terminated. This check is enabled by default and has a very negative effect on the training – in the early stage of the training, our method has no chance of figuring out how to make the ant stand on its legs. The reward in the environment is the distance traveled, but with this early termination, our training has no chance of discovering this. As a result, the training process got stuck forever in local minima without making progress. To overcome this, we need to disable this healthiness check by passing the —no-unhealthy command-line option (which only has to be done for MuJoCo training).

In principle, you can implement more advanced exploration methods, such as the OU process (discussed in Chapter 15) or other methods (covered in Chapter 18) to address the issue we just discussed.

The results of the training in the Ant environment are shown in Figure 16.4 and Figure 16.5.

Figure 16.4: The reward during training (left) and the test reward (right) for Ant on PyBullet

Figure 16.5: The reward during training (left) and the test reward (right) for Ant on MuJoCo

As you can see from the MuJoCo plots in Figure 16.5, the testing reward had almost no increase for the first 100M steps of training, but then grew to a score of 5,000 (the best model got 5,380 on testing). This result is quite impressive. According to the https://paperswithcode.com website, the state of the art for Ant MuJoCo environment is 4,362.9, obtained by IQ-Learn in 2021: https://paperswithcode.com/sota/mujoco-games-on-ant.

As in the previous chapter, there is a utility that can benchmark the trained model and record a video of the agent in action. As all the methods in this chapter share the same actor network, the tool is universal for all the methods illustrated here: 02_play.py.

You need to pass the model file stored in the saves directory during training, change the environment using the -e ant command line, and enable the MuJoCo engine with the —mujoco parameter. This is important because the same environments in PyBullet and MuJoCo have different amounts of observations, and so the physics engine has to match to the model.

You can find the individual videos for the best A2C models as follows:

The PPO method came from the OpenAI team, and it was proposed after TRPO, which is from 2015. However, we will start with PPO because it is much simpler than TRPO. It was first proposed in the 2017 paper named Proximal Policy Optimization Algorithms by Schulman et al. [Sch+17].

The core improvement over the classic A2C method is changing the formula used to estimate the policy gradients. Instead of using the gradient of the logarithm probability of the action taken, the PPO method uses a different objective: the ratio between the new and the old policy scaled by the advantages.

In math form, the A2C objective could be written like this

which means our gradient on model 𝜃 is estimated as the logarithm of the policy π multiplied by the advantage A.

The new objective proposed in PPO is the following:

π (a |s) = P[At = a|St = s]

The reason for changing the objective is the same as with the cross-entropy method covered in Chapter 4: importance sampling. However, if we just start to blindly maximize this value, it may lead to a very large update to the policy weights. To limit the update, the clipped objective is used. If we write the ratio between the new and the old policy as , the clipped objective could be written as

π (a |s) = P[At = a|St = s]

This objective limits the ratio between the old and the new policy to be in the interval [1 −𝜖,1 + 𝜖], so by varying 𝜖, we can limit the size of the update.

Another difference from the A2C method is the way that we estimate the advantage. In the A2C paper, the advantage obtained from the finite-horizon estimation of T steps is in the form

In the PPO paper, the authors used a more general estimation

where σ t = r t + γV (s t+1) −V (s t).

The original A2C estimation is a special case of the proposed method with λ = 1. The PPO method also uses a slightly different training procedure: a long sequence of samples is obtained from the environment and then the advantage is estimated for the whole sequence before several epochs of training are performed.

The code of the sample is placed in two source code files: Chapter16/04_train_ppo.py and Chapter16/lib/model.py. The actor, the critic, and the agent classes are exactly the same as we had in the A2C baseline.

The differences are in the training procedure and the way that we calculate advantages, but let’s start with the hyperparameters:

GAMMA = 0.99
GAE_LAMBDA = 0.95
TRAJECTORY_SIZE = 2049
LEARNING_RATE_ACTOR = 1e-5
LEARNING_RATE_CRITIC = 1e-4
PPO_EPS = 0.2
PPO_EPOCHES = 10
PPO_BATCH_SIZE = 64

The value of GAMMA is already familiar, but GAE_LAMBDA is the new constant that specifies the lambda factor in the advantage estimator. The authors chose to use a value of 0.95 in the PPO paper.

The method assumes that a large number of transitions will be obtained from the environment for every subiteration. (As mentioned previously in this section, when describing PPO, during training, it performs several epochs over the sampled training batch.) We also use two different optimizers for the actor and the critic (as they have no shared weights).

For every batch of TRAJECTORY_SIZE samples, we perform PPO_EPOCHES iterations of the PPO objective, with mini-batches of 64 samples. The value PPO_EPS specifies the clipping value for the ratio of the new and the old policy. The following function takes the trajectory with steps and calculates advantages for the actor and reference values for the critic training. Our trajectory is not a single episode, but could be several episodes concatenated together:

def calc_adv_ref(trajectory: tt.List[ptan.experience.Experience],
net_crt: model.ModelCritic, states_v: torch.Tensor, gamma: float,
gae_lambda: float, device: torch.device):
values_v = net_crt(states_v)
values = values_v.squeeze().data.cpu().numpy()

As the first step, we ask the critic to convert states into values.

The next loop joins the values obtained and experience points:

last_gae = 0.0
result_adv = []
result_ref = []
for val, next_val, (exp,) in zip(
reversed(values[:-1]), reversed(values[1:]), reversed(trajectory[:-1])):

For every trajectory step, we need the current value (obtained from the current state) and the value for the subsequent step (to perform the estimation using the Bellman equation). We also traverse the trajectory in reverse order in order to calculate more recent values of the advantage in one step.

if exp.done_trunc:
delta = exp.reward - val
last_gae = delta
else:
delta = exp.reward + gamma * next_val - val
last_gae = delta + gamma * gae_lambda * last_gae

In every step, our action depends on the done_trunc flag for this step. If this is the terminal step of the episode, we have no prior reward to take into account. (Remember, we’re processing the trajectory in reverse order.) So, our value of delta in this step is just the immediate reward minus the value predicted for the step. If the current step is not terminal, delta will be equal to the immediate reward plus the discounted value from the subsequent step, minus the value for the current step. In the classic A2C method, this delta was used as an advantage estimation, but here, the smoothed version is used, so the advantage estimation (tracked in the last_gae variable) is calculated as the sum of deltas with the discount factor γ λ.

The goal of the function is to calculate advantages and reference values for the critic, so we save them in lists:

result_adv.append(last_gae)
result_ref.append(last_gae + val)

At the end of the function, we convert values to tensors and return them:

adv_v = torch.FloatTensor(np.asarray(list(reversed(result_adv))))
ref_v = torch.FloatTensor(np.asarray(list(reversed(result_ref))))
return adv_v.to(device), ref_v.to(device)

In the training loop, we gather a trajectory of the desired size using the ExperienceSource(steps_count=1) class from the PTAN library. This configuration provides us with individual steps from the environment in Experience dataclass instances, containing the state, action, reward, and termination flag. The following is the relevant part of the training loop:

trajectory.append(exp)
if len(trajectory) < TRAJECTORY_SIZE:
continue
traj_states = [t[0].state for t in trajectory]
traj_actions = [t[0].action for t in trajectory]
traj_states_v = torch.FloatTensor(np.asarray(traj_states))
traj_states_v = traj_states_v.to(device)
traj_actions_v = torch.FloatTensor(np.asarray(traj_actions))
traj_actions_v = traj_actions_v.to(device)
traj_adv_v, traj_ref_v = common.calc_adv_ref(
trajectory, net_crt, traj_states_v, GAMMA, GAE_LAMBDA, device=device)

When we’ve got a trajectory that’s large enough for training (which is given by the TRAJECTORY_SIZE hyperparameter), we convert states and actions taken into tensors and use the already-described function to obtain advantages and reference values. Although our trajectory is quite long, the observations of our environments are small enough, so it’s fine to process our batch in one step. In the case of Atari frames, such a batch could cause a GPU memory error. In the next step, we calculate the logarithm of the probability of the actions taken. This value will be used as π 𝜃 old in the objective of PPO. Additionally, we normalize the advantage’s mean and variance to improve the training stability:

mu_v = net_act(traj_states_v)
old_logprob_v = model.calc_logprob(mu_v, net_act.logstd, traj_actions_v)
traj_adv_v = traj_adv_v - torch.mean(traj_adv_v)
traj_adv_v /= torch.std(traj_adv_v)

The two subsequent lines drop the last entry from the trajectory to reflect the fact that our advantages and reference values are one step shorter than the trajectory length (as we shifted values in the loop inside the calc_adv_ref function):

trajectory = trajectory[:-1]
old_logprob_v = old_logprob_v[:-1].detach()

When all the preparations have been done, we perform several epochs of training on our trajectory. For every batch, we extract the portions from the corresponding arrays and do the critic and the actor training separately:

for epoch in range(PPO_EPOCHES):
for batch_ofs in range(0, len(trajectory), PPO_BATCH_SIZE):
batch_l = batch_ofs + PPO_BATCH_SIZE
states_v = traj_states_v[batch_ofs:batch_l]
actions_v = traj_actions_v[batch_ofs:batch_l]
batch_adv_v = traj_adv_v[batch_ofs:batch_l]
batch_adv_v = batch_adv_v.unsqueeze(-1)
batch_ref_v = traj_ref_v[batch_ofs:batch_l]
batch_old_logprob_v = old_logprob_v[batch_ofs:batch_l]

To train the critic, all we need to do is calculate the mean squared error (MSE) loss with the reference values calculated beforehand:

opt_crt.zero_grad()
value_v = net_crt(states_v)
loss_value_v = F.mse_loss(value_v.squeeze(-1), batch_ref_v)
loss_value_v.backward()
opt_crt.step()

In the actor training, we minimize the negated clipped objective:

π (a |s) = P[At = a|St = s]

To achieve this, we use the following code:

opt_act.zero_grad()
mu_v = net_act(states_v)
logprob_pi_v = model.calc_logprob(mu_v, net_act.logstd, actions_v)
ratio_v = torch.exp(logprob_pi_v - batch_old_logprob_v)
surr_obj_v = batch_adv_v * ratio_v
c_ratio_v = torch.clamp(ratio_v, 1.0 - PPO_EPS, 1.0 + PPO_EPS)
clipped_surr_v = batch_adv_v * c_ratio_v
loss_policy_v = -torch.min(surr_obj_v, clipped_surr_v).mean()
loss_policy_v.backward()
opt_act.step()

After being trained in both our test environments, the PPO method has shown much faster convergence than the A2C method. On HalfCheetah using PyBullet, PPO reached an average training reward of 1,800 and 2,500 during the testing after 8 hours of training and 25M training steps. A2C got lower results after 110M steps and 20 hours. Figure 16.6 shows the comparison plots.

Figure 16.6: The reward during training (left) and the test reward (right) for HalfCheetah on PyBullet

But on HalfCheetah using MuJoCo, the situation is the opposite – PPO growth was much slower, and I stopped it after 50M training steps (12 hours). Figure 16.7 shows the plots.

Figure 16.7: The reward during training (left) and the test reward (right) for HalfCheetah on MuJoCo

After checking the video of the model (links are provided later in this section), we might guess the reason for the low score – our agent learned how to flip the cheetah on its back and move forward in this position. During training, it wasn’t able to get from this suboptimal “local maximum.” Most likely, running the training several times might yield a better policy. Another approach to solving this might be to optimize hyperparameters. Again, this is something you can try experimenting with.

In the Ant environment, PPO was better on both PyBullet and MuJoco and was able to reach the same level of reward almost twice as fast as A2C. This comparison is shown in the plots in Figure 16.8 and Figure 16.9:

Figure 16.8: The reward during training (left) and the test reward (right) for Ant on PyBullet

Figure 16.9: The reward during training (left) and the test reward (right) for Ant on MuJoCo

As before, you can use the 02_play.py utility to benchmark saved models and record videos of the learned policy in action. This is the list of the best models for my training experiments:

TRPO was proposed in 2015 by Berkeley researchers in a paper by Schulman et al., called Trust region policy optimization [Sch15]. This paper was a step towards improving the stability and consistency of stochastic policy gradient optimization and has shown good results on various control tasks.

Unfortunately, the paper and the method are quite math-heavy, so it can be hard to understand the details. The same could be said about the implementation, which uses the conjugate gradients method to efficiently solve the constrained optimization problem.

As the first step, the TRPO method defines the discounted visitation frequencies of the state as follows:

In this equation, P(s i = s) equals the sampled probability of state s to be met at position i of the sampled trajectories.

Then, TRPO defines the optimization objective as

π (a |s) = P[At = a|St = s]

where

π (a |s) = P[At = a|St = s]

is the expected discounted reward of the policy and π̃ = arg max a A π (s,a) defines the deterministic policy. To address the issue of large policy updates, TRPO defines the additional constraint on the policy update, which is expressed as the maximum KL divergence between the old and the new policies, which could be written as

As a reminder, KL divergence measures the similarity between probability distributions and is calculated as follows:

π (a |s) = P[At = a|St = s]

We met KL divergence in Chapter 4 and Chapter 11.

Most of the TRPO implementations available on GitHub, or in other open source repositories, are very similar to each other, probably because all of them grew from the original John Schulman TRPO implementation here: https://github.com/joschu/modular_rl. My version of TRPO is also not very different and uses the core functions that implement the conjugate gradient method (used by TRPO to solve the constrained optimization problem) from this repository: https://github.com/ikostrikov/pytorch-trpo.

The complete example is in 03_train_trpo.py and lib/trpo.py, and the training loop is very similar to the PPO example: we sample the trajectory of transitions of the predefined length and calculate the advantage estimation using the smoothed formula discussed in the PPO section (historically, this estimator was proposed first in the TRPO paper.) Next, we do one training step of the critic using MSE loss with the calculated reference value, and one step of the TRPO update, which consists of finding the direction we should go in by using the conjugate gradients method and doing a linear search in this direction to find a step that preserves the desired KL divergence.

The following is the piece of the training loop that carries out both those steps:

opt_crt.zero_grad()
value_v = net_crt(traj_states_v)
loss_value_v = F.mse_loss(value_v.squeeze(-1), traj_ref_v)
loss_value_v.backward()
opt_crt.step()

To perform the TRPO step, we need to provide two functions: the first will calculate the loss of the current actor policy, which uses the same ratio as the PPO of the new and the old policies multiplied by the advantage estimation. The second function has to calculate KL divergence between the old and the current policy:

def get_loss():
mu_v = net_act(traj_states_v)
logprob_v = model.calc_logprob(mu_v, net_act.logstd, traj_actions_v)
dp_v = torch.exp(logprob_v - old_logprob_v)
action_loss_v = -traj_adv_v.unsqueeze(dim=-1)*dp_v
return action_loss_v.mean()
def get_kl():
mu_v = net_act(traj_states_v)
logstd_v = net_act.logstd
mu0_v = mu_v.detach()
logstd0_v = logstd_v.detach()
std_v = torch.exp(logstd_v)
std0_v = std_v.detach()
v = (std0_v ** 2 + (mu0_v - mu_v) ** 2) / (2.0 * std_v ** 2)
kl = logstd_v - logstd0_v + v - 0.5
return kl.sum(1, keepdim=True)
trpo.trpo_step(net_act, get_loss, get_kl, args.maxkl,
TRPO_DAMPING, device=device)

In other words, the PPO method is TRPO that uses the simple clipping of the policy ratio to limit the policy update, instead of the complicated conjugate gradients and line search.

TRPO in the HalfCheetah environment was able to reach better rewards than PPO and A2C. In Figure 16.10, the results from PyBullet training is shown. On MuJoCo, the results are even more impressive – the best reward was over 5,000. The plots for MuJoCo are shown in Figure 16.11:

Figure 16.10: The reward during training (left) and test reward (right) for HalfCheetah on PyBullet

Figure 16.11: The reward during training (left) and the test reward (right) for HalfCheetah on MuJoCo

Unfortunately, the Ant environment shows much less stable convergence. The plots shown in Figure 16.12 and Figure 16.13 compare the train and test rewards on A2C and TRPO:

Figure 16.12: The reward during training (left) and the test reward (right) for Ant on PyBullet

Figure 16.13: The reward during training (left) and the test reward (right) for Ant on MuJoCo

Video recordings of the best actions could be done in the same way as before. Here are some videos for the best TRPO models:

The third method that we will compare, ACKTR, uses a different approach to address SGD stability. In the paper by Wu et al. called Scalable trust-region method for deep reinforcement learning using Kronecker-factored approximation, published in 2017 [Wu+17], the authors combined the second-order optimization methods and trust region approach.

The idea of the second-order methods is to improve the traditional SGD by taking the second-order derivatives of the optimized function (in other words, its curvature) to improve the convergence of the optimization process. To make things more complicated, working with the second-order derivatives usually requires you to build and invert a Hessian matrix, which can be prohibitively large, so the practical methods typically approximate it in some way. This area is currently very active in research because developing robust, scalable optimization methods is very important for the whole machine learning domain.

One of the second-order methods is called Kronecker-factored approximate curvature (K-FAC), which was proposed by James Martens and Roger Grosse in their paper Optimizing neural networks with Kronecker-factored approximate curvature, published in 2015 [MG15]. However, a detailed description of this method is well beyond the scope of this book.

There are not very many implementations of this method available, and none of them are part of PyTorch (unfortunately). As far as I know, there are two versions of the K-FAC optimizer that work with PyTorch; one from Ilya Kostrikov (https://github.com/ikostrikov/pytorch-a2c-ppo-acktr) and one from Nicholas Gao (https://github.com/n-gao/pytorch-kfac). I’ve experimented only with the first one; you can give the second one a try. There is a version of K-FAC available for TensorFlow, which comes with OpenAI Baselines, but porting and testing it on PyTorch can be difficult.

For my experiments, I’ve taken the K-FAC implementation from Kostrikov and adapted it to the existing code, which required replacing the optimizer and doing an extra backward() call to gather Fisher information. The critic was trained in the same way as in A2C. The complete example is in 05_train_acktr.py and is not shown here, as it’s basically the same as A2C. The only difference is that a different optimizer was used.

Overall, the ACKTR method was very unstable in both environments and physics engines. It could be due to a lack of fine-tuning of hyperparameters or some bugs in the implementation.

The results of experiments on HalfCheetah are shown in Figure 16.14 and Figure 16.15.

Figure 16.14: The reward during training (left) and the test reward (right) for HalfCheetah on PyBullet

Figure 16.15: The reward during training (left) and test reward (right) for HalfCheetah on MuJoCo

In the Ant environment, the ACKTR method shows bad results on PyBullet and no reward improvements compared to training on MuJoCo. Figure 16.16 shows plots for PyBullet.

Figure 16.16: The reward during training (left) and the test reward (right) for Ant on PyBullet

In the final section, we will check our environments on a relatively new method called SAC, which was proposed by a group of Berkeley researchers and introduced in the paper Soft actor-critic: Off-policy maximum entropy deep reinforcement learning, by Haarnoja et al., published in 2018 [Haa+18].

At the moment, it’s considered to be one of the best methods for continuous control problems and is very widely used. The core idea of the method is closer to the DDPG method than to A2C policy gradients. We will compare it directly with PPO’s performance, which has been considered to be the standard in continuous control problems for a long time.

The central idea of the SAC method is entropy regularization, which adds a bonus reward at each timestamp that is proportional to the entropy of the policy at this timestamp. In mathematical notation, the policy we’re looking for is the following:

π (a |s) = P[At = a|St = s]

Here, H(P) = 𝔼 x∼P [−log P(x)] is the entropy of distribution P. In other words, we give the agent a bonus for getting into situations where the entropy is at its maximum, which is very similar to the advanced exploration methods covered in Chapter 18. In addition, the SAC method incorporates the clipped double-Q trick, where, in addition to the value function, we learn two networks predicting Q-values, and choose the minimum of them for Bellman approximation. According to researchers, this helps with dealing with Q-value overestimation during training. This problem was discussed in Chapter 8, but was addressed differently.

So, in total, we train four networks: the policy, π(s), value, V (s,a) and two Q-networks, Q 1 (s,a) and Q 2 (s,a). For the value network, V (s,a), the target network is used. So, in summary, SAC training looks like this:

  • Q-networks are trained using the MSE objective by doing Bellman approximation using the target value network: y q (r,s′) = r+γV tgt (s′) (for non-terminating steps)
  • The V-network is trained using the MSE objective with the following target, y v (s) = min i=1,2 Q i (s,ã) −α log π 𝜃 (ã|s), where ã is sampled from policy π 𝜃 (⋅|s)
  • The policy network, π 𝜃, is trained in DDPG style by maximizing the following objective, Q 1 (s,ã 𝜃 (s)) −α log π 𝜃 (ã 𝜃 (s)|s), where ã 𝜃 is a sample from π 𝜃 (⋅|s)

The implementation of the SAC method is in 06_train_sac.py. The model consists of the following networks, defined in lib/model.py:

  • ModelActor: This is the same policy that we used in the previous examples in this chapter. As the policy variance is not parametrized by the state (the logstd field is not a network, but just a tensor), the training objective does not 100% comply with SAC. On the one hand, it might influence the convergence and performance, as the core idea of the SAC method is entropy regularization, which can’t be implemented without parametrized variance. On the other hand, it decreases the number of parameters in the model. If you’re curious, you can extend the example with the parametrized variance of the policy and implement a proper SAC method.
  • ModelCritic: This is the same value network as in the previous examples.
  • ModelSACTwinQ: These two networks take the state and action as the input and predict Q-values.

The first function implementing the method is unpack_batch_sac(), and it is defined in lib/common.py. Its goal is to take the batch of trajectory steps and calculate target values for V-networks and twin Q-networks:

@torch.no_grad()
def unpack_batch_sac(batch: tt.List[ptan.experience.ExperienceFirstLast],
val_net: model.ModelCritic, twinq_net: model.ModelSACTwinQ,
policy_net: model.ModelActor, gamma: float, ent_alpha: float,
device: torch.device):
states_v, actions_v, ref_q_v = unpack_batch_a2c(batch, val_net, gamma, device)
mu_v = policy_net(states_v)
act_dist = distr.Normal(mu_v, torch.exp(policy_net.logstd))
acts_v = act_dist.sample()
q1_v, q2_v = twinq_net(states_v, acts_v)
ref_vals_v = torch.min(q1_v, q2_v).squeeze() - \
ent_alpha * act_dist.log_prob(acts_v).sum(dim=1)
return states_v, actions_v, ref_vals_v, ref_q_v

The first step of the function uses the already defined unpack_batch_a2c() method, which unpacks the batch, converts states and actions into tensors, and calculates the reference for Q-networks using Bellman approximation. Once this is done, we need to calculate the reference for the V-network from the minimum of the twin Q-values minus the scaled entropy coefficient. The entropy is calculated from our current policy network. As was already mentioned, our policy has the parametrized mean value, but the variance is global and doesn’t depend on the state.

In the main training loop, we use the function defined previously and do three different optimization steps: for V, for Q, and for the policy. The following is the relevant part of the training loop defined in 06_train_sac.py:

batch = buffer.sample(BATCH_SIZE)
states_v, actions_v, ref_vals_v, ref_q_v = common.unpack_batch_sac(
batch, tgt_crt_net.target_model, twinq_net, act_net, GAMMA,
SAC_ENTROPY_ALPHA, device)

In the beginning, we unpack the batch to get the tensors and targets for the Q- and V-networks.

The twin Q-networks are optimized by the same target value:

twinq_opt.zero_grad()
q1_v, q2_v = twinq_net(states_v, actions_v)
q1_loss_v = F.mse_loss(q1_v.squeeze(), ref_q_v.detach())
q2_loss_v = F.mse_loss(q2_v.squeeze(), ref_q_v.detach())
q_loss_v = q1_loss_v + q2_loss_v
q_loss_v.backward()
twinq_opt.step()

The critic network is also optimized with the trivial MSE objective using the already calculated target value:

crt_opt.zero_grad()
val_v = crt_net(states_v)
v_loss_v = F.mse_loss(val_v.squeeze(), ref_vals_v.detach())
v_loss_v.backward()
crt_opt.step()

And finally, we optimize the actor network:

act_opt.zero_grad()
acts_v = act_net(states_v)
q_out_v, _ = twinq_net(states_v, acts_v)
act_loss = -q_out_v.mean()
act_loss.backward()
act_opt.step()

In comparison with the formulas given previously, the code is missing the entropy regularization term and corresponds to DDPG training. As our variance doesn’t depend on the state, it can be omitted from the optimization objective.

I ran SAC training in the HalfCheetah and Ant environments for 9-13 hours, with 5M observations. The results are a bit contradictory. On the one hand, the sample efficiency and reward growing dynamics of SAC were better than the PPO method. For example, SAC was able to reach a reward of 900 after just 0.5M observations on HalfCheetah. PPO required more than 1M observations to reach the same policy. In the MuJoCo environment, SAC was able to find the policy that got a reward of 7,063, which is an absolute record (demonstrating state-of-the-art performance on this environment).

On the other hand, due to the off-policy nature of SAC, the training speed was much slower, as we did more calculations than with on-policy methods. On my machine, 5M frames on HalfCheetah took 10 hours. As a reminder, A2C did 50M observations in the same time.

This demonstrates the trade-offs between on-policy and off-policy methods, as you have seen many times in this book so far: if your environment is fast and observations are cheap to obtain, an on-policy method like PPO might be the best choice. But if your observations are hard to obtain, off-policy methods will do a better job, but require more calculations to be performed.

Figure 16.17 and Figure 16.18 show the reward dynamics on HalfCheetah:

Figure 16.17: The reward during training (left) and the test reward (right) for HalfCheetah on PyBullet

Figure 16.18: The reward during training (left) and the test reward (right) for HalfCheetah on MuJoCo

The results in the Ant environment are much worse – according to the score, the learned policy can barely stand. The PyBullet plots are shown in Figure 16.19; MuJoCo plots are shown in Figure 16.20:

Figure 16.19: The reward during training (left) and the test reward (right) for Ant on PyBullet

Figure 16.20: The reward during training (left) and the test reward (right) for Ant on MuJoCo

Here are the videos for the best SAC models:

To simplify the comparison of the methods, I put all the numbers related to the best rewards obtained in the following table:

Method

HalfCheetah

Ant

PyBulletMuJoCoPyBulletMuJoCo
A2C2,1894,7182,4255,380
PPO2,5671,6232,5605,108
TRPO2,4195,753834993
ACKTR2503,1001,820—
SAC1,7657,063630—

Table 16.1: Summary table

As you can see, there is no single winning method – some do well in some environments but get worse results in others. In principle, we can call A2C and PPO as quite consistent methods because they’re getting good results everywhere (PPO’s “backflip cheetah” on MuJoCo could be attributed to a bad starting seed, so rerunning the training might lead to a better policy).

In this chapter, we checked three different methods with the aim of improving the stability of the stochastic policy gradient and compared them to the A2C implementation on two continuous control problems. Along with the methods covered in the previous chapter (DDPG and D4PG), these methods are basic tools to work with a continuous control domain. Finally, we checked a relatively new off-policy method that is an extension of DDPG: SAC. Here, we have just scratched the surface of this topic, but it could be a good starting point to dive into it in more depth. These methods are widely used in robotics and related areas.

In the next chapter, we will switch to a different set of RL methods that have been becoming popular recently: black-box or gradient-free methods.