Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Open In Colab   Open in Kaggle

(Bonus) Tutorial 5: Replay

Week 2, Day 4: Macro-Learning

By Neuromatch Academy

Content creators: Hlib Solodzhuk, Ximeng Mao, Grace Lindsay

Content reviewers: Aakash Agrawal, Alish Dipani, Hossein Rezaei, Yousef Ghanbari, Mostafa Abdollahi, Hlib Solodzhuk, Ximeng Mao, Grace Lindsay, Alex Murphy

Production editors: Konstantine Tsafatinos, Ella Batty, Spiros Chavlis, Samuele Bolotta, Hlib Solodzhuk, Alex Murphy


Tutorial Objectives

Estimated timing of tutorial: 40 minutes

Replay in reinforcement learning (RL) refers to the process where agents revisit and learn from past experiences stored in memory, rather than solely from new interactions with their environment. This mirrors how mammals, particularly during sleep, reactivate neural patterns from recent experiences to consolidate memories and extract generalizable patterns. In artificial RL systems, experience replay enables more efficient learning by breaking temporal correlations between consecutive experiences and allowing multiple learning updates from single experiences (runs of a series of steps in an RL experiment). This biologically inspired approach has proven crucial for deep RL algorithms like DQN, demonstrating how computational models can both draw from and inform our understanding of biological intelligence.

In this tutorial, you will discover what replay is and how it helps to solve the continual learning problem we’ve been investigating over today’s tutorials.


Setup

Install and import feedback gadget

Source

Imports

Source

Figure settings

Source

Plotting functions

Source

Helper functions

Source

Data retrieval

Source

Set random seed

Source

Section 0: Let’s play a new game!

As in the previous tutorial, this one is going to be focused on an RL setup, thus, we would like you to play a slightly different game to get an idea of what the agent is going to learn. The rules are the same: you need to pick one of two displayed objects. Please watch any exciting patterns and observations and discuss them with your group before going to the video.

Make sure you execute this cell to play the game!

Source
Loading...
Loading...
Loading...
Loading...
<Figure size 800x400 with 2 Axes>
Loading...
Loading...

Video 1: Replay

Youtube
Bilibili

Section 1: A Changing Environment

As mentioned in the video, to study replay, we need to use a slightly different task inspired by the Harlow task, which creates an incentive to remember past data. In this section, we will introduce this new task environment, which is modelled in a similar way to the game you played in Section 0, above.

Exercise 1: Colorful State

For this tutorial, each state will be represented by its color (via its RGB values; thus, it is a vector of 3 values), and each color is associated with a stable reward that remains unchanged over time (the rewards will correspond to the position of the color in the rainbow).

While the reward associated with each color does not change over time, the colors presented to the agent will change. Specifically, on each trial, the agent is presented with two colors and should choose the one associated with a higher reward. Initially (in ‘mode 1’), colors will be chosen from a set of 3 possible colors. Over time, one of these colors will be replaced by another, creating a different set of three possible colors (‘mode 2’). This constitutes a distribution shift (specifically: covariate shift, which I’m sure you all could instantly recognize!) This may cause the agent to forget the reward associated with the color that was replaced. This would be an instance of catastrophic forgetting in our continual learning setting.

As in the previous tutorial, let us test the environment with a dummy agent. For this particular environment (in mode 1), we will use a random strategy — just select one of the two colors by tossing a fair coin.

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 1 Axes>

Observe that the maximum reward is always higher than the obtained reward or coincides with it (when the agent luckily chooses a more rewarded color).


Section 2: A2C Agent in a Changing Environment

Estimated timing to here from start of tutorial: 10 minutes

For now, simply run the following 2 cells (ActorCritic class and train_agent function) without exploring their content. You can come back to the code if you have time at the end.

Welcome back our friend from the previous tutorial, the A2C agent ;) Here, we have slightly modified the architecture (replacing LSTM cells with a single linear layer with ReLUs on top of it). The variable num_inputs has also been changed, as the input is now represented by a 3-dimensional vector instead of a single digit. Moreover, we will separate the training and evaluation functions, as we don’t have a “task” and “meta-space of tasks” notion here, so we don’t need to keep track of this.

In the cell below, we define the training procedure for the A2C agent and its evaluation.

In the following code cell, let’s observe the agent’s performance on the first mode after being trained on it. As the training of the agent takes around 3 minutes, we have provided you with an already trained version (but feel free to uncomment the training code to achieve the same results). You will also have the opportunity to train the agent from scratch in the next section!

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 1 Axes>

Pretty nice! Let us also observe the confusion matrix. Indeed, it might reveal the weaknesses associated with particular colors. We will increase the number of evaluation trials to obtain more statistically accurate results.

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 2 Axes>

No specific patterns here; the only notable observation (which is also expected) is that whenever colors are close in their rewards, the agent makes more mistakes with those.

Notice that the blue color is missing, as it is indeed excluded from the first mode, as indicated in the code above (repeated here for clarity):

first_mode = ["red", "yellow", "green"]
second_mode = ["red", "green", "blue"]

Also, notice that the color red was never chosen, as it was never a maximum-reward color. Recall the reward values for the specific colors (again, reproducted below for clarity).

color_names_rewards = {
    "red": 1,
    "yellow": 2,
    "green": 3,
    "blue": 4
}

This is why, in the confusion matrix, we never see the color red being picked. In both modes, red always exists in company with a color that has a higher reward.

With the details of the confusion matrix hopefully a bit clearer, let us evaluate the agent in the second mode.

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 1 Axes>

Let’s check the confusion matrix. We can see that the green color is chosen often when the blue one provides a higher reward (which the agent doesn’t know yet).

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 2 Axes>

As expected, the agent doesn’t know perfectly how to handle a new color.

Let’s continue training the same agent in the second mode and see if we can improve this situation. Again, you are provided with a pretrained agent.

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 1 Axes>

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 2 Axes>

Awesome! The agent has improved its ability to perform in the second mode. But what about the first one? Did the agent forget the previously seen colors?

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 1 Axes>

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 2 Axes>

Oops! The introduction of the blue color in the second mode disrupted the learned relationships between red and yellow (since we didn’t include yellow in the second mode). What should we do? In the next section, you will explore a bio-inspired mechanism that allows for correcting this behavior!


Section 3: Replay Buffer

Estimated timing to here from start of tutorial: 25 minutes

This section discusses the underlying biological inspiration behind the replay buffer and proposes a way that in can be implemented in code and used to tackle the issue of catastrophic forgetting during continual learning.

Coding Exercise 2: Experience Again

A replay buffer is a mechanism that allows an animal to remember certain experiences within an environment, which can be replayed in its mind later. This can be seen as akin to joint training, as it lets information from a past environment impact current learning.

Each of the gradient steps in the first mode is going to be an “experience” we are going to save, and we will play artificially (train) during training in the second mode. For that, before going to the coding part, let us take a look at the training function defined earlier. Which variables do you think we need to preserve in the proposed auxiliary storage that will allow the agent to implement the replay?

The procedure for retrieving the past experience is as follows: for each gradient step in the new mode, there is going to be one gradient step from a remembered experience from the previous mode.

In this exercise, you need to complete the ReplayBuffer class, which will help you remember information about the training experience. Observe that train_agent is redefined and slightly modified so it accepts ReplayBuffer instance as input.

Test your implementation of ReplayBuffer!

Source
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
Cell In[23], line 5
      3 replay = ReplayBuffer()
      4 loss = 5
----> 5 replay.write_experience(loss)
      6 if (replay.read_experience() - loss < 1e-2):
      7     print("Your implementation is correct!")

Cell In[22], line 27, in ReplayBuffer.write_experience(self, loss)
     24 """Write new experience."""
     25 ###################################################################
     26 ## Fill out the following then remove
---> 27 raise NotImplementedError("Student exercise: complete retrieval and storing procedure for replay buffer.")
     28 ###################################################################
     29 self.losses[...] = ...

NotImplementedError: Student exercise: complete retrieval and storing procedure for replay buffer.

First, we are going to train the new agent in the first mode using the writing mode of the replay buffer. Then, during the training in the second mode, we will incorporate reading from this replay buffer and observe whether it impacts the agent’s performance.

The training time will take around 3 minutes.

Make sure you execute this cell to observe the plot!

Source
Loading...
<Figure size 800x600 with 2 Axes>

Great! We’ve trained the agent in the first mode and saved the experience in the replay buffer. Now, let us change the mode to “read” and train the agent in the second mode while replaying the saved experience with each gradient step of the new one. The observed plot is the confusion matrix for the second mode.

Loading...

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 2 Axes>

Make sure you execute this cell to observe the plot!

Source
<Figure size 800x600 with 2 Axes>

Perfect match!


Summary

Estimated timing of tutorial: 40 minutes

Here we have learned:

  • Reinforcement learning also suffers from forgetting after learning a new distribution.

  • Replay is a biologically-inspired way to learn from memories of past actions and rewards, thus preventing forgetting.

The Big Picture

Replay mechanisms serve as a foundational bridge between past and present knowledge in both biological and artificial learning systems, enabling the critical ability to learn continuously without catastrophically forgetting previous skills. By selectively revisiting and consolidating important experiences, replay helps systems extract generalizable patterns that extend beyond specific tasks or contexts. In biological systems, hippocampal replay during sleep and rest periods allows the brain to transfer episodic memories to neocortical regions where they can inform future behavior across varied situations. Similarly, in artificial systems, experience replay buffers and generative replay techniques significantly improve an agent’s ability to transfer knowledge across domains and protect against overfitting to recent experiences.

We hope that you have found today’s tutorials on Macrolearning insightful. There is a lot of material we covered today and we’re almost at the end of the course! Tomorrow, our final day of content, will introduce some exciting concepts that are still unsolved and so its appropriately named “Mysteries”. We will look into more speculative attempts to tackle some of the larger / grander outstanding questions in NeuroAI.