Recently I started working on a new reinforcement learning project of mine and came across the problem of sampling from replay buffers. I thought it is a fun exercise to write a blog post about.
There are two popular strategies to sample from a dataset in reinforcement learning: uniformly, where each data point has the same probability, and prioritised, where each data point has a different probability of getting sampled, i.e. weighted by training error.1
These two strategies are going to be discussed in this post. I will differentiate between sampling with and without replacement. The aim of this post is to give an outline of how to implement these strategies as efficient algorithms.
The default strategy in stochastic gradient descent is sampling batches uniformly. All data points have the same probability.
Here is a data point from our dataset .
The goal is to sample items from . We can either choose to sample without or with replacement. What’s the difference?
Sampling without replacement means samples are unique and cannot be sampled twice per batch. On the flip-side, sampling with replacement means items can appear twice in one batch. Implementing the latter is trivial. Simply pick integers in and you are done.
Sampling without replacement is more interesting. How can we implement this efficiently?
Sampling without Replacement
Let’s think of a physical analogy — picking cards. If you were asked to pick random cards out of a poker deck without replacement, you might come up with the following strategy: 1. Pick a random card out of one stack of cards, 2. Put that card on a different stack, 3. Repeat.
If we replace stacks with arrays in this description, we already have a quite convincing algorithm, although a few details are missing. Here is one way to do it:
Much like with a stack of cards, we keep two arrays. The first array stores the result (result array), the second array stores the integers which we can still choose from (open array). Initially, there are zero integers in the result array and integers in the open array. On each iteration we then randomly pick one integer in the open array, remove it and put it into the result array. After doing this times, we have a batch of unique samples.
To make this more efficient, we can store both arrays in one “super” array and segment that by index . The result array goes from index to index , while the open array goes from index to (inclusive). When we want to transfer the sample from open to result array, we simply swap the picked index with the integer at index and increase by one. Figure 1 visualises this algorithm.
Let’s implement this algorithm using C++. As we need to have an array of size in memory, it makes sense to reuse that througout multiple samples. Therefore we create a class for the sampler.
Now that we have our class, we can implement the algorithm. On each iteration , we sample and swap the -th with -th integer as previously discussed.
The per-sample runtime of this algorithm is . The memory requirement is . In contrast to other algorithms, the runtime does not depend on . More analysis on the runtime can be found in Figure 9.
Unnormalised Categorical Distribution
As mentioned in the introduction, uniform isn’t the only way to sample from a dataset. We may want to weight certain data points more than others. For this purpose, we use a categorical distribution which is a generalisation of the uniform distribution. All data points get their own probability.
Traditionally though, we only get an arbitrary weight with no guarantees. For example, we might get a set of weights like . For a valid probability distribution it is required that . Therefore, we need to normalise the weights.
Sampling from this distribution is tricky as there are thousands of data points, which makes the normalisation costly.
To normalise the categorical distribution efficiently, we can make use of a binary tree structure. All data points are arranged as the leafs of the tree. The key of each leaf is the weight of that data point. To maintain a sum over all weights, we define the key of higher-level nodes as the sum of its child nodes.
This is known as a segment tree or sum heap. Take a look at Figure 4 for an illustration of this data structure.
Given a segment tree of the weights, it is straightforward to sample from a categorical distribution. Take a random number between and sampled from a uniform distribution . Let where is the value of the root node. Start at the root node and descent left if , otherwise set and descent right. Once you reach a leaf node, you have your sample.
We essentially partition into intervals with the size , sample from and then find the interval in which that number falls.
To sample without replacement, simply set the weight to zero after each sample and update the tree. This has computational cost. The only drawback is that you need to store the old weights and restore them afterwards, if you want to sample from the same distribution again.
We start implementing this algorithm by designing a class that can hold the tree. To make things easy, we store the tree using an array representation where the two children of node are at position and . This requires that is a power of , resulting in an array that has size .
Next, we implement some basic functions to maintain the sum tree.
Heapify walks up the tree and restores the sum condition.
GetWeight are for users who wish to update the distribution.
After having all the setup done, we can focus on implementing the sampling algorithm as described earlier.
This segment tree-based algorithm has runtime complexity per sample. Its memory complexity is .
You might wonder how well these algorithms perform for bigger datasets in practice. To find that out, I ran some performance tests. Take a look at Figure 9.
1. Categorical Sampling (N vs T)
2. Categorical Sampling (k vs T)
3. Uniform Sampling (k vs T)
4. Uniform vs Categorical sampling
Figure 9: Runtime analysis of the presented algorithms. (1) Runtime of categorical sampling w.r.t. shows log-complexity ( fixed to ). (2) Runtime of categorical sampling w.r.t. to , linear complexity ( fixed to ). (3) Runtime of uniform algorithm w.r.t. ( fixed to ). (4) Computational cost of categorical over uniform distribution. Plot shows categorical divided by uniform runtime w.r.t. , and .
The log-complexity of categorical sampling w.r.t. to is noticeable in plot (1). There is some performance trade-off when using sampling without replacement. It takes around ms to sample a batch of size from a dataset with million data points (which by today’s machine learning standards is a reasonably large dataset). Categorical sampling is around to times slower compared to uniform sampling for , as seen in plot (4).
Effect on Training Neural Nets
We discussed sampling without replacement throughout this post. It might not be obvious what the effect on training a neural net is. From a theoretical standpoint, it reduces the variance of an estimator. Take for example a mean estimator with . Using sampling without replacement, the variance of this estimator reduces to2
where is the variance of the same estimator but with replacement sampling.
In domains where is small, this can make a difference. If is large, however, the factor gets closer and closer to . For example, with a batch size of of the dataset size, we get a factor of . Sampling without replacement reduces the variance by in this case.
Although this applies only to mean estimators, the analogy might give you some intuition about the effect on neural network training of sampling without replacement.
In this post, I presented algorithms to sample from a dataset uniformly or weighted. These algorithms find application in reinforcement learning for prioritised replay buffers 1 or in supervised learning when sampling batches. The effect of sampling without replacement is larger for small datasets.
Further research into the effect of prioritising training examples based on learning error would be interesting. The algorithms presented here could be used as a basis for ideas in that space.
If you want to read more about sampling algorithms, take a look at Tim Vieira’s blog: https://timvieira.github.io/blog/post/2019/09/16/algorithms-for-sampling-without-replacement/