concept experience replay in category reinforcement learning

appears as: experience replay, n experience replay, experience replay
Grokking Deep Reinforcement Learning

This is an excerpt from Manning's book Grokking Deep Reinforcement Learning.

9.1.4     Using experience replay

In our NFQ experiments, we use a mini-batch of 1,024 samples, and train with it for 40 iterations, alternating between calculating new targets and optimizing the network. These 1,024 samples are temporally correlated since most of them belong to the same trajectory since the maximum number of steps in a cart-pole episode is 500. One way to improve on this is to use a technique called experience replay. Experience replay consists of a data structure, often referred to as a replay buffer or a replay memory, that holds experience samples for several steps (much more than 1,024 steps), allowing the sampling of mini- batches from a broad set of past experiences. Having a replay buffer allows the agent two critical things. First, the training process can use a more diverse mini-batch for performing updates. Second, the agent no longer has to fit the model to the same small mini-batch for multiple iterations. Adequately sampling a sufficiently large replay buffer yields a slow- moving target, so the agent can now sample and train on every time step with a lower risk of divergence.

0001

A Bit Of History

Introduction of experience replay

 

Experience replay was introduced by Long-Ji Lin on a paper titled “Self-Improving Reactive Agents Based On Reinforcement Learning, Planning and Teaching”, believe it or not, published in 1992!

That’s right, 1992! Again, that’s when neural networks were referred to as “connectionism”... Sad times!

After getting his Ph.D. from CMU, Dr. Lin has moved through several technical roles in many different companies. Currently, he’s the Chief Scientist at Signifyd, leading a team that works on a system to predict and prevent online fraud.

There are multiple benefits to using experience replay. By sampling at random, we increase the probability that our updates to the neural network have low variance. When we use the batch in NFQ, most of the samples in that batch were correlated and similar. Updating with similar samples concentrates the changes on a limited area of the function, and that potentially over-emphasizes the magnitude of the updates. If we sample uniformly at random from a substantial buffer, on the other hand, chances are, our updates to the network are better distributed all across, and therefore more representative of the true value function.

Deep Reinforcement Learning in Action

This is an excerpt from Manning's book Deep Reinforcement Learning in Action.

Figure 3.13. This is the general overview of experience replay, a method for mitigating a major problem with online training algorithms: catastrophic forgetting. The idea is to employ mini-batching by storing past experiences and then using a random subset of these experiences to update the Q-network, rather than using just the single most recent experience.
Listing 3.5. DQN with experience replay
from collections import deque
epochs = 5000
losses = []
mem_size = 1000                                                                #1
batch_size = 200                                                               #2
replay = deque(maxlen=mem_size)                                                #3
max_moves = 50                                                                 #4
h = 0
for i in range(epochs):
    game = Gridworld(size=4, mode='random')
    state1_ = game.board.render_np().reshape(1,64) + np.random.rand(1,64)/100.0
    state1 = torch.from_numpy(state1_).float()
    status = 1
    mov = 0
    while(status == 1): 
        mov += 1
        qval = model(state1)                                                   #5
        qval_ = qval.data.numpy()
        if (random.random() < epsilon):                                        #6
            action_ = np.random.randint(0,4)
        else:
            action_ = np.argmax(qval_)
        
        action = action_set[action_]
        game.makeMove(action)
        state2_ = game.board.render_np().reshape(1,64) + np.random.rand(1,64)/100.0
        state2 = torch.from_numpy(state2_).float()
        reward = game.reward()
        done = True if reward > 0 else False
        exp =  (state1, action_, reward, state2, done)                         #7
        replay.append(exp)                                                     #8
        state1 = state2
        
        if len(replay) > batch_size:                                           #9
            minibatch = random.sample(replay, batch_size)                      #10
            state1_batch = torch.cat([s1 for (s1,a,r,s2,d) in minibatch])      #11
            action_batch = torch.Tensor([a for (s1,a,r,s2,d) in minibatch])
            reward_batch = torch.Tensor([r for (s1,a,r,s2,d) in minibatch])
            state2_batch = torch.cat([s2 for (s1,a,r,s2,d) in minibatch])
            done_batch = torch.Tensor([d for (s1,a,r,s2,d) in minibatch])
            
            Q1 = model(state1_batch)                                           #12
            with torch.no_grad():
                Q2 = model(state2_batch)                                       #13
            
            Y = reward_batch + gamma * ((1 - done_batch) * torch.max(Q2,dim=1)[0])                                                   #14
            X = \
            Q1.gather(dim=1,index=action_batch.long().unsqueeze(dim=1)).squeeze()
            loss = loss_fn(X, Y.detach())
            optimizer.zero_grad()
            loss.backward()
            losses.append(loss.item())
            optimizer.step()
 
        if reward != -1 or mov > max_moves:                                    #15
            status = 0
            mov = 0
losses = np.array(losses)
  • Experience replay is a mechanism to allow batch training of reinforcement learning algorithms in order to mitigate catastrophic forgetting and allow stable training.