├── src ├── clean.sh ├── opts.py ├── utils.py ├── main.py ├── sampling.py ├── fc_correction.py ├── training.py └── datasets.py ├── requirements.txt ├── scripts ├── class_sizes.npy ├── imagenet_folder_to_cls.pkl ├── copy_imnet21k_to_imnet2k.py ├── check_img21k.py ├── split_imgnet21k.py └── plot_results.py ├── .vscode └── settings.json ├── .gitignore ├── README.md └── LICENSE /src/clean.sh: -------------------------------------------------------------------------------- 1 | rm -rf __pycache__ 2 | rm -rf */__pycache__ 3 | rm -rf */*/__pycache__ 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | scikit-learn==1.2.2 2 | torch==1.13.1+cu116 3 | torchvision==0.14.1+cu116 4 | -------------------------------------------------------------------------------- /scripts/class_sizes.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drimpossible/BudgetCL/HEAD/scripts/class_sizes.npy -------------------------------------------------------------------------------- /scripts/imagenet_folder_to_cls.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drimpossible/BudgetCL/HEAD/scripts/imagenet_folder_to_cls.pkl -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "makefile.extensionOutputFolder": "./.vscode", 3 | "python.formatting.provider": "yapf", 4 | "python.testing.pytestArgs": [ 5 | "test" 6 | ], 7 | "python.testing.unittestEnabled": false, 8 | "python.testing.pytestEnabled": true, 9 | "python.linting.enabled": true, 10 | "python.linting.pylintEnabled": false, 11 | "python.linting.pycodestyleEnabled": false, 12 | "python.linting.flake8Enabled": true, 13 | "python.linting.lintOnSave": true, 14 | "python.linting.flake8Args": [ 15 | "--based_on_style=pep8", 16 | "--split_before_named_assigns=False" 17 | ], 18 | "editor.formatOnSave": true, 19 | "editor.codeActionsOnSave": { 20 | "source.sortImports": true, 21 | }, 22 | "[python]": { 23 | "editor.formatOnSave": true, 24 | "editor.codeActionsOnSave": { 25 | "source.organizeImports": true 26 | }, 27 | }, 28 | } -------------------------------------------------------------------------------- /scripts/copy_imnet21k_to_imnet2k.py: -------------------------------------------------------------------------------- 1 | import os, shutil 2 | 3 | IMNET21K_DIR = sys.argv[1] 4 | IMNET2K_DIR = sys.argv[2] 5 | ORDER_FILE_DIR = sys.argv[3] 6 | 7 | f = open(ORDER_FILE_DIR+'/class_order.txt', 'r') 8 | lines = f.readlines() 9 | 10 | for line in lines: 11 | os.makedirs(IMNET2K_DIR+'train/'+line.strip(), exist_ok=True) 12 | os.makedirs(IMNET2K_DIR+'val/'+line.strip(), exist_ok=True) 13 | os.makedirs(IMNET2K_DIR+'test/'+line.strip(), exist_ok=True) 14 | 15 | f = open(ORDER_FILE_DIR+'/val.txt', 'r') 16 | lines = f.readlines() 17 | 18 | for line in lines: 19 | line = line.strip() 20 | to = IMNET2K_DIR+line[1:] 21 | prev = IMNET21K_DIR+line.split('/')[2]+'/'+line.split('/')[3] 22 | shutil.copy(IMNET21K_DIR+line.split('/')[2]+'/'+line.split('/')[3], IMNET2K_DIR+line[1:]) 23 | 24 | f = open(ORDER_FILE_DIR+'/test.txt', 'r') 25 | lines = f.readlines() 26 | 27 | for line in lines: 28 | line = line.strip() 29 | to = IMNET2K_DIR+line[1:] 30 | prev = IMNET21K_DIR+line.split('/')[2]+'/'+line.split('/')[3] 31 | shutil.copy(IMNET21K_DIR+line.split('/')[2]+'/'+line.split('/')[3], IMNET2K_DIR+line[1:]) 32 | 33 | f = open(ORDER_FILE_DIR+'/class_incremental_ordering.txt', 'r') 34 | lines = f.readlines() 35 | 36 | for line in lines: 37 | line = line.strip() 38 | to = IMNET2K_DIR+line[1:] 39 | prev = IMNET21K_DIR+line.split('/')[2]+'/'+line.split('/')[3] 40 | shutil.copy(IMNET21K_DIR+line.split('/')[2]+'/'+line.split('/')[3], IMNET2K_DIR+line[1:]) 41 | -------------------------------------------------------------------------------- /scripts/check_img21k.py: -------------------------------------------------------------------------------- 1 | leafs, children = {}, {} 2 | 3 | f1 = open('is-a-relation-synsets.txt', 'r') 4 | lines = f1.readlines() 5 | 6 | f2 = open('cls.txt', 'r') 7 | lines_imgnet = f2.readlines() 8 | 9 | for line in lines: 10 | parent, child = line.strip().split(' ') 11 | if parent not in children: children[parent] = [child] 12 | else: children[parent].extend([child]) 13 | 14 | leafs[parent] = 0 15 | if child not in leafs: leafs[child] = 1 16 | 17 | 18 | def dfs(pline): 19 | all_children = [] 20 | if pline in children: 21 | all_children.extend(children[pline]) 22 | for child in children[pline]: 23 | all_children.extend(dfs(pline=child)) 24 | return all_children 25 | 26 | 27 | problematic = 0 28 | numparent = 0 29 | numchild = 0 30 | not_present = 0 31 | 32 | for line in lines_imgnet: 33 | if line.strip() not in leafs: 34 | not_present += 1 35 | print(line) 36 | elif leafs[line.strip()] == 1: 37 | numchild += 1 38 | elif leafs[line.strip()] == 0: 39 | numparent += 1 40 | all_children = dfs(pline=line.strip()) 41 | #print(all_children) 42 | flag = 0 43 | for child in all_children: 44 | if child in lines_imgnet: 45 | if not flag: 46 | flag = 1 47 | problematic += 1 48 | print(line.strip(), child) 49 | 50 | print(problematic, numparent, numchild, not_present) 51 | print(len(lines_imgnet), numparent + numchild + not_present) 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /scripts/split_imgnet21k.py: -------------------------------------------------------------------------------- 1 | # python split_imgnet21k.py 2 | # Reproduce ours by: python select_subset_imagenet21k.py PATH_TO_IMAGENET21K PATH_TO_IMAGENET1K 1000 1200 ../clim2k/ 3 | 4 | import copy, os, random, sys 5 | from os.path import isdir, isfile, join 6 | import numpy as np 7 | 8 | random.seed(0) 9 | os.environ['PYTHONHASHSEED'] = str(0) 10 | 11 | imnet21k_dir = sys.argv[1] 12 | save_dir = sys.argv[5] 13 | classes = [f for f in os.listdir(imnet21k_dir) if isdir(join(imnet21k_dir, f))] 14 | cnt = 0 15 | class_sizes, class_order, cls_list = [], [], [] 16 | order1, order2 = [], [] 17 | pretrainf, prevalf, pretestf, valf, testf = [], [], [], [], [] 18 | 19 | imnet1k_train_dir_1k = sys.argv[2] + '/train/' 20 | imnet1k_val_dir_1k = sys.argv[2] + '/val/' 21 | imnet1k_test_dir_1k = sys.argv[2] + '/test/' 22 | 23 | classes_1k = [ 24 | f for f in os.listdir(imnet1k_train_dir_1k) if isdir(join(imnet1k_train_dir_1k, f)) 25 | ] 26 | 27 | for cls in classes_1k: 28 | folder = join(imnet1k_train_dir_1k, cls) 29 | imgs = [ 30 | '/train/' + cls + '/' + f for f in os.listdir(folder) 31 | if (isfile(join(folder, f))) 32 | ] 33 | pretrainf.extend(imgs) 34 | 35 | for cls in classes_1k: 36 | folder = join(imnet1k_val_dir_1k, cls) 37 | imgs = [ 38 | '/val/' + cls + '/' + f for f in os.listdir(folder) 39 | if (isfile(join(folder, f))) 40 | ] 41 | prevalf.extend(imgs) 42 | 43 | for cls in classes_1k: 44 | folder = join(imnet1k_test_dir_1k, cls) 45 | imgs = [ 46 | '/test/' + cls + '/' + f for f in os.listdir(folder) 47 | if (isfile(join(folder, f))) 48 | ] 49 | pretestf.extend(imgs) 50 | 51 | problematic = [ 52 | 'n13867492', 'n15102894', 'n09450163', 'n10994097', 'n11196627', 53 | 'n11318824' 54 | ] 55 | for cls in problematic: 56 | assert (cls not in classes_1k), 'Problematic classes in Imagenet1k' 57 | classes_1k.extend(problematic) 58 | 59 | for cls in classes: 60 | folder = join(imnet21k_dir, cls) 61 | imgs = [ 62 | cls + '/' + f for f in os.listdir(folder) 63 | if (isfile(join(folder, f))) 64 | ] 65 | 66 | if len(imgs) < int(sys.argv[4]) or cls in classes_1k: 67 | pass 68 | else: 69 | cnt += 1 70 | if cnt > int(sys.argv[3]): break 71 | cls_list.extend([cls]) 72 | random.shuffle(imgs) 73 | 74 | testf.extend(imgs[:50]) 75 | valf.extend(imgs[50:60]) 76 | order1.extend(imgs[60:]) 77 | class_sizes.append(len(imgs) - 60) 78 | class_order.append(cls) 79 | 80 | order2 = copy.deepcopy(order1) 81 | random.shuffle(order2) 82 | 83 | print(len(pretrainf), len(pretestf), len(order1), len(order2)) 84 | 85 | # Create order files 86 | f = open(save_dir + '/pretrain.txt', 'w') 87 | for line in pretrainf: 88 | f.write(line + '\n') 89 | f.close() 90 | 91 | f = open(save_dir + '/preval.txt', 'w') 92 | for line in prevalf: 93 | f.write(line + '\n') 94 | f.close() 95 | 96 | f = open(save_dir + '/pretest.txt', 'w') 97 | for line in pretestf: 98 | f.write(line + '\n') 99 | f.close() 100 | 101 | f = open(save_dir + '/class_incremental_ordering.txt', 'w') 102 | for line in order1: 103 | f.write('/train/'+line + '\n') 104 | f.close() 105 | 106 | f = open(save_dir + '/data_incremental_ordering.txt', 'w') 107 | for line in order2: 108 | f.write('/train/'+line + '\n') 109 | f.close() 110 | 111 | f = open(save_dir + '/val.txt', 'w') 112 | for line in valf: 113 | f.write('/val/'+line + '\n') 114 | f.close() 115 | 116 | f = open(save_dir + '/test.txt', 'w') 117 | for line in testf: 118 | f.write('/test/'+line + '\n') 119 | f.close() 120 | 121 | f = open(save_dir + '/class_order.txt', 'w') 122 | for line in class_order: 123 | f.write(line + '\n') 124 | f.close() 125 | 126 | class_sizes = np.array(class_sizes) 127 | np.save(save_dir + '/class_sizes.npy', class_sizes) -------------------------------------------------------------------------------- /scripts/plot_results.py: -------------------------------------------------------------------------------- 1 | # Hasan-- can we modify this based on the plotting code used back when we ran the final version? I restored the basic class structure 2 | from re import L 3 | 4 | import matplotlib 5 | import matplotlib.pyplot as plt 6 | import numpy as np 7 | 8 | 9 | class Plotter(): 10 | def __init__(self, xlabel, ylabel, title, y_in_log=False): 11 | self.xlabel = xlabel 12 | self.ylabel = ylabel 13 | self.y_in_log = y_in_log 14 | self.y = [] 15 | self.x = [] 16 | self.labels = [] 17 | self.linecolors = [] 18 | self.linestyle = [] 19 | self.title = title 20 | 21 | def add_plot(self, x, y, label, linecolour, linestyle): 22 | self.y.append(y) 23 | self.x.append(x) 24 | self.labels.append(label) 25 | self.linecolors.append(linecolour) 26 | self.linestyle.append(linestyle) 27 | assert (len(self.y) == len(self.x) and len(self.x) == len(self.labels) 28 | and len(self.labels) == len(self.linecolors) 29 | and len(self.linecolors) == len(self.linestyle)) 30 | 31 | def show_plot(self): 32 | matplotlib.rcParams.update({'font.size': 15}) 33 | matplotlib.rcParams['legend.numpoints'] = 2 34 | fig, ax = plt.subplots(1, figsize=(8, 4)) 35 | if self.y_in_log: 36 | ax.set_yscale('log') 37 | plt.ylabel(self.ylabel) 38 | plt.xlabel(self.xlabel) 39 | matplotlib.rcParams.update({'font.size': 15}) 40 | matplotlib.rcParams['legend.numpoints'] = 2 41 | for idx in range(len(self.y)): 42 | markersize = 13 if self.linestyle[idx] == 'dotted' else 9 43 | ax.plot(self.x[idx], 44 | self.y[idx], 45 | label=self.labels[idx], 46 | linestyle=self.linestyle[idx], 47 | color=self.linecolors[idx], 48 | markersize=markersize) 49 | matplotlib.rcParams.update({'font.size': 7}) 50 | ax.grid(linestyle='--') 51 | legend = ax.legend(loc='upper left') 52 | plt.title(self.title) 53 | plt.show() 54 | 55 | 56 | def get_accs(expdir, timesteps): 57 | x, pretestacc, cltestacc, totacc = [], [], [], [] 58 | for i in range(timesteps): 59 | try: 60 | labels1, preds1 = np.load(expdir + '/labels_' + str(i + 1) + 61 | '_pretestset.npy'), np.load( 62 | expdir + '/preds_' + str(i + 1) + 63 | '_pretestset.npy') 64 | acc = ((labels1 == preds1) * 1.0).mean() * 100 65 | pretestacc.append(acc) 66 | labels2, preds2 = np.load(expdir + '/labels_' + str(i + 1) + 67 | '_cltestset.npy'), np.load( 68 | expdir + '/preds_' + str(i + 1) + 69 | '_cltestset.npy') 70 | acc = ((labels2 == preds2) * 1.0).mean() * 100 71 | cltestacc.append(acc) 72 | labelsconcat, predsconcat = np.concatenate((labels1, labels2), 73 | axis=0), np.concatenate( 74 | (preds1, preds2), 75 | axis=0) 76 | acc = ((labelsconcat == predsconcat) * 1.0).mean() * 100 77 | totacc.append(acc) 78 | x.append(i + 1) 79 | except: 80 | continue 81 | pretestacc, cltestacc, totacc = np.array(pretestacc), np.array( 82 | cltestacc), np.array(totacc) 83 | return x, pretestacc, cltestacc, totacc 84 | 85 | 86 | LOGDIR = 'YOUR_LOGDIR' 87 | linecolours = [ 88 | 'r', 'b', 'k', 'm', 'darkorange', 'g', 'y', 'c', 'olive', 'lime' 89 | ] 90 | 91 | x, preacc, clacc, totacc = get_accs(expdir=LOGDIR + 92 | '/CLSINC_Uniform_3000_0.1/', 93 | timesteps=20) 94 | plter.add_plot(x=x, 95 | y=preacc, 96 | label='Uniform -- 3000 Iters Optimal -- (Im1K)', 97 | linecolour=linecolours[6], 98 | linestyle='dashed') 99 | plter.add_plot(x=x, 100 | y=clacc, 101 | label='Uniform -- 3000 Iters Optimal -- (CL)', 102 | linecolour=linecolours[6], 103 | linestyle='solid') 104 | plter.add_plot(x=x, 105 | y=totacc, 106 | label='Uniform -- 3000 Iters (Total)', 107 | linecolour=linecolours[6], 108 | linestyle='dotted') 109 | 110 | plter.show_plot() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BudgetCL 2 | 3 | This repository contains the code for the paper: 4 | 5 | **Computationally Budgeted Continual Learning: What Does Matter?, CVPR 2023** 6 | [Ameya Prabhu*](https://drimpossible.github.io), [Hasan Abed Al Kader Hammoud*](https://scholar.google.com/citations?user=Plf1JSIAAAAJ&hl=en&oi=ao), [Puneet Dokania](https://puneetkdokania.github.io), [Philip Torr](https://www.robots.ox.ac.uk/~phst/), [Ser-Nam Lim](https://sites.google.com/site/sernam), [Bernard Ghanem](https://www.bernardghanem.com/), [Adel Bibi](https://www.adelbibi.com/) 7 | 8 | [[Arxiv](https://arxiv.org/abs/2303.11165)] 9 | [[PDF](https://github.com/drimpossible/drimpossible.github.io/raw/master/documents/BudgetCL.pdf)] 10 | [[Bibtex](https://github.com/drimpossible/BudgetCL/#citation)] 11 | 12 |

13 | Figure which describes our conclusions 14 |

15 | 16 | ## Getting started 17 | 18 | Running our code requires 1x80GB A100 GPU with PyTorch >=1.13. 19 | 20 | - Install all requirements required to run the code by: 21 | ``` 22 | # First, activate a new virtual environment 23 | $ pip install -r requirements.txt 24 | ``` 25 | 26 | ## Setting up the Datasets 27 | 28 | - We provide a fast, direct mechanism to download and use our datasets in [this repository](https://github.com/hammoudhasan/CLDatasets). 29 | - Input the directory where the dataset was downloaded into `data_dir` field in `src/opts.py`. 30 | 31 | ## Recreating the dataset 32 | 33 | ### ImageNet2K 34 | 35 | ImageNet2K is a dataset introduced by us, consists of 1K classes from the original dataset and 1K additional classes from ImageNet21K. 36 | 37 | To create ImageNet2K dataset: 38 | - Download ImageNet1K `train` and `val` set from [here](https://www.image-net.org/download.php). Copy them to the `ImageNet2K` folder in `train` and `test` subdirectories respectively. 39 | - Download ImageNetV2 dataset from [here](https://huggingface.co/datasets/vaishaal/ImageNetV2/resolve/main/imagenetv2-matched-frequency.tar.gz), and copy this to the `ImageNet2K` folder as `val` subdirectory. 40 | - Download ImageNet21K dataset from this [webpage](https://www.image-net.org/download.php). 41 | - Now, to select the subset of ImageNet21K dataset and generate ordering files, go to `scripts` and run the script: 42 | ``` 43 | python select_subset_imagenet21k.py PATH_TO_IMAGENET21K PATH_TO_IMAGENET1K 1000 1200 ../clim2k/ 44 | ``` 45 | - Finally, copy the new files from Imagenet21K to be included in ImageNet2K over to the folder by running: 46 | ``` 47 | python copy_imnet21k_to_imnet2k.py PATH_TO_IMAGENET21K PATH_TO_IMAGENET2K ../clim2k/ 48 | ``` 49 | 50 | ### Continual Google Landmarks V2 (CGLM) 51 | 52 | - This dataset was introduced in [ACM](https://github.com/drimpossible/ACM), please follow instructions in that repository for curation details. 53 | 54 | ### Directory structure 55 | 56 | - After setting up the datasets and the environment, the project root folder should look like this: 57 | 58 | ``` 59 | BudgetCL/ 60 | |–– data/ 61 | |–––– cglm/ 62 | |–––– clim2k/ 63 | |–– src/ 64 | |–– scripts/ 65 | |–– README.md 66 | |–– requirements.txt 67 | |–– .gitignore 68 | |–– LICENSE 69 | ``` 70 | 71 | ## Usage 72 | 73 | To run any model specified in the paper one needs to simply modify the arguments, an example command below (reproduces our Naive baseline on CI-ImageNet2K): 74 | 75 | ``` 76 | python main.py --log_dir='../logs/sampling/' \ 77 | --order_file_dir=../data/clim2k/order_files/ \ 78 | --train_batch_size 1500 \ 79 | --test_batch_size 1500 \ 80 | --crop_size 224 \ 81 | --dset_mode='class_incremental' \ 82 | --num_classes_per_timestep=50 \ 83 | --num_timesteps=20 \ 84 | --increment_size=0 \ 85 | --optimizer="SGD" \ 86 | --model='resnet50' \ 87 | --sampling_mode='uniform' \ 88 | --model_type='normal' \ 89 | --maxlr=0.1 \ 90 | --total_steps=400 \ 91 | --seed=1 \ 92 | --weight_decay=0 \ 93 | --clip=2.0 \ 94 | --num_workers=8 \ 95 | --momentum 0.9 96 | ``` 97 | 98 | Arguments you can tweak for your new cool CL pipeline/formulation/method: 99 | - Model (`--model`) 100 | - Dataset (`--order_file_dir`) 101 | - Total optimization steps changing the compute budget (`--total_steps`) 102 | 103 | To vary the number of timesteps change: 104 | 105 | In DI-ImageNet2K and CGLM: 106 | - Number of samples per timestep (`--num_samples_per_timestep`) 107 | 108 | In CI-ImageNet2K, increase one and decrease the other: 109 | - Number of classes per timestep (`--num_classes_per_timestep`) 110 | - Number of tasks (`--num_timesteps`) 111 | 112 | 113 | ### Extension to New Datasets 114 | 115 | - Create `train.txt`, `val.txt` and `test.txt` data orders for your new dataset. 116 | - Add the dataset details in `src/datasets.py` 117 | - Add the dataset folder name exactly to `src/opts.py` 118 | - Run you model with `--dataset your_fav_dataset`! 119 | 120 | 121 | ##### If you discover any bugs in the code please contact me, I will cross-check them with my nightmares. 122 | 123 | Discovered mistakes: 124 | 125 | - ACE Loss implemented by us deviated from the original work. The correct ACE loss function is unsuitable for our setting along with uniform sampling, being practically equivalent to CrossEntropy. However, we shall include the deviated ACE loss function in our code repository as it gave interesting results on CGLM and DI-ImageNet2K. 126 | 127 | ## Citation 128 | 129 | We hope our benchmark and contributions are valuable to advance your work in continual learning! To cite our work: 130 | 131 | ``` 132 | @inproceedings{prabhu2023computationally, 133 | title={Computationally Budgeted Continual Learning: What Does Matter?}, 134 | author={Prabhu, Ameya and Hammoud, Hasan Abed Al Kader and Dokania, Puneet and Torr, Philip HS and Lim, Ser-Nam and Ghanem, Bernard and Bibi, Adel}, 135 | booktitle={IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, 136 | year={2023}, 137 | } 138 | ``` 139 | -------------------------------------------------------------------------------- /src/opts.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | 4 | def parse_args(): 5 | parser = argparse.ArgumentParser(description='main.py') 6 | # Changing options -- Apart from these arguments, we do not mess with other arguments 7 | 8 | ## Paths 9 | parser.add_argument( 10 | '--log_dir', 11 | type=str, 12 | default='../logs/', 13 | help='Full path to the directory where all logs are stored') 14 | parser.add_argument('--order_file_dir', 15 | type=str, 16 | default='../../order_files/', 17 | help='Full path to the ordering files') 18 | parser.add_argument('--data_dir', 19 | type=str, 20 | default='', 21 | help='Path to dataset directory') 22 | 23 | ## Dataset 24 | parser.add_argument('--dataset', 25 | type=str, 26 | default='Imagenet2K', 27 | choices=['Imagenet2K', 'CGLM'], 28 | help='Dataset used for CL') 29 | parser.add_argument('--timestep', 30 | type=int, 31 | default=0, 32 | help='Timestep to start learning from (for resuming)') 33 | parser.add_argument('--train_batch_size', 34 | type=int, 35 | default=1500, 36 | help='Batch size to be used in training') 37 | parser.add_argument('--test_batch_size', 38 | type=int, 39 | default=1500, 40 | help='Batch size to be used in testing') 41 | parser.add_argument('--crop_size', 42 | type=int, 43 | default=224, 44 | help='Size of the image input') 45 | parser.add_argument( 46 | '--dset_mode', 47 | type=str, 48 | default='class_incremental', 49 | choices=['class_incremental', 'data_incremental', 'time_incremental'], 50 | help='Dataset Ordering to choose from') 51 | parser.add_argument( 52 | '--num_classes_per_timestep', 53 | type=int, 54 | default=0, 55 | help= 56 | 'Number of classes per timestep in case of class incremental setting') 57 | parser.add_argument('--num_timesteps', 58 | type=int, 59 | default=20, 60 | help='Number of timesteps to split data over') 61 | parser.add_argument( 62 | '--increment_size', 63 | type=int, 64 | default=0, 65 | help= 66 | 'Number of samples per timestep in case of time/data incremental setting' 67 | ) 68 | 69 | # ## Model 70 | parser.add_argument('--optimizer', 71 | type=str, 72 | default='SGD', 73 | choices=['SGD'], 74 | help='Optimizer type chosen for the network') 75 | parser.add_argument('--model', 76 | type=str, 77 | default='resnet50', 78 | choices=['resnet50_i1b', 'resnet50'], 79 | help='Model architecture') 80 | parser.add_argument('--model_type', 81 | type=str, 82 | default='normal', 83 | choices=['normal', 'gdumb'], 84 | help='Model architecture') 85 | parser.add_argument('--sampling_mode', 86 | type=str, 87 | default='uniform', 88 | choices=[ 89 | 'uniform', 'class_balanced', 'lastk', 'herding', 90 | 'kmeans', 'unc_lc', 'max_loss', 'recency_biased' 91 | ], 92 | help='Sampling Strategies Tested') 93 | parser.add_argument( 94 | '--fc', 95 | type=str, 96 | default='linear', 97 | choices=['linear', 'cosine_linear', 'linear_only', 'ace'], 98 | help='Last layer training strategies') 99 | parser.add_argument('--momentum', 100 | type=float, 101 | default=0.9, 102 | help='Optimizer Momentum') 103 | parser.add_argument('--distill', 104 | type=str, 105 | default=None, 106 | choices=['cosine', 'mse', 'bce', 'ce'], 107 | help='Disllation Mode') 108 | parser.add_argument( 109 | '--calibrator', 110 | type=str, 111 | default=None, 112 | choices=['Temperature', 'WA', 'BiC'], 113 | help='Types of restart: ER and GDumb or do full offline training') 114 | parser.add_argument('--pretrained', 115 | type=bool, 116 | default=True, 117 | help='Use pretrained weights or not') 118 | 119 | # ## Experiment Deets 120 | parser.add_argument( 121 | '--exp_name', 122 | type=str, 123 | default='test', 124 | help='Experiment name. Saving is done as log_dir/exp_name') 125 | parser.add_argument('--maxlr', 126 | type=float, 127 | default=0.001, 128 | help='Starting Learning rate') 129 | parser.add_argument('--total_steps', 130 | type=int, 131 | default=80, 132 | help='Maximum number of training steps') 133 | 134 | # # Default options 135 | parser.add_argument('--seed', 136 | type=int, 137 | default=0, 138 | help='Seed for reproducibility') 139 | parser.add_argument('--weight_decay', 140 | type=float, 141 | default=0, 142 | help='Weight decay') 143 | parser.add_argument( 144 | '--clip', 145 | type=float, 146 | default=2.0, 147 | help='Gradient Clipped if val >= clip, gives stable training') 148 | parser.add_argument('--num_workers', 149 | type=int, 150 | default=16, 151 | help='Starting learning rate') 152 | opt = parser.parse_args() 153 | return opt 154 | -------------------------------------------------------------------------------- /src/utils.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import random 4 | from enum import Enum 5 | 6 | import numpy as np 7 | import torch 8 | import torch.distributed as dist 9 | from torch.optim.lr_scheduler import _LRScheduler 10 | from torch.optim.optimizer import Optimizer, required 11 | 12 | 13 | class LinearLR(_LRScheduler): 14 | r"""Set the learning rate of each parameter group with a linear 15 | schedule: :math:`\eta_{t} = \eta_0*(1 - t/T)`, where :math:`\eta_0` is the 16 | initial lr, :math:`t` is the current epoch or iteration (zero-based) and 17 | :math:`T` is the total training epochs or iterations. It is recommended to 18 | use the iteration based calculation if the total number of epochs is small. 19 | When last_epoch=-1, sets initial lr as lr. 20 | It is studied in 21 | `Budgeted Training: Rethinking Deep Neural Network Training Under Resource 22 | Constraints`_. 23 | 24 | Args: 25 | optimizer (Optimizer): Wrapped optimizer. 26 | T (int): Total number of training epochs or iterations. 27 | last_epoch (int): The index of last epoch or iteration. Default: -1. 28 | 29 | .. _Budgeted Training\: Rethinking Deep Neural Network Training Under 30 | Resource Constraints: 31 | https://arxiv.org/abs/1905.04753 32 | """ 33 | 34 | def __init__(self, optimizer, T, last_epoch=-1): 35 | self.T = float(T) 36 | super(LinearLR, self).__init__(optimizer, last_epoch) 37 | 38 | def get_lr(self): 39 | rate = 1 - (self.last_epoch / self.T) 40 | return [rate * base_lr for base_lr in self.base_lrs] 41 | 42 | def _get_closed_form_lr(self): 43 | return self.get_lr() 44 | 45 | 46 | class Summary(Enum): 47 | NONE = 0 48 | AVERAGE = 1 49 | SUM = 2 50 | COUNT = 3 51 | 52 | 53 | class AverageMeter(object): 54 | """Computes and stores the average and current value""" 55 | 56 | def __init__(self, name, fmt=':f', summary_type=Summary.AVERAGE): 57 | self.name = name 58 | self.fmt = fmt 59 | self.summary_type = summary_type 60 | self.reset() 61 | 62 | def reset(self): 63 | self.val = 0 64 | self.avg = 0 65 | self.sum = 0 66 | self.count = 0 67 | 68 | def update(self, val, n=1): 69 | self.val = val 70 | self.sum += val * n 71 | self.count += n 72 | self.avg = self.sum / self.count 73 | 74 | def all_reduce(self): 75 | if torch.cuda.is_available(): 76 | device = torch.device("cuda") 77 | elif torch.backends.mps.is_available(): 78 | device = torch.device("mps") 79 | else: 80 | device = torch.device("cpu") 81 | total = torch.tensor([self.sum, self.count], 82 | dtype=torch.float32, 83 | device=device) 84 | dist.all_reduce(total, dist.ReduceOp.SUM, async_op=False) 85 | self.sum, self.count = total.tolist() 86 | self.avg = self.sum / self.count 87 | 88 | def __str__(self): 89 | fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' 90 | return fmtstr.format(**self.__dict__) 91 | 92 | def summary(self): 93 | fmtstr = '' 94 | if self.summary_type is Summary.NONE: 95 | fmtstr = '' 96 | elif self.summary_type is Summary.AVERAGE: 97 | fmtstr = '{name} {avg:.3f}' 98 | elif self.summary_type is Summary.SUM: 99 | fmtstr = '{name} {sum:.3f}' 100 | elif self.summary_type is Summary.COUNT: 101 | fmtstr = '{name} {count:.3f}' 102 | else: 103 | raise ValueError('invalid summary type %r' % self.summary_type) 104 | 105 | return fmtstr.format(**self.__dict__) 106 | 107 | 108 | class ProgressMeter(object): 109 | 110 | def __init__(self, logger, num_batches, meters, prefix=""): 111 | self.batch_fmtstr = self._get_batch_fmtstr(num_batches) 112 | self.meters = meters 113 | self.prefix = prefix 114 | self.logger = logger 115 | 116 | def display(self, batch): 117 | entries = [self.prefix + self.batch_fmtstr.format(batch)] 118 | entries += [str(meter) for meter in self.meters] 119 | self.logger.info('\t'.join(entries)) 120 | 121 | def display_summary(self): 122 | entries = [" *"] 123 | entries += [meter.summary() for meter in self.meters] 124 | self.logger.info(' '.join(entries)) 125 | 126 | def _get_batch_fmtstr(self, num_batches): 127 | num_digits = len(str(num_batches // 1)) 128 | fmt = '{:' + str(num_digits) + 'd}' 129 | return '[' + fmt + '/' + fmt.format(num_batches) + ']' 130 | 131 | 132 | def accuracy(output, target, topk=(1, )): 133 | """Computes the accuracy over the k top predictions for the specified values of k""" 134 | with torch.no_grad(): 135 | maxk = max(topk) 136 | batch_size = target.size(0) 137 | 138 | _, pred = output.topk(maxk, 1, True, True) 139 | pred = pred.t() 140 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 141 | 142 | res = [] 143 | for k in topk: 144 | correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) 145 | res.append(correct_k.mul_(100.0 / batch_size)) 146 | return res 147 | 148 | 149 | def get_logger(folder): 150 | # global logger 151 | logger = logging.getLogger(__name__) 152 | logger.setLevel(logging.DEBUG) 153 | formatter = logging.Formatter( 154 | "[%(asctime)s] %(levelname)s:%(name)s:%(message)s") 155 | # file logger 156 | if not os.path.isdir(folder): 157 | os.makedirs(folder) 158 | fh = logging.FileHandler(os.path.join(folder, 'checkpoint.log'), mode='a') 159 | fh.setLevel(logging.INFO) 160 | fh.setFormatter(formatter) 161 | logger.addHandler(fh) 162 | # console logger 163 | ch = logging.StreamHandler() 164 | ch.setLevel(logging.DEBUG) 165 | ch.setFormatter(formatter) 166 | logger.addHandler(ch) 167 | return logger 168 | 169 | 170 | def save_model(opt, model): 171 | ''' 172 | Saves the model along with opts (for reference), useful for fixing intermediate breaks while running the code. 173 | ''' 174 | state = { 175 | 'opt': opt, 176 | 'state_dict': model.state_dict() 177 | } # Add .module to model if using DataParallel 178 | 179 | filename = opt.log_dir + '/' + opt.exp_name + '/' + str( 180 | opt.timestep) + '/last.ckpt' 181 | torch.save(state, filename) 182 | 183 | 184 | def seed_everything(seed): 185 | ''' 186 | Fixes the class-to-task assignments and most other sources of randomness, except CUDA training aspects. 187 | ''' 188 | # Avoid all sorts of randomness for better replication 189 | random.seed(seed) 190 | torch.manual_seed(seed) 191 | torch.cuda.manual_seed_all(seed) 192 | np.random.seed(seed) 193 | os.environ['PYTHONHASHSEED'] = str(seed) 194 | if torch.cuda.is_available(): 195 | torch.backends.cudnn.benchmark = True # An exemption for speed :P 196 | -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import os 3 | from os.path import exists 4 | 5 | import numpy as np 6 | import torch 7 | import torchvision.models as models 8 | from torch import nn 9 | from torch.optim import SGD 10 | 11 | from datasets import CLImageFolder 12 | from fc_correction import CosineLinear, correct_weights 13 | from opts import parse_args 14 | from training import save_representations, test, train 15 | from utils import LinearLR, get_logger, save_model, seed_everything 16 | 17 | 18 | def per_timestep_loop(opt, logger, dataset): 19 | assert (opt.model in ['resnet50_I1B', 'resnet50']) 20 | if opt.model == 'resnet50': 21 | model = models.resnet50(weights="IMAGENET1K_V2") 22 | elif opt.model == 'resnet50_I1B': 23 | model = torch.hub.load( 24 | 'facebookresearch/semi-supervised-ImageNet1K-models', 25 | 'resnet50_swsl') 26 | 27 | linear_size = list(model.children())[-1].in_features 28 | 29 | if opt.fc == 'cosine_linear': 30 | model.fc = CosineLinear(in_features=linear_size, 31 | out_features=opt.num_curr_classes) 32 | else: 33 | model.fc = nn.Linear(linear_size, opt.num_curr_classes) 34 | 35 | prevmodel = None 36 | 37 | if opt.pretrain_modelpath is not None: 38 | logger.info('==> Loading from ' + opt.pretrain_modelpath + 39 | ' for continual training..') 40 | model.load_state_dict(torch.load(opt.pretrain_modelpath)['state_dict']) 41 | if opt.distill is not None and opt.timestep > 1: 42 | prevmodel = copy.deepcopy(model) 43 | prevmodel = prevmodel.cuda() 44 | else: 45 | prevmodel = None 46 | 47 | if opt.expand_size > 0: # Add new classes to the final classifier 48 | # Expand the linear size and set the new weights and biases to small random and zero respectively. 49 | new_weights = (torch.ones(opt.expand_size, linear_size)) 50 | new_weights = 0.001 * nn.init.xavier_normal_(new_weights) 51 | model.fc.weight = nn.Parameter( 52 | torch.cat((model.fc.weight, new_weights), dim=0)) 53 | if model.fc.bias is not None: 54 | new_biases = torch.zeros(opt.expand_size) 55 | model.fc.bias = nn.Parameter( 56 | torch.cat((model.fc.bias, new_biases), dim=0)) 57 | 58 | # model = torch.nn.DataParallel(model.cuda()) # Use Dataparallel for now if running on multiple GPUs -- need for distillation experiments if not wanting to store 59 | model = model.cuda() 60 | optimizer = SGD(model.parameters(), 61 | lr=opt.maxlr, 62 | momentum=opt.momentum, 63 | weight_decay=opt.weight_decay) 64 | scheduler = LinearLR(optimizer, T=opt.total_steps) 65 | 66 | if opt.fc == 'linear_only': # option to only tune the fully-connected layers 67 | for param in model.parameters(): 68 | param.requires_grad = False 69 | 70 | model.fc.weight.requires_grad = True 71 | if model.fc.bias is not None: 72 | model.fc.bias.requires_grad = True 73 | 74 | model, optimizer, scheduler = train(opt=opt, 75 | loader=dataset.trainloader, 76 | model=model, 77 | optimizer=optimizer, 78 | scheduler=scheduler, 79 | logger=logger, 80 | prevmodel=prevmodel) 81 | 82 | # Postprocessing 83 | if opt.dset_mode == 'class_incremental' and opt.calibrator != None: 84 | model = correct_weights(model=model, 85 | valloader=dataset.valloader, 86 | calibration_method=opt.calibrator, 87 | logger=logger, 88 | expand_size=opt.expand_size) 89 | 90 | if opt.sampling_mode in ['herding', 'kmeans']: 91 | save_representations(opt=opt, 92 | loader=dataset.trainloader_eval, 93 | model=model, 94 | mode='features') 95 | 96 | elif opt.sampling_mode in ['unc_lc', 'max_loss']: 97 | save_representations(loader=dataset.trainloader_eval, 98 | model=model, 99 | mode='predictions') 100 | 101 | # Testing Part 102 | predsarr, labelsarr = test(loader=dataset.testloader, 103 | model=model, 104 | logger=logger) 105 | np.save( 106 | opt.log_dir + '/' + opt.exp_name + '/labels_' + str(opt.timestep) + 107 | '_cltestset.npy', labelsarr.numpy()) 108 | np.save( 109 | opt.log_dir + '/' + opt.exp_name + '/preds_' + str(opt.timestep) + 110 | '_cltestset.npy', predsarr.numpy()) 111 | del predsarr, labelsarr 112 | 113 | if opt.dataset == 'Imagenet2K': 114 | predsarr, labelsarr = test(loader=dataset.pretestloader, 115 | model=model, 116 | logger=logger) 117 | np.save( 118 | opt.log_dir + '/' + opt.exp_name + '/labels_' + str(opt.timestep) + 119 | '_pretestset.npy', labelsarr.numpy()) 120 | np.save( 121 | opt.log_dir + '/' + opt.exp_name + '/preds_' + str(opt.timestep) + 122 | '_pretestset.npy', predsarr.numpy()) 123 | del predsarr, labelsarr 124 | 125 | save_model(opt, model) 126 | print('Finished timestep: ', opt.timestep) 127 | 128 | 129 | if __name__ == '__main__': 130 | # Parse arguments and init loggers 131 | torch.multiprocessing.set_sharing_strategy( 132 | 'file_system') # For error: Too many files open 133 | opt = parse_args() 134 | opt.exp_name = f'{opt.dataset}_{opt.model}_{opt.dset_mode}_{opt.sampling_mode}_{opt.optimizer}_{opt.maxlr}_{opt.total_steps}_{opt.increment_size}' 135 | opt.timestep = 0 136 | console_logger = get_logger(folder=opt.log_dir + '/' + opt.exp_name + '/') 137 | console_logger.info('==> Params for this experiment:' + str(opt)) 138 | seed_everything(opt.seed) 139 | opt.expand_size = 0 140 | 141 | # Pretraining phase starts here 142 | console_logger.debug('==> Loading pretraining dataset..') 143 | dataset = CLImageFolder(opt=opt) 144 | opt.num_curr_classes = len(dataset.curr_classes) 145 | 146 | # Continual phase starts here 147 | start = 0 148 | 149 | for timestep in range(opt.num_timesteps): 150 | opt.timestep = timestep + 1 # Note: opt.timestep starts from 1 and not 0. 151 | os.makedirs(opt.log_dir + '/' + opt.exp_name + '/' + 152 | str(opt.timestep) + '/', 153 | exist_ok=True) 154 | 155 | if opt.model_type == 'gdumb' or opt.timestep == 1: 156 | opt.pretrain_modelpath = None 157 | elif opt.model_type == 'normal': 158 | opt.pretrain_modelpath = opt.log_dir + '/' + opt.exp_name + '/' + str( 159 | opt.timestep - 1) + '/last.ckpt' 160 | assert (opt.model_type in ['normal', 'gdumb']) 161 | 162 | dataset.get_next_timestep_dataloader(opt) 163 | opt.expand_size = dataset.expand_size 164 | 165 | if opt.dataset == 'CGLM': 166 | opt.num_curr_classes = len(dataset.curr_classes) 167 | 168 | if (not exists(opt.log_dir + '/' + opt.exp_name + '/' + 169 | str(opt.timestep + 1) + '/last.ckpt')): 170 | console_logger.info('==> Starting training of timestep ' + 171 | str(opt.timestep) + '..') 172 | per_timestep_loop(opt=opt, logger=console_logger, dataset=dataset) 173 | console_logger.info('==> Completed training for timestep ' + 174 | str(opt.timestep) + '..') 175 | opt.num_curr_classes = len(dataset.curr_classes) 176 | 177 | console_logger.info('Experiment completed! Total timesteps: ' + 178 | str(opt.timestep)) 179 | -------------------------------------------------------------------------------- /src/sampling.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | from sklearn.cluster import KMeans 4 | from torch.nn import functional as F 5 | 6 | 7 | def select_samples(opt, num_samples, class_balanced=False): 8 | """ 9 | Selects a subset of samples from the training data for active learning. 10 | 11 | Args: 12 | opt (argparse.Namespace): The command-line arguments. 13 | num_samples (int): The number of samples to select. 14 | class_balanced (bool): Whether to balance the samples across classes. 15 | 16 | Returns: 17 | np.ndarray: The indices of the selected samples. 18 | """ 19 | if opt.timestep > 1: 20 | if not class_balanced: 21 | if opt.sampling_mode in ['herding', 'kmeans']: 22 | feats = np.load(opt.log_dir + '/' + opt.exp_name + '/feats_' + 23 | str(opt.timestep - 1) + '_train.npy') 24 | labels = np.load(opt.log_dir + '/' + opt.exp_name + 25 | '/labels_' + str(opt.timestep - 1) + 26 | '_train.npy') 27 | if opt.sampling_mode == 'herding': 28 | sampled_idxes = herding(feats, num_samples) 29 | elif opt.sampling_mode == 'kmeans': 30 | sampled_idxes = kmeans(feats, num_samples) 31 | elif opt.sampling_mode in ['unc_lc', 'max_loss']: 32 | probs, labels = np.load( 33 | opt.log_dir + '/' + opt.exp_name + '/predprobs_' + 34 | str(opt.timestep - 1) + 35 | '_train.npy'), np.load(opt.log_dir + '/' + opt.exp_name + 36 | '/labels_' + str(opt.timestep - 1) + 37 | '_train.npy') 38 | sampled_idxes = samplewise_losses(opt, probs, labels, 39 | num_samples) 40 | else: 41 | labels = np.load(opt.log_dir + '/' + opt.exp_name + '/labels_' + 42 | str(opt.timestep - 1) + '_train.npy') 43 | if opt.sampling_mode in ['herding', 'kmeans']: 44 | feats = np.load(opt.log_dir + '/' + opt.exp_name + '/feats_' + 45 | str(opt.timestep - 1) + '_train.npy') 46 | elif opt.sampling_mode in ['unc_lc', 'max_loss']: 47 | probs = np.load(opt.log_dir + '/' + opt.exp_name + 48 | '/predprobs_' + str(opt.timestep - 1) + 49 | '_train.npy') 50 | 51 | classweights = np.bincount(np.array(labels)) 52 | num_samples_per_class = ( 53 | num_samples // len(classweights) 54 | ) + 1 # If not divisible, then store slightly more than num_samples 55 | sampled_idxes = [] 56 | for cls in len(classweights): 57 | idx = np.where(labels == cls)[0] 58 | if idx.shape[ 59 | 0] < num_samples_per_class: # Can't do anything but undersample 60 | sampled_idxes += idx.tolist() 61 | else: 62 | if opt.sampling_mode == 'herding': 63 | cls_idx = herding(feats[idx], num_samples_per_class) 64 | elif opt.sampling_mode == 'kmeans': 65 | cls_idx = kmeans(feats[idx], num_samples_per_class) 66 | elif opt.sampling_mode in ['unc_lc', 'max_loss']: 67 | cls_idx = samplewise_losses(opt, probs[idx], 68 | labels[idx], 69 | num_samples_per_class) 70 | sampled_idxes += cls_idx.tolist() 71 | remaining = num_samples - len(sampled_idxes) 72 | if remaining > 0: 73 | add_idx = np.random.permutation(len(labels))[:remaining] 74 | sampled_idxes += add_idx.tolist() 75 | else: 76 | sampled_idxes = np.random.permutation(len(labels))[:num_samples] 77 | return sampled_idxes 78 | 79 | 80 | ### Note: Code borrowed from https://github.com/arthurdouillard/incremental_learning.pytorch/blob/4991787c2ca19b364a5769e2c6afda53eed74020/inclearn/lib/herding.py 81 | ### Please refer there for details, license and updates 82 | 83 | 84 | def closest_to_mean(features, nb_examplars): 85 | """ 86 | Selects the `nb_examplars` features that are closest to the mean feature vector. 87 | 88 | Args: 89 | features (np.ndarray): The feature vectors to select from. 90 | nb_examplars (int): The number of feature vectors to select. 91 | 92 | Returns: 93 | np.ndarray: The indices of the selected feature vectors. 94 | """ 95 | features = features / (np.linalg.norm(features, axis=0) + 1e-8) 96 | class_mean = np.mean(features, axis=0) 97 | 98 | return _l2_distance(features, class_mean).argsort()[:nb_examplars] 99 | 100 | 101 | def samplewise_losses(opt, probs, labels, num_samples): 102 | """ 103 | Selects a subset of samples from the input data based on the sampling mode. 104 | 105 | Args: 106 | opt (argparse.Namespace): The command-line arguments. 107 | probs (np.ndarray): The predicted probabilities for each sample. 108 | labels (np.ndarray): The true labels for each sample. 109 | num_samples (int): The number of samples to select. 110 | 111 | Returns: 112 | np.ndarray: The indices of the selected samples. 113 | """ 114 | if opt.sampling_mode == 'unc_lc': 115 | var_ratio = np.max(probs, axis=1) 116 | indexes = var_ratio.argsort() 117 | elif opt.sampling_mode == 'max_loss': 118 | prob_gt = np.array( 119 | [probs[j, labels[j]] for j in range(probs.shape[0])]) 120 | indexes = prob_gt.argsort() 121 | return indexes[:num_samples] 122 | 123 | 124 | def herding(features, nb_examplars): 125 | """ 126 | Selects the `nb_examplars` features that are most representative of the input feature vectors using the herding algorithm. 127 | 128 | Args: 129 | features (np.ndarray): The feature vectors to select from. 130 | nb_examplars (int): The number of feature vectors to select. 131 | 132 | Returns: 133 | np.ndarray: The indices of the selected feature vectors. 134 | """ 135 | D = features.T 136 | D = D / (np.linalg.norm(D, axis=0) + 1e-8) 137 | mu = np.mean(D, axis=1) 138 | herding_matrix = np.zeros((features.shape[0], )) 139 | 140 | w_t = mu 141 | iter_herding, iter_herding_eff = 0, 0 142 | 143 | while not ( 144 | np.sum(herding_matrix != 0) == min(nb_examplars, features.shape[0]) 145 | ) and iter_herding_eff < 100000000: # 10M iters are way too high, expected to converge before that. Converges in <100 iters in checks. 146 | tmp_t = np.dot(w_t, D) 147 | ind_max = np.argmax(tmp_t) 148 | iter_herding_eff += 1 149 | if herding_matrix[ind_max] == 0: 150 | herding_matrix[ind_max] = 1 + iter_herding 151 | iter_herding += 1 152 | 153 | w_t = w_t + mu - D[:, ind_max] 154 | 155 | herding_matrix[np.where( 156 | herding_matrix == 0)[0]] = 100000000 # Some high number 157 | 158 | return herding_matrix.argsort()[:nb_examplars] 159 | 160 | 161 | def kmeans(features, nb_examplars, k=5): 162 | """Samples examplars for memory according to KMeans. 163 | 164 | :param features: The image features of a single class. 165 | :param nb_examplars: Number of images to keep. 166 | :param k: Number of clusters for KMeans algo, defaults to 5 167 | :return: A numpy array of indexes. 168 | """ 169 | model = KMeans(n_clusters=k) 170 | cluster_assignements = model.fit_predict(features) 171 | 172 | nb_per_clusters = nb_examplars // k 173 | indexes = [] 174 | for c in range(k): 175 | c_indexes = np.random.choice(np.where(cluster_assignements == c)[0], 176 | size=nb_per_clusters) 177 | indexes.append(c_indexes) 178 | 179 | return np.concatenate(indexes) 180 | 181 | 182 | def _l2_distance(x, y): 183 | """ 184 | Computes the squared L2 distance between two arrays. 185 | 186 | Args: 187 | x (np.ndarray): The first array. 188 | y (np.ndarray): The second array. 189 | 190 | Returns: 191 | np.ndarray: The squared L2 distance between `x` and `y`. 192 | """ 193 | return np.power(x - y, 2).sum(-1) 194 | -------------------------------------------------------------------------------- /src/fc_correction.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import math 3 | import time 4 | 5 | import torch 6 | import torch.nn as nn 7 | import torch.nn.functional as F 8 | from torch import nn 9 | from torch.optim import Adam 10 | 11 | from utils import AverageMeter, ProgressMeter, accuracy 12 | 13 | 14 | class CosineLinear(nn.Module): 15 | """ 16 | A PyTorch module for a linear layer with cosine similarity. 17 | 18 | Args: 19 | in_features (int): The number of input features. 20 | out_features (int): The number of output features. 21 | sigma (bool): Whether to include a learnable scaling factor. 22 | 23 | Attributes: 24 | in_features (int): The number of input features. 25 | out_features (int): The number of output features. 26 | weight (nn.Parameter): The learnable weight tensor. 27 | bias (None): This module does not use a bias. 28 | sigma (Optional[nn.Parameter]): The learnable scaling factor tensor. 29 | """ 30 | 31 | def __init__(self, in_features, out_features, sigma=True): 32 | super(CosineLinear, self).__init__() 33 | self.in_features = in_features 34 | self.out_features = out_features 35 | self.weight = nn.Parameter(torch.Tensor(out_features, in_features)) 36 | self.bias = None 37 | if sigma: 38 | self.sigma = nn.Parameter(torch.Tensor(1)) 39 | self.reset_parameters() 40 | 41 | def reset_parameters(self): 42 | stdv = 1. / math.sqrt(self.weight.size(1)) 43 | self.weight.data.uniform_(-stdv, stdv) 44 | if self.sigma is not None: 45 | self.sigma.data.fill_(1) 46 | 47 | def forward(self, input): 48 | out = F.linear(F.normalize(input, p=2,dim=1), \ 49 | F.normalize(self.weight, p=2, dim=1)) 50 | if self.sigma is not None: 51 | out = self.sigma * out 52 | return out 53 | 54 | 55 | class Temperature(torch.nn.Module): 56 | """ 57 | A PyTorch module for temperature scaling during calibration. 58 | 59 | Attributes: 60 | temperature (nn.Parameter): The learnable temperature scaling factor. 61 | """ 62 | 63 | def __init__(self): 64 | super(Temperature, self).__init__() 65 | self.temperature = nn.Parameter(torch.ones(1) * 1.5) 66 | 67 | def forward(self, logits): 68 | """ 69 | Applies temperature scaling to the logits. 70 | 71 | Args: 72 | logits (torch.Tensor): The input logits. 73 | 74 | Returns: 75 | torch.Tensor: The logits after temperature scaling. 76 | """ 77 | return logits / self.temperature 78 | 79 | 80 | class BiC(nn.Module): 81 | """ 82 | A PyTorch module for bias adjustment of new classes in a classification model. 83 | 84 | Args: 85 | num_new_cls (int): The number of new classes to adjust the bias for. 86 | 87 | Attributes: 88 | alpha (nn.Parameter): The learnable scaling factor for the new classes. 89 | beta (nn.Parameter): The learnable bias term for the new classes. 90 | num_new_cls (int): The number of new classes to adjust the bias for. 91 | """ 92 | 93 | def __init__(self, num_new_cls): 94 | super(BiC, self).__init__() 95 | self.alpha, self.beta = nn.Parameter( 96 | torch.ones(1) * 0.75), nn.Parameter(torch.ones(1) * 0.001) 97 | self.num_new_cls = num_new_cls 98 | 99 | def forward(self, logits): 100 | """ 101 | Adjusts the bias of the new classes in the logits. 102 | 103 | Args: 104 | logits (torch.Tensor): The input logits. 105 | 106 | Returns: 107 | torch.Tensor: The logits with adjusted bias for the new classes. 108 | """ 109 | extra = logits.size(1) - self.num_new_cls 110 | old, new = logits[:, :extra], logits[:, extra:] 111 | new = self.alpha * new + self.beta 112 | outputs = torch.cat((old, new), dim=1) 113 | return outputs 114 | 115 | 116 | def correct_weights(model, valloader, calibration_method, logger, expand_size): 117 | """ 118 | Corrects the weights of the fully connected layer in a PyTorch model according to the WA calibration method. 119 | 120 | Args: 121 | model (nn.Module): The PyTorch model to correct the weights for. 122 | valloader (DataLoader): The validation data loader. 123 | calibration_method (str): The calibration method to use. 124 | logger (Logger): The logger object for logging. 125 | expand_size (int): The number of new classes to expand the model for. 126 | 127 | Raises: 128 | AssertionError: If `expand_size` is 0. 129 | 130 | Returns: 131 | None 132 | """ 133 | # Weights corrected according to: Maintaining Discrimination and Fairness in Class Incremental Learning (https://arxiv.org/pdf/1911.07053.pdf) 134 | if calibration_method == 'WA': 135 | assert (expand_size != 0) 136 | extra = model.fc.weight.size(0) - expand_size 137 | gamma = model.fc.weight[:extra].norm( 138 | p=2, dim=1).mean() / model.fc.weight[extra:].norm(p=2, 139 | dim=1).mean() 140 | with torch.no_grad(): 141 | intermediate = model.fc.weight[extra:] * gamma 142 | model.fc.weight[extra:] = nn.Parameter(intermediate) 143 | if model.fc.bias is not None: 144 | model.fc.bias[extra:] = nn.Parameter(model.fc.bias[extra:] * 145 | gamma) 146 | 147 | # Weights corrected according to: Large Scale Incremental Learning (https://arxiv.org/abs/1905.13260) 148 | elif calibration_method == 'BiC': 149 | assert (expand_size != 0) 150 | calibrator = BiC(num_new_cls=expand_size).cuda() 151 | calib_optimizer = Adam(calibrator.parameters(), lr=0.01) 152 | 153 | ### TODO: Optimize to consume tiny computational cost by optimizing on a small set of valset, reusing predictions 154 | for lr_exp in range(2, 4): 155 | # Assuming that 8 epochs each with a lr decay by 10 suffices to make the calibrator converge (loss does stop decreasing) 156 | for param_group in calib_optimizer.param_groups: 157 | param_group['lr'] = 0.1**(lr_exp) 158 | 159 | for epoch in range(5): 160 | calibrator, calib_optimizer = calibrate( 161 | loader=valloader, 162 | model=model, 163 | calibrator=calibrator, 164 | optimizer=calib_optimizer, 165 | logger=logger, 166 | epoch=epoch) 167 | 168 | extra = model.fc.weight.size(0) - expand_size 169 | with torch.no_grad(): 170 | intermediate = model.fc.weight[extra:] * calibrator.alpha 171 | model.fc.weight[extra:] = nn.Parameter(intermediate) 172 | if model.fc.bias is not None: 173 | model.fc.bias[extra:] = nn.Parameter(model.fc.bias[extra:] * 174 | calibrator.alpha + 175 | calibrator.beta) 176 | 177 | # Baseline weight correction according to: On Calibration of Modern Neural Networks (https://arxiv.org/abs/1706.04599) 178 | elif calibration_method == 'Temperature': 179 | assert (expand_size != 0) 180 | calibrator = Temperature().cuda() 181 | calib_optimizer = Adam(calibrator.parameters(), lr=0.01) 182 | 183 | ### TODO: Optimize for minimal computational overhead by ternary search, no sgd needed 184 | for lr_exp in range(2, 4): 185 | # Assuming that 8 epochs each with a lr decay by 10 suffices to make the calibrator converge (loss does stop decreasing) 186 | for param_group in calib_optimizer.param_groups: 187 | param_group['lr'] = 0.1**(lr_exp) 188 | 189 | for epoch in range(5): 190 | calibrator, calib_optimizer = calibrate( 191 | loader=valloader, 192 | model=model, 193 | calibrator=calibrator, 194 | optimizer=calib_optimizer, 195 | logger=logger, 196 | epoch=epoch) 197 | 198 | model.fc.weight = nn.Parameter(model.fc.weight / 199 | calibrator.temperature) 200 | if model.fc.bias is not None: 201 | model.fc.bias = nn.Parameter(model.fc.bias / 202 | calibrator.temperature) 203 | 204 | return model 205 | 206 | 207 | def calibrate(loader, model, calibrator, optimizer, logger, epoch): 208 | """ 209 | Calibrates a PyTorch model using a given calibrator module and optimizer. 210 | 211 | Args: 212 | loader (DataLoader): The data loader for calibration. 213 | model (nn.Module): The PyTorch model to calibrate. 214 | calibrator (nn.Module): The PyTorch module to use for calibration. 215 | optimizer (Optimizer): The optimizer to use for calibration. 216 | logger (Logger): The logger object for logging. 217 | epoch (int): The current epoch number. 218 | 219 | Returns: 220 | Tuple[nn.Module, Optimizer]: The calibrated model and optimizer. 221 | """ 222 | batch_time = AverageMeter('Time', ':6.3f') 223 | data_time = AverageMeter('Data', ':6.3f') 224 | losses = AverageMeter('Loss', ':.4e') 225 | top1 = AverageMeter('Acc@1', ':6.2f') 226 | top5 = AverageMeter('Acc@5', ':6.2f') 227 | progress = ProgressMeter(logger, 228 | len(loader), 229 | [batch_time, data_time, losses, top1, top5], 230 | prefix="Epoch: [{0}] LR: [{1:.4f}]".format( 231 | epoch, optimizer.param_groups[0]['lr'])) 232 | 233 | # switch to train mode 234 | model.eval() 235 | calibrator.train() 236 | end = time.time() 237 | 238 | for i, (images, target) in enumerate(loader): 239 | # measure data loading time 240 | data_time.update(time.time() - end) 241 | 242 | with torch.no_grad(): 243 | images = images.cuda(non_blocking=True) 244 | target = target.cuda(non_blocking=True) 245 | logits = model(images) 246 | 247 | output = calibrator(logits) 248 | loss = nn.CrossEntropyLoss()(output, target) 249 | 250 | # measure accuracy and record loss 251 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 252 | losses.update(loss.item(), images.size(0)) 253 | top1.update(acc1[0], images.size(0)) 254 | top5.update(acc5[0], images.size(0)) 255 | 256 | # compute gradient and do SGD step 257 | optimizer.zero_grad() 258 | loss.backward() 259 | optimizer.step() 260 | 261 | # measure elapsed time 262 | batch_time.update(time.time() - end) 263 | end = time.time() 264 | 265 | progress.display_summary() 266 | return calibrator, optimizer 267 | -------------------------------------------------------------------------------- /src/training.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import numpy as np 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | from torchvision.models.feature_extraction import create_feature_extractor 8 | 9 | from utils import AverageMeter, ProgressMeter, Summary, accuracy 10 | 11 | 12 | def train(opt, 13 | loader, 14 | model, 15 | optimizer, 16 | scheduler, 17 | logger, 18 | prevmodel=None, 19 | temperature=2.0): 20 | """ 21 | Trains a PyTorch model on a given dataset. 22 | 23 | Args: 24 | opt (argparse.Namespace): The command-line arguments. 25 | loader (torch.utils.data.DataLoader): The data loader for the training dataset. 26 | model (torch.nn.Module): The PyTorch model to train. 27 | optimizer (torch.optim.Optimizer): The optimizer to use for training. 28 | scheduler (torch.optim.lr_scheduler._LRScheduler): The learning rate scheduler. 29 | logger (Logger): The logger to use for logging training progress. 30 | prevmodel (torch.nn.Module, optional): The previous model to use for distillation. 31 | temperature (float, optional): The temperature to use for distillation. 32 | 33 | Returns: 34 | torch.nn.Module: The trained PyTorch model. 35 | torch.optim.Optimizer: The optimizer used for training. 36 | torch.optim.lr_scheduler._LRScheduler: The learning rate scheduler used for training. 37 | """ 38 | 39 | losses = AverageMeter('Loss', ':.4e') 40 | top1 = AverageMeter('Acc@1', ':6.2f') 41 | top5 = AverageMeter('Acc@5', ':6.2f') 42 | progress = ProgressMeter(logger, 43 | len(loader), [losses, top1, top5], 44 | prefix="Timestep: [{}]".format(opt.timestep)) 45 | 46 | # Switch to train mode 47 | model.train() 48 | if prevmodel is not None: 49 | prevmodel.eval() 50 | distill_target = None 51 | 52 | for i, (images, target) in enumerate(loader): 53 | # measure data loading time 54 | 55 | images = images.cuda(non_blocking=True) 56 | target = target.cuda(non_blocking=True) 57 | 58 | with torch.cuda.amp.autocast(enabled=True, dtype=torch.bfloat16): 59 | # compute output 60 | output = model(images) 61 | loss = nn.CrossEntropyLoss()(output, target) 62 | 63 | # Distillation of different types -- lambda is hyperparam-searched over 64 | if opt.distill is not None and prevmodel is not None: 65 | with torch.no_grad(): 66 | prevoutput = prevmodel(images) 67 | prevoutput = prevoutput.detach() / temperature 68 | 69 | distill_output = output[:, :prevoutput.size(1)] / temperature 70 | 71 | if opt.distill == 'BCE': 72 | # Ref: iCaRL Incremental Classifier and Representation Learning (https://arxiv.org/abs/1611.07725) 73 | prevprobs = F.softmax(prevoutput, dim=1) 74 | loss += 1.0 * F.binary_cross_entropy_with_logits( 75 | input=distill_output, target=prevprobs) 76 | elif opt.distill == 'CrossEntropy': 77 | # Ref: Large Scale Incremental Learning (https://arxiv.org/abs/1905.13260) 78 | prevprobs = F.softmax(prevoutput, dim=1) 79 | log_inp = F.log_softmax(distill_output, dim=1) 80 | loss += prevoutput.size(1) / (output.size(1)) * F.kl_div( 81 | input=log_inp, target=prevprobs) 82 | elif opt.distill == 'Cosine': 83 | if distill_target is None: 84 | distill_target = torch.ones(prevoutput.shape[0]).cuda() 85 | # Ref: Learning a Unified Classifier Incrementally via Rebalancing (http://openaccess.thecvf.com/content_CVPR_2019/papers/Hou_Learning_a_Unified_Classifier_Incrementally_via_Rebalancing_CVPR_2019_paper.pdf) 86 | loss += max( 87 | 0.5, 88 | np.sqrt((output.size(1) - prevoutput.size(1)) / 89 | prevoutput.size(1))) * F.cosine_embedding_loss( 90 | input1=distill_output, 91 | input2=prevoutput, 92 | target=distill_target) 93 | elif opt.distill == 'MSE': 94 | # Ref: Dark Experience for General Continual Learning: A Strong, Simple Baseline (https://arxiv.org/pdf/2004.07211.pdf) 95 | loss += 0.5 * F.mse_loss(input=distill_output, 96 | target=prevoutput) 97 | 98 | # measure accuracy and record loss 99 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 100 | losses.update(loss.item(), images.size(0)) 101 | top1.update(acc1[0], images.size(0)) 102 | top5.update(acc5[0], images.size(0)) 103 | 104 | # compute gradient and do SGD step 105 | optimizer.zero_grad() 106 | loss.backward() 107 | optimizer.step() 108 | scheduler.step() 109 | if opt.calibrator == 'WA': 110 | torch.clamp(model.fc.weight, min=0) 111 | 112 | if i > ((opt.total_steps)): 113 | return model, optimizer, scheduler 114 | return model, optimizer, scheduler 115 | 116 | 117 | def validate(loader, model, logger): 118 | """ 119 | Evaluates a PyTorch model on a given dataset. 120 | 121 | Args: 122 | loader (torch.utils.data.DataLoader): The data loader for the evaluation dataset. 123 | model (torch.nn.Module): The PyTorch model to evaluate. 124 | logger (Logger): The logger to use for logging evaluation progress. 125 | 126 | Returns: 127 | None 128 | """ 129 | top1 = AverageMeter('Acc@1', ':6.2f', Summary.AVERAGE) 130 | top5 = AverageMeter('Acc@5', ':6.2f', Summary.AVERAGE) 131 | progress = ProgressMeter(logger, 132 | len(loader), [top1, top5], 133 | prefix='Test: ') 134 | 135 | # switch to evaluate mode 136 | model.eval() 137 | 138 | with torch.no_grad(): 139 | for i, (images, target) in enumerate(loader): 140 | images = images.cuda(non_blocking=True) 141 | target = target.cuda(non_blocking=True) 142 | 143 | # compute output 144 | output = model(images) 145 | loss = nn.CrossEntropyLoss()(output, target) 146 | 147 | # measure accuracy and record loss 148 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 149 | top1.update(acc1[0], images.size(0)) 150 | top5.update(acc5[0], images.size(0)) 151 | 152 | progress.display_summary() 153 | return 154 | 155 | 156 | def test(loader, model, logger): 157 | """ 158 | Evaluates a PyTorch model on a given dataset. 159 | 160 | Args: 161 | loader (torch.utils.data.DataLoader): The data loader for the evaluation dataset. 162 | model (torch.nn.Module): The PyTorch model to evaluate. 163 | logger (Logger): The logger to use for logging evaluation progress. 164 | 165 | Returns: 166 | Tuple[np.ndarray, np.ndarray]: The predicted labels and true labels for each sample. 167 | """ 168 | top1 = AverageMeter('Acc@1', ':6.2f', Summary.AVERAGE) 169 | top5 = AverageMeter('Acc@5', ':6.2f', Summary.AVERAGE) 170 | progress = ProgressMeter(logger, len(loader), [top1, top5], prefix='Val: ') 171 | 172 | # switch to evaluate mode 173 | model.eval() 174 | 175 | predsarr, labelsarr = None, None 176 | with torch.no_grad(): 177 | for i, (images, target) in enumerate(loader): 178 | images = images.cuda(non_blocking=True) 179 | 180 | # compute output 181 | output = model(images) 182 | output = output.cpu() 183 | pred = torch.argmax(output, dim=1) 184 | loss = nn.CrossEntropyLoss()(output, target) 185 | 186 | if predsarr is None: 187 | labelsarr = target 188 | predsarr = pred 189 | else: 190 | labelsarr = torch.cat((labelsarr, target), dim=0) 191 | predsarr = torch.cat((predsarr, pred), dim=0) 192 | 193 | # measure accuracy and record loss 194 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 195 | top1.update(acc1[0], images.size(0)) 196 | top5.update(acc5[0], images.size(0)) 197 | 198 | progress.display_summary() 199 | return predsarr, labelsarr 200 | 201 | 202 | def save_representations(opt, loader, model, mode='features'): 203 | """ 204 | Saves the representations of a PyTorch model on a given dataset. 205 | 206 | Args: 207 | opt (argparse.Namespace): The command-line arguments. 208 | loader (torch.utils.data.DataLoader): The data loader for the dataset. 209 | model (torch.nn.Module): The PyTorch model to extract features from. 210 | mode (str, optional): The mode to use for feature extraction. Can be 'features' or 'predictions'. 211 | 212 | Returns: 213 | None 214 | """ 215 | assert (mode in ['features', 'predictions']) 216 | X_arr, y_arr = None, None 217 | 218 | node = 'flatten' if mode == 'features' else 'fc' 219 | new_model = create_feature_extractor(model, return_nodes=[node]) 220 | new_model.eval() 221 | 222 | with torch.no_grad(): 223 | for i, (images, labels) in enumerate(loader): 224 | images = images.cuda(non_blocking=True) 225 | out = new_model(images) 226 | 227 | X = out[node] 228 | X = X.cpu() 229 | X_arr = torch.cat((X_arr, X), dim=0) if X_arr is not None else X 230 | y_arr = torch.cat( 231 | (y_arr, labels), dim=0) if y_arr is not None else labels 232 | 233 | np.save( 234 | opt.log_dir + '/' + opt.exp_name + '/labels_' + str(opt.timestep) + 235 | '_train.npy', y_arr.numpy()) 236 | 237 | if mode == 'features': 238 | np.save( 239 | opt.log_dir + '/' + opt.exp_name + '/feats_' + str(opt.timestep) + 240 | '_train.npy', X_arr.numpy()) 241 | 242 | if opt.timestep > 2: # Optimize storage space 243 | if os.path.exists(opt.log_dir + '/' + opt.exp_name + '/feats_' + 244 | str(opt.timestep - 2) + '_train.npy'): 245 | os.remove(opt.log_dir + '/' + opt.exp_name + '/feats_' + 246 | str(opt.timestep - 2) + '_train.npy') 247 | else: 248 | np.save( 249 | opt.log_dir + '/' + opt.exp_name + '/predprobs_' + 250 | str(opt.timestep) + '_train.npy', X_arr.numpy()) 251 | 252 | if opt.timestep > 2: # Optimize scratch storage space 253 | if os.path.exists(opt.log_dir + '/' + opt.exp_name + 254 | '/predprobs_' + str(opt.timestep - 2) + 255 | '_train.npy'): 256 | os.remove(opt.log_dir + '/' + opt.exp_name + '/predprobs_' + 257 | str(opt.timestep - 2) + '_train.npy') 258 | -------------------------------------------------------------------------------- /src/datasets.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import copy 3 | import pickle 4 | import random 5 | from os.path import exists 6 | 7 | import numpy as np 8 | import torch 9 | from PIL import Image 10 | from torch.utils.data import DataLoader, Dataset 11 | from torchvision.transforms import autoaugment, transforms 12 | from torchvision.transforms.functional import InterpolationMode 13 | 14 | import opts 15 | from sampling import select_samples 16 | from training import train 17 | 18 | 19 | class CLImageFolder(object): 20 | """ 21 | Loading a continual learning dataloader from ordering specified in the .txt files for a given dataset 22 | ------ 23 | opt: configuration file 24 | ------ 25 | """ 26 | 27 | def __init__(self, opt): 28 | super(CLImageFolder, self).__init__() 29 | self.kwargs = { 30 | 'num_workers': opt.num_workers, 31 | 'batch_size': opt.train_batch_size, 32 | 'pin_memory': True, 33 | 'shuffle': False, 34 | 'drop_last': False 35 | } 36 | self.opt = opt 37 | self.curr_val_size, self.current_sample = 0, 0 # The total number of val/total samples 38 | 39 | # [self._classes, self._pretrain_paths, self._cl_{train/test}_paths] contain the full set of paths and classes -- do not use these for learning/sampling/anything. These are there for checks and ease-of-use. 40 | # Only self.curr_classes, self.curr_paths and self.{val/test}_paths should be exposed to the model. 41 | 42 | if opt.dataset == 'Imagenet2K': 43 | with open("../scripts/imagenet_folder_to_cls.pkl", 'rb') as f: 44 | self._classes = pickle.load(f) #{} 45 | 46 | self._pretrain_paths, self._preval_paths, self._pretest_paths, self._pretrain_labels, self._preval_labels, self._pretest_labels = self.populate_paths( 47 | trainpath=opt.order_file_dir + '/pretrain.txt', 48 | valpath=opt.order_file_dir + '/preval.txt', 49 | testpath=opt.order_file_dir + '/pretest.txt') 50 | self.curr_classes = copy.deepcopy(list(self._classes.values( 51 | ))) # At timestep 0, curr_paths is pretrain_paths 52 | 53 | assert (opt.dset_mode in ['class_incremental', 'data_incremental']) 54 | 55 | self._cltrain_paths, self._clval_paths, self._cltest_paths, self._cltrain_labels, self._clval_labels, self._cltest_labels = self.populate_paths( 56 | trainpath=opt.order_file_dir + '/ordering_' + opt.dset_mode + 57 | '.txt', 58 | valpath=opt.order_file_dir + '/val.txt', 59 | testpath=opt.order_file_dir + '/test.txt') 60 | self.class_sizes = np.load('../scripts/class_sizes.npy') 61 | 62 | # We usually split the curr_paths into train and val, excluding pretrain data. Currently 0 new data as everything is pretraining. 63 | self.curr_paths, self.val_paths, self.test_paths, self.fulltest_paths, self.curr_labels, self.val_labels, self.test_labels, self.fulltest_labels = copy.deepcopy( 64 | self._pretrain_paths), copy.deepcopy( 65 | self._preval_paths), [], copy.deepcopy( 66 | self._cltest_paths), copy.deepcopy( 67 | self._pretrain_labels), copy.deepcopy( 68 | self._preval_labels), [], copy.deepcopy( 69 | self._cltest_labels) 70 | self.classweights = np.bincount(np.array(self.curr_labels)) 71 | assert (not torch.any( 72 | torch.eq(torch.from_numpy(self.classweights), 73 | torch.zeros(len(self.classweights)))).item() 74 | ), 'Class cannot have 0 samples' 75 | 76 | # Each timestep will have its {train/val/test/mem}loader (timestep 0 won't have memloader) 77 | assert (len(self.curr_paths) > 0 and len(self.val_paths) > 0 78 | and len(self._pretest_paths) > 0 79 | and len(self.test_paths) == 0), 'Path list cannot be empty' 80 | assert (len(self.curr_paths) == len(self.curr_labels) 81 | and len(self.val_paths) == len(self.val_labels) 82 | and len(self._pretest_paths) == len(self._pretest_labels) 83 | and len(self.fulltest_paths) == len(self.fulltest_labels)) 84 | 85 | self.trainloader = self.get_loader(opt, 86 | paths=self.curr_paths, 87 | labels=self.curr_labels, 88 | train=True) 89 | self.trainloader_eval = self.get_loader(opt, 90 | paths=self.curr_paths, 91 | labels=self.curr_labels, 92 | train=False) 93 | self.valloader = self.get_loader(opt, 94 | paths=self.val_paths, 95 | labels=self.val_labels, 96 | train=False) 97 | self.pretestloader = self.get_loader( 98 | opt, 99 | paths=copy.deepcopy(self._pretest_paths), 100 | labels=copy.deepcopy(self._pretest_labels), 101 | train=False) 102 | self.fulltestloader = DataLoader( 103 | ListFolder(data_dir=opt.data_dir, 104 | imgpaths=self.fulltest_paths, 105 | labels=self.fulltest_labels, 106 | transform=ClassificationPresetEval( 107 | crop_size=self.opt.crop_size, 108 | resize_size=self.opt.crop_size + 32)), 109 | **self.kwargs) 110 | self.trainlen, self.vallen, self.pretestlen, self.fulltestlen = len( 111 | self.curr_paths), len(self.val_paths), len( 112 | self._pretest_paths), len(self.fulltest_paths) 113 | 114 | elif opt.dataset == 'CGLM': 115 | assert (opt.dset_mode == 'time_incremental') 116 | self._classes = {} 117 | self._cltrain_paths, _, self._test_paths, self._cltrain_labels, _, self._test_labels = self.populate_paths( 118 | trainpath=opt.order_file_dir + '/train.txt', 119 | valpath=opt.order_file_dir + '/test.txt', 120 | testpath=opt.order_file_dir + '/test.txt') 121 | self.curr_classes = copy.deepcopy(list(self._classes.values( 122 | ))) # At timestep 0, curr_paths is pretrain_paths 123 | 124 | # We usually split the curr_paths into train and val, excluding pretrain data. Currently 0 new data as everything is pretraining. 125 | self.curr_paths, self.curr_labels = [], [] 126 | 127 | # Each timestep will have its {train/val/test/mem}loader (timestep 0 won't have memloader) 128 | assert (len(self._test_paths) > 0), 'Path list cannot be empty' 129 | self.testloader = DataLoader( 130 | ListFolder(imgpaths=copy.deepcopy(self._test_paths), 131 | labels=self._test_labels, 132 | transform=ClassificationPresetEval( 133 | crop_size=self.opt.crop_size, 134 | resize_size=self.opt.crop_size + 32)), 135 | **self.kwargs) 136 | self.testlen = len(self._test_paths) 137 | 138 | def populate_paths(self, trainpath, valpath, testpath): 139 | # Add training paths (order important -- never shuffle) along with mapping to ensure dataloader always gets 0-n as class indexes 140 | filename = trainpath 141 | fp = open(filename, 'r') 142 | trainimgs = fp.readlines() 143 | trainlabels = [] 144 | for i in range(len(trainimgs)): 145 | if self.opt.dataset == 'Imagenet2K': 146 | clsname = trainimgs[i].strip().split('/')[-2] 147 | if clsname not in self._classes: 148 | self._classes[clsname] = len(self._classes) 149 | trainlabels.append(self._classes[clsname]) 150 | trainimgs[i] = trainimgs[i].strip() 151 | elif self.opt.dataset == 'CGLM': 152 | clsname = trainimgs[i].strip().split('\t')[0] 153 | if clsname not in self._classes: 154 | self._classes[clsname] = len(self._classes) 155 | trainlabels.append(self._classes[clsname]) 156 | trainimgs[i] = trainimgs[i].strip().split('\t')[1] 157 | fp.close() 158 | 159 | # Add val paths (order important -- never shuffle) and assert that classes for all samples are in the mapping function 160 | filename = valpath 161 | fp = open(filename, 'r') 162 | valimgs = fp.readlines() 163 | vallabels = [] 164 | for i in range(len(valimgs)): 165 | if self.opt.dataset == 'Imagenet2K': 166 | clsname = valimgs[i].strip().split('/')[-2] 167 | vallabels.append(self._classes[clsname]) 168 | valimgs[i] = valimgs[i].strip() 169 | elif self.opt.dataset == 'CGLM': 170 | clsname = valimgs[i].strip().split('\t')[0] 171 | vallabels.append(self._classes[clsname]) 172 | valimgs[i] = valimgs[i].strip().split('\t')[1] 173 | assert (clsname 174 | in self._classes), 'Class ' + str(clsname) + ' not found!' 175 | fp.close() 176 | 177 | # Add testing paths (order important -- never shuffle) and assert that classes for all samples are in the mapping function 178 | filename = testpath 179 | fp = open(filename, 'r') 180 | testimgs = fp.readlines() 181 | testlabels = [] 182 | for i in range(len(testimgs)): 183 | if self.opt.dataset == 'Imagenet2K': 184 | clsname = testimgs[i].strip().split('/')[-2] 185 | testlabels.append(self._classes[clsname]) 186 | testimgs[i] = testimgs[i].strip() 187 | elif self.opt.dataset == 'CGLM': 188 | clsname = testimgs[i].strip().split('\t')[0] 189 | testlabels.append(self._classes[clsname]) 190 | testimgs[i] = testimgs[i].strip().split('\t')[1] 191 | assert (clsname 192 | in self._classes), 'Class ' + str(clsname) + ' not found!' 193 | fp.close() 194 | 195 | assert (len(trainlabels) == len(trainimgs) 196 | and len(vallabels) == len(valimgs) 197 | and len(testlabels) == len(testimgs)) 198 | return trainimgs, valimgs, testimgs, trainlabels, vallabels, testlabels 199 | 200 | def get_loader(self, opt, paths, labels, train=True): 201 | # drop_last is False and shuffle is True while training, vice-versa in other cases (batchnorm cries if last batch has 1 sample) 202 | if train: 203 | self.kwargs['batch_size'] = self.opt.train_batch_size 204 | self.kwargs['shuffle'] = True 205 | else: 206 | self.kwargs['batch_size'] = self.opt.test_batch_size 207 | self.kwargs['shuffle'] = False 208 | 209 | if train: 210 | return DataLoader( 211 | ListFolder(data_dir=opt.data_dir, 212 | imgpaths=paths, 213 | labels=labels, 214 | transform=ClassificationPresetTrain( 215 | crop_size=self.opt.crop_size)), **self.kwargs) 216 | else: 217 | return DataLoader( 218 | ListFolder(data_dir=opt.data_dir, 219 | imgpaths=paths, 220 | labels=labels, 221 | transform=ClassificationPresetEval( 222 | crop_size=self.opt.crop_size, 223 | resize_size=self.opt.crop_size + 32)), 224 | **self.kwargs) 225 | 226 | def get_next_timestep_dataloader(self, opt): 227 | assert ( 228 | (self.opt.num_classes_per_timestep > 0 229 | and self.opt.increment_size == 0) 230 | or (self.opt.num_classes_per_timestep == 0 231 | and self.opt.increment_size > 0) 232 | ), 'Either increment by class sizes or by constant number of samples' 233 | 234 | # Load new samples into the curr_paths -- either by incrementing per-class or per-sample (different as classes may have very unequal distribution of samples) 235 | assert (self.opt.dset_mode 236 | in ['class_incremental', 'data_incremental']) 237 | if self.opt.dset_mode == 'class_incremental': 238 | assert (self.opt.increment_size == 0) 239 | increment_size, start = 0, (self.opt.timestep - 240 | 1) * self.opt.num_classes_per_timestep 241 | for i in range(self.opt.num_classes_per_timestep): 242 | increment_size += self.class_sizes[start + i] 243 | else: 244 | assert (self.opt.num_classes_per_timestep == 0) 245 | increment_size = self.opt.increment_size 246 | 247 | new_paths = self._cltrain_paths[self. 248 | current_sample:self.current_sample + 249 | increment_size] 250 | new_labels = self._cltrain_labels[self. 251 | current_sample:self.current_sample + 252 | increment_size] 253 | self.current_sample = self.current_sample + increment_size 254 | 255 | # Update the curr_classes dictionary to the new samples 256 | newclasses = [] 257 | for i in range(len(new_labels)): 258 | clsname = new_labels[i] 259 | if clsname not in self.curr_classes: 260 | self.curr_classes.append(clsname) 261 | newclasses.append(clsname) 262 | self.expand_size = len(newclasses) 263 | 264 | # Add val images for all the new classes 265 | if self.opt.dataset == 'Imagenet2K': 266 | for i in range(len(self._clval_paths)): 267 | clsname = self._clval_labels[i] 268 | if clsname in newclasses: 269 | self.val_paths.append(self._clval_paths[i]) 270 | self.val_labels.append(self._clval_labels[i]) 271 | 272 | # Add test images for all the new classes 273 | for i in range(len(self._cltest_paths)): 274 | clsname = self._cltest_labels[i] 275 | if clsname in newclasses: 276 | self.test_paths.append(self._cltest_paths[i]) 277 | self.test_labels.append(self._cltest_labels[i]) 278 | 279 | self.curr_paths.extend(new_paths) 280 | self.curr_labels.extend(new_labels) 281 | assert (len(self.curr_labels) == len(self.curr_paths)) 282 | print(len(self.curr_paths), len(self.curr_labels)) 283 | 284 | if (not exists(self.opt.log_dir + '/' + self.opt.exp_name + '/' + 285 | str(self.opt.timestep + 1) + '/last.ckpt')): 286 | self.classweights = np.bincount(np.array(self.curr_labels)) 287 | assert (not torch.any( 288 | torch.eq(torch.from_numpy(self.classweights), 289 | torch.zeros(len(self.classweights)))).item() 290 | ), 'Class cannot have 0 samples' 291 | curr_paths, curr_labels = self.sample_data() 292 | 293 | # Each timestep will have its {train/val/test}loader 294 | if self.opt.dataset == 'Imagenet2K': 295 | assert (len(self.curr_paths) > 0 and len(self.val_paths) > 0 296 | and len( 297 | self.test_paths) > 0), 'Path list cannot be empty' 298 | self.trainloader = self.get_loader(opt, 299 | paths=self.curr_paths, 300 | labels=self.curr_labels, 301 | train=True) 302 | self.trainloader_eval = self.get_loader( 303 | opt, 304 | paths=self.curr_paths, 305 | labels=self.curr_labels, 306 | train=False) 307 | self.valloader = self.get_loader( 308 | opt, 309 | paths=copy.deepcopy(self.val_paths), 310 | labels=copy.deepcopy(self.val_labels), 311 | train=False) 312 | self.testloader = self.get_loader( 313 | opt, 314 | paths=copy.deepcopy(self.test_paths), 315 | labels=copy.deepcopy(self.test_labels), 316 | train=False) 317 | self.trainlen, self.vallen, self.testlen = len( 318 | curr_paths), len(self.val_paths), len(self.test_paths) 319 | elif self.opt.dataset == 'CGLM': 320 | assert (len(curr_paths) > 0 and len(curr_labels) 321 | == len(curr_paths)), 'Path list cannot be empty' 322 | self.trainloader = self.get_loader(opt, 323 | paths=curr_paths, 324 | labels=curr_labels, 325 | train=True) 326 | self.trainloader_eval = self.get_loader( 327 | opt, 328 | paths=self.curr_paths, 329 | labels=self.curr_labels, 330 | train=False) 331 | self.trainlen = len(curr_paths) 332 | 333 | def sample_data(self): 334 | if len(self.curr_paths) < ( 335 | self.opt.total_steps * self.opt.train_batch_size 336 | ): # Edge case-- if sampling size is higher than the all stored data then we don't select, simply add all samples. Won't be the case in most experiments. 337 | remaining = self.opt.total_steps * self.opt.train_batch_size 338 | curr_paths = copy.deepcopy(self.curr_paths) 339 | curr_labels = copy.deepcopy(self.curr_labels) 340 | remaining -= len(self.curr_paths) 341 | 342 | while remaining > len(self.curr_paths): 343 | curr_paths += copy.deepcopy(self.curr_paths) 344 | curr_labels += copy.deepcopy(self.curr_labels) 345 | remaining -= len(self.curr_paths) 346 | 347 | # Use lastk for the rest of the samples (likely negligible in size compared to the sampling done before, tested as using lastk performs similar to everything else) 348 | curr_paths += copy.deepcopy(self.curr_paths[len(self.curr_paths) - 349 | (remaining):]) 350 | curr_labels += copy.deepcopy( 351 | self.curr_labels[len(self.curr_paths) - (remaining):]) 352 | else: 353 | if self.opt.sampling_mode == 'recency_biased': 354 | remaining = self.opt.total_steps * self.opt.train_batch_size 355 | curr_paths = copy.deepcopy(self.curr_paths[:(remaining)]) 356 | curr_labels = copy.deepcopy(self.curr_labels[:(remaining)]) 357 | for idx in range( 358 | (self.opt.total_steps * self.opt.train_batch_size), 359 | len(self.curr_paths)): 360 | dice = random.randint(0, idx) 361 | if dice < (self.opt.reservoir_alpha * 362 | self.opt.total_steps * 363 | self.opt.train_batch_size): 364 | curr_paths[dice] = self.curr_paths[idx] 365 | curr_labels[dice] = self.curr_labels[idx] 366 | elif self.opt.sampling_mode == 'lastk': 367 | remaining = self.opt.total_steps * self.opt.train_batch_size 368 | curr_paths = copy.deepcopy( 369 | self.curr_paths[len(self.curr_paths) - (remaining):]) 370 | curr_labels = copy.deepcopy( 371 | self.curr_labels[len(self.curr_paths) - (remaining):]) 372 | elif self.opt.sampling_mode == 'class_balanced': 373 | # Weights set to inverse frequency of samples per class in this timesteps. 374 | weights = np.array([ 375 | self.classweights[self.curr_labels[i]].item() 376 | for i in range(len(self.curr_labels)) 377 | ]) 378 | probabilities = weights / np.sum(weights) 379 | idxes = np.random.choice(range(0, probabilities.shape[0]), 380 | size=self.opt.total_steps * 381 | self.opt.train_batch_size, 382 | p=probabilities, 383 | replace=True) 384 | elif self.opt.sampling_mode == 'uniform': 385 | probabilities = np.ones(len(self.curr_labels)) / len( 386 | self.curr_labels) 387 | idxes = np.random.choice(range(0, probabilities.shape[0]), 388 | size=self.opt.total_steps * 389 | self.opt.train_batch_size, 390 | p=probabilities, 391 | replace=True) 392 | elif self.opt.sampling_mode in [ 393 | 'herding', 'kmeans', 'unc_lc', 'max_loss' 394 | ]: ## These still being cleaned 395 | idxes = select_samples( 396 | opt=self.opt, 397 | num_samples=self.opt.total_steps * 398 | self.opt.train_batch_size, 399 | class_balanced=True 400 | ) # Without class balancing performance is even crappier 401 | 402 | curr_paths = np.copy(np.array(self.curr_paths)) 403 | curr_labels = np.copy(np.array(self.curr_labels)) 404 | curr_paths = curr_paths[idxes] 405 | curr_labels = curr_labels[idxes] 406 | curr_paths = list(curr_paths) 407 | curr_labels = list(curr_labels) 408 | 409 | return curr_paths, curr_labels 410 | 411 | 412 | class ListFolder(Dataset): 413 | """ 414 | A PyTorch Dataset class for loading images from a list of file paths. 415 | 416 | Args: 417 | data_dir (str): The path to the directory containing the images. 418 | imgpaths (List[str]): A list of file paths to the images. 419 | labels (List[int]): A list of labels for the images. 420 | transform (Optional[Callable]): A function to apply to the images. 421 | return_paths (bool): Whether to return the image paths along with the images. 422 | 423 | Attributes: 424 | data_dir (str): The path to the directory containing the images. 425 | image_paths (List[str]): A list of file paths to the images. 426 | labels (torch.Tensor): A tensor of labels for the images. 427 | transform (Optional[Callable]): A function to apply to the images. 428 | return_paths (bool): Whether to return the image paths along with the images. 429 | """ 430 | 431 | def __init__(self, 432 | data_dir, 433 | imgpaths, 434 | labels, 435 | transform=None, 436 | return_paths=False): 437 | super(ListFolder, self).__init__() 438 | # Get image list and weights per index 439 | self.data_dir = data_dir 440 | self.image_paths = imgpaths 441 | self.labels = torch.from_numpy(np.array(labels)) 442 | 443 | # Check for correct sizes 444 | assert (len(imgpaths) == len(labels)) 445 | self.transform = transform 446 | self.return_paths = return_paths 447 | 448 | def __getitem__(self, index): 449 | path = self.data_dir + '/' + self.image_paths[index] 450 | label = self.labels[index] 451 | sample = pil_loader(path) 452 | 453 | if self.transform is not None: 454 | sample = self.transform(sample) 455 | 456 | return sample, label 457 | 458 | def __len__(self): 459 | assert (len(self.image_paths) == self.labels.size(0) 460 | ), 'Length of image path array and labels different' 461 | return len(self.image_paths) 462 | 463 | 464 | def pil_loader(path): 465 | """ 466 | Opens an image file at the given path and returns a PIL image object. 467 | 468 | Args: 469 | path (str): The path to the image file. 470 | 471 | Returns: 472 | PIL.Image.Image: The image object in RGB format. 473 | """ 474 | # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) 475 | with open(path, 'rb') as f: 476 | img = Image.open(f) 477 | return img.convert('RGB') 478 | 479 | 480 | class ClassificationPresetTrain: 481 | """ 482 | A PyTorch transform class for preprocessing images during training for classification. 483 | 484 | Args: 485 | crop_size (int): The size to crop the image to. 486 | mean (Tuple[float, float, float]): The mean values for normalization. 487 | std (Tuple[float, float, float]): The standard deviation values for normalization. 488 | interpolation (InterpolationMode): The interpolation mode for resizing the image. 489 | hflip_prob (float): The probability of horizontally flipping the image. 490 | auto_augment_policy (Optional[str]): The policy to use for auto-augmentation. 491 | random_erase_prob (float): The probability of randomly erasing part of the image. 492 | 493 | Attributes: 494 | transforms (Compose): A PyTorch Compose object containing the image transforms. 495 | """ 496 | 497 | def __init__(self, 498 | crop_size, 499 | mean=(0.485, 0.456, 0.406), 500 | std=(0.229, 0.224, 0.225), 501 | interpolation=InterpolationMode.BILINEAR, 502 | hflip_prob=0.5, 503 | auto_augment_policy=None, 504 | random_erase_prob=0.0): 505 | trans = [ 506 | transforms.RandomResizedCrop(crop_size, 507 | interpolation=interpolation) 508 | ] 509 | if hflip_prob > 0: 510 | trans.append(transforms.RandomHorizontalFlip(hflip_prob)) 511 | if auto_augment_policy is not None: 512 | if auto_augment_policy == "ra": 513 | trans.append( 514 | autoaugment.RandAugment(interpolation=interpolation)) 515 | elif auto_augment_policy == "ta_wide": 516 | trans.append( 517 | autoaugment.TrivialAugmentWide( 518 | interpolation=interpolation)) 519 | elif auto_augment_policy == "augmix": 520 | trans.append(autoaugment.AugMix(interpolation=interpolation)) 521 | else: 522 | aa_policy = autoaugment.AutoAugmentPolicy(auto_augment_policy) 523 | trans.append( 524 | autoaugment.AutoAugment(policy=aa_policy, 525 | interpolation=interpolation)) 526 | trans.extend([ 527 | transforms.PILToTensor(), 528 | transforms.ConvertImageDtype(torch.float), 529 | transforms.Normalize(mean=mean, std=std), 530 | ]) 531 | if random_erase_prob > 0: 532 | trans.append(transforms.RandomErasing(p=random_erase_prob)) 533 | 534 | self.transforms = transforms.Compose(trans) 535 | 536 | def __call__(self, img): 537 | return self.transforms(img) 538 | 539 | 540 | class ClassificationPresetEval: 541 | """ 542 | A PyTorch transform class for preprocessing images during evaluation for classification. 543 | 544 | Args: 545 | crop_size (int): The size to crop the image to. 546 | resize_size (int): The size to resize the image to. 547 | mean (Tuple[float, float, float]): The mean values for normalization. 548 | std (Tuple[float, float, float]): The standard deviation values for normalization. 549 | interpolation (InterpolationMode): The interpolation mode for resizing the image. 550 | 551 | Attributes: 552 | transforms (Compose): A PyTorch Compose object containing the image transforms. 553 | """ 554 | 555 | def __init__( 556 | self, 557 | crop_size, 558 | resize_size=256, 559 | mean=(0.485, 0.456, 0.406), 560 | std=(0.229, 0.224, 0.225), 561 | interpolation=InterpolationMode.BILINEAR, 562 | ): 563 | 564 | self.transforms = transforms.Compose([ 565 | transforms.Resize(resize_size, interpolation=interpolation), 566 | transforms.CenterCrop(crop_size), 567 | transforms.PILToTensor(), 568 | transforms.ConvertImageDtype(torch.float), 569 | transforms.Normalize(mean=mean, std=std), 570 | ]) 571 | 572 | def __call__(self, img): 573 | return self.transforms(img) 574 | 575 | 576 | if __name__ == '__main__': 577 | # Test dataloading 578 | opt = opts.parse_args() 579 | d = CLImageFolder(opt=opt) 580 | d.get_next_timestep_dataloader(opt=opt) 581 | for (inputs, labels) in d.valloader: 582 | print(labels, inputs.size()) 583 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------