Skip to content
ImagineWorld

Higher-Level RL Libraries

node_idnode-book_deep-reinforcement-learning-hands-on_chapter-07-higher-level-rl-libraries
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleHigher-Level RL Libraries
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In Chapter 6, we implemented the deep Q-network (DQN) model published by DeepMind in 2015 [Mni+15]. This paper had a significant effect on the RL field by demonstrating that, despite common belief, it’s possible to use nonlinear approximators in RL. This proof of concept stimulated great interest in the deep Q-learning field and in deep RL in general.

In this chapter, we will take another step toward a practical RL by discussing higher-level RL libraries, which will allow you to build your code from higher-level blocks and focus on the details of the method that you are implementing, avoiding reimplementing the same logic multiple times. Most of the chapter will describe the PyTorch AgentNet (PTAN) library, which will be used in the rest of the book to prevent code repetition, so will be covered in detail.

We will cover:

  • The motivation for using high-level libraries, rather than reimplementing everything from scratch
  • The PTAN library, including coverage of the most important parts, which will be illustrated with code examples
  • DQN on CartPole, implemented using the PTAN library
  • Other RL libraries that you might consider

Our implementation of basic DQN in Chapter 6 wasn’t very, long and complicated—about 200 lines of training code plus 50 lines in environment wrappers. When you are becoming familiar with RL methods, it is very useful to implement everything yourself to understand how things actually work. However, the more involved you become in the field, the more often you will realize that you are writing the same code over and over again.

This repetition comes from the generality of RL methods. As we discussed in Chapter 1, RL is quite flexible, and many real-life problems fall into the environment-agent interaction scheme. RL methods don’t make many assumptions about the specifics of observations and actions, so code implemented for the CartPole environment will be applicable to Atari games (maybe with some minor tweaks).

Writing the same code over and over again is not very efficient, as bugs might be introduced every time, which will cost you time for debugging and understanding. In addition, carefully designed code that has been used in several projects usually has a higher quality in terms of performance, unit tests, readability, and documentation.

The practical applications of RL are quite young by computer science standards, so in comparison to other more mature domains, you might not have that rich a choice of approaches. For example, in web development, even if you limit yourself to just Python, you have hundreds of very good libraries of all sorts: Django for heavyweight, fully functional websites; Flask for light Web Server Gateway Interface (WSGI) apps; and much more, large and small.

RL is not as mature as web frameworks, but still, you can choose from several projects that are trying to simplify RL practitioners’ lives. In addition, you can always write your own set of tools, as I did several years ago. The tool I created is a library called PTAN, and, as mentioned, it will be used in the rest of the book to illustrate examples.

This library is available on GitHub: https://github.com/Shmuma/ptan. All the subsequent examples were implemented using version 0.8 of PTAN, which can be installed in your virtual environment by running the following:

$ pip install ptan==0.8

The original goal of PTAN was to simplify my RL experiments, and it tries to keep the balance between two extremes:

  • Import the library and then write just a couple of lines with tons of parameters to train one of the provided methods, like DQN (a very vivid example is the OpenAI Baselines and Stable Baselines3 projects). This first approach is very inflexible. It works well when you are using the library the way it is supposed to be used. But if you want to do something fancy, you will quickly find yourself hacking the library and fighting with the constraints it imposes, rather than solving the problem you want to solve.
  • Implement all the method’s logic from scratch. This second extreme gives too much freedom and requires implementing replay buffers and trajectory handling over and over again, which is error-prone, boring, and inefficient.

PTAN tries to balance those extremes, providing high-quality building blocks to simplify your RL code, but at the same time being flexible and not limiting your creativity.

At a high level, PTAN provides the following entities:

  • Agent: A class that knows how to convert a batch of observations to a batch of actions to be executed. It can contain an optional state, in case you need to track some information between consequent actions in one episode. (We will use this approach in Chapter 15, in the deep deterministic policy gradient (DDPG) method, which includes the Ornstein–Uhlenbeck random process for exploration.) The library provides several agents for the most common RL cases, but you always can write your own subclass of BaseAgent if none of the predefined classes are meeting your needs.
  • ActionSelector: A small piece of logic that knows how to choose the action from some output of the network. It works in tandem with the Agent class.
  • ExperienceSource and subclasses: The Agent instance and a Gym environment object can provide information about the trajectory of the agent during the episodes. In its simplest form, it is one single (a, r, s′) transition at a time, but its functionality goes beyond this.
  • ExperienceSourceBuffer and subclasses: Replay buffers with various characteristics. They include a simple replay buffer and two versions of prioritized replay buffers.
  • Various utility classes: An example is TargetNet and wrappers for time-series preprocessing (used for tracking training progress in TensorBoard).
  • PyTorch Ignite helpers: These can be used to integrate PTAN into the Ignite framework.
  • Wrappers for Gym environments: For example, wrappers for Atari games (very similar to the wrappers we described in Chapter 6).

And that’s basically it. In the following sections, we will take a look at these entities in detail.

In PTAN terminology, an action selector is an object that helps with going from network output to concrete action values. The most common cases include:

  • Greedy (or argmax): Commonly used by Q-value methods when the network predicts Q-values for a set of actions and the desired action is the action with the largest Q(s,a).
  • Policy-based: The network outputs the probability distribution (in the form of logits or normalized distribution), and an action needs to be sampled from this distribution. You have already seen this in Chapter 4, when we discussed the cross-entropy method.

An action selector is used by the Agent and rarely needs to be customized (but you have the option). The concrete classes provided by the library are:

  • ArgmaxActionSelector: Applies argmax on the second axis of a passed tensor. It assumes a matrix with batch dimension along the first axis.
  • ProbabilityActionSelector: Samples from the probability distribution of a discrete set of actions.
  • EpsilonGreedyActionSelector: Has the epsilon parameter, which specifies the probability of a random action being taken. It also holds another ActionSelector instance, which is used when we’re not sampling random actions.

All the classes assume that NumPy arrays will be passed to them. The complete example from this section can be found in Chapter07/01_actions.py. Here, I’m going to show you how these classes are supposed to be used:

>>> import numpy as np
>>> import ptan
>>> q_vals = np.array([[1, 2, 3], [1, -1, 0]])
>>> q_vals
array([[ 1, 2, 3],
[ 1, -1, 0]])
>>> selector = ptan.actions.ArgmaxActionSelector()
>>> selector(q_vals)
array([2, 0])

As you can see, the selector returns indices of actions with the largest values.

The next action selector is EpisilonGreedyActionSelector, which ”wraps” another action selector and, depending on the epsilon parameter, either uses the wrapped action selector or takes the random action. This action selector is used during training to introduce randomness to the agent’s actions. If epsilon is 0.0, no random actions are taken:

>>> selector = ptan.actions.EpsilonGreedyActionSelector(epsilon=0.0, selector=ptan.actions.ArgmaxActionSelector())
>>> selector(q_vals)
array([2, 0])

If we change epsilon to 1, actions will be random:

>>> selector = ptan.actions.EpsilonGreedyActionSelector(epsilon=1.0)
>>> selector(q_vals)
array([0, 1])

You can also change the value of epsilon by assigning the action selector’s attribute:

>>> selector.epsilon
1.0
>>> selector.epsilon = 0.0
>>> selector(q_vals)
array([2, 0])

Working with ProbabilityActionSelector is the same, but the input needs to be a normalized probability distribution:

>>> selector = ptan.actions.ProbabilityActionSelector()
>>> for _ in range(10):
... acts = selector(np.array([
... [0.1, 0.8, 0.1],
... [0.0, 0.0, 1.0],
... [0.5, 0.5, 0.0]
... ]))
... print(acts)
...
[0 2 1]
[1 2 1]
[1 2 1]
[0 2 1]
[2 2 0]
[0 2 0]
[1 2 1]
[1 2 0]
[1 2 1]
[1 2 0]

In the preceding example, we sample from three distributions (as we have three rows in the passed matrix):

  • The first is defined by the vector [0.1, 0.8, 0.1]; as a result, the action with index 1 is chosen with probability 80%
  • The vector [0.0, 0.0, 1.0] always gives us an action with index 2
  • The distribution [0.5, 0.5, 0.0] produces actions 0 and 1 with 50% chance

The agent entity provides an unified way of bridging observations from the environment and the actions that we want to execute. So far, you have seen only a simple, stateless DQN agent that uses a neural network (NN) to obtain action values from the current observation and behaves greedily on those values. We have used epsilon-greedy behavior to explore the environment, but this doesn’t change the picture much.

In the RL field, this could be more complicated. For example, instead of predicting the values of the actions, our agent could predict a probability distribution over the actions. Such agents are called policy agents, and we will talk about those methods in Part 3 of the book.

In some situations, it might be neccesary for the agent to keep state between observations. For example, very often, one observation (or even the k last observations) is not enough to make a decision about the action, and we want to keep some memory in the agent to capture the necessary information. There is a whole subdomain of RL that tries to address this complication with partially observable Markov decision process (POMDP) formalism, which we briefly mentioned in Chapter 6 but is not covered extensively in the book.

The third variant of the agent is very common in continuous control problems, which will be discussed in Part 4 of the book. For now, it suffices to say that in such cases, actions are not discrete anymore but continuous values, and the agent needs to predict them from the observations.

To capture all those variants and make the code flexible, the agent in PTAN is implemented as an extensible hierarchy of classes with the ptan.agent.BaseAgent abstract class at the top. From a high level, the agent needs to accept the batch of observations (in the form of a NumPy array or a list of NumPy arrays) and return the batch of actions that it wants to take. The batch is used to make the processing more efficient, as processing several observations in one pass in a graphics processing unit (GPU) is frequently much faster than processing them individually.

The abstract base class doesn’t define the types of input and output, which makes it very flexible and easy to extend. For example, in the continuous domain, our actions will no longer be indices of discrete actions, but float values. In any case, the agent can be seen as something that knows how to convert observations into actions, and it’s up to the agent how to do this. In general, there are no assumptions made on observation and action types, but the concrete implementation of agents is more limiting. PTAN provides two of the most common ways to convert observations into actions: DQNAgent and PolicyAgent. We will explore these in subsequent sections.

However, in real problems, a custom agent is often needed. These are some of the reasons:

  • The architecture of the NN is fancy—its action space is a mixture of continuous and discrete and it has multimodal observations (text and pixels, for example), or something like that.
  • You want to use non-standard exploration strategies, for example, the Ornstein–Uhlenbeck process (a very popular exploration strategy in the continuous control domain).
  • You have a POMDP environment, and the agent’s decision is not fully defined by observations, but by some internal agent state (which is also the case for Ornstein–Uhlenbeck exploration).

All those cases are easily supported by subclassing the BaseAgent class, and in the rest of the book, several examples of such redefinition will be given.

Let’s now check the standard agents provided by the library: DQNAgent and PolicyAgent. The complete example is in Chapter07/02_agents.py.

This class is applicable in Q-learning when the action space is not very large, which covers Atari games and lots of classical problems. This representation is not universal and, later in the book, you will see ways of dealing with that. DQNAgent takes a batch of observations as input (as a NumPy array), applies the network to them to get Q-values, and then uses the provided ActionSelector to convert Q-values to indices of actions.

Let’s consider a small example. For simplicity, our network always produces the same output for the input batch.

First, we define the NN class, which is supposed to convert observations to actions. In our example, it doesn’t use NNs at all and always produces the same output:

class DQNNet(nn.Module):
def __init__(self, actions: int):
super(DQNNet, self).__init__()
self.actions = actions
def forward(self, x):
# we always produce diagonal tensor of shape
# (batch_size, actions)
return torch.eye(x.size()[0], self.actions)

Once we have defined the model class, we can use it as a DQN model:

>>> net = DQNNet(actions=3)
>>> net(torch.zeros(2, 10))
tensor([[1., 0., 0.],
[0., 1., 0.]])

We start with the simple argmax policy (which returns the action with the largest value), so the agent will always return actions corresponding to ones in the network output:

>>> selector = ptan.actions.ArgmaxActionSelector()
>>> agent = ptan.agent.DQNAgent(model=net, action_selector=selector)
>>> agent(torch.zeros(2, 5))
(array([0, 1]), [None, None])

In the input, a batch of two observations, each having five values, was given, and in the output, the agent returned a tuple of two objects:

  • An array with actions to be executed for our batch. In our case, this is action 0 for the first batch sample and action 1 for the second.
  • A list with the agent’s internal state. This is used for stateful agents and is a list of None in our case. As our agent is stateless, you can ignore it.

Now, let’s make the agent with an epsilon-greedy exploration strategy. To do this, we just need to pass a different action selector:

>>> selector = ptan.actions.EpsilonGreedyActionSelector(epsilon=1.0)
>>> agent = ptan.agent.DQNAgent(model=net, action_selector=selector)
>>> agent(torch.zeros(10, 5))[0]
array([2, 0, 0, 0, 1, 2, 1, 2, 2, 1])

As epsilon is 1.0, all the actions will be random, regardless of the network’s output. But we can change the epsilon value on the fly, which is very handy during the training when we anneal epsilon over time:

>>> selector.epsilon = 0.5
>>> agent(torch.zeros(10, 5))[0]
array([0, 1, 2, 2, 0, 0, 1, 2, 0, 2])
>>> selector.epsilon = 0.1
>>> agent(torch.zeros(10, 5))[0]
array([0, 1, 2, 0, 0, 0, 0, 0, 0, 0])

PolicyAgent expects the network to produce a policy distribution over a discrete set of actions. The policy distribution could be either logits (unnormalized) or a normalized distribution. In practice, you should always use logits to improve the numeric stability of the training process.

Let’s reimplement our previous example, but now, the network will produce a probability.

We begin by defining the following class:

class PolicyNet(nn.Module):
def __init__(self, actions: int):
super(PolicyNet, self).__init__()
self.actions = actions
def forward(self, x):
# Now we produce the tensor with first two actions
# having the same logit scores
shape = (x.size()[0], self.actions)
res = torch.zeros(shape, dtype=torch.float32)
res[:, 0] = 1
res[:, 1] = 1
return res

The class above could be used to get the action logits for a batch of observations:

>>> net = PolicyNet(actions=5)
>>> net(torch.zeros(6, 10))
tensor([[1., 1., 0., 0., 0.],
[1., 1., 0., 0., 0.],
[1., 1., 0., 0., 0.],
[1., 1., 0., 0., 0.],
[1., 1., 0., 0., 0.],
[1., 1., 0., 0., 0.]])

Now, we can use PolicyAgent in combination with ProbabilityActionSelector. As the latter expects normalized probabilities, we need to ask PolicyAgent to apply softmax to the network’s output:

>>> selector = ptan.actions.ProbabilityActionSelector()
>>> agent = ptan.agent.PolicyAgent(model=net, action_selector=selector, apply_softmax=True)
>>> agent(torch.zeros(6, 5))[0]
array([2, 1, 2, 0, 2, 3])

Please note that the softmax operation produces non-zero probabilities for zero logits, so our agent can still select actions with zero logit values:

>>> torch.nn.functional.softmax(torch.tensor([1., 1., 0., 0., 0.]))
tensor([0.3222, 0.3222, 0.1185, 0.1185, 0.1185])

The agent abstraction described in the previous section allows us to implement environment communications in a generic way. These communications happen in the form of trajectories, produced by applying the agent’s actions to the Gym environment.

At a high level, experience source classes take the agent instance and environment and provide you with step-by-step data from the trajectories. The functionality of those classes includes:

  • Support for multiple environments being communicated at the same time. This allows efficient GPU utilization as a batch of observations is being processed by the agent at once.
  • A trajectory can be preprocessed and presented in a convenient form for further training. For example, there is an implementation of subtrajectory rollouts with accumulation of the reward. That preprocessing is convenient for DQN and n-step DQN, when we are not interested in individual intermediate steps in subtrajectories, so they can be dropped. This saves memory and reduces the amount of code we need to write.
  • Support for vectorized environments from Gymnasium (classes AsyncVectorEnv and SyncVectorEnv). We will cover this in Chapter 17.

So, the experience source classes act as a ”magic black box” to hide the environment interaction and trajectory handling complexities from the library user. But the overall PTAN philosophy is to be flexible and extensible, so if you want, you can subclass one of the existing classes or implement your own version as needed.

Three classes are provided by the system:

  • ExperienceSource: Using the agent and the set of environments, it produces n-step subtrajectories with all intermediate steps.
  • ExperienceSourceFirstLast: This is the same as ExperienceSource, but instead of the full subtrajectory (with all steps), it keeps only the first and last steps, with proper reward accumulation in between. This can save a lot of memory in the case of n-step DQN or advantage actor-critic (A2C) rollouts.
  • ExperienceSourceRollouts: This follows the asynchronous advantage actor-critic (A3C) rollouts scheme described in Mnih’s paper about Atari games (we will discuss this topic in Chapter 12).

All the classes are written to be efficient both in terms of central processing unit (CPU) and memory, which is not very important for toy problems, but will become relevant in the next chapter when we get to Atari games with much larger amounts of data to be stored and processed.

For demonstration, we will implement a very simple Gym environment with a small predictable observation state to show how ExperienceSource classes work. This environment has integer observation, which increases from 0 to 4, integer action, and a reward equal to the action given. All episodes produced by the environment always have 10 steps:

class ToyEnv(gym.Env):
def __init__(self):
super(ToyEnv, self).__init__()
self.observation_space = gym.spaces.Discrete(n=5)
self.action_space = gym.spaces.Discrete(n=3)
self.step_index = 0
def reset(self):
self.step_index = 0
return self.step_index, {}
def step(self, action: int):
is_done = self.step_index == 10
if is_done:
return self.step_index % self.observation_space.n, 0.0, is_done, False, {}
self.step_index += 1
return self.step_index % self.observation_space.n, float(action), \
self.step_index == 10, False, {}

In addition to this environment, we will use an agent that always generates fixed actions regardless of observations:

class DullAgent(ptan.agent.BaseAgent):
def __init__(self, action: int):
self.action = action
def __call__(self, observations: tt.List[int], state: tt.Optional[list] = None) -> \
tt.Tuple[tt.List[int], tt.Optional[list]]:
return [self.action for _ in observations], state

Both classes are defined in the Chapter07/lib.py module. Now that we have defined the agent, let’s talk about the data it produces.

The first class we will discuss is ptan.experience.ExperienceSource, which generates chunks of agent trajectories of the given length. The implementation automatically handles the end-of-episode situation (when the step() method in the environment returns is_done=True) and resets the environment. The constructor accepts several arguments:

  • The Gym environment to be used. Alternatively, it could be the list of environments.
  • The agent instance.
  • steps_count=2: The length of subtrajectories to be generated.

The class instance provides the standard Python iterator interface, so you can just iterate over it to get subtrajectories:

>>> from lib import *
>>> env = ToyEnv()
>>> agent = DullAgent(action=1)
>>> exp_source = ptan.experience.ExperienceSource(env=env, agent=agent, steps_count=2)
>>> for idx, exp in zip(range(3), exp_source):
... print(exp)
...
(Experience(state=0, action=1, reward=1.0, done_trunc=False), Experience(state=1, action=1, reward=1.0, done_trunc=False))
(Experience(state=1, action=1, reward=1.0, done_trunc=False), Experience(state=2, action=1, reward=1.0, done_trunc=False))
(Experience(state=2, action=1, reward=1.0, done_trunc=False), Experience(state=3, action=1, reward=1.0, done_trunc=False))

On every iteration, ExperienceSource returns a piece of the agent’s trajectory in environment communication. It might look simple, but there are several things happening under the hood of our example:

  1. reset() was called in the environment to get the initial state.
  2. The agent was asked to select the action to execute from the state returned.
  3. The step() method was executed to get the reward and the next state.
  4. This next state was passed to the agent for the next action.
  5. Information about the transition from one state to the next state was returned.
  6. If the environment returns the end-of-episode flag, we emit the rest of the trajectory and reset the environment to start over.
  7. The process continues (from step 3) during the iteration over the experience source.

If the agent changes the way it generates actions (we can get this by updating the network weights, decreasing epsilon, or by some other means), it will immediately affect the experience trajectories that we get.

The ExperienceSource instance returns tuples with lengths equal to or less than the step_count argument passed on construction. In our case, we asked for two-step subtrajectories, so tuples will be of length 2 or 1 (at the end of episodes). Every object in a tuple is an instance of the ptan.experience.Experience class, which is a dataclass with the following fields:

  • state: The state we observed before taking the action
  • action: The action we completed
  • reward: The immediate reward we got from env
  • done_trunc: Whether the episode was done or truncated

If the episode reaches the end, the subtrajectory will be shorter and the underlying environment will be reset automatically, so we don’t need to bother with this and can just keep iterating:

>>> for idx, exp in zip(range(15), exp_source):
... print(exp)
...
(Experience(state=0, action=1, reward=1.0, done_trunc=False), Experience(state=1, action=1, reward=1.0, done_trunc=False))
.......
(Experience(state=3, action=1, reward=1.0, done_trunc=False), Experience(state=4, action=1, reward=1.0, done_trunc=True))
(Experience(state=4, action=1, reward=1.0, done_trunc=True),)
(Experience(state=0, action=1, reward=1.0, done_trunc=False), Experience(state=1, action=1, reward=1.0, done_trunc=False))
(Experience(state=1, action=1, reward=1.0, done_trunc=False), Experience(state=2, action=1, reward=1.0, done_trunc=False))

We can ask ExperienceSource for subtrajectories of any length:

>>> exp_source = ptan.experience.ExperienceSource(env=env, agent=agent, steps_count=4)
>>> next(iter(exp_source))
(Experience(state=0, action=1, reward=1.0, done_trunc=False), Experience(state=1, action=1, reward=1.0, done_trunc=False), Experience(state=2, action=1, reward=1.0, done_trunc=False), Experience(state=3, action=1, reward=1.0, done_trunc=False))

We can pass it several instances of gym.Env. In that case, they will be used in a round-robin fashion:

>>> exp_source = ptan.experience.ExperienceSource(env=[ToyEnv(), ToyEnv()], agent=agent, steps_count=4)
>>> for idx, exp in zip(range(5), exp_source):
... print(exp)
...
(Experience(state=0, action=1, reward=1.0, done_trunc=False), Experience(state=1, action=1, reward=1.0, done_trunc=False), Experience(state=2, action=1, reward=1.0, done_trunc=False), Experience(state=3, action=1, reward=1.0, done_trunc=False))
(Experience(state=0, action=1, reward=1.0, done_trunc=False), Experience(state=1, action=1, reward=1.0, done_trunc=False), Experience(state=2, action=1, reward=1.0, done_trunc=False), Experience(state=3, action=1, reward=1.0, done_trunc=False))
(Experience(state=1, action=1, reward=1.0, done_trunc=False), Experience(state=2, action=1, reward=1.0, done_trunc=False), Experience(state=3, action=1, reward=1.0, done_trunc=False), Experience(state=4, action=1, reward=1.0, done_trunc=False))
(Experience(state=1, action=1, reward=1.0, done_trunc=False), Experience(state=2, action=1, reward=1.0, done_trunc=False), Experience(state=3, action=1, reward=1.0, done_trunc=False), Experience(state=4, action=1, reward=1.0, done_trunc=False))
(Experience(state=2, action=1, reward=1.0, done_trunc=False), Experience(state=3, action=1, reward=1.0, done_trunc=False), Experience(state=4, action=1, reward=1.0, done_trunc=False), Experience(state=0, action=1, reward=1.0, done_trunc=False))

Please note that when you’re passing several environments to the ExperienceSource, they have to be independent instances and not a single environment instance, otherwise your observations will become a mess.

The ExperienceSource class provides us with full subtrajectories of the given length as a list of (s, a, r) objects. The next state, s′, is returned in the next tuple, which is not always convenient. For example, in DQN training, we want to have tuples (s, a, r, s′) at once to do one-step Bellman approximation during the training. In addition, some extension of DQN, like n-step DQN, might want to collapse longer sequences of observations into (first-state, action, total-reward-for-n-steps, state-after-step-n).

To support this in a generic way, a simple subclass of ExperienceSource is implemented: ExperienceSourceFirstLast. It accepts almost the same arguments in the constructor, but returns different data:

>>> exp_source = ptan.experience.ExperienceSourceFirstLast(env, agent, gamma=1.0, steps_count=1)
>>> for idx, exp in zip(range(11), exp_source):
... print(exp)
...
ExperienceFirstLast(state=0, action=1, reward=1.0, last_state=1)
ExperienceFirstLast(state=1, action=1, reward=1.0, last_state=2)
ExperienceFirstLast(state=2, action=1, reward=1.0, last_state=3)
ExperienceFirstLast(state=3, action=1, reward=1.0, last_state=4)
ExperienceFirstLast(state=4, action=1, reward=1.0, last_state=0)
ExperienceFirstLast(state=0, action=1, reward=1.0, last_state=1)
ExperienceFirstLast(state=1, action=1, reward=1.0, last_state=2)
ExperienceFirstLast(state=2, action=1, reward=1.0, last_state=3)
ExperienceFirstLast(state=3, action=1, reward=1.0, last_state=4)
ExperienceFirstLast(state=4, action=1, reward=1.0, last_state=None)
ExperienceFirstLast(state=0, action=1, reward=1.0, last_state=1)

Now, instead of the tuple, it returns a single object on every iteration, which is again a dataclass with the following fields:

  • state: The state we used to decide on the action to take.
  • action: The action we took at this step.
  • reward: The partial accumulated reward for steps_count (in our case, steps_count=1, so it is equal to the immediate reward).
  • last_state: The state we got after executing the action. If our episode ends, we have None here.

This data is much more convenient for DQN training, as we can apply Bellman approximation directly to it.

Let’s check the result with a larger number of steps:

>>> exp_source = ptan.experience.ExperienceSourceFirstLast(env, agent, gamma=1.0, steps_count=2)
>>> for idx, exp in zip(range(11), exp_source):
... print(exp)
...
ExperienceFirstLast(state=0, action=1, reward=2.0, last_state=2)
ExperienceFirstLast(state=1, action=1, reward=2.0, last_state=3)
ExperienceFirstLast(state=2, action=1, reward=2.0, last_state=4)
ExperienceFirstLast(state=3, action=1, reward=2.0, last_state=0)
ExperienceFirstLast(state=4, action=1, reward=2.0, last_state=1)
ExperienceFirstLast(state=0, action=1, reward=2.0, last_state=2)
ExperienceFirstLast(state=1, action=1, reward=2.0, last_state=3)
ExperienceFirstLast(state=2, action=1, reward=2.0, last_state=4)
ExperienceFirstLast(state=3, action=1, reward=2.0, last_state=None)
ExperienceFirstLast(state=4, action=1, reward=1.0, last_state=None)
ExperienceFirstLast(state=0, action=1, reward=2.0, last_state=2)

So, now we are collapsing two steps on every iteration and calculating the immediate reward (that’s why reward=2.0 for most of the samples). More interesting samples are at the end of the episode:

ExperienceFirstLast(state=3, action=1, reward=2.0, last_state=None)
ExperienceFirstLast(state=4, action=1, reward=1.0, last_state=None)

As the episode ends, we have last_state=None in those samples, but additionally, we calculate the reward for the tail of the episode. Those tiny details are very easy to implement wrongly if you are doing all the trajectory handling yourself.

In DQN, we rarely deal with immediate experience samples, as they are heavily correlated, which leads to instability in the training. Normally, we have large replay buffers, which are populated with experience pieces. Then the buffer is sampled (randomly or with priority weights) to get the training batch. The replay buffer normally has a maximum capacity, so old samples are pushed out when the replay buffer reaches the limit.

There are several implementation tricks here, which become extremely important when you need to deal with large problems:

  • How to efficiently sample from a large buffer
  • How to push old samples from the buffer
  • In the case of a prioritized buffer, how priorities need to be maintained and handled in the most efficient way

All this becomes a quite non-trivial task if you want to deal with Atari games, keeping 10-100M samples, where every sample is an image from the game. A small mistake can lead to a 10-100x memory increase and major slowdowns in the training process.

PTAN provides several variants of replay buffers, which integrate simply with the ExperienceSource and Agent machinery. Normally, what you need to do is ask the buffer to pull a new sample from the source and sample the training batch. The provided classes are:

  • ExperienceReplayBuffer: A simple replay buffer of a predefined size with uniform sampling.
  • PrioReplayBufferNaive: A simple, but not very efficient, prioritized replay buffer implementation. The complexity of sampling is O(n), which might become an issue with large buffers. This version has the advantage over the optimized class, having much easier code. For medium-sized buffers the performance is still acceptable, so we will use it in some examples.
  • PrioritizedReplayBuffer: Uses segment trees for sampling, which makes the code cryptic, but with O(log(n)) sampling complexity.

The following shows how the replay buffer could be used:

>>> exp_source = ptan.experience.ExperienceSourceFirstLast(env, agent, gamma=1.0, steps_count=1)
>>> buffer = ptan.experience.ExperienceReplayBuffer(exp_source, buffer_size=100)
>>> len(buffer)
0
>>> buffer.populate(1)
>>> len(buffer)
1

All replay buffers provide the following interface:

  • A Python iterator interface to walk over all the samples in the buffer
  • The populate(N) method to get N samples from the experience source and put them into the buffer
  • The method sample(N) to get the batch of N experience objects

So, the normal training loop for DQN looks like an infinite repetition of the following steps:

  1. Call buffer.populate(1) to get a fresh sample from the environment.
  2. Call batch = buffer.sample(BATCH_SIZE) to get the batch from the buffer.
  3. Calculate the loss on the sampled batch.
  4. Backpropagate.
  5. Repeat until convergence (hopefully).

All the rest happens automatically-—resetting the environment, handling subtrajectories, buffer size maintenance, and so on:

>>> for step in range(6):
... buffer.populate(1)
... if len(buffer) < 5:
... continue
... batch = buffer.sample(4)
... print(f"Train time, {len(batch)} batch samples")
... for s in batch:
... print(s)
...
Train time, 4 batch samples
ExperienceFirstLast(state=1, action=1, reward=1.0, last_state=2)
ExperienceFirstLast(state=2, action=1, reward=1.0, last_state=3)
ExperienceFirstLast(state=2, action=1, reward=1.0, last_state=3)
ExperienceFirstLast(state=0, action=1, reward=1.0, last_state=1)
Train time, 4 batch samples
ExperienceFirstLast(state=0, action=1, reward=1.0, last_state=1)
ExperienceFirstLast(state=4, action=1, reward=1.0, last_state=0)
ExperienceFirstLast(state=3, action=1, reward=1.0, last_state=4)
ExperienceFirstLast(state=3, action=1, reward=1.0, last_state=4)

We mentioned the bootstrapping problem in the previous chapter, when the network used for the next state evaluation becomes influenced by our training process. This was solved by disentangling the currently trained network from the network used for next-state Q-values prediction.

TargetNet is a small but useful class that allows us to synchronize two NNs of the same architecture. This class supports two modes of such synchronization:

  • sync(): Weights from the source network are copied into the target network.
  • alpha_sync(): The source network’s weights are blended into the target network with some alpha weight (between 0 and 1).

The first mode is the standard way to perform a target network sync in discrete action space problems, like Atari and CartPole, as we did in Chapter 6. The latter mode is used in continuous control problems, which will be described in Part 4 of the book. In such problems, the transition between two networks’ parameters should be smooth, so alpha blending is used, given by the formula w i = w i α + s i (1 −α), where w i is the target network’s i-th parameter and s i is the source network’s weight. The following is a small example of how TargetNet should be used in code. Let’s assume we have the following network:

class DQNNet(nn.Module):
def __init__(self):
super(DQNNet, self).__init__()
self.ff = nn.Linear(5, 3)
def forward(self, x):
return self.ff(x)

The target network could be created as follows:

>>> net = DQNNet()
>>> net
DQNNet(
(ff): Linear(in_features=5, out_features=3, bias=True)
)
>>> tgt_net = ptan.agent.TargetNet(net)

The target network contains two fields: model, which is the reference to the original network, and target_model, which is a deep copy of it. If we examine both networks’ weights, they will be the same:

>>> net.ff.weight
Parameter containing:
tensor([[ 0.2039, 0.1487, 0.4420, -0.0210, -0.2726],
[-0.2020, -0.0787, 0.2852, -0.1565, 0.4012],
[-0.0569, -0.4184, -0.3658, 0.4212, 0.3647]], requires_grad=True)
>>> tgt_net.target_model.ff.weight
Parameter containing:
tensor([[ 0.2039, 0.1487, 0.4420, -0.0210, -0.2726],
[-0.2020, -0.0787, 0.2852, -0.1565, 0.4012],
[-0.0569, -0.4184, -0.3658, 0.4212, 0.3647]], requires_grad=True)

They are independent of each other, however, just having the same architecture:

>>> net.ff.weight.data += 1.0
>>> net.ff.weight
Parameter containing:
tensor([[1.2039, 1.1487, 1.4420, 0.9790, 0.7274],
[0.7980, 0.9213, 1.2852, 0.8435, 1.4012],
[0.9431, 0.5816, 0.6342, 1.4212, 1.3647]], requires_grad=True)
>>> tgt_net.target_model.ff.weight
Parameter containing:
tensor([[ 0.2039, 0.1487, 0.4420, -0.0210, -0.2726],
[-0.2020, -0.0787, 0.2852, -0.1565, 0.4012],
[-0.0569, -0.4184, -0.3658, 0.4212, 0.3647]], requires_grad=True)

To synchronize them again, the sync() method can be used:

>>> tgt_net.sync()
>>> tgt_net.target_model.ff.weight
Parameter containing:
tensor([[1.2039, 1.1487, 1.4420, 0.9790, 0.7274],
[0.7980, 0.9213, 1.2852, 0.8435, 1.4012],
[0.9431, 0.5816, 0.6342, 1.4212, 1.3647]], requires_grad=True)

For the blended sync, you can use the alpha_sync() method:

>>> net.ff.weight.data += 1.0
>>> net.ff.weight
Parameter containing:
tensor([[2.2039, 2.1487, 2.4420, 1.9790, 1.7274],
[1.7980, 1.9213, 2.2852, 1.8435, 2.4012],
[1.9431, 1.5816, 1.6342, 2.4212, 2.3647]], requires_grad=True)
>>> tgt_net.target_model.ff.weight
Parameter containing:
tensor([[1.2039, 1.1487, 1.4420, 0.9790, 0.7274],
[0.7980, 0.9213, 1.2852, 0.8435, 1.4012],
[0.9431, 0.5816, 0.6342, 1.4212, 1.3647]], requires_grad=True)
>>> tgt_net.alpha_sync(0.1)
>>> tgt_net.target_model.ff.weight
Parameter containing:
tensor([[2.1039, 2.0487, 2.3420, 1.8790, 1.6274],
[1.6980, 1.8213, 2.1852, 1.7435, 2.3012],
[1.8431, 1.4816, 1.5342, 2.3212, 2.2647]], requires_grad=True)

PyTorch Ignite was briefly discussed in Chapter 3, and it will be used in the rest of the book to reduce the amount of training loop code. PTAN provides several small helpers to simplify integration with Ignite, which reside in the ptan.ignite package:

  • EndOfEpisodeHandler: Attached to ignite.Engine, it emits an EPISODE_COMPLETED event and tracks the reward and number of steps in the event in the engine’s metrics. It also can emit an event when the average reward for the last episodes reaches the predefined boundary, which is supposed to be used to stop the training when some goal reward has been reached.
  • EpisodeFPSHandler: Tracks the number of interactions between the agent and environment that are performed and calculates performance metrics as frames per second. It also tracks the number of seconds passed since the start of the training.
  • PeriodicEvents: Emits corresponding events every 10, 100, or 1,000 training iterations. It is useful for reducing the amount of data being written into TensorBoard.

A detailed illustration of how these classes can be used will be given in the next chapter, when we will use them to reimplement the DQN training from Chapter 6, and then check several DQN extensions and tweaks to improve basic DQN convergence.

Let’s now take the PTAN classes (without Ignite so far) and try to combine everything to solve our first environment: CartPole. The complete code is in Chapter07/06_cartpole.py. I will show only the important parts of the code related to the material that we have just covered.

First, we create the NN (the simple two-layer feed-forward NN that we used for CartPole before) and target the NN epsilon-greedy action selector and DQNAgent. Then, the experience source and replay buffer are created:

net = Net(obs_size, HIDDEN_SIZE, n_actions)
tgt_net = ptan.agent.TargetNet(net)
selector = ptan.actions.ArgmaxActionSelector()
selector = ptan.actions.EpsilonGreedyActionSelector(epsilon=1, selector=selector)
agent = ptan.agent.DQNAgent(net, selector)
exp_source = ptan.experience.ExperienceSourceFirstLast(env, agent, gamma=GAMMA)
buffer = ptan.experience.ExperienceReplayBuffer(exp_source, buffer_size=REPLAY_SIZE)

With these few lines, we have finished with our data pipeline.

Now, we just need to call populate() on the buffer and sample training batches from it:

while True:
step += 1
buffer.populate(1)
for reward, steps in exp_source.pop_rewards_steps():
episode += 1
print(f"{step}: episode {episode} done, reward={reward:.2f}, "
f"epsilon={selector.epsilon:.2f}")
solved = reward > 150
if solved:
print("Whee!")
break
if len(buffer) < 2*BATCH_SIZE:
continue
batch = buffer.sample(BATCH_SIZE)

At the beginning of every training loop iteration, we ask the buffer to fetch one sample from the experience source and then check for the finished episode. The pop_rewards_steps() method in the ExperienceSource class returns the list of tuples with information about episodes completed since the last call to the method.

Later in the training loop, we convert a batch of ExperienceFirstLast objects into tensors suitable for DQN training:

batch = buffer.sample(BATCH_SIZE)
states_v, actions_v, tgt_q_v = unpack_batch(batch, tgt_net.target_model, GAMMA)
optimizer.zero_grad()
q_v = net(states_v)
q_v = q_v.gather(1, actions_v.unsqueeze(-1)).squeeze(-1)
loss_v = F.mse_loss(q_v, tgt_q_v)
loss_v.backward()
optimizer.step()
selector.epsilon *= EPS_DECAY
if step % TGT_NET_SYNC == 0:
tgt_net.sync()

We calculate the loss and do a backpropagation step. Finally, we decay epsilon in our action selector (with the hyperparameters used, epsilon decays to zero at training step 500) and ask the target network to sync every 10 training iterations.

The unpack_batch method is the last piece of our implementation:

@torch.no_grad()
def unpack_batch(batch: tt.List[ExperienceFirstLast], net: Net, gamma: float):
states = []
actions = []
rewards = []
done_masks = []
last_states = []
for exp in batch:
states.append(exp.state)
actions.append(exp.action)
rewards.append(exp.reward)
done_masks.append(exp.last_state is None)
if exp.last_state is None:
last_states.append(exp.state)
else:
last_states.append(exp.last_state)
states_v = torch.as_tensor(np.stack(states))
actions_v = torch.tensor(actions)
rewards_v = torch.tensor(rewards)
last_states_v = torch.as_tensor(np.stack(last_states))
last_state_q_v = net(last_states_v)
best_last_q_v = torch.max(last_state_q_v, dim=1)[0]
best_last_q_v[done_masks] = 0.0
return states_v, actions_v, best_last_q_v * gamma + rewards_v

It takes a sampled batch of ExperienceFirstLast objects and converts them into three tensors: states, actions, and target Q-values. The code should converge in 2,000-3,000 training iterations:

Chapter07$ python 06_cartpole.py
26: episode 1 done, reward=25.00, epsilon=1.00
52: episode 2 done, reward=26.00, epsilon=0.82
67: episode 3 done, reward=15.00, epsilon=0.70
80: episode 4 done, reward=13.00, epsilon=0.62
112: episode 5 done, reward=32.00, epsilon=0.45
123: episode 6 done, reward=11.00, epsilon=0.40
139: episode 7 done, reward=16.00, epsilon=0.34
148: episode 8 done, reward=9.00, epsilon=0.31
156: episode 9 done, reward=8.00, epsilon=0.29
...
2481: episode 113 done, reward=58.00, epsilon=0.00
2544: episode 114 done, reward=63.00, epsilon=0.00
2594: episode 115 done, reward=50.00, epsilon=0.00
2786: episode 116 done, reward=192.00, epsilon=0.00
Whee!

As we discussed earlier, there are several RL-specific libraries available. A few years ago, TensorFlow was more popular than PyTorch, but nowadays, PyTorch is dominating the field, and there is a recent trend of JAX being used as it provides better performance. The following is my recommended list of libraries you might want to take into consideration for your projects:

  • stable-baselines3: We mentioned this library when we discussed Atari wrappers. This is a fork of the OpenAI Stable Baselines repository, and the main idea is to have an optimized and reproducible set of RL algorithms that you can use to check your methods ( https://github.com/DLR-RM/stable-baselines3).
  • TorchRL: RL extensions for PyTorch. This library is relatively young-—the first release was at the end of 2022—but provides rich set of helper classes for RL. Its design philosophy is very close to PTAN—a Python-first set of flexible classes that you can combine and extend to build your system—so I highly recommend that you learn this library. In the rest of the book, we’ll use this library’s classes. Most likely, examples in the next edition of this book (unless we reach ”AI Singularity” and books become obsolete, like clay tablets) will not be based on PTAN but on TorchRL, which is better maintained. Documentation: https://pytorch.org/rl/, source code: https://github.com/pytorch/rl.
  • Spinning Up: Another repo from OpenAI, but with a different goal in mind: providing valuable and clean education materials about state-of-the-art methods. This repo hasn’t been updated for several years (the last commit was in 2020), but still provides very valuable materials about the methods. Documentation: https://spinningup.openai.com/. Code: https://github.com/openai/spinningup.
  • Keras-RL: Started by Matthias Plappert in 2016, this includes basic deep RL methods. As suggested by the name, this library was implemented using Keras, which is a high-level wrapper around TensorFlow (https://github.com/keras-rl/keras-rl). Unfortunately, the last commit was in 2019, so the project has been abandoned.
  • Dopamine: A library from Google published in 2018. It is TensorFlow-specific, which is not surprising for a library from Google (https://github.com/google/dopamine).
  • Ray: A library for distributed execution of machine learning code. It includes RL utilities as part of the library ( https://github.com/ray-project/ray).
  • TF-Agents: Another library from Google published in 2018 ( https://github.com/tensorflow/agents).
  • ReAgent: A library from Facebook Research. It uses PyTorch internally and uses a declarative style of configuration (when you are creating a JSON file to describe your problem), which limits extensibility. But, of course, as it is open source, you can always extend the functionality (https://github.com/facebookresearch/ReAgent). Recently, ReAgent was archived and replaced by the Pearl library from the same team: https://github.com/facebookresearch/Pearl/.

In this chapter, we talked about higher-level RL libraries, their motivation, and their requirements. Then, we took a deep look at the PTAN library, which will be used in the rest of the book to simplify example code. This focus on the details of the methods rather than implementation will be extremely useful for you in later chapters of this book, as you progress further with RL.

In the next chapter, we will return to DQN methods by exploring extensions that researchers and practitioners have discovered since the classic DQN introduction to improve the stability and performance of the method.