Continuous Action Space
local graph
Chapter 15 — Continuous Action Space
Section titled “Chapter 15 — Continuous Action Space”This chapter kicks off the advanced reinforcement learning (RL) part of the book by taking a look at a problem that has only been briefly mentioned so far: working with environments when our action space is not discrete. Continuous action space problems are an important subfield of RL, both theoretically and practically, because they have essential applications in robotics, control problems, and other fields in which we communicate with physical objects. In this chapter, you will become familiar with the challenges that arise in such cases and learn how to solve them.
This material might be applicable even in problems and environments we’ve already seen. For example, in the previous chapter, when we implemented a mouse clicking in the browser environment, the x and y coordinates for the click position could be seen as two continuous variables to be predicted as actions. This might look a bit artificial, but such representation has a lot of sense from the environment perspective: it is much more compact and naturally captures possible click dispersion. At the end, clicking at coordinate (x,y) isn’t much different from clicking at the (x + 1,y + 1) position for most of the tasks.
In this chapter, we will:
- Cover the continuous action space, why it is important, how it differs from the already familiar discrete action space, and the way it is implemented in the Gym API
- Discuss the domain of continuous control using RL methods
- Check three different algorithms on the problem of a four-legged robot
Why a continuous space?
Section titled “Why a continuous space?”All the examples that we have seen so far in the book had a discrete action space, so you might have the wrong impression that discrete actions dominate the field. This is a very biased view, of course, and just reflects the selection of domains that we picked our test problems from. Besides Atari games and simple, classic RL problems, there are many tasks that require more than just making a selection from a small and discrete set of things to do.
To give you an example, just imagine a simple robot with only one controllable joint that can be rotated in some range of degrees. Usually, to control a physical joint, you have to specify either the desired position or the force applied. In both cases, you need to make a decision about a continuous value. This value is fundamentally different from a discrete action space, as the set of values on which you can make a decision is potentially infinite. For instance, you could ask the joint to move to a 13.5 ∘ angle or 13.512 ∘ angle, and the results could be different. Of course, there are always some physical limitations of the system, as you can’t specify the action with infinite precision, but the size of the potential values could be very large.
In fact, when you need to communicate with a physical world, a continuous action space is much more likely than having a discrete set of actions. As an example, different kinds of robots control systems (such as a heating/cooling controller). The methods of RL could be applied to this domain, but there are some details that you need to take into consideration before using the advantage actor-critic (A2C) or deep Q-network (DQN) methods.
In this chapter, we will explore how to deal with this family of problems. This will act as a good starting point for learning about this very interesting and important domain of RL.
The action space
Section titled “The action space”The fundamental and obvious difference with a continuous action space is its continuity. In contrast to a discrete action space, when the action is defined as a discrete, mutually exclusive set of options to choose from (for example {left, right}, which contains only two elements), the continuous action has a value from some range (for instance, [0…1], which includes infinite elements, like 0.5,, and ). On every time step, the agent needs to select the concrete value for the action and pass it to the environment.
In Gym, a continuous action space is represented as the gym.spaces.Box class, which was described, when we talked about the observation space. You may remember that Box includes a set of values with a shape and bounds. For example, every observation from the Atari emulator was represented as Box(low=0, high=255, shape=(210, 160, 3)), which means 100,800 values organized as a 3D tensor, with values from the 0…255 range. For the action space, it’s unlikely that you’ll work with such large numbers of actions. For example, the four-legged robot that we will use as a testing environment has eight continuous actions, which correspond to eight motors, two in every leg. For this environment, the action space will be defined as Box(low=-1, high=1, shape= (8, )), which means eight values from the range −1…1 have to be selected at every timestamp to control the robot.
In this case, the action passed to the env.step() at every step won’t be an integer anymore; it will be a NumPy vector of some shape with individual action values. Of course, there could be more complicated cases when the action space is a combination of discrete and continuous actions, which may be represented with the gym.spaces.Tuple class.
Environments
Section titled “Environments”Most of the environments that include continuous action spaces are related to the physical world, so physics simulations are normally used. There are lots of software packages that can simulate physical processes, from very simple open source tools to complex commercial packages that can simulate multiphysics processes (such as fluid, burning, and strength simulations).
In the case of robotics, one of the most popular packages is MuJoCo, which stands for Multi-Joint dynamics with Contact (https://www.mujoco.org). This is a physics engine in which you can define the components of the system and their interaction and properties. Then the simulator is responsible for solving the system by taking into account your intervention and finding the parameters (usually the location, velocities, and accelerations) of the components. This makes it ideal as a playground for RL environments, as you can define fairly complicated systems (such as multipede robots, robotic arms, or humanoids) and then feed the observation into the RL agent, getting actions back.
For a long time, MuJoCo was a commercial package and required an expensive license to be purchased. Trial licenses and education licenses existed, but they limited the audience for this software. But in 2022, DeepMind acquired MuJoCo and made the source code publicly available for everybody, which was a really great and generous move. Farama Gymnasium includes several MuJoCo environments (https://gymnasium.farama.org/environments/mujoco/) out of the box; to get them working, you need to install the gymnasium[mujoco] package.
Besides MuJoCo, there are other physics simulators you can use for RL. One of the most popular is PyBullet (https://pybullet.org/), which was open source from the very beginning. In this chapter, we’ll use PyBullet in our experiments, and later in the book, we’ll take a look at MuJoCo as well. To install PyBullet, you need to execute pip install pybullet==3.2.6 in your Python environment. As PyBullet wasn’t updated to the Gymnasium API, we also need to install OpenAI Gym for compatibility:
pip install gym==0.25.1We use version 0.25.1, as later versions of OpenAI Gym are not compatible with the latest version of PyBullet.
The following code (which is available in Chapter15/01_check_env.py) allows you to check that PyBullet works. It looks at the action space and renders an image of the environment that we will use as a guinea pig in this chapter:
import gymnasium as gym
ENV_ID = "MinitaurBulletEnv-v0"ENTRY = "pybullet_envs.bullet.minitaur_gym_env:MinitaurBulletEnv"RENDER = True
if __name__ == "__main__": gym.register(ENV_ID, entry_point=ENTRY, max_episode_steps=1000, reward_threshold=15.0, disable_env_checker=True) env = gym.make(ENV_ID, render=RENDER)
print("Observation space:", env.observation_space) print("Action space:", env.action_space) print(env) print(env.reset()) input("Press any key to exit\n") env.close()After you start the utility, it should open the graphical user interface (GUI) window with our four-legged robot, shown in the following figure, that we will train to move:

Figure 15.1: The Minitaur environment in the PyBullet GUI (for better visualization, refer to )
This environment provides you with 28 numbers as the observation and they correspond to different physical parameters of the robot: velocity, position, and acceleration. (You can check the source code of MinitaurBulletEnv-v0 for details.) The action space is eight numbers that define the parameters of the motors. There are two in every leg (one in every knee). The reward of this environment is the distance traveled by the robot minus the energy spent.
The A2C method
Section titled “The A2C method”The first method that we will apply to our walking robot problem is A2C, which we experimented with in Part 3 of the book. This choice of method is quite obvious, as A2C is very easy to adapt to the continuous action domain. As a quick refresher, A2C’s idea is to estimate the gradient of our policy as ∇J = ∇ 𝜃 log π 𝜃 (a|s)(R −V 𝜃 (s)). The policy π 𝜃 (s) is supposed to provide the probability distribution of actions given the observed state. The quantity V 𝜃 (s) is called a critic, equal to the value of the state, and is trained using the mean squared error (MSE) loss between the critic’s return and the value estimated by the Bellman equation. To improve exploration, the entropy bonus L H = π 𝜃 (s)log π 𝜃 (s) is usually added to the loss.
Obviously, the value head of the actor-critic will be unchanged for continuous actions. The only thing that is affected is the representation of the policy. In the discrete cases that we have seen, we had only one action with several mutually exclusive discrete values. For such a case, the obvious representation of the policy was the probability distribution over all actions.
In a continuous case, we usually have several actions, each of which can take a value from some range. With that in mind, the simplest policy representation will be just those values returned for every action. These values should not be confused with the value of the state, V (s), which indicates how many rewards we can get from the state. To illustrate the difference, let’s imagine a simple car steering case in which we can only turn the wheel. The action at every moment will be the wheel angle (action value), but the value of every state will be the potential discounted reward from the state (for example, the distance the car can travel), which is a totally different thing.
Returning to our action representation options, if you remember what we covered in the Policy representation section in Chapter 11, the representation of an action as a concrete value has different disadvantages, mostly related to the exploration of the environment. A much better choice will be something stochastic, for example, the network returning parameters of the Gaussian distribution. For N actions, those parameters will be two vectors of size N. The first will be the mean values, μ, and the second vector will contain variances, σ 2. In that case, our policy will be represented as a random N-dimensional vector of uncorrelated, normally distributed random variables, and our network can make a selection about the mean and the variance of every variable.
By definition, the probability density function of the Gaussian distribution is given by

We could directly use this formula to get the probabilities, but to improve numerical stability, it is worth doing some math and simplifying the expression for log π 𝜃 (a|s).
The final result will be this:

The entropy of the Gaussian distribution could be obtained using the differential entropy definition and will be. Now we have everything we need to implement the A2C method, so let’s do this.
Implementation
Section titled “Implementation”The complete source code is in 02_train_a2c.py, lib/model.py, and lib/common.py. You will be familiar with most of the code, so the following includes only the parts that differ. Let’s start with the model class defined in lib/model.py:
HID_SIZE = 128
class ModelA2C(nn.Module): def __init__(self, obs_size: int, act_size: int): super(ModelA2C, self).__init__()
self.base = nn.Sequential( nn.Linear(obs_size, HID_SIZE), nn.ReLU(), ) self.mu = nn.Sequential( nn.Linear(HID_SIZE, act_size), nn.Tanh(), ) self.var = nn.Sequential( nn.Linear(HID_SIZE, act_size), nn.Softplus(), ) self.value = nn.Linear(HID_SIZE, 1)As you can see, our network has three heads, instead of the normal two for a discrete variant of A2C. The first two heads return the mean value and the variance of the actions, while the last is the critic head returning the value of the state. The mean value returned has an activation function of a hyperbolic tangent, which is the squashed output to the range of −1…1. The variance is transformed with the softplus activation function, which is log(1 + e x) and has the shape of a smoothed rectified linear unit (ReLU) function. This activation helps to make our variance positive. The value head, as usual, has no activation function applied.
The forward pass is obvious; we apply the common layer first, and then we calculate individual heads:
def forward(self, x: torch.Tensor): base_out = self.base(x) return self.mu(base_out), self.var(base_out), self.value(base_out)The next step is to implement the PTAN Agent class, which is used to convert the observation into actions:
class AgentA2C(ptan.agent.BaseAgent): def __init__(self, net: ModelA2C, 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, var_v, _ = self.net(states_v) mu = mu_v.data.cpu().numpy() sigma = torch.sqrt(var_v).data.cpu().numpy() actions = np.random.normal(mu, sigma) actions = np.clip(actions, -1, 1) return actions, agent_statesIn the discrete case, we used the ptan.agent.DQNAgent and ptan.agent.PolicyAgent classes, but for our problem, we need to write our own, which is not complicated: you just need to write a class, derived from ptan.agent.BaseAgent, and override the __call__ method, which needs to convert observations into actions.
In this class, we get the mean and the variance from the network and sample the normal distribution using NumPy functions. To prevent the actions from going outside of the environment’s −1…1 bounds, we use np.clip(), which replaces all values less than -1 with -1, and values more than 1 with 1. The agent_states argument is not used, but it needs to be returned with the chosen actions, as our BaseAgent supports keeping the state of the agent. We don’t need this functionality right now, but it will be handy in the next section on deep deterministic policy gradients, when we will need to implement a random exploration using the Ornstein-Uhlenbeck (OU) process.
With the model and the agent at hand, we can now go to the training process, defined in 02_train_a2c.py. It consists of the training loop and two functions. The first is used to perform periodical tests of our model on the separate testing environment. During the testing, we don’t need to do any exploration; we will just use the mean value returned by the model directly, without any random sampling. The testing function is as follows:
def test_net(net: model.ModelA2C, env: gym.Env, count: int = 10, device: torch.device = torch.device("cpu")): rewards = 0.0 steps = 0 for _ in range(count): obs, _ = env.reset() while True: obs_v = ptan.agent.float32_preprocessor([obs]) obs_v = obs_v.to(device) mu_v = net(obs_v)[0] action = mu_v.squeeze(dim=0).data.cpu().numpy() action = np.clip(action, -1, 1) obs, reward, done, is_tr, _ = env.step(action) rewards += reward steps += 1 if done or is_tr: break return rewards / count, steps / countThe second function defined in the training module implements the calculation of the logarithm of the taken actions’ probabilities given the policy. The function is a straightforward implementation of the formula we saw earlier:

def calc_logprob(mu_v: torch.Tensor, var_v: torch.Tensor, actions_v: torch.Tensor): p1 = - ((mu_v - actions_v) ** 2) / (2*var_v.clamp(min=1e-3)) p2 = - torch.log(torch.sqrt(2 * math.pi * var_v)) return p1 + p2The only tiny difference is in using the torch.clamp() function to prevent the division on zero when the returned variance is too small.
The training loop, as usual, creates the network and the agent, and then instantiates the two-step experience source and optimizer. The hyperparameters used are given as follows. They weren’t tweaked much, so there is plenty of room for optimization:
GAMMA = 0.99REWARD_STEPS = 2BATCH_SIZE = 32LEARNING_RATE = 5e-5ENTROPY_BETA = 1e-4
TEST_ITERS = 1000The code used to perform the optimization step on the collected batch is very similar to the A2C training that we implemented in Chapter 12. The difference is only in using our calc_logprob() function and a different expression for the entropy bonus, which is shown next:
states_v, actions_v, vals_ref_v = common.unpack_batch_a2c( batch, net, device=device, last_val_gamma=GAMMA ** REWARD_STEPS)batch.clear()
optimizer.zero_grad()mu_v, var_v, value_v = net(states_v)
loss_value_v = F.mse_loss(value_v.squeeze(-1), vals_ref_v)adv_v = vals_ref_v.unsqueeze(dim=-1) - value_v.detach()log_prob_v = adv_v * calc_logprob(mu_v, var_v, actions_v)loss_policy_v = -log_prob_v.mean()ent_v = -(torch.log(2*math.pi*var_v) + 1)/2entropy_loss_v = ENTROPY_BETA * ent_v.mean()
loss_v = loss_policy_v + entropy_loss_v + loss_value_vloss_v.backward()optimizer.step()Every TEST_ITERS frames, the model is tested, and in the case of the best reward obtained, the model weights are saved.
Results
Section titled “Results”In comparison to other methods that we will look at in this chapter, A2C shows the worst results, both in terms of the best reward and convergence speed. That’s likely because of the single environment used to gather experience, which is a weak point of the policy gradient (PG) methods. So, you may want to check the effect of several parallel environments on A2C.
To start the training, we pass the -n argument with the run name, which will be used in TensorBoard and a new directory to save the models. The —dev option could be used to enable the GPU usage, but due to the small dimensionality of the input and the tiny network size, it gives only a marginal increase in speed.
After 9M frames, which took 16 hours of optimization, the training process reached the best score of 0.35 during the testing, which is not very impressive. If we leave it running for a week or two, we might be able to achieve a better score. The reward and episode steps during the training and testing are shown in the following graphs:

Figure 15.2: The reward (left) and steps (right) for training episodes

Figure 15.3: The reward (left) and steps (right) for testing episodes
The episode steps charts (right plots on both figures) shows the average count of steps performed in the episode before the end. The time limit of the environment is 1,000 steps, so everything lower than 1,000 indicates that the episode was stopped due to environment checks. For most of the PyBullet environments, special checks for self-damage are implemented internally, which stop the simulation.
Using models and recording videos
Section titled “Using models and recording videos”As you have seen before, the physical simulator can render the state of the environment, which makes it possible to see how our trained model behaves. To do that for our A2C models, there is a utility, 03_play_a2c.py. Its logic is the same as in the test_net() function, so its code is not shown here.
To start it, you need to pass the -m option with the model file and optional parameter -r with a directory name, which will be used to save the video using the RecordVideo wrapper we discussed in Chapter 2.
At the end of the simulation, the utility shows the number of steps and accumulated reward. For example, the best A2C model from my training was able to get the reward 0.312 and the video is just 2 seconds long (you can find it here: https://youtu.be/s9BReDUtpQs). Figure 15.4 shows the last frame of the video and it looks like our model had problems keeping the balance.

Figure 15.4: Last frame of A2C model simulation
Deep deterministic policy gradients
Section titled “Deep deterministic policy gradients”The next method that we will take a look at is called deep deterministic policy gradients (DDPG), which is an actor-critic method but has a very nice property of being off-policy. The following is a simplified interpretation of the strict proofs. If you are interested in understanding the core of this method deeply, you can always refer to the article by Silver et al. called Deterministic policy gradient algorithms [Sil+14], published in 2014, and the paper by Lillicrap et al. called Continuous control with deep reinforcement learning [Lil15], published in 2015.
The simplest way to illustrate the method is through comparison with the already familiar A2C method. In this method, the actor estimates the stochastic policy, which returns the probability distribution over discrete actions or, as we have just covered in the previous section, the parameters of normal distribution. In both cases, our policy is stochastic, so, in other words, our action taken is sampled from this distribution.
Deterministic policy gradients also belong to the A2C family, but the policy is deterministic, which means that it directly provides us with the action to take from the state. This makes it possible to apply the chain rule to the Q-value, and by maximizing the Q, the policy will be improved as well. To understand this, let’s look at how the actor and critic are connected in a continuous action domain.
Let’s start with the actor, as it is the simpler of the two. What we want from it is the action to take for every given state. In a continuous action domain, every action is a number, so the actor network will take the state as an input and return N values, one for every action. This mapping will be deterministic, as the same network always returns the same output if the input is the same. (We’re not going to use dropout or anything adding stochasticity to the inference; we’re just going to use an ordinary feed-forward network.)
Now let’s look at the critic. The role of the critic is to estimate the Q-value, which is a discounted reward of the action taken in some state. However, our action is a vector of numbers, so our critic network now accepts two inputs: the state and the action. The output from the critic will be the single number, which corresponds to the Q-value. This architecture is different from the DQN, when our action space was discrete and, for efficiency, we returned values for all actions in one pass. This mapping is also deterministic.
So, we have two functions:
- The actor, let’s call it μ(s), which converts the state into the action
- The critic, which, through the state and the action, gives us the Q-value: Q(s,a)
We can substitute the actor function into the critic and get the expression with only one input parameter of our state: Q(s,μ(s)). In the end, neural networks are just functions.
Now, the output of the critic gives us the approximation of the entity that we’re interested in maximizing in the first place: the discounted total reward. This value depends not only on the input state but also on the parameters of the 𝜃 μ actor and the 𝜃 Q critic networks. At every step of our optimization, we want to change the actor’s weights to improve the total reward that we get. In mathematical terms, we want the gradient of our policy.
In his deterministic policy gradient theorem, Silver et al. proved that the stochastic policy gradient is equivalent to the deterministic policy gradient. In other words, to improve the policy, we just need to calculate the gradient of the Q(s,μ(s)) function. By applying the chain rule, we get the gradient: ∇ a Q(s,a)∇ 𝜃 μ μ(s).
Note that, despite both the A2C and DDPG methods belonging to the A2C family, the way that the critic is used is different. In A2C, we use the critic as a baseline for a reward from the experienced trajectories, so the critic is an optional piece (without it, we will get the REINFORCE method) and is used to improve the stability. This happens as the policy in A2C is stochastic, which builds a barrier in our backpropagation capabilities (we have no way of differentiating the random sampling step).
In DDPG, the critic is used in a different way. As our policy is deterministic, we can now calculate the gradients from Q, which is obtained from the critic network, which uses actions produced by the actor (check Figure 15.5), so the whole system is differentiable and could be optimized end to end with stochastic gradient descent (SGD). To update the critic network, we can use the Bellman equation to find the approximation of Q(s,a) and minimize the MSE objective.
All this may look a bit cryptic, but behind it stands a quite simple idea: the critic is updated as we did in A2C, and the actor is updated in a way to maximize the critic’s output. The beauty of this method is that it is off-policy, which means that we can now have a huge replay buffer and other tricks that we used in DQN training. Nice, right?
Exploration
Section titled “Exploration”The price we have to pay for all this goodness is that our policy is now deterministic, so we have to explore the environment somehow. We can do this by adding noise to the actions returned by the actor before we pass them to the environment. There are several options here. The simplest method is just to add the random noise to the actions: μ(s) + 𝜖𝒩. We will use this in the next method that we will consider in this chapter.
A more advanced (and sometimes giving better results) approach to the exploration is to use the previously mentioned Ornstein-Uhlenbeck process, which is very popular in the financial world and other domains dealing with stochastic processes. This process models the velocity of a massive Brownian particle under the influence of friction and is defined by this stochastic differential equation:
∂x t = 𝜃(μ −x t)∂t + σ∂W,
where 𝜃, μ, and σ are parameters of the process and W t is the Wiener process. In a discrete-time case, the OU process could be written as
x t+1 = x t + 𝜃(μ −x) + σ𝒩.
This equation expresses the next value generated by the process via the previous value of the noise, adding normal noise, 𝒩. In our exploration, we will add the value of the OU process to the action returned by the actor.
Implementation
Section titled “Implementation”This example consists of three source files:
- lib/model.py contains the model and the PTAN agent
- lib/common.py has a function used to unpack the batch
- 04_train_ddpg.py has the startup code and the training loop
Here, I will show only the significant pieces of the code. The model consists of two separate networks for the actor and critic, and it follows the architecture from the paper by Lillicrap et al. [Lil15] mentioned earlier. The actor is extremely simple and is a feed-forward network with two hidden layers. The input is an observation vector, whereas the output is a vector with N values, one for each action. The output actions are transformed with hyperbolic tangent nonlinearity to squeeze the values to the −1…1 range.
The critic is a bit unusual, as it includes two separate paths for the observation and the actions, and those paths are concatenated together to be transformed into the critic output of one number. Figure 15.5 shows the structure of both networks:

Figure 15.5: The DDPG actor and critic networks
The code for the actor includes a three-layer network that produces the action value:
class DDPGActor(nn.Module): def __init__(self, obs_size: int, act_size: int): super(DDPGActor, self).__init__()
self.net = nn.Sequential( nn.Linear(obs_size, 400), nn.ReLU(), nn.Linear(400, 300), nn.ReLU(), nn.Linear(300, act_size), nn.Tanh() )
def forward(self, x: torch.Tensor): return self.net(x)Similarly, the following is the code used for the critic:
class DDPGCritic(nn.Module): def __init__(self, obs_size: int, act_size: int): super(DDPGCritic, self).__init__()
self.obs_net = nn.Sequential( nn.Linear(obs_size, 400), nn.ReLU(), )
self.out_net = nn.Sequential( nn.Linear(400 + act_size, 300), nn.ReLU(), nn.Linear(300, 1) )
def forward(self, x: torch.Tensor, a: torch.Tensor): obs = self.obs_net(x) return self.out_net(torch.cat([obs, a], dim=1))The forward() function of the critic first transforms the observations with its small network and then concatenates the output and given actions to transform them into one single value of Q. To use the actor network with the PTAN experience source, we need to define the agent class that has to transform the observations into actions. This class is the most convenient place to put our OU exploration process, but to do this properly, we should use the functionality of the PTAN agents that we haven’t used so far: optional statefulness.
The idea is simple: our agent transforms the observations into actions. But what if it needs to remember something between the observations? All our examples have been stateless so far, but sometimes this is not enough. The issue with OU is that we have to track the OU values between the observations.
Another very useful use case for stateful agents is a partially observable Markov decision process (POMDP), which was briefly mentioned in Chapter 6 and Chapter 14. The POMDP is a Markov decision process when the state observed by the agent doesn’t comply with the Markov property and doesn’t include the full information to distinguish one state from another. In that case, our agent needs to track the state along the trajectory to be able to take the action.
So, the code for the agent that implements the OU for exploration is as follows:
class AgentDDPG(ptan.agent.BaseAgent): def __init__(self, net: DDPGActor, device: torch.device = torch.device(’cpu’), ou_enabled: bool = True, ou_mu: float = 0.0, ou_teta: float = 0.15, ou_sigma: float = 0.2, ou_epsilon: float = 1.0): self.net = net self.device = device self.ou_enabled = ou_enabled self.ou_mu = ou_mu self.ou_teta = ou_teta self.ou_sigma = ou_sigma self.ou_epsilon = ou_epsilon
def initial_state(self): return NoneThe constructor accepts a lot of parameters, most of which are the default hyperparameters of the OU process taken from the paper Continuous Control with Deep Reinforcement Learning.
The initial_state() method is derived from the BaseAgent class and has to return the initial state of the agent when a new episode is started. As our initial state has to have the same dimension as the actions (we want to have individual exploration trajectories for every action of the environment), we postpone the initialization by returning None as the initial state.
In the __call__ method, we’ll take this into account:
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) actions = mu_v.data.cpu().numpy()This method is the core of the agent and the purpose of it is to convert the observed state and internal agent state into the action. As the first step, we convert the observations into the appropriate form and ask the actor network to convert them into deterministic actions. The rest of the method is for adding the exploration noise by applying the OU process.
In this loop, we iterate over the batch of observations and the list of the agent states from the previous call, and we update the OU process value, which is a straightforward implementation of the already shown formula:
if self.ou_enabled and self.ou_epsilon > 0: new_a_states = [] for a_state, action in zip(agent_states, actions): if a_state is None: a_state = np.zeros(shape=action.shape, dtype=np.float32) a_state += self.ou_teta * (self.ou_mu - a_state) a_state += self.ou_sigma * np.random.normal(size=action.shape)
action += self.ou_epsilon * a_state new_a_states.append(a_state)To finalize the loop, we add the noise from the OU process to our actions and save the noise value for the next step.
Finally, we clip the actions to enforce them to fall into the −1…1 range; otherwise, PyBullet will throw an exception:
else: new_a_states = agent_statesactions = np.clip(actions, -1, 1)return actions, new_a_statesThe final piece of the DDPG implementation is the training loop in the 04_train_ddpg.py file. To improve the stability, we use the replay buffer with 100,000 transitions and target networks for both the actor and the critic (we discussed both in Chapter 6):
act_net = model.DDPGActor(env.observation_space.shape[0], env.action_space.shape[0]).to(device)crt_net = model.DDPGCritic(env.observation_space.shape[0], env.action_space.shape[0]).to(device)print(act_net)print(crt_net)tgt_act_net = ptan.agent.TargetNet(act_net)tgt_crt_net = ptan.agent.TargetNet(crt_net)
writer = SummaryWriter(comment="-ddpg_" + args.name)agent = model.AgentDDPG(act_net, device=device)exp_source = ptan.experience.ExperienceSourceFirstLast( env, agent, gamma=GAMMA, steps_count=1)buffer = ptan.experience.ExperienceReplayBuffer(exp_source, buffer_size=REPLAY_SIZE)act_opt = optim.Adam(act_net.parameters(), lr=LEARNING_RATE)crt_opt = optim.Adam(crt_net.parameters(), lr=LEARNING_RATE)We also use two different optimizers to simplify the way that we handle gradients for the actor and critic training steps. The most interesting code is inside the training loop. On every iteration, we store the experience into the replay buffer and sample the training batch:
batch = buffer.sample(BATCH_SIZE)states_v, actions_v, rewards_v, dones_mask, last_states_v = \ common.unpack_batch_ddqn(batch, device)Then, two separate training steps are performed. To train the critic, we need to calculate the target Q-value using the one-step Bellman equation, with the target critic network as the approximation of the next state:
crt_opt.zero_grad()q_v = crt_net(states_v, actions_v)last_act_v = tgt_act_net.target_model(last_states_v)q_last_v = tgt_crt_net.target_model(last_states_v, last_act_v)q_last_v[dones_mask] = 0.0q_ref_v = rewards_v.unsqueeze(dim=-1) + q_last_v * GAMMAWhen we have got the reference, we can calculate the MSE loss and ask the critic’s optimizer to tweak the critic’s weights. The whole process is similar to the training for the DQN, so nothing is really new here:
critic_loss_v = F.mse_loss(q_v, q_ref_v.detach())critic_loss_v.backward()crt_opt.step()tb_tracker.track("loss_critic", critic_loss_v, frame_idx)tb_tracker.track("critic_ref", q_ref_v.mean(), frame_idx)On the actor’s training step, we need to update the actor’s weights in a direction that will increase the critic’s output. As both the actor and critic are represented as differentiable functions, what we need to do is just pass the actor’s output to the critic and then minimize the negated value returned by the critic:
act_opt.zero_grad()cur_actions_v = act_net(states_v)actor_loss_v = -crt_net(states_v, cur_actions_v)actor_loss_v = actor_loss_v.mean()This negated output of the critic could be used as a loss to backpropagate it to the critic network and, finally, the actor. We don’t want to touch the critic’s weights, so it’s important to ask only the actor’s optimizer to do the optimization step. The weights of the critic will still keep the gradients from this call, but they will be discarded on the next optimization step:
actor_loss_v.backward()act_opt.step()tb_tracker.track("loss_actor", actor_loss_v, frame_idx)As the last step of the training loop, we perform the update of the target networks in an unusual way:
tgt_act_net.alpha_sync(alpha=1 - 1e-3)tgt_crt_net.alpha_sync(alpha=1 - 1e-3)Previously, we synced the weights from the optimized network into the target periodically. In continuous action problems, such syncing works worse than so-called “soft sync.” The soft sync is carried out on every step, but only a small ratio of the optimized network’s weights are added to the target network. This makes a smooth and slow transition from the old weight to the new ones.
Results and video
Section titled “Results and video”The code can be started in the same way as the A2C example: you need to pass the run name and optional —dev flag. My experiments have shown ≈ 30% speed increase from a GPU, so if you’re in a hurry, using CUDA may be a good idea, but the increase is not that dramatic, as we have seen in the case of Atari games.
After 5M observations, which took about 20 hours, the DDPG algorithm was able to reach the mean reward of 4.5 on 10 test episodes, which is an improvement over the A2C result. The training dynamics are shown in Figure 15.6 and Figure 15.7.

Figure 15.6: The reward (left) and steps (right) for training episodes

Figure 15.7: Actor loss (left) and critic loss (right) during the training
The “Episode steps” plot shows the mean length of the episodes that we used for training. The critic loss is an MSE loss and should be low, but the actor loss, as you will remember, is the negated critic’s output, so the smaller it is, the better the reward that the actor can (potentially) achieve.
In Figure 15.8, the shown values were obtained during the testing (which are average values obtained for 10 episodes).

Figure 15.8: The reward (left) and steps (right) for testing episodes
To test the saved model and record the video the same way we did for the A2C model, you can use the utility 05_play_ddpg.py. It uses the same command-line options, but is supposed to load DDPG models. In figure Figure 15.9, the last frame of my video is shown:

Figure 15.9: Last frame of DDPG model simulation
The score during the testing was 3.033 and the video is avaliable at https://youtu.be/vVnd0Nu1d9s. Now the video is 11 seconds long and the model fails after falling forward.
Distributional policy gradients
Section titled “Distributional policy gradients”As the last method of this chapter, we will take a look at the paper by Barth-Maron et al., called Distributed distributional deterministic policy gradients [Bar+18], published in 2018.
The full name of the method is Distributed Distributional Deep Deterministic Policy Gradients or D4PG for short. The authors proposed several improvements to the DDPG method to improve stability, convergence, and sample efficiency.
First, they adapted the distributional representation of the Q-value proposed in the paper by Bellemare et al. called A distributional perspective on reinforcement learning, published in 2017 [BDM17]. We discussed this approach in Chapter 8, when we talked about DQN improvements, so refer to it or to the original Bellemare paper for details. The core idea is to replace a single Q-value from the critic with a probability distribution. The Bellman equation is replaced with the Bellman operator, which transforms this distributional representation in a similar way. The second improvement was the usage of the n-step Bellman equation, unrolled to speed up the convergence. We also discussed this in detail in Chapter 8.
Another difference versus the original DDPG method was the usage of the prioritized replay buffer instead of the uniformly sampled buffer. So, strictly speaking, the authors took relevant improvements from the paper by Hassel et al., called Rainbow: Combining Improvements in Deep Reinforcement Learning, which was published in 2017 [Hes+18], and adapted them to the DDPG method. The result was impressive: this combination showed state-of-the-art results on the set of continuous control problems. Let’s try to reimplement the method and check it ourselves.
Architecture
Section titled “Architecture”The most notable change between D4PG and DDPG is the critic’s output. Instead of returning the single Q-value for the given state and the action, it now returns N_ATOMS values, corresponding to the probabilities of values from the predefined range. In my code, I used N_ATOMS=51 and the distribution range of Vmin=-10 and Vmax=10, so the critic returned 51 numbers, representing the probabilities of the discounted reward falling into bins with bounds in [−10,−9.6,−9.2,…,9.6,10].
Another difference between D4PG and DDPG is the exploration. DDPG used the OU process for exploration, but according to the D4PG authors, they tried both OU and adding simple random noise to the actions, and the result was the same. So, they used a simpler approach for exploration in the paper.
The last significant difference in the code is related to the training, as D4PG uses cross-entropy loss to calculate the difference between two probability distributions (returned by the critic and obtained as a result of the Bellman operator). To make both distributions aligned to the same supporting atoms, distribution projection is used in the same way as in the original paper by Bellemare et al.
Implementation
Section titled “Implementation”The complete source code is in 06_train_d4pg.py, lib/model.py, and lib/common.py. As before, we start with the model class. The actor class has exactly the same architecture as in DDPG, so during the training class, DDPGActor is used. The critic has the same size and count of hidden layers; however, the output is not a single number, but N_ATOMS:
class D4PGCritic(nn.Module): def __init__(self, obs_size: int, act_size: int, n_atoms: int, v_min: float, v_max: float): super(D4PGCritic, self).__init__()
self.obs_net = nn.Sequential( nn.Linear(obs_size, 400), nn.ReLU(), )
self.out_net = nn.Sequential( nn.Linear(400 + act_size, 300), nn.ReLU(), nn.Linear(300, n_atoms) )
delta = (v_max - v_min) / (n_atoms - 1) self.register_buffer("supports", torch.arange(v_min, v_max + delta, delta))We also create a helper PyTorch buffer with reward supports, which will be used to get from the probability distribution to the single mean Q-value:
def forward(self, x: torch.Tensor, a: torch.Tensor): obs = self.obs_net(x) return self.out_net(torch.cat([obs, a], dim=1))
def distr_to_q(self, distr: torch.Tensor): weights = F.softmax(distr, dim=1) * self.supports res = weights.sum(dim=1) return res.unsqueeze(dim=-1)As you can see, softmax() application is not part of the network’s forward() method, as we’re going to use the more stable log_softmax() function during the training. Due to this, softmax() needs to be applied when we want to get actual probabilities.
The agent class is much simpler for D4PG and has no state to track:
class AgentD4PG(ptan.agent.BaseAgent): def __init__(self, net: DDPGActor, device: torch.device = torch.device("cpu"), epsilon: float = 0.3): self.net = net self.device = device self.epsilon = epsilon
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) actions = mu_v.data.cpu().numpy() actions += self.epsilon * np.random.normal(size=actions.shape) actions = np.clip(actions, -1, 1) return actions, agent_statesFor every state to be converted to actions, the agent applies the actor network and adds Gaussian noise to the actions, scaled by the epsilon value. In the training code, we have the following hyperparameters:
GAMMA = 0.99BATCH_SIZE = 64LEARNING_RATE = 1e-4REPLAY_SIZE = 100000REPLAY_INITIAL = 10000REWARD_STEPS = 5
TEST_ITERS = 1000
Vmax = 10Vmin = -10N_ATOMS = 51DELTA_Z = (Vmax - Vmin) / (N_ATOMS - 1)I used a smaller replay buffer of 100,000, and it worked fine. (In the D4PG paper, the authors used 1M transitions in the buffer.) The buffer is prepopulated with 10,000 samples from the environment, and then the training starts.
For every training loop, we perform the same two steps as before: we train the critic and the actor. The difference is in the way that the loss for the critic is calculated:
batch = buffer.sample(BATCH_SIZE)states_v, actions_v, rewards_v, dones_mask, last_states_v = \ common.unpack_batch_ddqn(batch, device)
crt_opt.zero_grad()crt_distr_v = crt_net(states_v, actions_v)last_act_v = tgt_act_net.target_model(last_states_v)last_distr_v = F.softmax( tgt_crt_net.target_model(last_states_v, last_act_v), dim=1)As the first step in the critic’s training, we ask it to return the probability distribution for the states and actions taken. This probability distribution will be used as an input in the cross-entropy loss calculation. To get the target probability distribution, we need to calculate the distribution from the last states in the batch and then perform the Bellman projection of the distribution:
proj_distr = distr_projection( last_distr_v.detach().cpu().numpy(), rewards_v.detach().cpu().numpy(), dones_mask.detach().cpu().numpy(), gamma=GAMMA**REWARD_STEPS)proj_distr_v = torch.tensor(proj_distr).to(device)This projection function is a bit complicated and is exactly the same as the implementation explained in detail in Chapter 8. As a quick reminder, it calculates the transformation of the last_states probability distribution, which is shifted according to the immediate reward and scaled to respect the discount factor. The result is the target probability distribution that we want our network to return. As there is no general cross-entropy loss function in PyTorch, we calculate it manually by multiplying the logarithm of the input probability by the target probabilities:
prob_dist_v = -F.log_softmax(crt_distr_v, dim=1) * proj_distr_vcritic_loss_v = prob_dist_v.sum(dim=1).mean()critic_loss_v.backward()crt_opt.step()The actor’s training is much simpler, and the only difference from the DDPG method is the use of the distr_to_q() method of the model to convert from the probability distribution to the single mean Q-value using support atoms:
act_opt.zero_grad()cur_actions_v = act_net(states_v)crt_distr_v = crt_net(states_v, cur_actions_v)actor_loss_v = -crt_net.distr_to_q(crt_distr_v)actor_loss_v = actor_loss_v.mean()actor_loss_v.backward()act_opt.step()Results
Section titled “Results”The D4PG method showed the best results in both convergence speed and the reward obtained. Following 20 hours of training, after about 3.5M observations, it was able to reach the mean test reward of 17.912. Given that “gym environment threshold” is 15.0 (which is a score when the environment considered it solved), that is a great result. And this result could be improved, as the count of steps is less than 1,000 (which is a time limit for the environment). This means that our model is being terminated prematurely because of internal environment checks. In Figure 15.10 and Figure 15.11, we have the train and test metrics.

Figure 15.10: The reward (left) and steps (right) for training episodes

Figure 15.11: The reward (left) and steps (right) for testing episodes
To compare the implemented methods, Figure 15.12 contains test episode metrics from all three methods.

Figure 15.12: The reward (left) and steps (right) for test episodes
To check the model “in action,” you can use the same tool, 05_play_ddpg.py (as actor has the same network structure as in DDPG). Now the video produced by the best model lasts 33 seconds and the final score was 17.827. You can watch it here: https://youtu.be/XZdVrGPaI0M.
Things to try
Section titled “Things to try”Here is a list of things you can do to improve your understanding of the topic:
- In the D4PG code, I used a simple replay buffer, which was enough to get good improvement over DDPG. You can try to switch the example to the prioritized replay buffer in the same way as we did in Chapter 8.
- There are lots of interesting and challenging environments around. For example, you can start with other PyBullet environments, but there is also the DeepMind Control Suite (Tassa et al., DeepMind Control Suite, arXiv abs/1801.00690 (2018)), MuJoCo-based environments in Gym, and many others.
- You can play with the very challenging Learning to Run competition from NIPS-2017 (which also took place in 2018 and 2019 with more challenging problems), where you are given a simulator of the human body and your agent needs to figure out how to move it around.
Summary
Section titled “Summary”In this chapter, we quickly skimmed through the very interesting domain of continuous control using RL methods, and we checked three different algorithms on one problem of a four-legged robot. In our training, we used an emulator, but there are real models of this robot made by the Ghost Robotics company. (You can check out the cool video on YouTube: https://youtu.be/bnKOeMoibLg.) We applied three training methods to this environment: A2C, DDPG, and D4PG (which showed the best results).
In the next chapter, we will continue exploring the continuous action domain and check a different set of improvements: trust region extension.
Get This Book’s PDF Version and Exclusive Extras
|