Repository: mattriemer/MER Branch: master Commit: 4b7b9c977f31 Files: 22 Total size: 88.6 KB Directory structure: gitextract_jqq8_utk/ ├── LICENSE ├── MIT-LICENSE ├── README.md ├── data/ │ └── README.md ├── download.py ├── get_data.py ├── main.py ├── mer_examples.sh ├── metrics/ │ └── metrics.py ├── model/ │ ├── common.py │ ├── eralg4.py │ ├── eralg5.py │ ├── ewc.py │ ├── gem.py │ ├── independent.py │ ├── meralg1.py │ ├── meralg6.py │ ├── meralg7.py │ ├── online.py │ └── taskinput.py ├── requirements.txt └── unit_test.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: MIT-LICENSE ================================================ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Meta-Experience Replay (MER) Source code for the paper "Learning to Learn without Forgetting by Maximizing Transfer and Minimizing Interference". Link: https://openreview.net/pdf?id=B1gTShAct7 Reference: ``` @inproceedings{MER, title={Learning to Learn without Forgetting by Maximizing Transfer and Minimizing Interference}, author={Riemer, Matthew and Cases, Ignacio and Ajemian, Robert and Liu, Miao and Rish, Irina and Tu, Yuhai and Tesauro, Gerald}, booktitle={In International Conference on Learning Representations (ICLR)}, year={2019} } ``` This project is a fork of the GEM project https://github.com/facebookresearch/GradientEpisodicMemory in order to reproduce baselines from their paper. These baselines have been copied into the model/ directory of this repository. Our output and logging mechanisms for all models follow the same format used in the GEM project. # Available Datasets The code in this repository should work on the variants of MNIST used in the experiments. This includes Rotations, Permutations, and Many Permutations. It would need to be slightly extended to be applied to other interesting continual learning benchmarks like CIFAR-100 or Omniglot. The original MNIST database is available at http://yann.lecun.com/exdb/mnist/ and interface for generating your own MNIST variants is provided as part of the GEM project https://github.com/facebookresearch/GradientEpisodicMemory/tree/master/data. To maximize reproducibility, we have provided an interface for directly downloading the dataset versions used in our experiments. ## Basic Setup (Python 3.5 & torch 0.3.1) As a first step to get up and running, clone this git repository and navigate into the root directory of your local version of the repository. To get started, please install the requirements inside your environment. If you don't have an environment, we recommend that you create one (using [conda](http://anaconda.org)). The following instructions will guide you: Install `conda` and type ```conda create --name mer python=3.5``` This will create a conda environment (an isolated workplace) in which we can install the right versions of the software. Then, activate the environment: ```source activate mer``` or ```conda activate mer``` Within the `mer` environment, install PyTorch and Cython using conda as follows: ```conda install pytorch=0.3.1 -c pytorch``` ```conda install cython``` and then install the rest of the requirements using the following command: ```pip install --user -r requirements.txt``` ## Basic Setup (Python 3.6+ & torch 1.4+) As a first step to get up and running, clone this git repository and navigate into the root directory of your local version of the repository. To get started, please install the requirements inside your environment. If you don't have an environment, we recommend that you create one (using [conda](http://anaconda.org)). The following instructions will guide you: Install `conda` and type ```conda create --name mer python``` This will create a conda environment (an isolated workplace) in which we can install the right versions of the software. Then, activate the environment: ```source activate mer``` or ```conda activate mer``` Within the `mer` environment, install PyTorch and Cython using conda as follows: ```conda install torch``` ```conda install cython``` _For python 3.6+, to install quadprog, first do:_ ```sudo apt install gcc build-essential``` and then install the rest of the requirements using the following command: ```pip install --user -r requirements.txt``` ## Getting the datasets The first step is to download and uncompress all three datasets (30 GB of storage needed) execute the following command: ```python get_data.py all``` For just MNIST Rotations (4.1 GB) execute: ```python get_data.py rotations``` For just MNIST Permutations (4.1 GB) execute: ```python get_data.py permutations``` For just MNIST Many Permutations (21 GB) execute: ```python get_data.py manypermutations``` # Getting Started In mer_examples.sh see examples of how to run variants of MER from the paper and baseline models from the experiments. We make sure first that this script is excutable: ```chmod +x mer_examples.sh``` Now, executing the following command leads to running a full suite of experiments with a random seed of 0: ``` ./mer_examples.sh "0" ``` Within the file you can see examples of how to run models from our experiments on each datasets and memory size setting. For instance, we can execute MER from Algorithm 1 in the paper (meralg1) on MNIST Rotations with 5120 memories using the following commands: ``` export ROT="--n_layers 2 --n_hiddens 100 --data_path data/ --save_path results/ --batch_size 1 --log_every 100 --samples_per_task 1000 --data_file mnist_rotations.pt --cuda no --seed 0" python3 main.py $ROT --model meralg1 --lr 0.03 --beta 0.03 --gamma 1.0 --memories 5120 --replay_batch_size 100 --batches_per_example 10 ``` # Available Models In the model/ directory we have provided various models that were used for experiments on varients of MNIST in the paper. These models include: - Online Learning (online) - Task Specific Input Layer (taskinput) - Independent Models per Task (independent) - Elastic Weight Consolidation (ewc) - Gradient Episodic Memory (gem) - Experience Replay Algorithm 4 (eralg4) - Experience Replay Algorithm 5 (eralg5) - Meta-Experience Replay Algorithm 1 (meralg1) - Meta-Experience Replay Algorithm 6 (meralg6) - Meta-Experience Replay Algorithm 7 (meralg7) # System Requirements The repository has been developed for Python 3.5.2 using PyTorch 0.3.1. # Reproducing Our Experiments We have conducted comprehensive experiments detailed in Appendix M of our paper to make sure that our results are reproducible across runs regardless of the machine and random seed. You should be able to reproduce these experiments using the provided mer_examples.sh script. ================================================ FILE: data/README.md ================================================ This is the directory where data should be stored in order to use main.py for executing continual learning models. If you have not already, populate this folder using the get_data.py file in the root directory. ================================================ FILE: download.py ================================================ ######################################################################## # # Functions for downloading and extracting data-files from the internet. # # Implemented in Python 3.5 # ######################################################################## # # This file is part of the TensorFlow Tutorials available at: # # https://github.com/Hvass-Labs/TensorFlow-Tutorials # # Published under the MIT License. See the file LICENSE for details. # # Copyright 2016 by Magnus Erik Hvass Pedersen # ######################################################################## import sys import os import urllib.request import tarfile import zipfile ######################################################################## def _print_download_progress(count, block_size, total_size): """ Function used for printing the download progress. Used as a call-back function in maybe_download_and_extract(). """ # Percentage completion. pct_complete = float(count * block_size) / total_size # Limit it because rounding errors may cause it to exceed 100%. pct_complete = min(1.0, pct_complete) # Status-message. Note the \r which means the line should overwrite itself. msg = "\r- Download progress: {0:.1%}".format(pct_complete) # Print it. sys.stdout.write(msg) sys.stdout.flush() ######################################################################## def download(base_url, filename, download_dir): """ Download the given file if it does not already exist in the download_dir. :param base_url: The internet URL without the filename. :param filename: The filename that will be added to the base_url. :param download_dir: Local directory for storing the file. :return: Nothing. """ # Path for local file. save_path = os.path.join(download_dir, filename) # Check if the file already exists, otherwise we need to download it now. if not os.path.exists(save_path): # Check if the download directory exists, otherwise create it. if not os.path.exists(download_dir): os.makedirs(download_dir) print("Downloading", filename, "...") # Download the file from the internet. url = base_url + filename file_path, _ = urllib.request.urlretrieve(url=url, filename=save_path, reporthook=_print_download_progress) print(" Done!") def maybe_download_and_extract(url, download_dir): """ Download and extract the data if it doesn't already exist. Assumes the url is a tar-ball file. :param url: Internet URL for the tar-file to download. Example: "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" :param download_dir: Directory where the downloaded file is saved. Example: "data/CIFAR-10/" :return: Nothing. """ # Filename for saving the file downloaded from the internet. # Use the filename from the URL and add it to the download_dir. filename = url.split('/')[-1] file_path = os.path.join(download_dir, filename) # Check if the file already exists. # If it exists then we assume it has also been extracted, # otherwise we need to download and extract it now. if not os.path.exists(file_path): # Check if the download directory exists, otherwise create it. if not os.path.exists(download_dir): os.makedirs(download_dir) # Download the file from the internet. file_path, _ = urllib.request.urlretrieve(url=url, filename=file_path, reporthook=_print_download_progress) print() print("Download finished. Extracting files.") if file_path.endswith(".zip"): # Unpack the zip-file. zipfile.ZipFile(file=file_path, mode="r").extractall(download_dir) elif file_path.endswith((".tar.gz", ".tgz")): # Unpack the tar-ball. tarfile.open(name=file_path, mode="r:gz").extractall(download_dir) print("Done.") else: print("Data has apparently already been downloaded and unpacked.") ######################################################################## ================================================ FILE: get_data.py ================================================ # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os import download import argparse def get_mnist_data(url, data_dir): print("Downloading {} into {}".format(url, data_dir)) download.maybe_download_and_extract(url, data_dir) def get_datasets(): parser = argparse.ArgumentParser() parser.add_argument("dataset", help="Either the name of the dataset (rotations, permutations, manypermutations), or `all` to download all datasets") args = parser.parse_args() # Change dir to the location of this file (repo's root) get_data_path = os.path.realpath(__file__) os.chdir(os.path.dirname(get_data_path)) data_dir = os.path.join(os.getcwd(), 'data') # get files mnist_rotations = "https://nlp.stanford.edu/data/mer/mnist_rotations.tar.gz" mnist_permutations = "https://nlp.stanford.edu/data/mer/mnist_permutations.tar.gz" mnist_many = "https://nlp.stanford.edu/data/mer/mnist_manypermutations.tar.gz" all = {"rotations": mnist_rotations, "permutations": mnist_permutations, "manypermutations": mnist_many} if args.dataset == "all": for dataset in all.values(): get_mnist_data(dataset, data_dir) else: get_mnist_data(all[args.dataset], data_dir) if __name__ == "__main__": get_datasets() ================================================ FILE: main.py ================================================ ### This is a modified version of main.py from https://github.com/facebookresearch/GradientEpisodicMemory ### The most significant changes are to the arguments: 1) allowing for new models and 2) changing the default settings in some cases # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import importlib import datetime import argparse import random import uuid import time import os import numpy as np import torch from torch.autograd import Variable from metrics.metrics import confusion_matrix # continuum iterator ######################################################### def load_datasets(args): d_tr, d_te = torch.load(args.data_path + '/' + args.data_file) n_inputs = d_tr[0][1].size(1) n_outputs = 0 for i in range(len(d_tr)): n_outputs = max(n_outputs, d_tr[i][2].max()) n_outputs = max(n_outputs, d_te[i][2].max()) return d_tr, d_te, n_inputs, n_outputs + 1, len(d_tr) class Continuum: def __init__(self, data, args): self.data = data self.batch_size = args.batch_size n_tasks = len(data) task_permutation = range(n_tasks) if args.shuffle_tasks == 'yes': task_permutation = torch.randperm(n_tasks).tolist() sample_permutations = [] for t in range(n_tasks): N = data[t][1].size(0) if args.samples_per_task <= 0: n = N else: n = min(args.samples_per_task, N) p = torch.randperm(N)[0:n] sample_permutations.append(p) self.permutation = [] for t in range(n_tasks): task_t = task_permutation[t] for _ in range(args.n_epochs): task_p = [[task_t, i] for i in sample_permutations[task_t]] random.shuffle(task_p) self.permutation += task_p self.length = len(self.permutation) self.current = 0 def __iter__(self): return self def next(self): return self.__next__() def __next__(self): if self.current >= self.length: raise StopIteration else: ti = self.permutation[self.current][0] j = [] i = 0 while (((self.current + i) < self.length) and (self.permutation[self.current + i][0] == ti) and (i < self.batch_size)): j.append(self.permutation[self.current + i][1]) i += 1 self.current += i j = torch.LongTensor(j) return self.data[ti][1][j], ti, self.data[ti][2][j] # train handle ############################################################### def eval_tasks(model, tasks, args): model.eval() result = [] for i, task in enumerate(tasks): t = i x = task[1] y = task[2] rt = 0 eval_bs = x.size(0) with torch.no_grad(): # torch 0.4+ for b_from in range(0, x.size(0), eval_bs): b_to = min(b_from + eval_bs, x.size(0) - 1) if b_from == b_to: xb = x[b_from].view(1, -1) yb = torch.LongTensor([y[b_to]]).view(1, -1) else: xb = x[b_from:b_to] yb = y[b_from:b_to] if args.cuda: xb = xb.cuda() # xb = Variable(xb, volatile=True) # torch 0.4+ _, pb = torch.max(model(xb, t).data.cpu(), 1, keepdim=False) rt += (pb == yb).float().sum() result.append(rt / x.size(0)) return result def life_experience(model, continuum, x_te, args): result_a = [] result_t = [] current_task = 0 time_start = time.time() for (i, (x, t, y)) in enumerate(continuum): if(((i % args.log_every) == 0) or (t != current_task)): result_a.append(eval_tasks(model, x_te, args)) result_t.append(current_task) current_task = t v_x = x.view(x.size(0), -1) v_y = y.long() if args.cuda: v_x = v_x.cuda() v_y = v_y.cuda() model.train() model.observe(Variable(v_x), t, Variable(v_y)) result_a.append(eval_tasks(model, x_te, args)) result_t.append(current_task) time_end = time.time() time_spent = time_end - time_start return torch.Tensor(result_t), torch.Tensor(result_a), time_spent if __name__ == "__main__": parser = argparse.ArgumentParser(description='Continuum learning') # model details parser.add_argument('--model', type=str, default='single', help='model to train') parser.add_argument('--n_hiddens', type=int, default=100, help='number of hidden neurons at each layer') parser.add_argument('--n_layers', type=int, default=2, help='number of hidden layers') parser.add_argument('--finetune', default='yes', type=str,help='whether to initialize nets in indep. nets') # optimizer parameters influencing all models parser.add_argument('--n_epochs', type=int, default=1, help='Number of epochs per task') parser.add_argument('--batch_size', type=int, default=1, help='the amount of items received by the algorithm at one time (set to 1 across all experiments). Variable name is from GEM project.') parser.add_argument('--lr', type=float, default=1e-3, help='learning rate') # memory parameters for GEM baselines parser.add_argument('--n_memories', type=int, default=0, help='number of memories per task') parser.add_argument('--memory_strength', default=0, type=float, help='memory strength (meaning depends on memory)') # parameters specific to models in https://openreview.net/pdf?id=B1gTShAct7 parser.add_argument('--memories', type=int, default=5120, help='number of total memories stored in a reservoir sampling based buffer') parser.add_argument('--gamma', type=float, default=1.0, help='gamma learning rate parameter') #gating net lr in roe parser.add_argument('--batches_per_example', type=float, default=1, help='the number of batch per incoming example') parser.add_argument('--s', type=float, default=1, help='current example learning rate multiplier (s)') parser.add_argument('--replay_batch_size', type=float, default=20, help='The batch size for experience replay. Denoted as k-1 in the paper.') parser.add_argument('--beta', type=float, default=1.0, help='beta learning rate parameter') # exploration factor in roe # experiment parameters parser.add_argument('--cuda', type=str, default='no', help='Use GPU?') parser.add_argument('--seed', type=int, default=0, help='random seed of model') parser.add_argument('--log_every', type=int, default=100, help='frequency of logs, in minibatches') parser.add_argument('--save_path', type=str, default='results/', help='save models at the end of training') # data parameters parser.add_argument('--data_path', default='data/', help='path where data is located') parser.add_argument('--data_file', default='mnist_permutations.pt', help='data file') parser.add_argument('--samples_per_task', type=int, default=-1, help='training samples per task (all if negative)') parser.add_argument('--shuffle_tasks', type=str, default='no', help='present tasks in order') args = parser.parse_args() args.cuda = True if args.cuda == 'yes' else False args.finetune = True if args.finetune == 'yes' else False # taskinput model has one extra layer if args.model == 'taskinput': args.n_layers -= 1 # unique identifier uid = uuid.uuid4().hex # initialize seeds torch.backends.cudnn.enabled = False torch.manual_seed(args.seed) np.random.seed(args.seed) random.seed(args.seed) if args.cuda: print("Found GPU:", torch.cuda.get_device_name(0)) torch.cuda.manual_seed_all(args.seed) # load data x_tr, x_te, n_inputs, n_outputs, n_tasks = load_datasets(args) n_outputs = n_outputs.item() # outputs should not be a tensor, otherwise "TypeError: expected Float (got Long)" # set up continuum continuum = Continuum(x_tr, args) # load model Model = importlib.import_module('model.' + args.model) model = Model.Net(n_inputs, n_outputs, n_tasks, args) if args.cuda: try: model.cuda() except: pass # run model on continuum result_t, result_a, spent_time = life_experience( model, continuum, x_te, args) # prepare saving path and file name if not os.path.exists(args.save_path): os.makedirs(args.save_path) fname = args.model + '_' + args.data_file + '_' fname += datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") fname += '_' + uid fname = os.path.join(args.save_path, fname) # save confusion matrix and print one line of stats stats = confusion_matrix(result_t, result_a, fname + '.txt') one_liner = str(vars(args)) + ' # ' one_liner += ' '.join(["%.3f" % stat for stat in stats]) print(fname + ': ' + one_liner + ' # ' + str(spent_time)) # save all results in binary file torch.save((result_t, result_a, model.state_dict(), stats, one_liner, args), fname + '.pt') ================================================ FILE: mer_examples.sh ================================================ #!/bin/bash seed=$1 ROT="--n_layers 2 --n_hiddens 100 --data_path data/ --save_path results/ --batch_size 1 --log_every 100 --samples_per_task 1000 --data_file mnist_rotations.pt --cuda no --seed" PERM="--n_layers 2 --n_hiddens 100 --data_path data/ --save_path results/ --batch_size 1 --log_every 100 --samples_per_task 1000 --data_file mnist_permutations.pt --cuda no --seed" MANY="--n_layers 2 --n_hiddens 100 --data_path data/ --save_path results/ --batch_size 1 --log_every 100 --samples_per_task 200 --data_file mnist_manypermutations.pt --cuda no --seed" echo "Beginning Online Learning" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model online --lr 0.0003 echo "MNIST Permutations:" python3 main.py $PERM $seed --model online --lr 0.003 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model online --lr 0.003 echo "Beginning Independent Model Per Task" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model independent --lr 0.01 echo "MNIST Permutations:" python3 main.py $PERM $seed --model independent --lr 0.01 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model independent --lr 0.01 echo "Beginning EWC" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model ewc --lr 0.001 --n_memories 10 --memory_strength 100.0 echo "MNIST Permutations:" python3 main.py $PERM $seed --model ewc --lr 0.01 --n_memories 10 --memory_strength 10.0 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model ewc --lr 0.003 --n_memories 10 --memory_strength 1.0 echo "Beginning GEM With 5120 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model gem --lr 0.01 --n_memories 256 --memory_strength 1.0 echo "MNIST Permutations:" python3 main.py $PERM $seed --model gem --lr 0.01 --n_memories 256 --memory_strength 1.0 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model gem --lr 0.01 --n_memories 51 --memory_strength 0.0 echo "Beginning GEM With 500 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model gem --lr 0.01 --n_memories 25 --memory_strength 0.0 echo "MNIST Permutations:" python3 main.py $PERM $seed --model gem --lr 0.01 --n_memories 25 --memory_strength 1.0 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model gem --lr 0.003 --n_memories 5 --memory_strength 0.1 echo "Beginning GEM With 200 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model gem --lr 0.01 --n_memories 10 --memory_strength 0.0 echo "MNIST Permutations:" python3 main.py $PERM $seed --model gem --lr 0.01 --n_memories 10 --memory_strength 0.0 echo "Beginning ER (Algorithm 4) With 5120 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model eralg4 --lr 0.1 --memories 5120 --replay_batch_size 25 echo "MNIST Permutations:" python3 main.py $PERM $seed --model eralg4 --lr 0.1 --memories 5120 --replay_batch_size 25 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model eralg4 --lr 0.1 --memories 5120 --replay_batch_size 25 echo "Beginning ER (Algorithm 4) With 500 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model eralg4 --lr 0.1 --memories 500 --replay_batch_size 5 echo "MNIST Permutations:" python3 main.py $PERM $seed --model eralg4 --lr 0.1 --memories 500 --replay_batch_size 10 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model eralg4 --lr 0.1 --memories 500 --replay_batch_size 25 echo "Beginning ER (Algorithm 4) With 200 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model eralg4 --lr 0.1 --memories 200 --replay_batch_size 10 echo "MNIST Permutations:" python3 main.py $PERM $seed --model eralg4 --lr 0.1 --memories 200 --replay_batch_size 10 echo "Beginning ER (Algorithm 5) With 5120 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model eralg5 --lr 0.03 --memories 5120 --replay_batch_size 100 echo "MNIST Permutations:" python3 main.py $PERM $seed --model eralg5 --lr 0.01 --memories 5120 --replay_batch_size 25 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model eralg5 --lr 0.003 --memories 5120 --replay_batch_size 10 echo "Beginning ER (Algorithm 5) With 500 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model eralg5 --lr 0.01 --memories 500 --replay_batch_size 100 echo "MNIST Permutations:" python3 main.py $PERM $seed --model eralg5 --lr 0.01 --memories 500 --replay_batch_size 25 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model eralg5 --lr 0.01 --memories 500 --replay_batch_size 5 echo "Beginning ER (Algorithm 5) With 200 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model eralg5 --lr 0.01 --memories 200 --replay_batch_size 50 echo "MNIST Permutations:" python3 main.py $PERM $seed --model eralg5 --lr 0.01 --memories 200 --replay_batch_size 10 echo "Beginning MER (Algorithm 1) With 5120 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model meralg1 --lr 0.03 --beta 0.03 --gamma 1.0 --memories 5120 --replay_batch_size 100 --batches_per_example 10 echo "MNIST Permutations:" python3 main.py $PERM $seed --model meralg1 --lr 0.03 --beta 0.03 --gamma 1.0 --memories 5120 --replay_batch_size 100 --batches_per_example 10 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model meralg1 --lr 0.1 --beta 0.01 --gamma 1.0 --memories 5120 --replay_batch_size 5 --batches_per_example 10 echo "Beginning MER (Algorithm 1) With 500 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model meralg1 --lr 0.1 --beta 0.01 --gamma 1.0 --memories 500 --replay_batch_size 10 --batches_per_example 10 echo "MNIST Permutations:" python3 main.py $PERM $seed --model meralg1 --lr 0.03 --beta 0.03 --gamma 1.0 --memories 500 --replay_batch_size 25 --batches_per_example 10 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model meralg1 --lr 0.03 --beta 0.03 --gamma 1.0 --memories 500 --replay_batch_size 5 --batches_per_example 10 echo "Beginning MER (Algorithm 1) With 200 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model meralg1 --lr 0.1 --beta 0.01 --gamma 1.0 --memories 200 --replay_batch_size 10 --batches_per_example 5 echo "MNIST Permutations:" python3 main.py $PERM $seed --model meralg1 --lr 0.03 --beta 0.03 --gamma 1.0 --memories 200 --replay_batch_size 10 --batches_per_example 10 echo "Beginning MER (Algorithm 6) With 5120 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model meralg6 --lr 0.03 --gamma 0.1 --memories 5120 --replay_batch_size 100 echo "MNIST Permutations:" python3 main.py $PERM $seed --model meralg6 --lr 0.03 --gamma 0.1 --memories 5120 --replay_batch_size 50 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model meralg6 --lr 0.03 --gamma 0.1 --memories 5120 --replay_batch_size 25 echo "Beginning MER (Algorithm 6) With 500 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model meralg6 --lr 0.1 --gamma 0.03 --memories 500 --replay_batch_size 10 echo "MNIST Permutations:" python3 main.py $PERM $seed --model meralg6 --lr 0.03 --gamma 0.3 --memories 500 --replay_batch_size 10 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model meralg6 --lr 0.1 --gamma 0.03 --memories 500 --replay_batch_size 5 echo "Beginning MER (Algorithm 6) With 200 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model meralg6 --lr 0.1 --gamma 0.03 --memories 200 --replay_batch_size 25 echo "MNIST Permutations:" python3 main.py $PERM $seed --model meralg6 --lr 0.1 --gamma 0.03 --memories 200 --replay_batch_size 5 echo "Beginning MER (Algorithm 7) With 5120 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model meralg7 --lr 0.03 --gamma 0.03 --memories 5120 --replay_batch_size 100 --s 5 echo "MNIST Permutations:" python3 main.py $PERM $seed --model meralg7 --lr 0.01 --gamma 0.1 --memories 5120 --replay_batch_size 100 --s 10 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model meralg7 --lr 0.03 --gamma 0.03 --memories 5120 --replay_batch_size 100 --s 10 echo "Beginning MER (Algorithm 7) With 500 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model meralg7 --lr 0.03 --gamma 0.03 --memories 500 --replay_batch_size 50 --s 5 echo "MNIST Permutations:" python3 main.py $PERM $seed --model meralg7 --lr 0.01 --gamma 0.1 --memories 500 --replay_batch_size 25 --s 10 echo "MNIST Many Permutations:" python3 main.py $MANY $seed --model meralg7 --lr 0.03 --gamma 0.03 --memories 500 --replay_batch_size 5 --s 10 echo "Beginning MER (Algorithm 7) With 200 Memories" "( seed =" $seed ")" echo "MNIST Rotations:" python3 main.py $ROT $seed --model meralg7 --lr 0.03 --gamma 0.03 --memories 200 --replay_batch_size 50 --s 5 echo "MNIST Permutations:" python3 main.py $PERM $seed --model meralg7 --lr 0.03 --gamma 0.1 --memories 200 --replay_batch_size 5 --s 2 ================================================ FILE: metrics/metrics.py ================================================ ### We directly copied the metrics.py model file from the GEM project https://github.com/facebookresearch/GradientEpisodicMemory # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import print_function import torch def task_changes(result_t): n_tasks = int(result_t.max() + 1) changes = [] current = result_t[0] for i, t in enumerate(result_t): if t != current: changes.append(i) current = t return n_tasks, changes def confusion_matrix(result_t, result_a, fname=None): nt, changes = task_changes(result_t) baseline = result_a[0] changes = torch.LongTensor(changes + [result_a.size(0)]) - 1 result = result_a.index_select(0, torch.LongTensor(changes)) # .index (torch<0.3.1) | .index_select (torch>0.4) # acc[t] equals result[t,t] acc = result.diag() fin = result[nt - 1] # bwt[t] equals result[T,t] - acc[t] bwt = result[nt - 1] - acc # fwt[t] equals result[t-1,t] - baseline[t] fwt = torch.zeros(nt) for t in range(1, nt): fwt[t] = result[t - 1, t] - baseline[t] if fname is not None: f = open(fname, 'w') print(' '.join(['%.4f' % r for r in baseline]), file=f) print('|', file=f) for row in range(result.size(0)): print(' '.join(['%.4f' % r for r in result[row]]), file=f) print('', file=f) # print('Diagonal Accuracy: %.4f' % acc.mean(), file=f) print('Final Accuracy: %.4f' % fin.mean(), file=f) print('Backward: %.4f' % bwt.mean(), file=f) print('Forward: %.4f' % fwt.mean(), file=f) f.close() stats = [] # stats.append(acc.mean()) stats.append(fin.mean()) stats.append(bwt.mean()) stats.append(fwt.mean()) return stats ================================================ FILE: model/common.py ================================================ ### A copy of common.py from https://github.com/facebookresearch/GradientEpisodicMemory. ### We leveraged the same architecture and weight initialization for all of our experiments. # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import math import torch import torch.nn as nn from torch.nn.functional import relu, avg_pool2d def Xavier(m): if m.__class__.__name__ == 'Linear': fan_in, fan_out = m.weight.data.size(1), m.weight.data.size(0) std = 1.0 * math.sqrt(2.0 / (fan_in + fan_out)) a = math.sqrt(3.0) * std m.weight.data.uniform_(-a, a) m.bias.data.fill_(0.0) class MLP(nn.Module): def __init__(self, sizes): super(MLP, self).__init__() layers = [] for i in range(0, len(sizes) - 1): layers.append(nn.Linear(sizes[i], sizes[i + 1])) if i < (len(sizes) - 2): layers.append(nn.ReLU()) self.net = nn.Sequential(*layers) self.net.apply(Xavier) def forward(self, x): return self.net(x) def conv3x3(in_planes, out_planes, stride=1): return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(in_planes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = nn.Sequential( nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(self.expansion * planes) ) def forward(self, x): out = relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) out += self.shortcut(x) out = relu(out) return out class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes, nf): super(ResNet, self).__init__() self.in_planes = nf self.conv1 = conv3x3(3, nf * 1) self.bn1 = nn.BatchNorm2d(nf * 1) self.layer1 = self._make_layer(block, nf * 1, num_blocks[0], stride=1) self.layer2 = self._make_layer(block, nf * 2, num_blocks[1], stride=2) self.layer3 = self._make_layer(block, nf * 4, num_blocks[2], stride=2) self.layer4 = self._make_layer(block, nf * 8, num_blocks[3], stride=2) self.linear = nn.Linear(nf * 8 * block.expansion, num_classes) def _make_layer(self, block, planes, num_blocks, stride): strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion return nn.Sequential(*layers) def forward(self, x): bsz = x.size(0) out = relu(self.bn1(self.conv1(x.view(bsz, 3, 32, 32)))) out = self.layer1(out) out = self.layer2(out) out = self.layer3(out) out = self.layer4(out) out = avg_pool2d(out, 4) out = out.view(out.size(0), -1) out = self.linear(out) return out def ResNet18(nclasses, nf=20): return ResNet(BasicBlock, [2, 2, 2, 2], nclasses, nf) ================================================ FILE: model/eralg4.py ================================================ # An implementation of Experience Replay (ER) with reservoir sampling and without using tasks from Algorithm 4 of https://openreview.net/pdf?id=B1gTShAct7 # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import numpy as np from .common import MLP, ResNet18 import random from torch.nn.modules.loss import CrossEntropyLoss from random import shuffle import sys import warnings warnings.filterwarnings("ignore") class Net(nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() nl, nh = args.n_layers, args.n_hiddens self.net = MLP([n_inputs] + [nh] * nl + [n_outputs]) self.bce = CrossEntropyLoss() self.n_outputs = n_outputs self.opt = optim.SGD(self.parameters(), args.lr) self.batchSize = int(args.replay_batch_size) self.memories = args.memories # allocate buffer self.M = [] self.age = 0 # handle gpus if specified self.cuda = args.cuda if self.cuda: self.net = self.net.cuda() def forward(self, x, t): output = self.net(x) return output def getBatch(self,x,y,t): mxi = np.array(x) myi = np.array(y) bxs = [] bys = [] if len(self.M) > 0: order = [i for i in range(0,len(self.M))] osize = min(self.batchSize,len(self.M)) for j in range(0,osize): shuffle(order) k = order[j] x,y,t = self.M[k] xi = np.array(x) yi = np.array(y) bxs.append(xi) bys.append(yi) bxs.append(mxi) bys.append(myi) bxs = Variable(torch.from_numpy(np.array(bxs))).float().view(-1,784) bys = Variable(torch.from_numpy(np.array(bys))).long().view(-1) # handle gpus if specified if self.cuda: bxs = bxs.cuda() bys = bys.cuda() return bxs,bys def observe(self, x, t, y): ### step through elements of x for i in range(0,x.size()[0]): self.age += 1 xi = x[i].data.cpu().numpy() yi = y[i].data.cpu().numpy() self.net.zero_grad() # Draw batch from buffer: bx,by = self.getBatch(xi,yi,t) # Update parameters with mini-batch SGD: prediction = self.forward(bx,0) loss = self.bce(prediction,by) loss.backward() self.opt.step() # Reservoir sampling memory update: if len(self.M) < self.memories: self.M.append([xi,yi,t]) else: p = random.randint(0,self.age) if p < self.memories: self.M[p] = [xi,yi,t] ================================================ FILE: model/eralg5.py ================================================ # An implementation of Experience Replay (ER) with tasks from Algorithm 5 in https://openreview.net/pdf?id=B1gTShAct7 # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import numpy as np from .common import MLP, ResNet18 import random from torch.nn.modules.loss import CrossEntropyLoss from random import shuffle import sys import warnings warnings.filterwarnings("ignore") class Net(nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() nl, nh = args.n_layers, args.n_hiddens self.net = MLP([n_inputs] + [nh] * nl + [n_outputs]) self.bce = CrossEntropyLoss() self.n_outputs = n_outputs self.opt = optim.SGD(self.parameters(), args.lr) self.batchSize = int(args.replay_batch_size) self.memories = args.memories # allocate buffer self.M = [] self.age = 0 # handle gpus if specified self.cuda = args.cuda if self.cuda: self.net = self.net.cuda() def forward(self, x, t): output = self.net(x) return output def getBatch(self,x,y,t): bx = {} by = {} bx[t] = [x] by[t] = [y] if len(self.M) > 0: order = [i for i in range(0,len(self.M))] osize = min(self.batchSize,len(self.M)) for j in range(0,osize): shuffle(order) k = order[j] x,y,t = self.M[k] if t in bx: bx[t].append(x) by[t].append(y) else: bx[t] = [x] by[t] = [y] for task in bx: bx[task] = Variable(torch.from_numpy(np.array(bx[task]))).float() by[task] = Variable(torch.from_numpy(np.array(by[task]))).long().view(-1) # handle gpus if specified if self.cuda: bx[task] = bx[task].cuda() by[task] = by[task].cuda() return bx,by def observe(self, x, t, y): ### step through elements of x for i in range(0,x.size()[0]): self.age += 1 xi = x[i].data.cpu().numpy() yi = y[i].data.cpu().numpy() self.net.zero_grad() # Draw batch from buffer: bx,by = self.getBatch(xi,yi,t) # Update parameters with balanced loss across tasks: loss = 0.0 for kz in bx: prediction = self.forward(bx[kz],kz) loss += self.bce(prediction,by[kz]) loss.backward() self.opt.step() # Reservoir sampling memory update: if len(self.M) < self.memories: self.M.append([xi,yi,t]) else: p = random.randint(0,self.age) if p < self.memories: self.M[p] = [xi,yi,t] ================================================ FILE: model/ewc.py ================================================ ### We use the same version of EwC https://www.pnas.org/content/114/13/3521 originally used in https://github.com/facebookresearch/GradientEpisodicMemory ### We directly copied the ewc.py model file from the GEM project https://github.com/facebookresearch/GradientEpisodicMemory # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch.autograd import Variable from .common import MLP, ResNet18 class Net(torch.nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() nl, nh = args.n_layers, args.n_hiddens self.reg = args.memory_strength # setup network self.is_cifar = (args.data_file == 'cifar100.pt') if self.is_cifar: self.net = ResNet18(n_outputs) else: self.net = MLP([n_inputs] + [nh] * nl + [n_outputs]) # setup optimizer self.opt = torch.optim.SGD(self.net.parameters(), lr=args.lr) # setup losses self.bce = torch.nn.CrossEntropyLoss() # setup memories self.current_task = 0 self.fisher = {} self.optpar = {} self.memx = None self.memy = None if self.is_cifar: self.nc_per_task = n_outputs / n_tasks else: self.nc_per_task = n_outputs self.n_outputs = n_outputs self.n_memories = args.n_memories # handle gpus if specified self.cuda = args.cuda if self.cuda: self.net = self.net.cuda() def compute_offsets(self, task): if self.is_cifar: offset1 = task * self.nc_per_task offset2 = (task + 1) * self.nc_per_task else: offset1 = 0 offset2 = self.n_outputs return int(offset1), int(offset2) def forward(self, x, t): output = self.net(x) if self.is_cifar: # make sure we predict classes within the current task offset1, offset2 = self.compute_offsets(t) if offset1 > 0: output[:, :offset1].data.fill_(-10e10) if offset2 < self.n_outputs: output[:, int(offset2):self.n_outputs].data.fill_(-10e10) return output def observe(self, x, t, y): self.net.train() # next task? if t != self.current_task: self.net.zero_grad() if self.is_cifar: offset1, offset2 = self.compute_offsets(self.current_task) self.bce((self.net(Variable(self.memx))[:, offset1: offset2]), Variable(self.memy) - offset1).backward() else: self.bce(self(Variable(self.memx), self.current_task), Variable(self.memy)).backward() self.fisher[self.current_task] = [] self.optpar[self.current_task] = [] for p in self.net.parameters(): pd = p.data.clone() pg = p.grad.data.clone().pow(2) self.optpar[self.current_task].append(pd) self.fisher[self.current_task].append(pg) self.current_task = t self.memx = None self.memy = None if self.memx is None: self.memx = x.data.clone() self.memy = y.data.clone() else: if self.memx.size(0) < self.n_memories: self.memx = torch.cat((self.memx, x.data.clone())) self.memy = torch.cat((self.memy, y.data.clone())) if self.memx.size(0) > self.n_memories: self.memx = self.memx[:self.n_memories] self.memy = self.memy[:self.n_memories] self.net.zero_grad() if self.is_cifar: offset1, offset2 = self.compute_offsets(t) loss = self.bce((self.net(x)[:, offset1: offset2]), y - offset1) else: loss = self.bce(self(x, t), y) for tt in range(t): for i, p in enumerate(self.net.parameters()): l = self.reg * Variable(self.fisher[tt][i]) l = l * (p - Variable(self.optpar[tt][i])).pow(2) loss += l.sum() loss.backward() self.opt.step() ================================================ FILE: model/gem.py ================================================ ### This is a copy of GEM from https://github.com/facebookresearch/GradientEpisodicMemory. ### In order to ensure complete reproducability, we do not change the file and treat it as a baseline. # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import numpy as np import quadprog from .common import MLP, ResNet18 # Auxiliary functions useful for GEM's inner optimization. def compute_offsets(task, nc_per_task, is_cifar): """ Compute offsets for cifar to determine which outputs to select for a given task. """ if is_cifar: offset1 = task * nc_per_task offset2 = (task + 1) * nc_per_task else: offset1 = 0 offset2 = nc_per_task return offset1, offset2 def store_grad(pp, grads, grad_dims, tid): """ This stores parameter gradients of past tasks. pp: parameters grads: gradients grad_dims: list with number of parameters per layers tid: task id """ # store the gradients grads[:, tid].fill_(0.0) cnt = 0 for param in pp(): if param.grad is not None: beg = 0 if cnt == 0 else sum(grad_dims[:cnt]) en = sum(grad_dims[:cnt + 1]) grads[beg: en, tid].copy_(param.grad.data.view(-1)) cnt += 1 def overwrite_grad(pp, newgrad, grad_dims): """ This is used to overwrite the gradients with a new gradient vector, whenever violations occur. pp: parameters newgrad: corrected gradient grad_dims: list storing number of parameters at each layer """ cnt = 0 for param in pp(): if param.grad is not None: beg = 0 if cnt == 0 else sum(grad_dims[:cnt]) en = sum(grad_dims[:cnt + 1]) this_grad = newgrad[beg: en].contiguous().view( param.grad.data.size()) param.grad.data.copy_(this_grad) cnt += 1 def project2cone2(gradient, memories, margin=0.5): """ Solves the GEM dual QP described in the paper given a proposed gradient "gradient", and a memory of task gradients "memories". Overwrites "gradient" with the final projected update. input: gradient, p-vector input: memories, (t * p)-vector output: x, p-vector """ memories_np = memories.cpu().t().double().numpy() gradient_np = gradient.cpu().contiguous().view(-1).double().numpy() t = memories_np.shape[0] P = np.dot(memories_np, memories_np.transpose()) P = 0.5 * (P + P.transpose()) q = np.dot(memories_np, gradient_np) * -1 G = np.eye(t) h = np.zeros(t) + margin v = quadprog.solve_qp(P, q, G, h)[0] x = np.dot(v, memories_np) + gradient_np gradient.copy_(torch.Tensor(x).view(-1, 1)) class Net(nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() nl, nh = args.n_layers, args.n_hiddens self.margin = args.memory_strength self.is_cifar = (args.data_file == 'cifar100.pt') if self.is_cifar: self.net = ResNet18(n_outputs) else: self.net = MLP([n_inputs] + [nh] * nl + [n_outputs]) self.ce = nn.CrossEntropyLoss() self.n_outputs = n_outputs self.opt = optim.SGD(self.parameters(), args.lr) self.n_memories = args.n_memories self.gpu = args.cuda # allocate episodic memory self.memory_data = torch.FloatTensor( n_tasks, self.n_memories, n_inputs) self.memory_labs = torch.LongTensor(n_tasks, self.n_memories) if args.cuda: self.memory_data = self.memory_data.cuda() self.memory_labs = self.memory_labs.cuda() # allocate temporary synaptic memory self.grad_dims = [] for param in self.parameters(): self.grad_dims.append(param.data.numel()) self.grads = torch.Tensor(sum(self.grad_dims), n_tasks) if args.cuda: self.grads = self.grads.cuda() # allocate counters self.observed_tasks = [] self.old_task = -1 self.mem_cnt = 0 if self.is_cifar: self.nc_per_task = int(n_outputs / n_tasks) else: self.nc_per_task = n_outputs if args.cuda: self.cuda() def forward(self, x, t): output = self.net(x) if self.is_cifar: # make sure we predict classes within the current task offset1 = int(t * self.nc_per_task) offset2 = int((t + 1) * self.nc_per_task) if offset1 > 0: output[:, :offset1].data.fill_(-10e10) if offset2 < self.n_outputs: output[:, offset2:self.n_outputs].data.fill_(-10e10) return output def observe(self, x, t, y): # update memory if t != self.old_task: self.observed_tasks.append(t) self.old_task = t # Update ring buffer storing examples from current task bsz = y.data.size(0) endcnt = min(self.mem_cnt + bsz, self.n_memories) effbsz = endcnt - self.mem_cnt self.memory_data[t, self.mem_cnt: endcnt].copy_( x.data[: effbsz]) if bsz == 1: self.memory_labs[t, self.mem_cnt] = y.data[0] else: self.memory_labs[t, self.mem_cnt: endcnt].copy_( y.data[: effbsz]) self.mem_cnt += effbsz if self.mem_cnt == self.n_memories: self.mem_cnt = 0 # compute gradient on previous tasks if len(self.observed_tasks) > 1: for tt in range(len(self.observed_tasks) - 1): self.zero_grad() # fwd/bwd on the examples in the memory past_task = self.observed_tasks[tt] offset1, offset2 = compute_offsets(past_task, self.nc_per_task, self.is_cifar) ptloss = self.ce( self.forward( Variable(self.memory_data[past_task]), past_task)[:, offset1: offset2], Variable(self.memory_labs[past_task] - offset1)) ptloss.backward() store_grad(self.parameters, self.grads, self.grad_dims, past_task) # now compute the grad on the current minibatch self.zero_grad() offset1, offset2 = compute_offsets(t, self.nc_per_task, self.is_cifar) loss = self.ce(self.forward(x, t)[:, offset1: offset2], y - offset1) loss.backward() # check if gradient violates constraints if len(self.observed_tasks) > 1: # copy gradient store_grad(self.parameters, self.grads, self.grad_dims, t) indx = torch.cuda.LongTensor(self.observed_tasks[:-1]) if self.gpu \ else torch.LongTensor(self.observed_tasks[:-1]) dotp = torch.mm(self.grads[:, t].unsqueeze(0), self.grads.index_select(1, indx)) if (dotp < 0).sum() != 0: project2cone2(self.grads[:, t].unsqueeze(1), self.grads.index_select(1, indx), self.margin) # copy gradients back overwrite_grad(self.parameters, self.grads[:, t], self.grad_dims) self.opt.step() ================================================ FILE: model/independent.py ================================================ ### code for this basline is copied directly from independent.py in https://github.com/facebookresearch/GradientEpisodicMemory # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch.autograd import Variable from .common import MLP, ResNet18 class Net(torch.nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() nl, nh = args.n_layers, args.n_hiddens self.nets = torch.nn.ModuleList() self.opts = [] self.is_cifar = (args.data_file == 'cifar100.pt') if self.is_cifar: self.nc_per_task = n_outputs / n_tasks self.n_outputs = n_outputs # setup network for _ in range(n_tasks): if self.is_cifar: self.nets.append( ResNet18(int(n_outputs / n_tasks), int(20 / n_tasks))) else: self.nets.append( MLP([n_inputs] + [int(nh / n_tasks)] * nl + [n_outputs])) # setup optimizer for t in range(n_tasks): self.opts.append(torch.optim.SGD(self.nets[t].parameters(), lr=args.lr)) # setup loss self.bce = torch.nn.CrossEntropyLoss() self.finetune = args.finetune self.gpu = args.cuda self.old_task = 0 def forward(self, x, t): output = self.nets[t](x) if self.is_cifar: bigoutput = torch.Tensor(x.size(0), self.n_outputs) if self.gpu: bigoutput = bigoutput.cuda() bigoutput.fill_(-10e10) bigoutput[:, int(t * self.nc_per_task): int((t + 1) * self.nc_per_task)].copy_( output.data) return Variable(bigoutput) else: return output def observe(self, x, t, y): # detect beginning of a new task if self.finetune and t > 0 and t != self.old_task: # initialize current network like the previous one for ppold, ppnew in zip(self.nets[self.old_task].parameters(), self.nets[t].parameters()): ppnew.data.copy_(ppold.data) self.old_task = t self.train() self.zero_grad() if self.is_cifar: self.bce(self.nets[t](x), y - int(t * self.nc_per_task)).backward() else: self.bce(self(x, t), y).backward() self.opts[t].step() ================================================ FILE: model/meralg1.py ================================================ # An implementation of MER Algorithm 1 from https://openreview.net/pdf?id=B1gTShAct7 # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import numpy as np from .common import MLP, ResNet18 import random from torch.nn.modules.loss import CrossEntropyLoss from random import shuffle import sys from copy import deepcopy import warnings warnings.filterwarnings("ignore") class Net(nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() nl, nh = args.n_layers, args.n_hiddens self.net = MLP([n_inputs] + [nh] * nl + [n_outputs]) self.bce = CrossEntropyLoss() self.n_outputs = n_outputs self.opt = optim.SGD(self.parameters(), args.lr) self.batchSize = int(args.replay_batch_size) self.memories = args.memories self.steps = int(args.batches_per_example) self.beta = args.beta self.gamma = args.gamma # allocate buffer self.M = [] self.age = 0 # handle gpus if specified self.cuda = args.cuda if self.cuda: self.net = self.net.cuda() def forward(self, x, t): output = self.net(x) return output def getBatch(self,x,y,t): xi = Variable(torch.from_numpy(np.array(x))).float().view(1,-1) yi = Variable(torch.from_numpy(np.array(y))).long().view(1) if self.cuda: xi = xi.cuda() yi = yi.cuda() bxs = [xi] bys = [yi] if len(self.M) > 0: order = [i for i in range(0,len(self.M))] osize = min(self.batchSize,len(self.M)) for j in range(0,osize): shuffle(order) k = order[j] x,y,t = self.M[k] xi = Variable(torch.from_numpy(np.array(x))).float().view(1,-1) yi = Variable(torch.from_numpy(np.array(y))).long().view(1) # handle gpus if specified if self.cuda: xi = xi.cuda() yi = yi.cuda() bxs.append(xi) bys.append(yi) return bxs,bys def observe(self, x, t, y): ### step through elements of x for i in range(0,x.size()[0]): self.age += 1 xi = x[i].data.cpu().numpy() yi = y[i].data.cpu().numpy() self.net.zero_grad() before = deepcopy(self.net.state_dict()) for step in range(0,self.steps): weights_before = deepcopy(self.net.state_dict()) # Draw batch from buffer: bxs,bys = self.getBatch(xi,yi,t) loss = 0.0 for idx in range(len(bxs)): self.net.zero_grad() bx = bxs[idx] by = bys[idx] prediction = self.forward(bx,0) loss = self.bce(prediction,by) loss.backward() self.opt.step() weights_after = self.net.state_dict() # Within batch Reptile meta-update: self.net.load_state_dict({name : weights_before[name] + ((weights_after[name] - weights_before[name]) * self.beta) for name in weights_before}) after = self.net.state_dict() # Across batch Reptile meta-update: self.net.load_state_dict({name : before[name] + ((after[name] - before[name]) * self.gamma) for name in before}) # Reservoir sampling memory update: if len(self.M) < self.memories: self.M.append([xi,yi,t]) else: p = random.randint(0,self.age) if p < self.memories: self.M[p] = [xi,yi,t] ================================================ FILE: model/meralg6.py ================================================ # An implementation of Meta-Experience Replay (MER) Algorithm 6 from https://openreview.net/pdf?id=B1gTShAct7 # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import numpy as np from .common import MLP, ResNet18 import random from torch.nn.modules.loss import CrossEntropyLoss from random import shuffle import sys from copy import deepcopy import warnings from random import shuffle warnings.filterwarnings("ignore") class Net(nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() nl, nh = args.n_layers, args.n_hiddens self.net = MLP([n_inputs] + [nh] * nl + [n_outputs]) self.bce = CrossEntropyLoss() self.n_outputs = n_outputs self.opt = optim.SGD(self.parameters(), args.lr) self.batchSize = int(args.replay_batch_size) self.memories = args.memories self.steps = int(args.batches_per_example) self.gamma = args.gamma # allocate buffer self.M = [] self.age = 0 # handle gpus if specified self.cuda = args.cuda if self.cuda: self.net = self.net.cuda() def forward(self, x, t): output = self.net(x) return output def getBatch(self,x,y,t): mxi = Variable(torch.from_numpy(np.array(x))).float().view(1,-1) myi = Variable(torch.from_numpy(np.array(y))).long().view(1) if self.cuda: mxi = mxi.cuda() myi = myi.cuda() bxs = [] bys = [] if len(self.M) > 0: order = [i for i in range(0,len(self.M))] osize = min(self.batchSize,len(self.M)) for j in range(0,osize): shuffle(order) k = order[j] x,y,t = self.M[k] xi = Variable(torch.from_numpy(np.array(x))).float().view(1,-1) yi = Variable(torch.from_numpy(np.array(y))).long().view(1) # handle gpus if specified if self.cuda: xi = xi.cuda() yi = yi.cuda() bxs.append(xi) bys.append(yi) bxs.append(mxi) bys.append(myi) return bxs,bys def observe(self, x, t, y): ### step through elements of x for i in range(0,x.size()[0]): self.age += 1 xi = x[i].data.cpu().numpy() yi = y[i].data.cpu().numpy() bx,by = self.getBatch(xi,yi,t) self.net.zero_grad() for step in range(0,self.steps): weights_before = deepcopy(self.net.state_dict()) # Draw batch from buffer: bxs,bys = self.getBatch(xi,yi,t) loss = 0.0 for idx in range(len(bxs)): self.net.zero_grad() bx = bxs[idx] by = bys[idx] prediction = self.forward(bx,0) loss = self.bce(prediction,by) loss.backward() self.opt.step() weights_after = self.net.state_dict() # Reptile meta-update: self.net.load_state_dict({name : weights_before[name] + ((weights_after[name] - weights_before[name]) * self.gamma) for name in weights_before}) sys.stdout.flush() # Reservoir sampling memory update: if len(self.M) < self.memories: self.M.append([xi,yi,t]) else: p = random.randint(0,self.age) if p < self.memories: self.M[p] = [xi,yi,t] ================================================ FILE: model/meralg7.py ================================================ # An implementation of Meta-Experience Replay (MER) Algorithm 7 from https://openreview.net/pdf?id=B1gTShAct7 # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import numpy as np from .common import MLP, ResNet18 import random from torch.nn.modules.loss import CrossEntropyLoss from random import shuffle import sys from copy import deepcopy import warnings from random import shuffle warnings.filterwarnings("ignore") class Net(nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() nl, nh = args.n_layers, args.n_hiddens self.net = MLP([n_inputs] + [nh] * nl + [n_outputs]) self.bce = CrossEntropyLoss() self.n_outputs = n_outputs self.opt = optim.SGD(self.parameters(), args.lr) self.batchSize = int(args.replay_batch_size) self.memories = args.memories self.s = float(args.s) self.gamma = args.gamma # allocate buffer self.M = [] self.age = 0 # handle gpus if specified self.cuda = args.cuda if self.cuda: self.net = self.net.cuda() def forward(self, x, t): output = self.net(x) return output def getBatch(self,x,y,t): mxi = Variable(torch.from_numpy(np.array(x))).float().view(1,-1) myi = Variable(torch.from_numpy(np.array(y))).long().view(1) if self.cuda: mxi = mxi.cuda() myi = myi.cuda() bxs = [mxi] bys = [myi] if len(self.M) > 0: order = [i for i in range(0,len(self.M))] osize = min(self.batchSize,len(self.M)) for j in range(0,osize): shuffle(order) k = order[j] x,y,t = self.M[k] xi = Variable(torch.from_numpy(np.array(x))).float().view(1,-1) yi = Variable(torch.from_numpy(np.array(y))).long().view(1) if self.cuda: xi = xi.cuda() yi = yi.cuda() bxs.append(xi) bys.append(yi) bx2 = [] by2 = [] indexes = [ind for ind in range(len(bxs))] shuffle(indexes) for index in indexes: if index == 0: myindex = len(bx2) bx2.append(bxs[index]) by2.append(bys[index]) return bx2,by2,myindex def observe(self, x, t, y): ### step through elements of x for i in range(0,x.size()[0]): self.age += 1 xi = x[i].data.cpu().numpy() yi = y[i].data.cpu().numpy() if self.age > 1: self.net.zero_grad() weights_before = deepcopy(self.net.state_dict()) # Draw batch from buffer: bxs,bys,myind = self.getBatch(xi,yi,t) # SGD on individual samples from batch: loss = 0.0 for idx in range(len(bxs)): self.net.zero_grad() bx = bxs[idx] by = bys[idx] prediction = self.forward(bx,0) if myind == idx: # High learning rate SGD on current example: loss = self.s*self.bce(prediction,by) else: loss = self.bce(prediction,by) loss.backward() self.opt.step() weights_after = self.net.state_dict() # Reptile meta-update: self.net.load_state_dict({name : weights_before[name] + ((weights_after[name] - weights_before[name]) * self.gamma) for name in weights_before}) sys.stdout.flush() # Reservoir sampling memory update: if len(self.M) < self.memories: self.M.append([xi,yi,t]) else: p = random.randint(0,self.age) if p < self.memories: self.M[p] = [xi,yi,t] ================================================ FILE: model/online.py ================================================ ### code for this basline is copied directly from single.py in https://github.com/facebookresearch/GradientEpisodicMemory # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from .common import MLP, ResNet18 class Net(torch.nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() nl, nh = args.n_layers, args.n_hiddens # setup network self.is_cifar = (args.data_file == 'cifar100.pt') if self.is_cifar: self.net = ResNet18(n_outputs) else: self.net = MLP([n_inputs] + [nh] * nl + [n_outputs]) # setup optimizer self.opt = torch.optim.SGD(self.parameters(), lr=args.lr) # setup losses self.bce = torch.nn.CrossEntropyLoss() if self.is_cifar: self.nc_per_task = n_outputs / n_tasks else: self.nc_per_task = n_outputs self.n_outputs = n_outputs # handle gpus if specified self.cuda = args.cuda if self.cuda: self.net = self.net.cuda() def compute_offsets(self, task): if self.is_cifar: offset1 = task * self.nc_per_task offset2 = (task + 1) * self.nc_per_task else: offset1 = 0 offset2 = self.n_outputs return int(offset1), int(offset2) def forward(self, x, t): output = self.net(x) if self.is_cifar: # make sure we predict classes within the current task offset1, offset2 = self.compute_offsets(t) if offset1 > 0: output[:, :offset1].data.fill_(-10e10) if offset2 < self.n_outputs: output[:, offset2:self.n_outputs].data.fill_(-10e10) return output def observe(self, x, t, y): self.train() self.zero_grad() if self.is_cifar: offset1, offset2 = self.compute_offsets(t) self.bce((self.net(x)[:, offset1: offset2]), y - offset1).backward() else: self.bce(self(x, t), y).backward() self.opt.step() ================================================ FILE: model/taskinput.py ================================================ ### Code for this basline is copied directly from multimodal.py in https://github.com/facebookresearch/GradientEpisodicMemory # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn def reset_bias(m): m.bias.data.fill_(0.0) class Net(nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() self.i_layer = nn.ModuleList() self.h_layer = nn.ModuleList() self.o_layer = nn.ModuleList() self.n_layers = args.n_layers nh = args.n_hiddens if self.n_layers > 0: # dedicated input layer for _ in range(n_tasks): self.i_layer += [nn.Linear(n_inputs, nh)] reset_bias(self.i_layer[-1]) # shared hidden layer self.h_layer += [nn.ModuleList()] for _ in range(self.n_layers): self.h_layer[0] += [nn.Linear(nh, nh)] reset_bias(self.h_layer[0][0]) # shared output layer self.o_layer += [nn.Linear(nh, n_outputs)] reset_bias(self.o_layer[-1]) # linear model falls back to independent models else: self.i_layer += [nn.Linear(n_inputs, n_outputs)] reset_bias(self.i_layer[-1]) self.relu = nn.ReLU() self.soft = nn.LogSoftmax() self.loss = nn.NLLLoss() self.optimizer = torch.optim.SGD(self.parameters(), args.lr) def forward(self, x, t): h = x if self.n_layers == 0: y = self.soft(self.i_layer[t if isinstance(t, int) else t[0]](h)) else: # task-specific input h = self.relu(self.i_layer[t if isinstance(t, int) else t[0]](h)) # shared hiddens for l in range(self.n_layers): h = self.relu(self.h_layer[0][l](h)) # shared output y = self.soft(self.o_layer[0](h)) return y def observe(self, x, t, y): self.zero_grad() self.loss(self.forward(x, t), y).backward() self.optimizer.step() ================================================ FILE: requirements.txt ================================================ argparse datetime matplotlib numpy pillow quadprog torchvision urllib3 uuid ================================================ FILE: unit_test.sh ================================================ #!/bin/bash seed=0 # Test on a small number of samples per task ROT="--n_layers 2 --n_hiddens 100 --data_path data/ --save_path results/ --batch_size 1 --log_every 100 --samples_per_task 10 --data_file mnist_rotations.pt --cuda no --seed" echo "Begin Unit Test with seed =" $seed " on MNIST Rotations" echo "Testing Online" python3 main.py $ROT $seed --model online --lr 0.0003 if [ $? -eq 0 ] then echo "Online finished successfully" else echo "Exited with error." >&2 # Redirect stdout from echo command to stderr. fi echo "Testing Independent" python3 main.py $ROT $seed --model independent --lr 0.01 if [ $? -eq 0 ] then echo "Independent finished successfully" else echo "Exited with error." >&2 # Redirect stdout from echo command to stderr. fi echo "Testing EWC" python3 main.py $ROT $seed --model ewc --lr 0.001 --n_memories 10 --memory_strength 100.0 if [ $? -eq 0 ] then echo "EWC finished successfully" else echo "Exited with error." >&2 # Redirect stdout from echo command to stderr. fi echo "Testing GEM" python3 main.py $ROT $seed --model gem --lr 0.01 --n_memories 256 --memory_strength 1.0 if [ $? -eq 0 ] then echo "GEM finished successfully" else echo "Exited with error." >&2 # Redirect stdout from echo command to stderr. fi echo "Testing eralg4" python3 main.py $ROT $seed --model eralg4 --lr 0.1 --memories 5120 --replay_batch_size 25 if [ $? -eq 0 ] then echo "eralg4 finished successfully" else echo "Exited with error." >&2 # Redirect stdout from echo command to stderr. fi echo "Testing eralg5" python3 main.py $ROT $seed --model eralg5 --lr 0.03 --memories 5120 --replay_batch_size 100 if [ $? -eq 0 ] then echo "eralg5 finished successfully" else echo "Exited with error." >&2 # Redirect stdout from echo command to stderr. fi echo "Testing meralg1" python3 main.py $ROT $seed --model meralg1 --lr 0.03 --beta 0.03 --gamma 1.0 --memories 5120 --replay_batch_size 100 --batches_per_example 10 if [ $? -eq 0 ] then echo "meralg1 finished successfully" else echo "Exited with error." >&2 # Redirect stdout from echo command to stderr. fi echo "Testing meralg6" python3 main.py $ROT $seed --model meralg6 --lr 0.03 --gamma 0.1 --memories 5120 --replay_batch_size 100 if [ $? -eq 0 ] then echo "meralg6 finished successfully" else echo "Exited with error." >&2 # Redirect stdout from echo command to stderr. fi echo "Testing meralg7" python3 main.py $ROT $seed --model meralg7 --lr 0.03 --gamma 0.03 --memories 500 --replay_batch_size 50 --s 5 if [ $? -eq 0 ] then echo "meralg7 finished successfully" else echo "Exited with error." >&2 # Redirect stdout from echo command to stderr. fi echo "Finished"