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