Learn Avalanche in 5 Minutes
A Short Guide for Researchers on the Run
Avalanche is mostly about making the life of a continual learning researcher easier.

What are the three pillars of any respectful continual learning research project?

  • Benchmarks: Machine learning researchers need multiple benchmarks with efficient data handling utils to design and prototype new algorithms. Quantitative results on ever-changing benchmarks has been one of the driving forces of Deep Learning.
  • Training: Efficient implementation and training of continual learning algorithms; comparisons with other baselines and state-of-the-art methods become fundamental to asses the quality of an original algorithmic proposal.
  • Evaluation: Training utils and Benchmarks are not enough alone to push continual learning research forward. Comprehensive and sound evaluation protocols and metrics need to be employed as well.

With Avalanche, you can find all these three fundamental pieces together and much more, in a single and coherent, well-maintained codebase.

Let's take a quick tour on how you can use Avalanche for your research projects with a 5-minutes guide, for researchers on the run!
In this short guide we assume you have already installed Avalanche. If you haven't yet, check out how you can do it following our How to Install guide.

๐Ÿ›๏ธ General Architecture

Avalanche is organized in five main modules:
  • Benchmarks: This module maintains a uniform API for data handling: mostly generating a stream of data from one or more datasets. It contains all the major CL benchmarks (similar to what has been done for torchvision).
  • Training: This module provides all the necessary utilities concerning model training. This includes simple and efficient ways of implement new continual learning strategies as well as a set pre-implemented CL baselines and state-of-the-art algorithms you will be able to use for comparison!
  • Evaluation: This modules provides all the utilities and metrics that can help in evaluating a CL algorithm with respect to all the factors we believe to be important for a continually learning system.
  • Models: In this module you'll be able to find several model architectures and pre-trained models that can be used for your continual learning experiment (similar to what has been done in torchvision.models).
  • Logging: It includes advanced logging and plotting features, including native stdout, file and Tensorboard support (How cool it is to have a complete, interactive dashboard, tracking your experiment metrics in real-time with a single line of code?)
In the graphic below, you can see how Avalanche sub-modules are available and organized as well:
Avalanche Main Modules and Sub-Modules
1
Avalanche
2
โ”œโ”€โ”€ Benchmarks
3
โ”‚ โ”œโ”€โ”€ Classic
4
โ”‚ โ”œโ”€โ”€ Datasets
5
โ”‚ โ”œโ”€โ”€ Generators
6
โ”‚ โ”œโ”€โ”€ Scenarios
7
โ”‚ โ””โ”€โ”€ Utils
8
โ”œโ”€โ”€ Evaluation
9
โ”‚ โ”œโ”€โ”€ Metrics
10
| โ””โ”€โ”€ Utils
11
โ”œโ”€โ”€ Training
12
โ”‚ โ”œโ”€โ”€ Strategies
13
โ”‚ โ”œโ”€โ”€ Plugins
14
| โ””โ”€โ”€ Utils
15
โ”œโ”€โ”€ Models
16
โ””โ”€โ”€ Loggers
Copied!
We will learn more about each of them during this tutorial series, but keep in mind that the Avalanche API documentation is your friend as well!
All right, let's start with the benchmarks module right away ๐Ÿ‘‡

๐Ÿ“š Benchmarks

The benchmark module offers three main features:
  1. 1.
    Datasets: a comprehensive list of PyTorch Datasets ready to use (It includes all the Torchvision Datasets and more!).
  2. 2.
    Classic Benchmarks: a set of classic Continual Learning Benchmarks ready to be used (there can be multiple benchmarks based on a single dataset).
  3. 3.
    Generators: a set of functions you can use to generate your own benchmark starting from any PyTorch Dataset!

Datasets

Datasets can be imported in Avalanche as simply as:
1
from avalanche.benchmarks.datasets import MNIST, FashionMNIST, KMNIST, EMNIST,
2
QMNIST, FakeData, CocoCaptions, CocoDetection, LSUN, ImageNet, CIFAR10,
3
CIFAR100, STL10, SVHN, PhotoTour, SBU, Flickr8k, Flickr30k, VOCDetection,
4
VOCSegmentation, Cityscapes, SBDataset, USPS, Kinetics400, HMDB51, UCF101,
5
CelebA, CORe50Dataset, TinyImagenet, CUB200, OpenLORIS, MiniImageNetDataset, Stream51
Copied!
Of course, you can use them as you would use any PyTorch Dataset.

Benchmarks Basics

The Avalanche benchmarks (instances of the Scenario class), contains several attributes that describe the benchmark. However, the most important ones are the train and test streams.
In Avalanche we often suppose to have access to these two parallel stream of data (even though some benchmarks may not provide such feature, but contain just a unique test set).
Each of these streams are iterable, indexable and sliceable objects that are composed of experiences. Experiences are batch of data (or "tasks") that can be provided with or without a specific task label.

Classic Benchmarks

Avalanche maintains a set of commonly used benchmarks built on top of one or multiple datasets.
1
from avalanche.benchmarks.classic import CORe50, SplitTinyImageNet, SplitCIFAR10,\
2
SplitCIFAR100, SplitCIFAR110, SplitMNIST, RotatedMNIST, PermutedMNIST, SplitCUB200
3
โ€‹
4
# creating the benchmark (scenario object)
5
perm_mnist = PermutedMNIST(
6
n_experiences=3,
7
seed=1234,
8
)
9
โ€‹
10
# recovering the train and test streams
11
train_stream = perm_mnist.train_stream
12
test_stream = perm_mnist.test_stream
13
โ€‹
14
# iterating over the train stream
15
for experience in train_stream:
16
print("Start of task ", experience.task_label)
17
print('Classes in this task:', experience.classes_in_this_experience)
18
โ€‹
19
# The current Pytorch training set can be easily recovered through the
20
# experience
21
current_training_set = experience.dataset
22
# ...as well as the task_label
23
print('Task {}'.format(experience.task_label))
24
print('This task contains', len(current_training_set), 'training examples')
25
โ€‹
26
# we can recover the corresponding test experience in the test stream
27
current_test_set = test_stream[experience.current_experience].dataset
28
print('This task contains', len(current_test_set), 'test examples')
Copied!

Benchmarks Generators

What if we want to create a new benchmark that is not present in the "Classic" ones? Well, in that case Avalanche offers a number of utilities that you can use to create your own benchmark with maximum flexibility: the benchmark generators!
The specific scenario generators are useful when starting from one or multiple PyTorch datasets and you want to create a "New Instances" or "New Classes" benchmark: i.e. it supports the easy and flexible creation of a Domain-Incremental, Class-Incremental or Task-Incremental scenarios among others.
1
from avalanche.benchmarks.generators import nc_scenario, ni_scenario
2
โ€‹
3
scenario = ni_scenario(
4
mnist_train, mnist_test, n_experiences=10, shuffle=True, seed=1234,
5
balance_experiences=True
6
)
7
scenario = nc_scenario(
8
mnist_train, mnist_test, n_experiences=10, shuffle=True, seed=1234,
9
task_labels=False
10
)
Copied!
Finally, if your ideal benchmark does not fit well in the aforementioned Domain-Incremental, Class-Incremental or Task-Incremental scenarios, you can always use our generic generators:
  • filelist_scenario
  • paths_scenario
  • dataset_scenario
  • tensor_scenario
1
from avalanche.benchmarks.generators import filelist_scenario, dataset_scenario, \
2
tensor_scenario, paths_scenario
Copied!
You can read more about how to use them the full Benchmarks module tutorial!

๐Ÿ’ชTraining

The training module in Avalanche is build on modularity and it has two main goals:
  1. 1.
    provide a set of standard continual learning baselines that can be easily run for comparison;
  2. 2.
    provide the necessary utilities to implement and run your own strategy in the most efficient and simple way possible thanks to the building blocks we already prepared for you.

Strategies

If you want to compare your strategy with other classic continual learning algorithms or baselines, in Avalanche this is as simple as creating an object:
1
from avalanche.models import SimpleMLP
2
from avalanche.training.strategies import Naive, CWRStar, Replay, GDumb,
3
Cumulative, LwF, GEM, AGEM, EWC, AR1
4
โ€‹
5
model = SimpleMLP(num_classes=10)
6
cl_strategy = Naive(
7
model, SGD(model.parameters(), lr=0.001, momentum=0.9),
8
CrossEntropyLoss(), train_mb_size=100, train_epochs=4, eval_mb_size=100
9
)
Copied!

Create your own Strategy

The simplest way to build your own strategy is to create a python class that implements the main train and eval methods.
Let's define our Continual Learning algorithm "MyStrategy" as a simple python class:
1
class MyStrategy():
2
"""My Basic Strategy"""
3
โ€‹
4
def __init__(self, model, optimizer, criterion):
5
self.model = model
6
self.optimizer = optimizer
7
self.criterion = criterion
8
โ€‹
9
def train(self, experience):
10
# here you can implement your own training loop for each experience (i.e.
11
# batch or task).
12
โ€‹
13
train_dataset = experience.dataset
14
t = experience.task_label
15
train_data_loader = DataLoader(
16
train_dataset, num_workers=4, batch_size=128
17
)
18
โ€‹
19
for epoch in range(1):
20
for mb in train_data_loader:
21
# you magin here...
22
pass
23
โ€‹
24
def eval(self, experience):
25
# here you can implement your own eval loop for each experience (i.e.
26
# batch or task).
27
โ€‹
28
eval_dataset = experience.dataset
29
t = experience.task_label
30
eval_data_loader = DataLoader(
31
eval_dataset, num_workers=4, batch_size=128
32
)
33
โ€‹
34
# eval here
Copied!
Then, we can use our strategy as we would do for the pre-implemented ones:
1
# Model Creation
2
model = SimpleMLP(num_classes=scenario.n_classes)
3
โ€‹
4
# Create the Strategy Instance (MyStrategy)
5
cl_strategy = MyStrategy(
6
model, SGD(model.parameters(), lr=0.001, momentum=0.9),
7
CrossEntropyLoss())
8
โ€‹
9
# Training Loop
10
print('Starting experiment...')
11
โ€‹
12
for experience in scenario.train_stream:
13
print("Start of experience ", experience.current_experience)
14
โ€‹
15
cl_strategy.train(experience)
16
print('Training completed')
17
โ€‹
18
print('Computing accuracy on the whole test set')
19
cl_strategy.eval(scenario.test_stream[experience.current_experience])
Copied!
While this is the easiest possible way to add your own strategy, Avalanche supports more sophisticated modalities (based on callbacks) that lets you write more neat, modular and reusable code, inheriting functionality from a parent classes and using pre-implemented plugins.
Check out more details about what Avalanche can offer in this module following the "Training" chapter of the "From Zero to Hero" tutorial!

๐Ÿ“ˆ Evaluation

The evaluation module is quite straightforward: it offers all the basic functionalities to evaluate and keep track of a continual learning experiment.
This is mostly done through the Metrics and the Loggers. The Metrics provide a set of classes which implements the main continual learning metrics like Accuracy, Forgetting, Memory Usage, Running Times, etc. Metrics should be created via the utility functions (e.g. accuracy_metrics, timing_metricsand others) specifying in the arguments when those metrics should be computed (after each minibatch, epoch, experience etc...). The Loggers specify a way to report the metrics (e.g. with Tensorboard, on console or others). Loggers are created by instantiating the respective class.
Metrics and loggers interact via the Evaluation Plugin: this is the main object responsible of tracking the experiment progress. Metrics and loggers are directly passed to the EvaluationPlugin instance. You will see the output of the loggers automatically during training and evaluation! Let's see how to put this together in few lines of code:
1
# utility functions to create plugin metrics
2
from avalanche.evaluation.metrics import accuracy_metrics, \
3
loss_metrics, forgetting_metrics
4
from avalanche.loggers import InteractiveLogger, TensorboardLogger
5
from avalanche.training.plugins import EvaluationPlugin
6
โ€‹
7
eval_plugin = EvaluationPlugin(
8
# accuracy after each training epoch
9
# and after each evaluation experience
10
accuracy_metrics(epoch=True, experience=True),
11
# loss after each training minibatch and each
12
# evaluation stream
13
loss_metrics(minibatch=True, stream=True),
14
# catastrophic forgetting after each evaluation
15
# experience
16
forgetting_metrics(experience=True, stream=True),
17
# add as many metrics as you like
18
loggers=[InteractiveLogger(), TensorboardLogger()])
19
โ€‹
20
# pass the evaluation plugin instance to the strategy
21
# strategy = EWC(..., evaluator=eval_plugin)
22
โ€‹
23
# THAT'S IT!!
Copied!
For more details about the evaluation module (how to write new metrics/loggers, a deeper tutorial on metrics) check out the extended guide in the "Evaluation" chapter of the "From Zero to Hero" Avalanche tutorial!

๐Ÿ”— Putting all Together

You've learned how to install Avalanche, how to create benchmarks that can suit your needs, how you can create your own continual learning algorithm and how you can evaluate its performance.
Here we show how you can use all these modules together to design your experiments as quantitative supporting evidence for your research project or paper.
1
from avalanche.benchmarks.classic import SplitMNIST
2
from avalanche.evaluation.metrics import forgetting_metrics, accuracy_metrics,\
3
loss_metrics, timing_metrics, cpu_usage_metrics, StreamConfusionMatrix,\
4
disk_usage_metrics, gpu_usage_metrics
5
from avalanche.models import SimpleMLP
6
from avalanche.logging import InteractiveLogger, TextLogger, TensorboardLogger
7
from avalanche.training.plugins import EvaluationPlugin
8
from avalanche.training.strategies import Naive
9
โ€‹
10
from torch.optim import SGD
11
from torch.nn import CrossEntropyLoss
12
โ€‹
13
scenario = SplitMNIST(n_experiences=5)
14
โ€‹
15
# MODEL CREATION
16
model = SimpleMLP(num_classes=scenario.n_classes)
17
โ€‹
18
# DEFINE THE EVALUATION PLUGIN and LOGGERS
19
# The evaluation plugin manages the metrics computation.
20
# It takes as argument a list of metrics, collectes their results and returns
21
# them to the strategy it is attached to.
22
โ€‹
23
# log to Tensorboard
24
tb_logger = TensorboardLogger()
25
โ€‹
26
# log to text file
27
text_logger = TextLogger(open('log.txt', 'a'))
28
โ€‹
29
# print to stdout
30
interactive_logger = InteractiveLogger()
31
โ€‹
32
eval_plugin = EvaluationPlugin(
33
accuracy_metrics(minibatch=True, epoch=True, experience=True, stream=True),
34
loss_metrics(minibatch=True, epoch=True, experience=True, stream=True),
35
timing_metrics(epoch=True),
36
cpu_usage_metrics(experience=True),
37
forgetting_metrics(experience=True, stream=True),
38
StreamConfusionMatrix(num_classes=scenario.n_classes, save_image=False),
39
disk_usage_metrics(minibatch=True, epoch=True, experience=True, stream=True),
40
loggers=[interactive_logger, text_logger, tb_logger]
41
)
42
โ€‹
43
# CREATE THE STRATEGY INSTANCE (NAIVE)
44
cl_strategy = Naive(
45
model, SGD(model.parameters(), lr=0.001, momentum=0.9),
46
CrossEntropyLoss(), train_mb_size=500, train_epochs=1, eval_mb_size=100,
47
evaluator=eval_plugin)
48
โ€‹
49
# TRAINING LOOP
50
print('Starting experiment...')
51
results = []
52
for experience in scenario.train_stream:
53
print("Start of experience: ", experience.current_experience)
54
print("Current Classes: ", experience.classes_in_this_experience)
55
โ€‹
56
# train returns a dictionary which contains all the metric values
57
res = cl_strategy.train(experience, num_workers=4)
58
print('Training completed')
59
โ€‹
60
print('Computing accuracy on the whole test set')
61
# eval also returns a dictionary which contains all the metric values
62
results.append(cl_strategy.eval(scenario.test_stream, num_workers=4))
Copied!

๐Ÿค Run it on Google Colab

You can run this chapter and play with it on Google Colaboratory:
Notebook currently unavailable.
Last modified 15d ago