Skip to content
ImagineWorld

Ways to Speed up RL Methods

node_idnode-book_deep-reinforcement-learning-hands-on_chapter-09-ways-to-speed-up-rl-methods
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleWays to Speed up RL Methods
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In Chapter 8, you saw several practical tricks to make the deep Q-network (DQN) method more stable and converge faster. They involved basic DQN method modifications (like injecting noise into the network or unrolling the Bellman equation) to get a better policy, with less time spent on training. But in this chapter, we will explore another way to do this: tweaking the implementation details of the method to improve the speed of the training. This is a pure engineering approach, but it’s also important since it is useful in practice.

In this chapter, we will:

  • Take the Pong environment from the previous chapter and try to get it solved as fast as possible
  • In a step-by-step manner, get Pong solved almost 2 times faster using exactly the same commodity hardware

First, let’s talk a bit about why speed is important and why we optimize it at all. It might not be obvious, but enormous hardware performance improvements have happened in the last decade or two. Almost 20 years ago, I was involved with a project that focused on building a supercomputer for computational fluid dynamics (CFD) simulations performed by an aircraft engine design company. The system consisted of 64 servers, occupied three 42-inch racks, and required dedicated cooling and power subsystems. The hardware alone (without cooling) cost around $1M.

In 2005, this supercomputer was ranked fourth among ex-USSR supercomputers and was the fastest system installed in the industry. Its theoretical performance was 922 GFLOPS (almost a trillion floating-point operations per second), but in comparison to the GTX 1080 Ti released 12 years later, all the capabilities of this pile of iron look tiny.

One single GTX 1080 Ti is able to perform 11,340 GFLOPS, which is 12.3 times more than what supercomputers from 2005 could do. And the price was only 700perGPUwhenitwasreleased!Ifwecountcomputationpowerper700 per GPU when it was released! If we count computation power per 1, we get a price drop of more than 17,500 times for every GFLOP. This number is even more dramatic with the latest (at the time of writing) H100 GPU, which provides 134 teraflops (with FP32 operations).

It has been said many times that artificial intelligence (AI) progress (and machine learning (ML) in general) is being driven by data availability and computing power increases, and I believe that this is absolutely true. Imagine some computations that require a month to complete on one machine (a very common situation in CFD and other physics simulations). If we are able to increase speed by five times, this month of patient waiting will turn into six days. Speeding up by 100 times will mean that this heavy one-month computation will end up taking eight hours, so you could have three of them done in just one day! It’s very cool to be able to get 20,000 times more power for the same money nowadays. By the way, speeding up by 20k times will mean that our one-month problem will be done in two to three minutes!

This has happened not only in the “big iron” (also known as high-performance computing) world; basically, it is everywhere. Modern microcontrollers have the performance characteristics of the desktops that we worked with 15 years ago (for example, you can build a pocket computer for $50, with a 32-bit microcontroller running at 120 MHz, that is able to run the Atari 2600 emulator: https://hackaday.io/project/80627-badge-for-hackaday-conference-2018-in-belgrade). I’m not even talking about modern smartphones, which normally have four to eight cores, a graphics processing unit (GPU), and several GB of RAM.

Of course, there are a lot of complications there. It’s not just taking the same code that you used a decade ago and now, magically, finding that it works several thousand times faster. It might be the opposite: you might not be able to run it at all, due to a change in libraries, operating system interfaces, and other factors. (Have you ever tried to read old CD-RW disks written just a decade ago?) Nowadays, to get the full capabilities of modern hardware, you need to parallelize your code, which automatically means tons of details about distributed systems, data locality, communications, and the internal characteristics of the hardware and libraries. High-level libraries try to hide all those complications from you, but you can’t ignore all of them if you want to use these libraries efficiently. However, it is definitely worth it — one month of patient waiting could be turned into three minutes, remember. On the other hand, it might not be fully obvious why we need to speed things up in the first place. One month is not that long, after all; just lock the computer in a server room and go on vacation! But think about the process involved in preparing and making this computation work. You might already have noticed that even simple ML problems can be almost impossible to implement properly on the first attempt.

They require many trial runs before you find good hyperparameters and fix all the bugs and code ready for a clean launch. There is exactly the same process in physics simulations, RL research, big data processing, and programming in general. So, if we are able to make something run faster, it’s not only beneficial for the single run but also enables us to iterate quickly and do more experiments with code, which might significantly speed up the whole process and improve the quality of the final result.

I remember one situation from my career when we deployed a Hadoop cluster in our department, where we were developing a web search engine (similar to Google, but for Russian websites). Before the deployment, it took several weeks to conduct even simple experiments with data. Several terabytes of data were lying on different servers; you needed to run your code several times on every machine, gather and combine intermediate results, deal with occasional hardware failures, and do a lot of manual tasks not related to the problem that you were supposed to solve. After integrating the Hadoop platform into the data processing, the time needed for experiments dropped to several hours, which was completely game-changing. Since then, developers have been able to conduct many experiments much more easily and faster without bothering with unnecessary details. The number of experiments (and willingness to run them) has increased significantly, which has also increased the quality of the final product.

Another reason in favor of optimization is the size of problems that we can deal with. Making some method run faster might mean two different things: we can get the results sooner, or we can increase the size (or some other measure of the problem’s complexity). A complexity increase might have different meanings in different cases, like getting more accurate results, making fewer simplifications of the real world, or taking into account more data, but, almost always, this is a good thing.

Returning to the main topic of the book, let’s outline how RL methods might benefit from speed-ups. First of all, even state-of-the-art RL methods are not very sample efficient, which means that training needs to communicate with the environment many times (in the case of Atari, millions of times) before learning a good policy, and that might mean weeks of training. If we can speed up this process a bit, we can get the results faster, do more experiments, and find better hyperparameters. Besides this, if we have faster code, we can even increase the complexity of the problems that they are applied to.

In modern RL, Atari games are considered solved; even so-called “hard-exploration games,” like Montezuma’s Revenge, can be trained to superhuman accuracy. Therefore, new frontiers in research require more complex problems, with richer observation and action spaces, which inevitably require more training time and more hardware. Such research has already been started (and has increased the complexity of problems a bit too much, from my point of view) by DeepMind and OpenAI, which have switched from Atari to much more challenging problems like protein folding (AlphaFold system) and Large Language Models (LLMs). Those problems require thousands of GPUs working in parallel.

I want to end this introduction with a small warning: all performance optimizations make sense only when the core method is working properly (which is not always obvious in cases of RL and ML in general). As an instructor of an online course about performance optimizations said, “It’s much better to have a slow and correct program than a fast but incorrect one.”

In this chapter, we will take the Atari Pong environment that you are already familiar with and try to speed up its convergence. As a baseline, we will take the same simple DQN that we used in Chapter 8, and the hyperparameters will also be the same. To compare the effect of our changes, we will use two characteristics:

  • The number of frames that we consume from the environment every second (FPS). This indicates how fast we can communicate with the environment during the training. It is very common in RL papers to indicate the number of frames that the agent observed during the training; normal numbers are 25M–50M frames. So, if our FPS=200, it will take ≈ 2.89 days. In such calculations, you need to take into account that RL papers commonly report raw environment frames. But if frame skip is used (and it almost always is), the count of frames needs to be divided by this factor, which is commonly equal to 4. In our measurements, we calculate FPS in terms of agent communications with the environment, so the “raw environment FPS” will be four times larger.
  • The wall clock time before the game is solved. We stop training when the smoothed reward for the last 100 episodes reaches 18 (the maximum score in Pong is 21.) This boundary could be increased, but normally 18 is a good indication that the agent has almost mastered the game and polishing the policy to perfection is just a matter of the training time. We check the wall clock time because FPS alone is not the best indicator of training speed-up.

Due to our manipulations performed with the code, we can get a very high FPS, but convergence might suffer. This value alone also can’t be used as a reliable characteristic of our improvements, as the training process is stochastic. Even by specifying random seeds (we need to set seeds explicitly for PyTorch, Gym, and NumPy), parallelization (which will be used in subsequent steps) adds randomness to the process, which is almost impossible to avoid. So, the best we can do is run the benchmark several times and average the results. But one single run’s outcome can’t be used to make any decisions.

Because of the randomness mentioned above, all the charts in this chapter were obtained from averaging 5 runs of the same experiment. All the benchmarks use the same machine with an Intel i5-7600K CPU, a GTX 1080 Ti GPU with CUDA 12.3, and NVIDIA drivers version 545.29.06.

Our first benchmark will be our baseline version, which is in Chapter09/01_baseline.py. I will not provide the source code here, as it has already been given in the previous chapter and is the same here. During the training, the code writes into TensorBoard several metrics:

  • reward: The raw undiscounted reward from the episode; the x axis is the episode number.
  • avg_reward: The same as reward but smoothed by running the average with α = 0.98.
  • steps: The number of steps that the episode lasted. Normally, in the beginning, the agent loses very quickly, so every episode is around 1,000 steps. Then, it learns how to act better, so the number of steps increases to 3,000–4,000 with the reward increase; but, in the end, when the agent masters the game, the number of steps drops back to 2,000 steps, as the policy is polished to win as quickly as possible (due to the discount factor γ). In fact, this drop in episode length might be an indication of overfitting to the environment, which is a huge problem in RL. However, dealing with this issue is beyond the scope of our experiments.
  • loss: The loss during the training, sampled every 100 iterations. It should be around 2⋅10 −3 …1⋅10 −2, with occasional increases when the agent discovers new behavior, leading to a different reward from that learned by the Q-value.
  • avg_loss: A smoothed version of the loss.
  • epsilon: The current value of 𝜖 — probability of taking the random action.
  • avg_fps: The speed of agent communication with the environment (observations per second), smoothed with a running average.

In Figure 9.1 and Figure 9.2, the charts are averaged from 5 baseline runs. As before, each chart is drawn with two x axes: the bottom one is the wall clock time in hours, and the top is the step number (episode in Figure 9.1 and training iteration in Figure 9.2):

Figure 9.1: Reward and episode length in baseline version

Figure 9.2: Loss and FPS during the training of baseline version

Our first examples won’t be around speeding up the baseline, but will show one common, and not always obvious, situation that can cost you performance. In Chapter 3, we discussed the way PyTorch calculates gradients: it builds the graph of all operations that you perform on tensors, and when you call the backward() method of the final loss, all gradients in the model parameters are automatically calculated.

This works well, but RL code is normally much more complex than traditional supervised learning training, so the RL model that we are currently training is also being applied to get the actions that the agent needs to perform in the environment. The target network discussed in Chapter 6 makes it even more tricky. So, in DQN, a neural network (NN) is normally used in three different situations:

  • When we want to calculate Q-values predicted by the network to get the loss in respect to reference Q-values approximated by the Bellman equation
  • When we apply the target network to get Q-values for the next state to calculate a Bellman approximation
  • When the agent wants to make a decision about the action to perform

In our training, we need gradients calculated only for the first situation. In Chapter 6, we avoided gradients by explicitly calling detach() on the tensor returned by the target network. This detach is very important, as it prevents gradients from flowing into our model “from the unexpected direction” and, without this, the DQN might not converge at all. In the third situation, gradients were stopped by converting the network result into a NumPy array.

Our code in Chapter 6, worked, but we missed one subtle detail: the computation graph that is created for all three situations. This is not a major problem, but creating the graph still uses some resources (in terms of both speed and memory), which are wasted because PyTorch creates this computation graph even if we don’t call backward() on some graph. To prevent this, one very nice option exists: the decorator torch.no_grad().

Decorators in Python is a very wide topic. They give the developer a lot of power (when properly used), but are well beyond the scope of this book. Here, I’ll just give an example where we define two functions:

>>> import torch
>>> @torch.no_grad
... def fun_a(t):
... return t*2
...
>>> def fun_b(t):
... return t*2
...

Both these functions are doing the same thing, doubling its argument, but the first function is declared with torch.no_grad() and the second is just a normal function. This decorator temporarily disables gradient computation for all tensors passed to the function. As you can see, although the tensor, t, requires grad, the result from fun_a (the decorated function) doesn’t have gradients:

>>> t = torch.ones(3, requires_grad=True)
>>> t
tensor([1., 1., 1.], requires_grad=True)
>>> a = fun_a(t)
>>> b = fun_b(t)
>>> b
tensor([2., 2., 2.], grad_fn=<MulBackward0>)
>>> a
tensor([2., 2., 2.])

But this effect is bounded inside the decorated function:

>>> a*t
tensor([2., 2., 2.], grad_fn=<MulBackward0>)

The function torch.no_grad() also could be used as a context manager (another powerful Python concept that I recommend you learn about) to stop gradients in some chunk of code:

>>> with torch.no_grad():
... c = t*2
...
>>> c
tensor([2., 2., 2.])

This functionality provides you with a very convenient way to indicate parts of your code that should be excluded from the gradient machinery completely. This has already been done in ptan.agent.DQNAgent (and other agents provided by PTAN) and in the common.calc_loss_dqn function. But if you are writing a custom agent or implementing your own code, it might be very easy to forget about this.

To benchmark the effect of unnecessary graph calculation, I’ve provided the modified baseline code in Chapter09/00_slow_grads.py, which is exactly the same, but the agent and loss calculations are copied without torch.no_grad(). The following charts show the effect of this:

Figure 9.3: A comparison of reward and FPS between the baseline and version without torch.no_grad()

As you can see, the speed penalty is not that large (around 10 FPS), but that might become different in the case of a larger network with a more complicated structure. I’ve seen a 50% performance boost in more complex recurrent NNs obtained after adding torch.no_grad().

The first idea that we usually apply to speed up deep learning training is larger batch size. It’s also applicable to the domain of deep RL, but you need to be careful here. In the normal supervised learning case, the simple rule “a large batch is better” is usually true: you just increase your batch as your GPU memory allows, and a larger batch normally means more samples will be processed in a unit of time thanks to enormous GPU parallelism.

The RL case is slightly different. During the training, two things happen simultaneously:

  • Your network is trained to get better predictions on the current data
  • Your agent explores the environment

As the agent explores the environment and learns about the outcome of its actions, the training data changes. In a shooter example, your agent can run randomly for a time while being shot by monsters and have only a miserable “death is everywhere” experience in the training buffer. But after a while, the agent will discover that it has a weapon it can use. This new experience can dramatically change the data that we are using for training. RL convergence usually lies on a fragile balance between training and exploration. If we just increase a batch size without tweaking other options, we can easily overfit to the current data (for our shooter example, your agent can start thinking that “dying young” is the only option to minimize suffering and may never discover the gun it has).

So, in the example in Chapter09/02_n_envs.py, our agent uses several copies of the same environment to gather the training data. On every training iteration, we populate our replay buffer with samples from all those environments and then sample a proportionally larger batch size. This also allows us to speed up inference time a bit, as we can make a decision about the actions to execute for all N environments in one forward pass of the NN. In terms of implementation, the preceding logic requires just a couple of changes in the code:

  • As PTAN supports several environments out of the box, what we need to do is just pass N Gym environments to the ExperienceSource instance
  • The agent code (in our case, DQNAgent) is already optimized for the batched application of the NN

Several pieces of code were changed to address this. The function that generates batches now performs multiple steps (equal to the total number of environments) for every training iteration:

def batch_generator(buffer: ptan.experience.ExperienceReplayBuffer,
initial: int, batch_size: int, steps: int):
buffer.populate(initial)
while True:
buffer.populate(steps)
yield buffer.sample(batch_size)

The experience source accepts the array of environments instead of a single environment:

envs = [
ptan.common.wrappers.wrap_dqn(gym.make(params.env_name))
for _ in range(args.envs)
]
params.batch_size *= args.envs
exp_source = ptan.experience.ExperienceSourceFirstLast(
envs, agent, gamma=params.gamma, env_seed=common.SEED)

Other changes are just minor tweaks of constants to adjust the FPS tracker and compensated speed of epsilon decay (ratio of random steps). As the number of environments is the new hyperparameter that needs to be tuned, I ran several experiments with N from 2…6. The following charts show the averaged dynamics:

Figure 9.4: Reward and FPS in the baseline, two, and three environments

Figure 9.5: Reward and FPS for n = 3…6

As you can see from the charts, adding an extra environment provided a 47% gain in FPS (from 227 FPS to 335 FPS) and sped up the convergence about 10% (from 52 minutes to 48 minutes). The same effect came from adding the third environment (398 FPS, and 36 minutes), but adding more environments had a negative effect on convergence speed, despite a further increase in FPS. So, it looks like N = 3 is more or less the optimal value for our hyperparameter, but, of course, you are free to tweak and experiment. It also illustrates why we’re monitoring not just raw speed in FPS but also how quickly the agent is able to solve the game.

Playing and training in separate processes

Section titled “Playing and training in separate processes”

At a high level, our training contains a repetition of the following steps:

  1. Ask the current network to choose actions and execute them in our array of environments.
  2. Put observations into the replay buffer.
  3. Randomly sample the training batch from the replay buffer.
  4. Train on this batch.

The purpose of the first two steps is to populate the replay buffer with samples from the environment (which are observation, action, reward, and next observation). The last two steps are for training our network.

The following is an illustration of the preceding steps that will make potential parallelism slightly more obvious. On the left, the training flow is shown. The training steps use environments, the replay buffer, and our NN. The solid lines show data and code flow. Dotted lines represent usage of the NN for training and inference.

Figure 9.6: A sequential diagram of the training process

As you can see, the top two steps communicate with the bottom only via the replay buffer and NN. This makes it possible to separate those two parts in different parallel processes. The following figure is a diagram of the scheme:

Figure 9.7: The parallel version of the training and play steps

In the case of our Pong environment, it might look like an unnecessary complication of the code, but this separation might be extremely useful in some cases. Imagine that you have a very slow and heavy environment, so every step takes seconds of computations. That’s not a contrived example; for instance, past NeurIPS competitions, such as Learning to Run, AI for Prosthetics Challenge, and Learn to Move ( https://www.aicrowd.com/challenges/neurips-2019-learn-to-move-walk-around), have very slow neuromuscular simulators, so you have to separate experience gathering from the training process. In such cases, you can have many concurrent environments that deliver the experience to the central training process.

To turn our serial code into parallel code, some modifications are needed. In the file Chapter09/03_parallel.py, you can find the full source of the example. In the following, I’ll focus only on major differences.

First, we use the torch.multiprocessing module as a drop-in replacement for the standard Python multiprocessing module:

import torch.multiprocessing as mp
@dataclass
class EpisodeEnded:
reward: float
steps: int
epsilon: float
def play_func(params: common.Hyperparams, net: dqn_model.DQN,
dev_name: str, exp_queue: mp.Queue):
env = gym.make(params.env_name)
env = ptan.common.wrappers.wrap_dqn(env)
device = torch.device(dev_name)
selector = ptan.actions.EpsilonGreedyActionSelector(epsilon=params.epsilon_start)
epsilon_tracker = common.EpsilonTracker(selector, params)
agent = ptan.agent.DQNAgent(net, selector, device=device)
exp_source = ptan.experience.ExperienceSourceFirstLast(
env, agent, gamma=params.gamma, env_seed=common.SEED)
for frame_idx, exp in enumerate(exp_source):
epsilon_tracker.frame(frame_idx//2)
exp_queue.put(exp)
for reward, steps in exp_source.pop_rewards_steps():
ee = EpisodeEnded(reward=reward, steps=steps, epsilon=selector.epsilon)
exp_queue.put(ee)

The version from the standard library provides several primitives to work with code executed in separated processes, such as mp.Queue (distributed queue), mp.Process (child process), and others. PyTorch provides a wrapper around the standard multiprocessing library, which allows torch tensors to be shared between processes without copying them. This is implemented using shared memory in the case of CPU tensors, or CUDA references for tensors on a GPU. This sharing mechanism removes the major bottleneck when communication is performed within a single computer. Of course, in the case of truly distributed communications, you need to serialize data yourself.

The function play_func implements our “play process” and will be running in a separate child process started by the main process. Its responsibility is to get experience from the environment and push it into the shared queue. In addition, it wraps information about the end of the episode into a dataclass and pushes it into the same queue to keep the training process informed about the episode reward and the number of steps.

The function batch_generator is replaced by the class BatchGenerator:

class BatchGenerator:
def __init__(self, buffer_size: int, exp_queue: mp.Queue,
fps_handler: ptan_ignite.EpisodeFPSHandler,
initial: int, batch_size: int):
self.buffer = ptan.experience.ExperienceReplayBuffer(
experience_source=None, buffer_size=buffer_size)
self.exp_queue = exp_queue
self.fps_handler = fps_handler
self.initial = initial
self.batch_size = batch_size
self._rewards_steps = []
self.epsilon = None
def pop_rewards_steps(self) -> tt.List[tt.Tuple[float, int]]:
res = list(self._rewards_steps)
self._rewards_steps.clear()
return res
def __iter__(self):
while True:
while self.exp_queue.qsize() > 0:
exp = self.exp_queue.get()
if isinstance(exp, EpisodeEnded):
self._rewards_steps.append((exp.reward, exp.steps))
self.epsilon = exp.epsilon
else:
self.buffer._add(exp)
self.fps_handler.step()
if len(self.buffer) < self.initial:
continue
yield self.buffer.sample(self.batch_size)

This class provides an iterator over batches and additionally mimics the ExperienceSource interface with the method pop_reward_steps(). The logic of this class is simple: it consumes the queue (populated by the “play process”), and if the EpisodeEnded object was received, it remembers information about epsilon and the count of steps the game took; otherwise, the object is a piece of experience that needs to be added into the replay buffer. From the queue, we consume all objects available at the moment, and then the training batch is sampled from the buffer and yielded.

In the beginning of the training process, we need to tell torch.multiprocessing which start method to use:

if __name__ == "__main__":
warnings.simplefilter("ignore", category=UserWarning)
mp.set_start_method(’spawn’)

There are several of them, but spawn is the most flexible.

Then, the queue for communication is created, and we start our play_func as a separate process. As arguments, we pass the NN, hyperparameters, and queue to be used for experience:

exp_queue = mp.Queue(maxsize=2)
proc_args = (params, net, args.dev, exp_queue)
play_proc = mp.Process(target=play_func, args=proc_args)
play_proc.start()

The rest of the code is almost the same, with the exception that we use a BatchGenerator instance as the data source for Ignite and for EndOfEpisodeHandler (which requires the method pop_rewards_steps()). The following charts were obtained from my benchmarks:

Figure 9.8: Reward and FPS in the baseline and parallel version

As you can see, in terms of FPS, we got an increase of 27%: 290 FPS in the parallel version versus 228 in the baseline. The average time to solve the environment decreased by 41%.

In terms of FPS increase, the parallel version looks worse than the best result from the previous section (with 3 game environments, we got almost 400 FPS), but the convergence speed is better.

The final step in our sequence of experiments will be tweaking wrappers applied to the environment. This is very easy to overlook, as wrappers are normally written once or just borrowed from other code, applied to the environment, and left to sit there. But you should be aware of their importance in terms of the speed and convergence of your method. For example, the normal DeepMind-style stack of wrappers applied to an Atari game looks like this:

  1. NoopResetEnv: Applies a random amount of NOOP operations to the game reset. In some Atari games, this is needed to remove weird initial observations.
  2. MaxAndSkipEnv: Applies max to N observations (four by default) and returns this as an observation for the step. This solves the “flickering” problem in some Atari games, when the game draws different portions of the screen on even and odd frames (a normal practice among Atari developers to overcome the platform’s limitations and increase the complexity of the game’s sprites).
  3. EpisodicLifeEnv: In some games, this detects a lost life and turns this situation into the end of the episode. This significantly increases convergence, as our episodes become shorter (one single life versus several given by the game logic). This is relevant only for some games supported by the Atari 2600 Learning Environment.
  4. FireResetEnv: Executes a FIRE action on game reset. Some games require this to start the gameplay. Without this, our environment becomes a partially observable Markov decision process (POMDP), which makes it impossible to converge.
  5. WarpFrame: Also known as ProcessFrame84, this converts an image to grayscale and resizes it to 84 × 84.
  6. ClipRewardEnv: Clips the reward to a −1…1 range, which unifies wide variability in scoring among different Atari games. For example, Pong might have a −21…21 score range, but the score in the River Raid game could be 0…∞.
  7. FrameStack: Stacks N sequential observations into the stack (the default is four). As we already discussed in Chapter 6, in some games, this is required to fulfill the Markov property. For example, in Pong, from one single frame, it is impossible to get the direction the ball is moving in.

The code of those wrappers was heavily optimized by many people and several versions exist. My personal favorite is the Stable Baselines3, which is a fork from the OpenAI Baselines project. You can find it here: https://stable-baselines3.readthedocs.io/.

But you shouldn’t take this code as the final source of truth, as your concrete environment might have different requirements and specifics. For example, if you are interested in speeding up one specific game from the Atari suite, NoopResetEnv and MaxAndSkipEnv (more precisely, the max pooling operation from MaxAndSkipEnv) might not be needed. Another thing that could be tweaked is the number of frames in the FrameStack wrapper. The normal practice is to use four, but you need to understand that this number was used by DeepMind and other researchers to train on the full Atari 2600 game suite, which currently includes more than 50 games. For your specific case, a history of two frames might be enough to give you a performance boost, as less data will need to be processed by the NN.

Finally, the image resize could be the bottleneck of wrappers, so you might want to optimize libraries used by wrappers, for example, rebuilding them or replacing them with faster versions. Prior to 2020, replacing the OpenCV2 library with the pillow-simd library gave a boost of about 50 frames per second. Nowadays, OpenCV2 uses an optimized rescaling operation, so such replacement has no effect. But still, you might experiment with different scaling methods and different libraries.

Here, we’ll apply the following changes to the Pong wrappers:

  • Disable NoopResetEnv
  • Replace MaxAndSkipEnv with a simplified version, which just skips four frames without max pooling
  • Keep only two frames in FrameStack

To check the combined effect of our tweaks, we’ll add the above changes to the modifications done in the previous two sections: several environments and parallel execution of playing and training.

As the changes are not complex, let’s just quickly discuss them without the actual code (the full code can be found in the files Chapter09/04_wrappers_n_env.py, Chapter09/04_wrappers_parallel.py, and Chapter09/lib/atari_wrappers.py):

  • Library atari_wrappers.py is quite simple — it contains the copy of the wrap_dqn function from PTAN and the AtariWrapper class from Stable Baselines3.
  • In AtariWrapper, the class MaxAndSkipEnv was replaced with a simplified version without max pooling between frames.
  • Two modules, 04_wrappers_n_env.py and 04_wrappers_prallel.py, are just copies of 02_n_env.py and 03_parallel.py we’ve already seen, with tweaked environment creation.

That’s it! The following are charts with reward dynamics and FPS for both versions:

Figure 9.9: Reward and FPS in the baseline and “3 environments and 2 frames” version

Figure 9.10: Reward and FPS in the baseline and “parallel and 2 frames” version

Out of curiosity, I also tried to reduce the number of frames kept in FrameStack to just one frame (you can repeat the experiment with the command-line argument —stack 1). Surprisingly, such a version was able to solve the game, but it took significantly longer in terms of games needed and the training became unstable (about 3 out of 8 training runs didn’t converge at all). This might be an indication that Pong with just one frame is not POMDP and the agent still can learn how to win the game having just one frame as observation. But the efficiency of training definitely suffers.

I’ve summarized our experiments in the following table. The percentages show the changes versus the baseline version:

StepFPSFPS ΔTime, minsTime Δ
Baseline22952.2
Without torch.no_grad()219-4.3%51.0-2.3%
3 environments395+72.5%36.0-31.0%
Parallel version290+26.6%31.2-40.2%
Wrappers + 3 environments448+95.6%47.4-9.2%
Wrappers + parallel325+41.9%30.0-42.5%

Table 9.1: Optimization results

In this chapter, you saw several ways to improve the performance of the RL method using a pure engineering approach, which was in contrast to the “algorithmic” or “theoretical” approach covered in Chapter 8. From my perspective, both approaches complement each other, and a good RL practitioner needs to both know the latest tricks that researchers have found and be aware of the implementation details.

In the next chapter, we will begin applying our DQN knowledge to stocks trading as a practical example.

Get This Book’s PDF Version and Exclusive Extras