├── LICENSE.md ├── setup.py ├── .gitignore ├── nas_201_api ├── __init__.py ├── api_201.py └── api_utils.py └── README.md /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) since 2019 Xuanyi Dong (GitHub: https://github.com/D-X-Y) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | ##################################################### 2 | # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019.08 # 3 | ##################################################### 4 | # [2020.02.25] Initialize the API as v1.1 5 | # [2020.03.09] Upgrade the API to v1.2 6 | # [2020.03.16] Upgrade the API to v1.3 7 | # [2020.06.30] Upgrade the API to v2.0 8 | # [2020.10.12] Upgrade the API to v2.1 -- deprecate this repo, switch to NATS-Bench. 9 | import os 10 | from setuptools import setup 11 | 12 | 13 | def read(fname='README.md'): 14 | with open(os.path.join(os.path.dirname(__file__), fname), encoding='utf-8') as cfile: 15 | return cfile.read() 16 | 17 | 18 | setup( 19 | name = "nas_bench_201", 20 | version = "2.1", 21 | author = "Xuanyi Dong", 22 | author_email = "dongxuanyi888@gmail.com", 23 | description = "API for NAS-Bench-201 (a benchmark for neural architecture search).", 24 | license = "MIT", 25 | keywords = "NAS Dataset API DeepLearning", 26 | url = "https://github.com/D-X-Y/NAS-Bench-201", 27 | packages=['nas_201_api'], 28 | long_description=read('README.md'), 29 | long_description_content_type='text/markdown', 30 | classifiers=[ 31 | "Programming Language :: Python", 32 | "Topic :: Database", 33 | "Topic :: Scientific/Engineering :: Artificial Intelligence", 34 | "License :: OSI Approved :: MIT License", 35 | ], 36 | ) 37 | -------------------------------------------------------------------------------- /.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 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # Pycharm project 92 | .idea 93 | snapshots 94 | *.pytorch 95 | *.tar.bz 96 | data 97 | .*.swp 98 | *.sh 99 | main_main.py 100 | dist 101 | build 102 | *.egg-info 103 | -------------------------------------------------------------------------------- /nas_201_api/__init__.py: -------------------------------------------------------------------------------- 1 | ##################################################### 2 | # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019.08 # 3 | ##################################################### 4 | from .api_utils import ArchResults, ResultsCount 5 | from .api_201 import NASBench201API 6 | 7 | # NAS_BENCH_201_API_VERSION="v1.1" # [2020.02.25] 8 | # NAS_BENCH_201_API_VERSION="v1.2" # [2020.03.09] 9 | # NAS_BENCH_201_API_VERSION="v1.3" # [2020.03.16] 10 | NAS_BENCH_201_API_VERSION="v2.0" # [2020.06.30] 11 | 12 | 13 | def test_api(path): 14 | """This is used to test the API of NAS-Bench-201.""" 15 | api = NASBench201API(path) 16 | num = len(api) 17 | for i, arch_str in enumerate(api): 18 | print ('{:5d}/{:5d} : {:}'.format(i, len(api), arch_str)) 19 | indexes = [1, 2, 11, 301] 20 | for index in indexes: 21 | print('\n--- index={:} ---'.format(index)) 22 | api.show(index) 23 | # show the mean loss and accuracy of an architecture 24 | info = api.query_meta_info_by_index(index) # This is an instance of `ArchResults` 25 | res_metrics = info.get_metrics('cifar10', 'train') # This is a dict with metric names as keys 26 | cost_metrics = info.get_compute_costs('cifar100') # This is a dict with metric names as keys, e.g., flops, params, latency 27 | 28 | # get the detailed information 29 | results = api.query_by_index(index, 'cifar100') # a dict of all trials for 1st net on cifar100, where the key is the seed 30 | print ('There are {:} trials for this architecture [{:}] on cifar100'.format(len(results), api[1])) 31 | for seed, result in results.items(): 32 | print ('Latency : {:}'.format(result.get_latency())) 33 | print ('Train Info : {:}'.format(result.get_train())) 34 | print ('Valid Info : {:}'.format(result.get_eval('x-valid'))) 35 | print ('Test Info : {:}'.format(result.get_eval('x-test'))) 36 | # for the metric after a specific epoch 37 | print ('Train Info [10-th epoch] : {:}'.format(result.get_train(10))) 38 | config = api.get_net_config(index, 'cifar10') 39 | print ('config={:}'.format(config)) 40 | index = api.query_index_by_arch('|nor_conv_3x3~0|+|nor_conv_3x3~0|avg_pool_3x3~1|+|skip_connect~0|nor_conv_3x3~1|skip_connect~2|') 41 | api.show(index) 42 | print('TEST NAS-BENCH-201 DONE.') 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NAS-BENCH-201 has been extended to [NATS-Bench](https://github.com/D-X-Y/NATS-Bench) 2 | 3 | **Since our NAS-BENCH-201 has been extended to NATS-Bench, this repo is deprecated and not maintained. Please use [NATS-Bench](https://github.com/D-X-Y/NATS-Bench), which has 5x more architecture information and faster API than NAS-BENCH-201.** 4 | 5 | # [NAS-BENCH-201: Extending the Scope of Reproducible Neural Architecture Search](https://openreview.net/forum?id=HJxyZkBKDr) 6 | 7 | We propose an algorithm-agnostic NAS benchmark (NAS-Bench-201) with a fixed search space, which provides a unified benchmark for almost any up-to-date NAS algorithms. 8 | The design of our search space is inspired by that used in the most popular cell-based searching algorithms, where a cell is represented as a directed acyclic graph. 9 | Each edge here is associated with an operation selected from a predefined operation set. 10 | For it to be applicable for all NAS algorithms, the search space defined in NAS-Bench-201 includes 4 nodes and 5 associated operation options, which generates 15,625 neural cell candidates in total. 11 | 12 | In this Markdown file, we provide: 13 | - [How to Use NAS-Bench-201](#how-to-use-nas-bench-201) 14 | 15 | For the following two things, please use [AutoDL-Projects](https://github.com/D-X-Y/AutoDL-Projects): 16 | - [Instruction to re-generate NAS-Bench-201](#instruction-to-re-generate-nas-bench-201) 17 | - [10 NAS algorithms evaluated in our paper](#to-reproduce-10-baseline-nas-algorithms-in-nas-bench-201) 18 | 19 | Note: please use `PyTorch >= 1.2.0` and `Python >= 3.6.0`. 20 | 21 | You can simply type `pip install nas-bench-201` to install our api. Please see source codes of `nas-bench-201` module in [this repo](https://github.com/D-X-Y/NAS-Bench-201). 22 | 23 | **If you have any questions or issues, please post it at [here](https://github.com/D-X-Y/AutoDL-Projects/issues) or email me.** 24 | 25 | ### Preparation and Download 26 | 27 | [deprecated] The **old** benchmark file of NAS-Bench-201 can be downloaded from [Google Drive](https://drive.google.com/file/d/1SKW0Cu0u8-gb18zDpaAGi0f74UdXeGKs/view?usp=sharing) or [Baidu-Wangpan (code:6u5d)](https://pan.baidu.com/s/1CiaNH6C12zuZf7q-Ilm09w). 28 | 29 | [recommended] The **latest** benchmark file of NAS-Bench-201 (`NAS-Bench-201-v1_1-096897.pth`) can be downloaded from [Google Drive](https://drive.google.com/file/d/16Y0UwGisiouVRxW-W5hEtbxmcHw_0hF_/view?usp=sharing). The files for model weight are too large (431G) and I need some time to upload it. Please be patient, thanks for your understanding. 30 | 31 | You can move it to anywhere you want and send its path to our API for initialization. 32 | - [2020.02.25] APIv1.0/FILEv1.0: [`NAS-Bench-201-v1_0-e61699.pth`](https://drive.google.com/open?id=1SKW0Cu0u8-gb18zDpaAGi0f74UdXeGKs) (2.2G), where `e61699` is the last six digits for this file. It contains all information except for the trained weights of each trial. 33 | - [2020.02.25] APIv1.0/FILEv1.0: The full data of each architecture can be download from [ 34 | NAS-BENCH-201-4-v1.0-archive.tar](https://drive.google.com/open?id=1X2i-JXaElsnVLuGgM4tP-yNwtsspXgdQ) (about 226GB). This compressed folder has 15625 files containing the the trained weights. 35 | - [2020.02.25] APIv1.0/FILEv1.0: Checkpoints for 3 runs of each baseline NAS algorithm are provided in [Google Drive](https://drive.google.com/open?id=1eAgLZQAViP3r6dA0_ZOOGG9zPLXhGwXi). 36 | - [2020.03.09] APIv1.2/FILEv1.0: More robust API with more functions and descriptions 37 | - [2020.03.16] APIv1.3/FILEv1.1: [`NAS-Bench-201-v1_1-096897.pth`](https://drive.google.com/open?id=16Y0UwGisiouVRxW-W5hEtbxmcHw_0hF_) (4.7G), where `096897` is the last six digits for this file. It contains information of more trials compared to `NAS-Bench-201-v1_0-e61699.pth`, especially all models trained by 12 epochs on all datasets are avaliable. 38 | - [2020.06.30] APIv2.0: Use abstract class (NASBenchMetaAPI) for APIs of NAS-Bench-x0y. 39 | - [2020.06.30] FILEv2.0: coming soon! 40 | 41 | **We recommend to use `NAS-Bench-201-v1_1-096897.pth`** 42 | 43 | 44 | The training and evaluation data used in NAS-Bench-201 can be downloaded from [Google Drive](https://drive.google.com/open?id=1L0Lzq8rWpZLPfiQGd6QR8q5xLV88emU7) or [Baidu-Wangpan (code:4fg7)](https://pan.baidu.com/s/1XAzavPKq3zcat1yBA1L2tQ). 45 | It is recommended to put these data into `$TORCH_HOME` (`~/.torch/` by default). If you want to generate NAS-Bench-201 or similar NAS datasets or training models by yourself, you need these data. 46 | 47 | ## How to Use NAS-Bench-201 48 | 49 | **More usage can be found in [our test codes](https://github.com/D-X-Y/AutoDL-Projects/blob/master/exps/NAS-Bench-201/test-nas-api.py)**. 50 | 51 | 1. Creating an API instance from a file: 52 | ``` 53 | from nas_201_api import NASBench201API as API 54 | api = API('$path_to_meta_nas_bench_file') 55 | # Create an API without the verbose log 56 | api = API('NAS-Bench-201-v1_1-096897.pth', verbose=False) 57 | # The default path for benchmark file is '{:}/{:}'.format(os.environ['TORCH_HOME'], 'NAS-Bench-201-v1_1-096897.pth') 58 | api = API(None) 59 | ``` 60 | 61 | 2. Show the number of architectures `len(api)` and each architecture `api[i]`: 62 | ``` 63 | num = len(api) 64 | for i, arch_str in enumerate(api): 65 | print ('{:5d}/{:5d} : {:}'.format(i, len(api), arch_str)) 66 | ``` 67 | 68 | 3. Show the results of all trials for a single architecture: 69 | ``` 70 | # show all information for a specific architecture 71 | api.show(1) 72 | api.show(2) 73 | 74 | # show the mean loss and accuracy of an architecture 75 | info = api.query_meta_info_by_index(1) # This is an instance of `ArchResults` 76 | res_metrics = info.get_metrics('cifar10', 'train') # This is a dict with metric names as keys 77 | cost_metrics = info.get_comput_costs('cifar100') # This is a dict with metric names as keys, e.g., flops, params, latency 78 | 79 | # get the detailed information 80 | results = api.query_by_index(1, 'cifar100') # a dict of all trials for 1st net on cifar100, where the key is the seed 81 | print ('There are {:} trials for this architecture [{:}] on cifar100'.format(len(results), api[1])) 82 | for seed, result in results.items(): 83 | print ('Latency : {:}'.format(result.get_latency())) 84 | print ('Train Info : {:}'.format(result.get_train())) 85 | print ('Valid Info : {:}'.format(result.get_eval('x-valid'))) 86 | print ('Test Info : {:}'.format(result.get_eval('x-test'))) 87 | # for the metric after a specific epoch 88 | print ('Train Info [10-th epoch] : {:}'.format(result.get_train(10))) 89 | ``` 90 | 91 | 4. Query the index of an architecture by string 92 | ``` 93 | index = api.query_index_by_arch('|nor_conv_3x3~0|+|nor_conv_3x3~0|avg_pool_3x3~1|+|skip_connect~0|nor_conv_3x3~1|skip_connect~2|') 94 | api.show(index) 95 | ``` 96 | This string `|nor_conv_3x3~0|+|nor_conv_3x3~0|avg_pool_3x3~1|+|skip_connect~0|nor_conv_3x3~1|skip_connect~2|` means: 97 | ``` 98 | node-0: the input tensor 99 | node-1: conv-3x3( node-0 ) 100 | node-2: conv-3x3( node-0 ) + avg-pool-3x3( node-1 ) 101 | node-3: skip-connect( node-0 ) + conv-3x3( node-1 ) + skip-connect( node-2 ) 102 | ``` 103 | 104 | 5. Create the network from api: 105 | ``` 106 | config = api.get_net_config(123, 'cifar10') # obtain the network configuration for the 123-th architecture on the CIFAR-10 dataset 107 | from models import get_cell_based_tiny_net # this module is in AutoDL-Projects/lib/models 108 | network = get_cell_based_tiny_net(config) # create the network from configurration 109 | print(network) # show the structure of this architecture 110 | ``` 111 | If you want to load the trained weights of this created network, you need to use `api.get_net_param(123, ...)` to obtain the weights and then load it to the network. 112 | 113 | 6. `api.get_more_info(...)` can return the loss / accuracy / time on training / validation / test sets, which is very helpful. For more details, please look at the comments in the get_more_info function. 114 | 115 | 7. For other usages, please see `lib/nas_201_api/api.py`. We provide some usage information in the comments for the corresponding functions. If what you want is not provided, please feel free to open an issue for discussion, and I am happy to answer any questions regarding NAS-Bench-201. 116 | 117 | 118 | ### Detailed Instruction 119 | 120 | In `nas_201_api`, we define three classes: `NASBench201API`, `ArchResults`, `ResultsCount`. 121 | 122 | `ResultsCount` maintains all information of a specific trial. One can instantiate ResultsCount and get the info via the following codes (`000157-FULL.pth` saves all information of all trials of 157-th architecture): 123 | ``` 124 | from nas_201_api import ResultsCount 125 | xdata = torch.load('000157-FULL.pth') 126 | odata = xdata['full']['all_results'][('cifar10-valid', 777)] 127 | result = ResultsCount.create_from_state_dict( odata ) 128 | print(result) # print it 129 | print(result.get_train()) # print the final training loss/accuracy/[optional:time-cost-of-a-training-epoch] 130 | print(result.get_train(11)) # print the training info of the 11-th epoch 131 | print(result.get_eval('x-valid')) # print the final evaluation info on the validation set 132 | print(result.get_eval('x-valid', 11)) # print the info on the validation set of the 11-th epoch 133 | print(result.get_latency()) # print the evaluation latency [in batch] 134 | result.get_net_param() # the trained parameters of this trial 135 | arch_config = result.get_config(CellStructure.str2structure) # create the network with params 136 | net_config = dict2config(arch_config, None) 137 | network = get_cell_based_tiny_net(net_config) 138 | network.load_state_dict(result.get_net_param()) 139 | ``` 140 | 141 | `ArchResults` maintains all information of all trials of an architecture. Please see the following usages: 142 | ``` 143 | from nas_201_api import ArchResults 144 | xdata = torch.load('000157-FULL.pth') 145 | archRes = ArchResults.create_from_state_dict(xdata['less']) # load trials trained with 12 epochs 146 | archRes = ArchResults.create_from_state_dict(xdata['full']) # load trials trained with 200 epochs 147 | 148 | print(archRes.arch_idx_str()) # print the index of this architecture 149 | print(archRes.get_dataset_names()) # print the supported training data 150 | print(archRes.get_compute_costs('cifar10-valid')) # print all computational info when training on cifar10-valid 151 | print(archRes.get_metrics('cifar10-valid', 'x-valid', None, False)) # print the average loss/accuracy/time on all trials 152 | print(archRes.get_metrics('cifar10-valid', 'x-valid', None, True)) # print loss/accuracy/time of a randomly selected trial 153 | ``` 154 | 155 | `NASBench201API` is the topest level api. Please see the following usages: 156 | ``` 157 | from nas_201_api import NASBench201API as API 158 | api = API('NAS-Bench-201-v1_1-096897.pth') # This will load all the information of NAS-Bench-201 except the trained weights 159 | api = API('{:}/{:}'.format(os.environ['TORCH_HOME'], 'NAS-Bench-201-v1_1-096897.pth')) # The same as the above line while I usually save NAS-Bench-201-v1_1-096897.pth in ~/.torch/. 160 | api.show(-1) # show info of all architectures 161 | api.reload('{:}/{:}'.format(os.environ['TORCH_HOME'], 'NAS-BENCH-201-4-v1.0-archive'), 3) # This code will reload the information 3-th architecture with the trained weights 162 | 163 | weights = api.get_net_param(3, 'cifar10', None) # Obtaining the weights of all trials for the 3-th architecture on cifar10. It will returns a dict, where the key is the seed and the value is the trained weights. 164 | ``` 165 | 166 | To obtain the training and evaluation information (please see the comments [here](https://github.com/D-X-Y/AutoDL-Projects/blob/master/lib/nas_201_api/api_201.py#L142)): 167 | ``` 168 | api.get_more_info(112, 'cifar10', None, hp='200', is_random=True) 169 | # Query info of last training epoch for 112-th architecture 170 | # using 200-epoch-hyper-parameter and randomly select a trial. 171 | api.get_more_info(112, 'ImageNet16-120', None, hp='200', is_random=True) 172 | ``` 173 | 174 | # Citation 175 | 176 | If you find that NAS-Bench-201 helps your research, please consider citing it: 177 | ``` 178 | @inproceedings{dong2020nasbench201, 179 | title = {NAS-Bench-201: Extending the Scope of Reproducible Neural Architecture Search}, 180 | author = {Dong, Xuanyi and Yang, Yi}, 181 | booktitle = {International Conference on Learning Representations (ICLR)}, 182 | url = {https://openreview.net/forum?id=HJxyZkBKDr}, 183 | year = {2020} 184 | } 185 | ``` 186 | -------------------------------------------------------------------------------- /nas_201_api/api_201.py: -------------------------------------------------------------------------------- 1 | ##################################################### 2 | # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019.08 # 3 | ############################################################################################ 4 | # NAS-Bench-201: Extending the Scope of Reproducible Neural Architecture Search, ICLR 2020 # 5 | ############################################################################################ 6 | # The history of benchmark files: 7 | # [2020.02.25] NAS-Bench-201-v1_0-e61699.pth : 6219 architectures are trained once, 1621 architectures are trained twice, 7785 architectures are trained three times. `LESS` only supports CIFAR10-VALID. 8 | # [2020.03.16] NAS-Bench-201-v1_1-096897.pth : 2225 architectures are trained once, 5439 archiitectures are trained twice, 7961 architectures are trained three times on all training sets. For the hyper-parameters with the total epochs of 12, each model is trained on CIFAR-10, CIFAR-100, ImageNet16-120 once, and is trained on CIFAR-10-VALID twice. 9 | # 10 | # I'm still actively enhancing this benchmark, while it is now maintained at https://github.com/D-X-Y/NATS-Bench 11 | # 12 | import os, copy, random, torch, numpy as np 13 | from pathlib import Path 14 | from typing import List, Text, Union, Dict, Optional 15 | from collections import OrderedDict, defaultdict 16 | 17 | from .api_utils import ArchResults 18 | from .api_utils import NASBenchMetaAPI 19 | from .api_utils import remap_dataset_set_names 20 | 21 | 22 | ALL_BENCHMARK_FILES = ['NAS-Bench-201-v1_0-e61699.pth', 'NAS-Bench-201-v1_1-096897.pth'] 23 | ALL_ARCHIVE_DIRS = ['NAS-Bench-201-v1_1-archive'] 24 | 25 | 26 | def print_information(information, extra_info=None, show=False): 27 | dataset_names = information.get_dataset_names() 28 | strings = [information.arch_str, 'datasets : {:}, extra-info : {:}'.format(dataset_names, extra_info)] 29 | def metric2str(loss, acc): 30 | return 'loss = {:.3f}, top1 = {:.2f}%'.format(loss, acc) 31 | 32 | for ida, dataset in enumerate(dataset_names): 33 | metric = information.get_compute_costs(dataset) 34 | flop, param, latency = metric['flops'], metric['params'], metric['latency'] 35 | str1 = '{:14s} FLOP={:6.2f} M, Params={:.3f} MB, latency={:} ms.'.format(dataset, flop, param, '{:.2f}'.format(latency*1000) if latency is not None and latency > 0 else None) 36 | train_info = information.get_metrics(dataset, 'train') 37 | if dataset == 'cifar10-valid': 38 | valid_info = information.get_metrics(dataset, 'x-valid') 39 | str2 = '{:14s} train : [{:}], valid : [{:}]'.format(dataset, metric2str(train_info['loss'], train_info['accuracy']), metric2str(valid_info['loss'], valid_info['accuracy'])) 40 | elif dataset == 'cifar10': 41 | test__info = information.get_metrics(dataset, 'ori-test') 42 | str2 = '{:14s} train : [{:}], test : [{:}]'.format(dataset, metric2str(train_info['loss'], train_info['accuracy']), metric2str(test__info['loss'], test__info['accuracy'])) 43 | else: 44 | valid_info = information.get_metrics(dataset, 'x-valid') 45 | test__info = information.get_metrics(dataset, 'x-test') 46 | str2 = '{:14s} train : [{:}], valid : [{:}], test : [{:}]'.format(dataset, metric2str(train_info['loss'], train_info['accuracy']), metric2str(valid_info['loss'], valid_info['accuracy']), metric2str(test__info['loss'], test__info['accuracy'])) 47 | strings += [str1, str2] 48 | if show: print('\n'.join(strings)) 49 | return strings 50 | 51 | 52 | """ 53 | This is the class for the API of NAS-Bench-201. 54 | """ 55 | class NASBench201API(NASBenchMetaAPI): 56 | 57 | """ The initialization function that takes the dataset file path (or a dict loaded from that path) as input. """ 58 | def __init__(self, file_path_or_dict: Optional[Union[Text, Dict]]=None, 59 | verbose: bool=True): 60 | self.filename = None 61 | self.reset_time() 62 | if file_path_or_dict is None: 63 | file_path_or_dict = os.path.join(os.environ['TORCH_HOME'], ALL_BENCHMARK_FILES[-1]) 64 | print ('Try to use the default NAS-Bench-201 path from {:}.'.format(file_path_or_dict)) 65 | if isinstance(file_path_or_dict, str) or isinstance(file_path_or_dict, Path): 66 | file_path_or_dict = str(file_path_or_dict) 67 | if verbose: print('try to create the NAS-Bench-201 api from {:}'.format(file_path_or_dict)) 68 | assert os.path.isfile(file_path_or_dict), 'invalid path : {:}'.format(file_path_or_dict) 69 | self.filename = Path(file_path_or_dict).name 70 | file_path_or_dict = torch.load(file_path_or_dict, map_location='cpu') 71 | elif isinstance(file_path_or_dict, dict): 72 | file_path_or_dict = copy.deepcopy(file_path_or_dict) 73 | else: raise ValueError('invalid type : {:} not in [str, dict]'.format(type(file_path_or_dict))) 74 | assert isinstance(file_path_or_dict, dict), 'It should be a dict instead of {:}'.format(type(file_path_or_dict)) 75 | self.verbose = verbose # [TODO] a flag indicating whether to print more logs 76 | keys = ('meta_archs', 'arch2infos', 'evaluated_indexes') 77 | for key in keys: assert key in file_path_or_dict, 'Can not find key[{:}] in the dict'.format(key) 78 | self.meta_archs = copy.deepcopy( file_path_or_dict['meta_archs'] ) 79 | # This is a dict mapping each architecture to a dict, where the key is #epochs and the value is ArchResults 80 | self.arch2infos_dict = OrderedDict() 81 | self._avaliable_hps = set(['12', '200']) 82 | for xkey in sorted(list(file_path_or_dict['arch2infos'].keys())): 83 | all_info = file_path_or_dict['arch2infos'][xkey] 84 | hp2archres = OrderedDict() 85 | # self.arch2infos_less[xkey] = ArchResults.create_from_state_dict( all_info['less'] ) 86 | # self.arch2infos_full[xkey] = ArchResults.create_from_state_dict( all_info['full'] ) 87 | hp2archres['12'] = ArchResults.create_from_state_dict(all_info['less']) 88 | hp2archres['200'] = ArchResults.create_from_state_dict(all_info['full']) 89 | self.arch2infos_dict[xkey] = hp2archres 90 | self.evaluated_indexes = sorted(list(file_path_or_dict['evaluated_indexes'])) 91 | self.archstr2index = {} 92 | for idx, arch in enumerate(self.meta_archs): 93 | assert arch not in self.archstr2index, 'This [{:}]-th arch {:} already in the dict ({:}).'.format(idx, arch, self.archstr2index[arch]) 94 | self.archstr2index[ arch ] = idx 95 | 96 | def reload(self, archive_root: Text = None, index: int = None): 97 | """Overwrite all information of the 'index'-th architecture in the search space. 98 | It will load its data from 'archive_root'. 99 | """ 100 | if archive_root is None: 101 | archive_root = os.path.join(os.environ['TORCH_HOME'], ALL_ARCHIVE_DIRS[-1]) 102 | assert os.path.isdir(archive_root), 'invalid directory : {:}'.format(archive_root) 103 | if index is None: 104 | indexes = list(range(len(self))) 105 | else: 106 | indexes = [index] 107 | for idx in indexes: 108 | assert 0 <= idx < len(self.meta_archs), 'invalid index of {:}'.format(idx) 109 | xfile_path = os.path.join(archive_root, '{:06d}-FULL.pth'.format(idx)) 110 | assert os.path.isfile(xfile_path), 'invalid data path : {:}'.format(xfile_path) 111 | xdata = torch.load(xfile_path, map_location='cpu') 112 | assert isinstance(xdata, dict) and 'full' in xdata and 'less' in xdata, 'invalid format of data in {:}'.format(xfile_path) 113 | hp2archres = OrderedDict() 114 | hp2archres['12'] = ArchResults.create_from_state_dict(xdata['less']) 115 | hp2archres['200'] = ArchResults.create_from_state_dict(xdata['full']) 116 | self.arch2infos_dict[idx] = hp2archres 117 | 118 | def query_info_str_by_arch(self, arch, hp: Text='12'): 119 | """ This function is used to query the information of a specific architecture 120 | 'arch' can be an architecture index or an architecture string 121 | When hp=12, the hyper-parameters used to train a model are in 'configs/nas-benchmark/hyper-opts/12E.config' 122 | When hp=200, the hyper-parameters used to train a model are in 'configs/nas-benchmark/hyper-opts/200E.config' 123 | The difference between these three configurations are the number of training epochs. 124 | """ 125 | if self.verbose: 126 | print('Call query_info_str_by_arch with arch={:} and hp={:}'.format(arch, hp)) 127 | return self._query_info_str_by_arch(arch, hp, print_information) 128 | 129 | # obtain the metric for the `index`-th architecture 130 | # `dataset` indicates the dataset: 131 | # 'cifar10-valid' : using the proposed train set of CIFAR-10 as the training set 132 | # 'cifar10' : using the proposed train+valid set of CIFAR-10 as the training set 133 | # 'cifar100' : using the proposed train set of CIFAR-100 as the training set 134 | # 'ImageNet16-120' : using the proposed train set of ImageNet-16-120 as the training set 135 | # `iepoch` indicates the index of training epochs from 0 to 11/199. 136 | # When iepoch=None, it will return the metric for the last training epoch 137 | # When iepoch=11, it will return the metric for the 11-th training epoch (starting from 0) 138 | # `use_12epochs_result` indicates different hyper-parameters for training 139 | # When use_12epochs_result=True, it trains the network with 12 epochs and the LR decayed from 0.1 to 0 within 12 epochs 140 | # When use_12epochs_result=False, it trains the network with 200 epochs and the LR decayed from 0.1 to 0 within 200 epochs 141 | # `is_random` 142 | # When is_random=True, the performance of a random architecture will be returned 143 | # When is_random=False, the performanceo of all trials will be averaged. 144 | def get_more_info(self, index, dataset, iepoch=None, hp='12', is_random=True): 145 | if self.verbose: 146 | print('Call the get_more_info function with index={:}, dataset={:}, iepoch={:}, hp={:}, and is_random={:}.'.format(index, dataset, iepoch, hp, is_random)) 147 | index = self.query_index_by_arch(index) # To avoid the input is a string or an instance of a arch object 148 | if index not in self.arch2infos_dict: 149 | raise ValueError('Did not find {:} from arch2infos_dict.'.format(index)) 150 | archresult = self.arch2infos_dict[index][str(hp)] 151 | # if randomly select one trial, select the seed at first 152 | if isinstance(is_random, bool) and is_random: 153 | seeds = archresult.get_dataset_seeds(dataset) 154 | is_random = random.choice(seeds) 155 | # collect the training information 156 | train_info = archresult.get_metrics(dataset, 'train', iepoch=iepoch, is_random=is_random) 157 | total = train_info['iepoch'] + 1 158 | xinfo = {'train-loss' : train_info['loss'], 159 | 'train-accuracy': train_info['accuracy'], 160 | 'train-per-time': train_info['all_time'] / total if train_info['all_time'] is not None else None, 161 | 'train-all-time': train_info['all_time']} 162 | # collect the evaluation information 163 | if dataset == 'cifar10-valid': 164 | valid_info = archresult.get_metrics(dataset, 'x-valid', iepoch=iepoch, is_random=is_random) 165 | try: 166 | test_info = archresult.get_metrics(dataset, 'ori-test', iepoch=iepoch, is_random=is_random) 167 | except: 168 | test_info = None 169 | valtest_info = None 170 | else: 171 | try: # collect results on the proposed test set 172 | if dataset == 'cifar10': 173 | test_info = archresult.get_metrics(dataset, 'ori-test', iepoch=iepoch, is_random=is_random) 174 | else: 175 | test_info = archresult.get_metrics(dataset, 'x-test', iepoch=iepoch, is_random=is_random) 176 | except: 177 | test_info = None 178 | try: # collect results on the proposed validation set 179 | valid_info = archresult.get_metrics(dataset, 'x-valid', iepoch=iepoch, is_random=is_random) 180 | except: 181 | valid_info = None 182 | try: 183 | if dataset != 'cifar10': 184 | valtest_info = archresult.get_metrics(dataset, 'ori-test', iepoch=iepoch, is_random=is_random) 185 | else: 186 | valtest_info = None 187 | except: 188 | valtest_info = None 189 | if valid_info is not None: 190 | xinfo['valid-loss'] = valid_info['loss'] 191 | xinfo['valid-accuracy'] = valid_info['accuracy'] 192 | xinfo['valid-per-time'] = valid_info['all_time'] / total if valid_info['all_time'] is not None else None 193 | xinfo['valid-all-time'] = valid_info['all_time'] 194 | if test_info is not None: 195 | xinfo['test-loss'] = test_info['loss'] 196 | xinfo['test-accuracy'] = test_info['accuracy'] 197 | xinfo['test-per-time'] = test_info['all_time'] / total if test_info['all_time'] is not None else None 198 | xinfo['test-all-time'] = test_info['all_time'] 199 | if valtest_info is not None: 200 | xinfo['valtest-loss'] = valtest_info['loss'] 201 | xinfo['valtest-accuracy'] = valtest_info['accuracy'] 202 | xinfo['valtest-per-time'] = valtest_info['all_time'] / total if valtest_info['all_time'] is not None else None 203 | xinfo['valtest-all-time'] = valtest_info['all_time'] 204 | return xinfo 205 | 206 | def show(self, index: int = -1) -> None: 207 | """This function will print the information of a specific (or all) architecture(s).""" 208 | self._show(index, print_information) 209 | 210 | @staticmethod 211 | def str2lists(arch_str: Text) -> List[tuple]: 212 | """ 213 | This function shows how to read the string-based architecture encoding. 214 | It is the same as the `str2structure` func in `AutoDL-Projects/lib/models/cell_searchs/genotypes.py` 215 | 216 | :param 217 | arch_str: the input is a string indicates the architecture topology, such as 218 | |nor_conv_1x1~0|+|none~0|none~1|+|none~0|none~1|skip_connect~2| 219 | :return: a list of tuple, contains multiple (op, input_node_index) pairs. 220 | 221 | :usage 222 | arch = api.str2lists( '|nor_conv_1x1~0|+|none~0|none~1|+|none~0|none~1|skip_connect~2|' ) 223 | print ('there are {:} nodes in this arch'.format(len(arch)+1)) # arch is a list 224 | for i, node in enumerate(arch): 225 | print('the {:}-th node is the sum of these {:} nodes with op: {:}'.format(i+1, len(node), node)) 226 | """ 227 | node_strs = arch_str.split('+') 228 | genotypes = [] 229 | for i, node_str in enumerate(node_strs): 230 | inputs = list(filter(lambda x: x != '', node_str.split('|'))) 231 | for xinput in inputs: assert len(xinput.split('~')) == 2, 'invalid input length : {:}'.format(xinput) 232 | inputs = ( xi.split('~') for xi in inputs ) 233 | input_infos = tuple( (op, int(IDX)) for (op, IDX) in inputs) 234 | genotypes.append( input_infos ) 235 | return genotypes 236 | 237 | @staticmethod 238 | def str2matrix(arch_str: Text, 239 | search_space: List[Text] = ['none', 'skip_connect', 'nor_conv_1x1', 'nor_conv_3x3', 'avg_pool_3x3']) -> np.ndarray: 240 | """ 241 | This func shows how to convert the string-based architecture encoding to the encoding strategy in NAS-Bench-101. 242 | 243 | :param 244 | arch_str: the input is a string indicates the architecture topology, such as 245 | |nor_conv_1x1~0|+|none~0|none~1|+|none~0|none~1|skip_connect~2| 246 | search_space: a list of operation string, the default list is the search space for NAS-Bench-201 247 | the default value should be be consistent with this line https://github.com/D-X-Y/AutoDL-Projects/blob/master/lib/models/cell_operations.py#L24 248 | :return 249 | the numpy matrix (2-D np.ndarray) representing the DAG of this architecture topology 250 | :usage 251 | matrix = api.str2matrix( '|nor_conv_1x1~0|+|none~0|none~1|+|none~0|none~1|skip_connect~2|' ) 252 | This matrix is 4-by-4 matrix representing a cell with 4 nodes (only the lower left triangle is useful). 253 | [ [0, 0, 0, 0], # the first line represents the input (0-th) node 254 | [2, 0, 0, 0], # the second line represents the 1-st node, is calculated by 2-th-op( 0-th-node ) 255 | [0, 0, 0, 0], # the third line represents the 2-nd node, is calculated by 0-th-op( 0-th-node ) + 0-th-op( 1-th-node ) 256 | [0, 0, 1, 0] ] # the fourth line represents the 3-rd node, is calculated by 0-th-op( 0-th-node ) + 0-th-op( 1-th-node ) + 1-th-op( 2-th-node ) 257 | In NAS-Bench-201 search space, 0-th-op is 'none', 1-th-op is 'skip_connect', 258 | 2-th-op is 'nor_conv_1x1', 3-th-op is 'nor_conv_3x3', 4-th-op is 'avg_pool_3x3'. 259 | :(NOTE) 260 | If a node has two input-edges from the same node, this function does not work. One edge will be overlapped. 261 | """ 262 | node_strs = arch_str.split('+') 263 | num_nodes = len(node_strs) + 1 264 | matrix = np.zeros((num_nodes, num_nodes)) 265 | for i, node_str in enumerate(node_strs): 266 | inputs = list(filter(lambda x: x != '', node_str.split('|'))) 267 | for xinput in inputs: assert len(xinput.split('~')) == 2, 'invalid input length : {:}'.format(xinput) 268 | for xi in inputs: 269 | op, idx = xi.split('~') 270 | if op not in search_space: raise ValueError('this op ({:}) is not in {:}'.format(op, search_space)) 271 | op_idx, node_idx = search_space.index(op), int(idx) 272 | matrix[i+1, node_idx] = op_idx 273 | return matrix 274 | 275 | -------------------------------------------------------------------------------- /nas_201_api/api_utils.py: -------------------------------------------------------------------------------- 1 | ##################################################### 2 | # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019.08 # 3 | ############################################################################################ 4 | # NAS-Bench-201: Extending the Scope of Reproducible Neural Architecture Search, ICLR 2020 # 5 | ############################################################################################ 6 | # In this Python file, we define NASBenchMetaAPI, the abstract class for benchmark APIs. 7 | # We also define the class ArchResults, which contains all information of a single architecture trained by one kind of hyper-parameters on three datasets. 8 | # We also define the class ResultsCount, which contains all information of a single trial for a single architecture. 9 | ############################################################################################ 10 | # History: 11 | # [2020.06.30] The first version. 12 | # 13 | import os, abc, copy, random, torch, numpy as np 14 | from pathlib import Path 15 | from typing import List, Text, Union, Dict, Optional 16 | from collections import OrderedDict, defaultdict 17 | 18 | 19 | def remap_dataset_set_names(dataset, metric_on_set, verbose=False): 20 | """re-map the metric_on_set to internal keys""" 21 | if verbose: 22 | print('Call internal function _remap_dataset_set_names with dataset={:} and metric_on_set={:}'.format(dataset, metric_on_set)) 23 | if dataset == 'cifar10' and metric_on_set == 'valid': 24 | dataset, metric_on_set = 'cifar10-valid', 'x-valid' 25 | elif dataset == 'cifar10' and metric_on_set == 'test': 26 | dataset, metric_on_set = 'cifar10', 'ori-test' 27 | elif dataset == 'cifar10' and metric_on_set == 'train': 28 | dataset, metric_on_set = 'cifar10', 'train' 29 | elif (dataset == 'cifar100' or dataset == 'ImageNet16-120') and metric_on_set == 'valid': 30 | metric_on_set = 'x-valid' 31 | elif (dataset == 'cifar100' or dataset == 'ImageNet16-120') and metric_on_set == 'test': 32 | metric_on_set = 'x-test' 33 | if verbose: 34 | print(' return dataset={:} and metric_on_set={:}'.format(dataset, metric_on_set)) 35 | return dataset, metric_on_set 36 | 37 | 38 | class NASBenchMetaAPI(metaclass=abc.ABCMeta): 39 | 40 | @abc.abstractmethod 41 | def __init__(self, file_path_or_dict: Optional[Union[Text, Dict]]=None, verbose: bool=True): 42 | """The initialization function that takes the dataset file path (or a dict loaded from that path) as input.""" 43 | 44 | def __getitem__(self, index: int): 45 | return copy.deepcopy(self.meta_archs[index]) 46 | 47 | def arch(self, index: int): 48 | """Return the topology structure of the `index`-th architecture.""" 49 | if self.verbose: 50 | print('Call the arch function with index={:}'.format(index)) 51 | assert 0 <= index < len(self.meta_archs), 'invalid index : {:} vs. {:}.'.format(index, len(self.meta_archs)) 52 | return copy.deepcopy(self.meta_archs[index]) 53 | 54 | def __len__(self): 55 | return len(self.meta_archs) 56 | 57 | def __repr__(self): 58 | return ('{name}({num}/{total} architectures, file={filename})'.format(name=self.__class__.__name__, num=len(self.evaluated_indexes), total=len(self.meta_archs), filename=self.filename)) 59 | 60 | @property 61 | def avaliable_hps(self): 62 | return list(copy.deepcopy(self._avaliable_hps)) 63 | 64 | @property 65 | def used_time(self): 66 | return self._used_time 67 | 68 | def reset_time(self): 69 | self._used_time = 0 70 | 71 | def simulate_train_eval(self, arch, dataset, hp='12', account_time=True): 72 | index = self.query_index_by_arch(arch) 73 | all_names = ('cifar10', 'cifar100', 'ImageNet16-120') 74 | assert dataset in all_names, 'Invalid dataset name : {:} vs {:}'.format(dataset, all_names) 75 | if dataset == 'cifar10': 76 | info = self.get_more_info(index, 'cifar10-valid', iepoch=None, hp=hp, is_random=True) 77 | else: 78 | info = self.get_more_info(index, dataset, iepoch=None, hp=hp, is_random=True) 79 | valid_acc, time_cost = info['valid-accuracy'], info['train-all-time'] + info['valid-per-time'] 80 | latency = self.get_latency(index, dataset) 81 | if account_time: 82 | self._used_time += time_cost 83 | return valid_acc, latency, time_cost, self._used_time 84 | 85 | def random(self): 86 | """Return a random index of all architectures.""" 87 | return random.randint(0, len(self.meta_archs)-1) 88 | 89 | def query_index_by_arch(self, arch): 90 | """ This function is used to query the index of an architecture in the search space. 91 | In the topology search space, the input arch can be an architecture string such as '|nor_conv_3x3~0|+|nor_conv_3x3~0|avg_pool_3x3~1|+|skip_connect~0|nor_conv_3x3~1|skip_connect~2|'; 92 | or an instance that has the 'tostr' function that can generate the architecture string; 93 | or it is directly an architecture index, in this case, we will check whether it is valid or not. 94 | This function will return the index. 95 | If return -1, it means this architecture is not in the search space. 96 | Otherwise, it will return an int in [0, the-number-of-candidates-in-the-search-space). 97 | """ 98 | if self.verbose: 99 | print('Call query_index_by_arch with arch={:}'.format(arch)) 100 | if isinstance(arch, int): 101 | if 0 <= arch < len(self): 102 | return arch 103 | else: 104 | raise ValueError('Invalid architecture index {:} vs [{:}, {:}].'.format(arch, 0, len(self))) 105 | elif isinstance(arch, str): 106 | if arch in self.archstr2index: arch_index = self.archstr2index[ arch ] 107 | else : arch_index = -1 108 | elif hasattr(arch, 'tostr'): 109 | if arch.tostr() in self.archstr2index: arch_index = self.archstr2index[ arch.tostr() ] 110 | else : arch_index = -1 111 | else: arch_index = -1 112 | return arch_index 113 | 114 | def query_by_arch(self, arch, hp): 115 | # This is to make the current version be compatible with the old version. 116 | return self.query_info_str_by_arch(arch, hp) 117 | 118 | @abc.abstractmethod 119 | def reload(self, archive_root: Text = None, index: int = None): 120 | """Overwrite all information of the 'index'-th architecture in the search space, where the data will be loaded from 'archive_root'. 121 | If index is None, overwrite all ckps. 122 | """ 123 | 124 | def clear_params(self, index: int, hp: Optional[Text]=None): 125 | """Remove the architecture's weights to save memory. 126 | :arg 127 | index: the index of the target architecture 128 | hp: a flag to controll how to clear the parameters. 129 | -- None: clear all the weights in '01'/'12'/'90', which indicates the number of training epochs. 130 | -- '01' or '12' or '90': clear all the weights in arch2infos_dict[index][hp]. 131 | """ 132 | if self.verbose: 133 | print('Call clear_params with index={:} and hp={:}'.format(index, hp)) 134 | if hp is None: 135 | for key, result in self.arch2infos_dict[index].items(): 136 | result.clear_params() 137 | else: 138 | if str(hp) not in self.arch2infos_dict[index]: 139 | raise ValueError('The {:}-th architecture only has hyper-parameters of {:} instead of {:}.'.format(index, list(self.arch2infos_dict[index].keys()), hp)) 140 | self.arch2infos_dict[index][str(hp)].clear_params() 141 | 142 | @abc.abstractmethod 143 | def query_info_str_by_arch(self, arch, hp: Text='12'): 144 | """This function is used to query the information of a specific architecture.""" 145 | 146 | def _query_info_str_by_arch(self, arch, hp: Text='12', print_information=None): 147 | arch_index = self.query_index_by_arch(arch) 148 | if arch_index in self.arch2infos_dict: 149 | if hp not in self.arch2infos_dict[arch_index]: 150 | raise ValueError('The {:}-th architecture only has hyper-parameters of {:} instead of {:}.'.format(index, list(self.arch2infos_dict[arch_index].keys()), hp)) 151 | info = self.arch2infos_dict[arch_index][hp] 152 | strings = print_information(info, 'arch-index={:}'.format(arch_index)) 153 | return '\n'.join(strings) 154 | else: 155 | print ('Find this arch-index : {:}, but this arch is not evaluated.'.format(arch_index)) 156 | return None 157 | 158 | def query_meta_info_by_index(self, arch_index, hp: Text = '12'): 159 | """Return the ArchResults for the 'arch_index'-th architecture. This function is similar to query_by_index.""" 160 | if self.verbose: 161 | print('Call query_meta_info_by_index with arch_index={:}, hp={:}'.format(arch_index, hp)) 162 | if arch_index in self.arch2infos_dict: 163 | if hp not in self.arch2infos_dict[arch_index]: 164 | raise ValueError('The {:}-th architecture only has hyper-parameters of {:} instead of {:}.'.format(arch_index, list(self.arch2infos_dict[arch_index].keys()), hp)) 165 | info = self.arch2infos_dict[arch_index][hp] 166 | else: 167 | raise ValueError('arch_index [{:}] does not in arch2infos'.format(arch_index)) 168 | return copy.deepcopy(info) 169 | 170 | def query_by_index(self, arch_index: int, dataname: Union[None, Text] = None, hp: Text = '12'): 171 | """ This 'query_by_index' function is used to query information with the training of 01 epochs, 12 epochs, 90 epochs, or 200 epochs. 172 | ------ 173 | If hp=01, we train the model by 01 epochs (see config in configs/nas-benchmark/hyper-opts/01E.config) 174 | If hp=12, we train the model by 01 epochs (see config in configs/nas-benchmark/hyper-opts/12E.config) 175 | If hp=90, we train the model by 01 epochs (see config in configs/nas-benchmark/hyper-opts/90E.config) 176 | If hp=200, we train the model by 01 epochs (see config in configs/nas-benchmark/hyper-opts/200E.config) 177 | ------ 178 | If dataname is None, return the ArchResults 179 | else, return a dict with all trials on that dataset (the key is the seed) 180 | Options are 'cifar10-valid', 'cifar10', 'cifar100', 'ImageNet16-120'. 181 | -- cifar10-valid : training the model on the CIFAR-10 training set. 182 | -- cifar10 : training the model on the CIFAR-10 training + validation set. 183 | -- cifar100 : training the model on the CIFAR-100 training set. 184 | -- ImageNet16-120 : training the model on the ImageNet16-120 training set. 185 | """ 186 | if self.verbose: 187 | print('Call query_by_index with arch_index={:}, dataname={:}, hp={:}'.format(arch_index, dataname, hp)) 188 | info = self.query_meta_info_by_index(arch_index, hp) 189 | if dataname is None: return info 190 | else: 191 | if dataname not in info.get_dataset_names(): 192 | raise ValueError('invalid dataset-name : {:} vs. {:}'.format(dataname, info.get_dataset_names())) 193 | return info.query(dataname) 194 | 195 | def find_best(self, dataset, metric_on_set, FLOP_max=None, Param_max=None, hp: Text = '12'): 196 | """Find the architecture with the highest accuracy based on some constraints.""" 197 | if self.verbose: 198 | print('Call find_best with dataset={:}, metric_on_set={:}, hp={:} | with #FLOPs < {:} and #Params < {:}'.format(dataset, metric_on_set, hp, FLOP_max, Param_max)) 199 | dataset, metric_on_set = remap_dataset_set_names(dataset, metric_on_set, self.verbose) 200 | best_index, highest_accuracy = -1, None 201 | for i, arch_index in enumerate(self.evaluated_indexes): 202 | arch_info = self.arch2infos_dict[arch_index][hp] 203 | info = arch_info.get_compute_costs(dataset) # the information of costs 204 | flop, param, latency = info['flops'], info['params'], info['latency'] 205 | if FLOP_max is not None and flop > FLOP_max : continue 206 | if Param_max is not None and param > Param_max: continue 207 | xinfo = arch_info.get_metrics(dataset, metric_on_set) # the information of loss and accuracy 208 | loss, accuracy = xinfo['loss'], xinfo['accuracy'] 209 | if best_index == -1: 210 | best_index, highest_accuracy = arch_index, accuracy 211 | elif highest_accuracy < accuracy: 212 | best_index, highest_accuracy = arch_index, accuracy 213 | if self.verbose: 214 | print(' the best architecture : [{:}] {:} with accuracy={:.3f}%'.format(best_index, self.arch(best_index), highest_accuracy)) 215 | return best_index, highest_accuracy 216 | 217 | def get_net_param(self, index, dataset, seed: Optional[int], hp: Text = '12'): 218 | """ 219 | This function is used to obtain the trained weights of the `index`-th architecture on `dataset` with the seed of `seed` 220 | Args [seed]: 221 | -- None : return a dict containing the trained weights of all trials, where each key is a seed and its corresponding value is the weights. 222 | -- a interger : return the weights of a specific trial, whose seed is this interger. 223 | Args [hp]: 224 | -- 01 : train the model by 01 epochs 225 | -- 12 : train the model by 12 epochs 226 | -- 90 : train the model by 90 epochs 227 | -- 200 : train the model by 200 epochs 228 | """ 229 | if self.verbose: 230 | print('Call the get_net_param function with index={:}, dataset={:}, seed={:}, hp={:}'.format(index, dataset, seed, hp)) 231 | info = self.query_meta_info_by_index(index, hp) 232 | return info.get_net_param(dataset, seed) 233 | 234 | def get_net_config(self, index: int, dataset: Text): 235 | """ 236 | This function is used to obtain the configuration for the `index`-th architecture on `dataset`. 237 | Args [dataset] (4 possible options): 238 | -- cifar10-valid : training the model on the CIFAR-10 training set. 239 | -- cifar10 : training the model on the CIFAR-10 training + validation set. 240 | -- cifar100 : training the model on the CIFAR-100 training set. 241 | -- ImageNet16-120 : training the model on the ImageNet16-120 training set. 242 | This function will return a dict. 243 | ========= Some examlpes for using this function: 244 | config = api.get_net_config(128, 'cifar10') 245 | """ 246 | if self.verbose: 247 | print('Call the get_net_config function with index={:}, dataset={:}.'.format(index, dataset)) 248 | if index in self.arch2infos_dict: 249 | info = self.arch2infos_dict[index] 250 | else: 251 | raise ValueError('The arch_index={:} is not in arch2infos_dict.'.format(arch_index)) 252 | info = next(iter(info.values())) 253 | results = info.query(dataset, None) 254 | results = next(iter(results.values())) 255 | return results.get_config(None) 256 | 257 | def get_cost_info(self, index: int, dataset: Text, hp: Text = '12') -> Dict[Text, float]: 258 | """To obtain the cost metric for the `index`-th architecture on a dataset.""" 259 | if self.verbose: 260 | print('Call the get_cost_info function with index={:}, dataset={:}, and hp={:}.'.format(index, dataset, hp)) 261 | info = self.query_meta_info_by_index(index, hp) 262 | return info.get_compute_costs(dataset) 263 | 264 | def get_latency(self, index: int, dataset: Text, hp: Text = '12') -> float: 265 | """ 266 | To obtain the latency of the network (by default it will return the latency with the batch size of 256). 267 | :param index: the index of the target architecture 268 | :param dataset: the dataset name (cifar10-valid, cifar10, cifar100, ImageNet16-120) 269 | :return: return a float value in seconds 270 | """ 271 | if self.verbose: 272 | print('Call the get_latency function with index={:}, dataset={:}, and hp={:}.'.format(index, dataset, hp)) 273 | cost_dict = self.get_cost_info(index, dataset, hp) 274 | return cost_dict['latency'] 275 | 276 | @abc.abstractmethod 277 | def show(self, index=-1): 278 | """This function will print the information of a specific (or all) architecture(s).""" 279 | 280 | def _show(self, index=-1, print_information=None) -> None: 281 | """ 282 | This function will print the information of a specific (or all) architecture(s). 283 | 284 | :param index: If the index < 0: it will loop for all architectures and print their information one by one. 285 | else: it will print the information of the 'index'-th architecture. 286 | :return: nothing 287 | """ 288 | if index < 0: # show all architectures 289 | print(self) 290 | for i, idx in enumerate(self.evaluated_indexes): 291 | print('\n' + '-' * 10 + ' The ({:5d}/{:5d}) {:06d}-th architecture! '.format(i, len(self.evaluated_indexes), idx) + '-'*10) 292 | print('arch : {:}'.format(self.meta_archs[idx])) 293 | for key, result in self.arch2infos_dict[index].items(): 294 | strings = print_information(result) 295 | print('>' * 40 + ' {:03d} epochs '.format(result.get_total_epoch()) + '>' * 40) 296 | print('\n'.join(strings)) 297 | print('<' * 40 + '------------' + '<' * 40) 298 | else: 299 | if 0 <= index < len(self.meta_archs): 300 | if index not in self.evaluated_indexes: print('The {:}-th architecture has not been evaluated or not saved.'.format(index)) 301 | else: 302 | arch_info = self.arch2infos_dict[index] 303 | for key, result in self.arch2infos_dict[index].items(): 304 | strings = print_information(result) 305 | print('>' * 40 + ' {:03d} epochs '.format(result.get_total_epoch()) + '>' * 40) 306 | print('\n'.join(strings)) 307 | print('<' * 40 + '------------' + '<' * 40) 308 | else: 309 | print('This index ({:}) is out of range (0~{:}).'.format(index, len(self.meta_archs))) 310 | 311 | def statistics(self, dataset: Text, hp: Union[Text, int]) -> Dict[int, int]: 312 | """This function will count the number of total trials.""" 313 | if self.verbose: 314 | print('Call the statistics function with dataset={:} and hp={:}.'.format(dataset, hp)) 315 | valid_datasets = ['cifar10-valid', 'cifar10', 'cifar100', 'ImageNet16-120'] 316 | if dataset not in valid_datasets: 317 | raise ValueError('{:} not in {:}'.format(dataset, valid_datasets)) 318 | nums, hp = defaultdict(lambda: 0), str(hp) 319 | for index in range(len(self)): 320 | archInfo = self.arch2infos_dict[index][hp] 321 | dataset_seed = archInfo.dataset_seed 322 | if dataset not in dataset_seed: 323 | nums[0] += 1 324 | else: 325 | nums[len(dataset_seed[dataset])] += 1 326 | return dict(nums) 327 | 328 | 329 | class ArchResults(object): 330 | 331 | def __init__(self, arch_index, arch_str): 332 | self.arch_index = int(arch_index) 333 | self.arch_str = copy.deepcopy(arch_str) 334 | self.all_results = dict() 335 | self.dataset_seed = dict() 336 | self.clear_net_done = False 337 | 338 | def get_compute_costs(self, dataset): 339 | x_seeds = self.dataset_seed[dataset] 340 | results = [self.all_results[ (dataset, seed) ] for seed in x_seeds] 341 | 342 | flops = [result.flop for result in results] 343 | params = [result.params for result in results] 344 | latencies = [result.get_latency() for result in results] 345 | latencies = [x for x in latencies if x > 0] 346 | mean_latency = np.mean(latencies) if len(latencies) > 0 else None 347 | time_infos = defaultdict(list) 348 | for result in results: 349 | time_info = result.get_times() 350 | for key, value in time_info.items(): time_infos[key].append( value ) 351 | 352 | info = {'flops' : np.mean(flops), 353 | 'params' : np.mean(params), 354 | 'latency': mean_latency} 355 | for key, value in time_infos.items(): 356 | if len(value) > 0 and value[0] is not None: 357 | info[key] = np.mean(value) 358 | else: info[key] = None 359 | return info 360 | 361 | def get_metrics(self, dataset, setname, iepoch=None, is_random=False): 362 | """ 363 | This `get_metrics` function is used to obtain obtain the loss, accuracy, etc information on a specific dataset. 364 | If not specify, each set refer to the proposed split in NAS-Bench-201 paper. 365 | If some args return None or raise error, then it is not avaliable. 366 | ======================================== 367 | Args [dataset] (4 possible options): 368 | -- cifar10-valid : training the model on the CIFAR-10 training set. 369 | -- cifar10 : training the model on the CIFAR-10 training + validation set. 370 | -- cifar100 : training the model on the CIFAR-100 training set. 371 | -- ImageNet16-120 : training the model on the ImageNet16-120 training set. 372 | Args [setname] (each dataset has different setnames): 373 | -- When dataset = cifar10-valid, you can use 'train', 'x-valid', 'ori-test' 374 | ------ 'train' : the metric on the training set. 375 | ------ 'x-valid' : the metric on the validation set. 376 | ------ 'ori-test' : the metric on the test set. 377 | -- When dataset = cifar10, you can use 'train', 'ori-test'. 378 | ------ 'train' : the metric on the training + validation set. 379 | ------ 'ori-test' : the metric on the test set. 380 | -- When dataset = cifar100 or ImageNet16-120, you can use 'train', 'ori-test', 'x-valid', 'x-test' 381 | ------ 'train' : the metric on the training set. 382 | ------ 'x-valid' : the metric on the validation set. 383 | ------ 'x-test' : the metric on the test set. 384 | ------ 'ori-test' : the metric on the validation + test set. 385 | Args [iepoch] (None or an integer in [0, the-number-of-total-training-epochs) 386 | ------ None : return the metric after the last training epoch. 387 | ------ an integer i : return the metric after the i-th training epoch. 388 | Args [is_random]: 389 | ------ True : return the metric of a randomly selected trial. 390 | ------ False : return the averaged metric of all avaliable trials. 391 | ------ an integer indicating the 'seed' value : return the metric of a specific trial (whose random seed is 'is_random'). 392 | """ 393 | x_seeds = self.dataset_seed[dataset] 394 | results = [self.all_results[ (dataset, seed) ] for seed in x_seeds] 395 | infos = defaultdict(list) 396 | for result in results: 397 | if setname == 'train': 398 | info = result.get_train(iepoch) 399 | else: 400 | info = result.get_eval(setname, iepoch) 401 | for key, value in info.items(): infos[key].append( value ) 402 | return_info = dict() 403 | if isinstance(is_random, bool) and is_random: # randomly select one 404 | index = random.randint(0, len(results)-1) 405 | for key, value in infos.items(): return_info[key] = value[index] 406 | elif isinstance(is_random, bool) and not is_random: # average 407 | for key, value in infos.items(): 408 | if len(value) > 0 and value[0] is not None: 409 | return_info[key] = np.mean(value) 410 | else: return_info[key] = None 411 | elif isinstance(is_random, int): # specify the seed 412 | if is_random not in x_seeds: raise ValueError('can not find random seed ({:}) from {:}'.format(is_random, x_seeds)) 413 | index = x_seeds.index(is_random) 414 | for key, value in infos.items(): return_info[key] = value[index] 415 | else: 416 | raise ValueError('invalid value for is_random: {:}'.format(is_random)) 417 | return return_info 418 | 419 | def show(self, is_print=False): 420 | return print_information(self, None, is_print) 421 | 422 | def get_dataset_names(self): 423 | return list(self.dataset_seed.keys()) 424 | 425 | def get_dataset_seeds(self, dataset): 426 | return copy.deepcopy( self.dataset_seed[dataset] ) 427 | 428 | def get_net_param(self, dataset: Text, seed: Union[None, int] =None): 429 | """ 430 | This function will return the trained network's weights on the 'dataset'. 431 | :arg 432 | dataset: one of 'cifar10-valid', 'cifar10', 'cifar100', and 'ImageNet16-120'. 433 | seed: an integer indicates the seed value or None that indicates returing all trials. 434 | """ 435 | if seed is None: 436 | x_seeds = self.dataset_seed[dataset] 437 | return {seed: self.all_results[(dataset, seed)].get_net_param() for seed in x_seeds} 438 | else: 439 | xkey = (dataset, seed) 440 | if xkey in self.all_results: 441 | return self.all_results[xkey].get_net_param() 442 | else: 443 | raise ValueError('key={:} not in {:}'.format(xkey, list(self.all_results.keys()))) 444 | 445 | def reset_latency(self, dataset: Text, seed: Union[None, Text], latency: float) -> None: 446 | """This function is used to reset the latency in all corresponding ResultsCount(s).""" 447 | if seed is None: 448 | for seed in self.dataset_seed[dataset]: 449 | self.all_results[(dataset, seed)].update_latency([latency]) 450 | else: 451 | self.all_results[(dataset, seed)].update_latency([latency]) 452 | 453 | def reset_pseudo_train_times(self, dataset: Text, seed: Union[None, Text], estimated_per_epoch_time: float) -> None: 454 | """This function is used to reset the train-times in all corresponding ResultsCount(s).""" 455 | if seed is None: 456 | for seed in self.dataset_seed[dataset]: 457 | self.all_results[(dataset, seed)].reset_pseudo_train_times(estimated_per_epoch_time) 458 | else: 459 | self.all_results[(dataset, seed)].reset_pseudo_train_times(estimated_per_epoch_time) 460 | 461 | def reset_pseudo_eval_times(self, dataset: Text, seed: Union[None, Text], eval_name: Text, estimated_per_epoch_time: float) -> None: 462 | """This function is used to reset the eval-times in all corresponding ResultsCount(s).""" 463 | if seed is None: 464 | for seed in self.dataset_seed[dataset]: 465 | self.all_results[(dataset, seed)].reset_pseudo_eval_times(eval_name, estimated_per_epoch_time) 466 | else: 467 | self.all_results[(dataset, seed)].reset_pseudo_eval_times(eval_name, estimated_per_epoch_time) 468 | 469 | def get_latency(self, dataset: Text) -> float: 470 | """Get the latency of a model on the target dataset. [Timestamp: 2020.03.09]""" 471 | latencies = [] 472 | for seed in self.dataset_seed[dataset]: 473 | latency = self.all_results[(dataset, seed)].get_latency() 474 | if not isinstance(latency, float) or latency <= 0: 475 | raise ValueError('invalid latency of {:} with seed={:} : {:}'.format(dataset, seed, latency)) 476 | latencies.append(latency) 477 | return sum(latencies) / len(latencies) 478 | 479 | def get_total_epoch(self, dataset=None): 480 | """Return the total number of training epochs.""" 481 | if dataset is None: 482 | epochss = [] 483 | for xdata, x_seeds in self.dataset_seed.items(): 484 | epochss += [self.all_results[(xdata, seed)].get_total_epoch() for seed in x_seeds] 485 | elif isinstance(dataset, str): 486 | x_seeds = self.dataset_seed[dataset] 487 | epochss = [self.all_results[(dataset, seed)].get_total_epoch() for seed in x_seeds] 488 | else: 489 | raise ValueError('invalid dataset={:}'.format(dataset)) 490 | if len(set(epochss)) > 1: raise ValueError('Each trial mush have the same number of training epochs : {:}'.format(epochss)) 491 | return epochss[-1] 492 | 493 | def query(self, dataset, seed=None): 494 | """Return the ResultsCount object (containing all information of a single trial) for 'dataset' and 'seed'""" 495 | if seed is None: 496 | x_seeds = self.dataset_seed[dataset] 497 | return {seed: self.all_results[(dataset, seed)] for seed in x_seeds} 498 | else: 499 | return self.all_results[(dataset, seed)] 500 | 501 | def arch_idx_str(self): 502 | return '{:06d}'.format(self.arch_index) 503 | 504 | def update(self, dataset_name, seed, result): 505 | if dataset_name not in self.dataset_seed: 506 | self.dataset_seed[dataset_name] = [] 507 | assert seed not in self.dataset_seed[dataset_name], '{:}-th arch alreadly has this seed ({:}) on {:}'.format(self.arch_index, seed, dataset_name) 508 | self.dataset_seed[ dataset_name ].append( seed ) 509 | self.dataset_seed[ dataset_name ] = sorted( self.dataset_seed[ dataset_name ] ) 510 | assert (dataset_name, seed) not in self.all_results 511 | self.all_results[ (dataset_name, seed) ] = result 512 | self.clear_net_done = False 513 | 514 | def state_dict(self): 515 | state_dict = dict() 516 | for key, value in self.__dict__.items(): 517 | if key == 'all_results': # contain the class of ResultsCount 518 | xvalue = dict() 519 | assert isinstance(value, dict), 'invalid type of value for {:} : {:}'.format(key, type(value)) 520 | for _k, _v in value.items(): 521 | assert isinstance(_v, ResultsCount), 'invalid type of value for {:}/{:} : {:}'.format(key, _k, type(_v)) 522 | xvalue[_k] = _v.state_dict() 523 | else: 524 | xvalue = value 525 | state_dict[key] = xvalue 526 | return state_dict 527 | 528 | def load_state_dict(self, state_dict): 529 | new_state_dict = dict() 530 | for key, value in state_dict.items(): 531 | if key == 'all_results': # to convert to the class of ResultsCount 532 | xvalue = dict() 533 | assert isinstance(value, dict), 'invalid type of value for {:} : {:}'.format(key, type(value)) 534 | for _k, _v in value.items(): 535 | xvalue[_k] = ResultsCount.create_from_state_dict(_v) 536 | else: xvalue = value 537 | new_state_dict[key] = xvalue 538 | self.__dict__.update(new_state_dict) 539 | 540 | @staticmethod 541 | def create_from_state_dict(state_dict_or_file): 542 | x = ArchResults(-1, -1) 543 | if isinstance(state_dict_or_file, str): # a file path 544 | state_dict = torch.load(state_dict_or_file, map_location='cpu') 545 | elif isinstance(state_dict_or_file, dict): 546 | state_dict = state_dict_or_file 547 | else: 548 | raise ValueError('invalid type of state_dict_or_file : {:}'.format(type(state_dict_or_file))) 549 | x.load_state_dict(state_dict) 550 | return x 551 | 552 | # This function is used to clear the weights saved in each 'result' 553 | # This can help reduce the memory footprint. 554 | def clear_params(self): 555 | for key, result in self.all_results.items(): 556 | del result.net_state_dict 557 | result.net_state_dict = None 558 | self.clear_net_done = True 559 | 560 | def debug_test(self): 561 | """This function is used for me to debug and test, which will call most methods.""" 562 | all_dataset = ['cifar10-valid', 'cifar10', 'cifar100', 'ImageNet16-120'] 563 | for dataset in all_dataset: 564 | print('---->>>> {:}'.format(dataset)) 565 | print('The latency on {:} is {:} s'.format(dataset, self.get_latency(dataset))) 566 | for seed in self.dataset_seed[dataset]: 567 | result = self.all_results[(dataset, seed)] 568 | print(' ==>> result = {:}'.format(result)) 569 | print(' ==>> cost = {:}'.format(result.get_times())) 570 | 571 | def __repr__(self): 572 | return ('{name}(arch-index={index}, arch={arch}, {num} runs, clear={clear})'.format(name=self.__class__.__name__, index=self.arch_index, arch=self.arch_str, num=len(self.all_results), clear=self.clear_net_done)) 573 | 574 | 575 | """ 576 | This class (ResultsCount) is used to save the information of one trial for a single architecture. 577 | I did not write much comment for this class, because it is the lowest-level class in NAS-Bench-201 API, which will be rarely called. 578 | If you have any question regarding this class, please open an issue or email me. 579 | """ 580 | class ResultsCount(object): 581 | 582 | def __init__(self, name, state_dict, train_accs, train_losses, params, flop, arch_config, seed, epochs, latency): 583 | self.name = name 584 | self.net_state_dict = state_dict 585 | self.train_acc1es = copy.deepcopy(train_accs) 586 | self.train_acc5es = None 587 | self.train_losses = copy.deepcopy(train_losses) 588 | self.train_times = None 589 | self.arch_config = copy.deepcopy(arch_config) 590 | self.params = params 591 | self.flop = flop 592 | self.seed = seed 593 | self.epochs = epochs 594 | self.latency = latency 595 | # evaluation results 596 | self.reset_eval() 597 | 598 | def update_train_info(self, train_acc1es, train_acc5es, train_losses, train_times) -> None: 599 | self.train_acc1es = train_acc1es 600 | self.train_acc5es = train_acc5es 601 | self.train_losses = train_losses 602 | self.train_times = train_times 603 | 604 | def reset_pseudo_train_times(self, estimated_per_epoch_time: float) -> None: 605 | """Assign the training times.""" 606 | train_times = OrderedDict() 607 | for i in range(self.epochs): 608 | train_times[i] = estimated_per_epoch_time 609 | self.train_times = train_times 610 | 611 | def reset_pseudo_eval_times(self, eval_name: Text, estimated_per_epoch_time: float) -> None: 612 | """Assign the evaluation times.""" 613 | if eval_name not in self.eval_names: raise ValueError('invalid eval name : {:}'.format(eval_name)) 614 | for i in range(self.epochs): 615 | self.eval_times['{:}@{:}'.format(eval_name,i)] = estimated_per_epoch_time 616 | 617 | def reset_eval(self): 618 | self.eval_names = [] 619 | self.eval_acc1es = {} 620 | self.eval_times = {} 621 | self.eval_losses = {} 622 | 623 | def update_latency(self, latency): 624 | self.latency = copy.deepcopy( latency ) 625 | 626 | def get_latency(self) -> float: 627 | """Return the latency value in seconds. -1 represents not avaliable ; otherwise it should be a float value""" 628 | if self.latency is None: return -1.0 629 | else: return sum(self.latency) / len(self.latency) 630 | 631 | def update_eval(self, accs, losses, times): # new version 632 | data_names = set([x.split('@')[0] for x in accs.keys()]) 633 | for data_name in data_names: 634 | assert data_name not in self.eval_names, '{:} has already been added into eval-names'.format(data_name) 635 | self.eval_names.append( data_name ) 636 | for iepoch in range(self.epochs): 637 | xkey = '{:}@{:}'.format(data_name, iepoch) 638 | self.eval_acc1es[ xkey ] = accs[ xkey ] 639 | self.eval_losses[ xkey ] = losses[ xkey ] 640 | self.eval_times [ xkey ] = times[ xkey ] 641 | 642 | def update_OLD_eval(self, name, accs, losses): # old version 643 | assert name not in self.eval_names, '{:} has already added'.format(name) 644 | self.eval_names.append( name ) 645 | for iepoch in range(self.epochs): 646 | if iepoch in accs: 647 | self.eval_acc1es['{:}@{:}'.format(name,iepoch)] = accs[iepoch] 648 | self.eval_losses['{:}@{:}'.format(name,iepoch)] = losses[iepoch] 649 | 650 | def __repr__(self): 651 | num_eval = len(self.eval_names) 652 | set_name = '[' + ', '.join(self.eval_names) + ']' 653 | return ('{name}({xname}, arch={arch}, FLOP={flop:.2f}M, Param={param:.3f}MB, seed={seed}, {num_eval} eval-sets: {set_name})'.format(name=self.__class__.__name__, xname=self.name, arch=self.arch_config['arch_str'], flop=self.flop, param=self.params, seed=self.seed, num_eval=num_eval, set_name=set_name)) 654 | 655 | def get_total_epoch(self): 656 | return copy.deepcopy(self.epochs) 657 | 658 | def get_times(self): 659 | """Obtain the information regarding both training and evaluation time.""" 660 | if self.train_times is not None and isinstance(self.train_times, dict): 661 | train_times = list( self.train_times.values() ) 662 | time_info = {'T-train@epoch': np.mean(train_times), 'T-train@total': np.sum(train_times)} 663 | else: 664 | time_info = {'T-train@epoch': None, 'T-train@total': None } 665 | for name in self.eval_names: 666 | try: 667 | xtimes = [self.eval_times['{:}@{:}'.format(name,i)] for i in range(self.epochs)] 668 | time_info['T-{:}@epoch'.format(name)] = np.mean(xtimes) 669 | time_info['T-{:}@total'.format(name)] = np.sum(xtimes) 670 | except: 671 | time_info['T-{:}@epoch'.format(name)] = None 672 | time_info['T-{:}@total'.format(name)] = None 673 | return time_info 674 | 675 | def get_eval_set(self): 676 | return self.eval_names 677 | 678 | # get the training information 679 | def get_train(self, iepoch=None): 680 | if iepoch is None: iepoch = self.epochs-1 681 | assert 0 <= iepoch < self.epochs, 'invalid iepoch={:} < {:}'.format(iepoch, self.epochs) 682 | if self.train_times is not None: 683 | xtime = self.train_times[iepoch] 684 | atime = sum([self.train_times[i] for i in range(iepoch+1)]) 685 | else: xtime, atime = None, None 686 | return {'iepoch' : iepoch, 687 | 'loss' : self.train_losses[iepoch], 688 | 'accuracy': self.train_acc1es[iepoch], 689 | 'cur_time': xtime, 690 | 'all_time': atime} 691 | 692 | def get_eval(self, name, iepoch=None): 693 | """Get the evaluation information ; there could be multiple evaluation sets (identified by the 'name' argument).""" 694 | if iepoch is None: iepoch = self.epochs-1 695 | assert 0 <= iepoch < self.epochs, 'invalid iepoch={:} < {:}'.format(iepoch, self.epochs) 696 | def _internal_query(xname): 697 | if isinstance(self.eval_times,dict) and len(self.eval_times) > 0: 698 | xtime = self.eval_times['{:}@{:}'.format(xname, iepoch)] 699 | atime = sum([self.eval_times['{:}@{:}'.format(xname, i)] for i in range(iepoch+1)]) 700 | else: 701 | xtime, atime = None, None 702 | return {'iepoch' : iepoch, 703 | 'loss' : self.eval_losses['{:}@{:}'.format(xname, iepoch)], 704 | 'accuracy': self.eval_acc1es['{:}@{:}'.format(xname, iepoch)], 705 | 'cur_time': xtime, 706 | 'all_time': atime} 707 | if name == 'valid': 708 | return _internal_query('x-valid') 709 | else: 710 | return _internal_query(name) 711 | 712 | def get_net_param(self, clone=False): 713 | if clone: return copy.deepcopy(self.net_state_dict) 714 | else: return self.net_state_dict 715 | 716 | def get_config(self, str2structure): 717 | """This function is used to obtain the config dict for this architecture.""" 718 | if str2structure is None: 719 | # In this case, this is NAS-Bench-301 720 | if 'name' in self.arch_config and self.arch_config['name'] == 'infer.shape.tiny': 721 | return {'name': 'infer.shape.tiny', 'channels': self.arch_config['channels'], 722 | 'genotype': self.arch_config['genotype'], 'num_classes': self.arch_config['class_num']} 723 | # In this case, this is NAS-Bench-201 724 | else: 725 | return {'name': 'infer.tiny', 'C': self.arch_config['channel'], 726 | 'N' : self.arch_config['num_cells'], 727 | 'arch_str': self.arch_config['arch_str'], 'num_classes': self.arch_config['class_num']} 728 | else: 729 | # In this case, this is NAS-Bench-301 730 | if 'name' in self.arch_config and self.arch_config['name'] == 'infer.shape.tiny': 731 | return {'name': 'infer.shape.tiny', 'channels': self.arch_config['channels'], 732 | 'genotype': str2structure(self.arch_config['genotype']), 'num_classes': self.arch_config['class_num']} 733 | # In this case, this is NAS-Bench-201 734 | else: 735 | return {'name': 'infer.tiny', 'C': self.arch_config['channel'], 736 | 'N' : self.arch_config['num_cells'], 737 | 'genotype': str2structure(self.arch_config['arch_str']), 'num_classes': self.arch_config['class_num']} 738 | 739 | def state_dict(self): 740 | _state_dict = {key: value for key, value in self.__dict__.items()} 741 | return _state_dict 742 | 743 | def load_state_dict(self, state_dict): 744 | self.__dict__.update(state_dict) 745 | 746 | @staticmethod 747 | def create_from_state_dict(state_dict): 748 | x = ResultsCount(None, None, None, None, None, None, None, None, None, None) 749 | x.load_state_dict(state_dict) 750 | return x 751 | --------------------------------------------------------------------------------