Create NATS
This commit is contained in:
		| @@ -1,9 +1,11 @@ | ||||
| ############################################################### | ||||
| # NAS-Bench-201, ICLR 2020 (https://arxiv.org/abs/2001.00326) # | ||||
| ############################################################### | ||||
| # NATS-Bench: Benchmarking NAS algorithms for Architecture Topology and Size | ||||
| ############################################################### | ||||
| # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2020.06           # | ||||
| ############################################################### | ||||
| # Usage: python exps/NAS-Bench-201/test-nas-api.py | ||||
| # Usage: python exps/NAS-Bench-201/test-nas-api.py            # | ||||
| ############################################################### | ||||
| import os, sys, time, torch, argparse | ||||
| import numpy as np | ||||
| @@ -21,7 +23,7 @@ import matplotlib.ticker as ticker | ||||
| lib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve() | ||||
| if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir)) | ||||
| from config_utils import dict2config, load_config | ||||
| from nas_201_api import NASBench201API, NASBench301API | ||||
| from nats_bench import create | ||||
| from log_utils import time_string | ||||
| from models import get_cell_based_tiny_net, CellStructure | ||||
|  | ||||
| @@ -97,15 +99,14 @@ def test_issue_81_82(api): | ||||
|  | ||||
| if __name__ == '__main__': | ||||
|  | ||||
|   api201 = NASBench201API(os.path.join(os.environ['TORCH_HOME'], 'NAS-Bench-201-v1_0-e61699.pth'), verbose=True) | ||||
|   api201 = create(os.path.join(os.environ['TORCH_HOME'], 'NAS-Bench-201-v1_0-e61699.pth'), 'topology', True) | ||||
|   test_issue_81_82(api201) | ||||
|   # test_api(api201, False) | ||||
|   print ('Test {:} done'.format(api201)) | ||||
|  | ||||
|   api201 = NASBench201API(None, verbose=True) | ||||
|   api201 = create(None, 'topology', True)  # use the default file path | ||||
|   test_issue_81_82(api201) | ||||
|   test_api(api201, False) | ||||
|   print ('Test {:} done'.format(api201)) | ||||
|  | ||||
|   # api301 = NASBench301API(None, verbose=True) | ||||
|   # test_api(api301, True) | ||||
|   api301 = create(None, 'size', True) | ||||
|   test_api(api301, True) | ||||
|   | ||||
| @@ -16,7 +16,7 @@ from log_utils    import AverageMeter, time_string, convert_secs2time | ||||
| from config_utils import dict2config | ||||
| # NAS-Bench-201 related module or function | ||||
| from models       import CellStructure, get_cell_based_tiny_net | ||||
| from nas_201_api  import NASBench301API, ArchResults, ResultsCount | ||||
| from nas_201_api  import ArchResults, ResultsCount | ||||
| from procedures   import bench_pure_evaluate as pure_evaluate, get_nas_bench_loaders | ||||
|  | ||||
|  | ||||
|   | ||||
| @@ -1 +1,3 @@ | ||||
| # Benchmarking NAS Algorithms | ||||
| # NATS-Bench: Benchmarking NAS algorithms for Architecture Topology and Size | ||||
|  | ||||
| # Benchmarking 13 NAS Algorithm | ||||
|   | ||||
| @@ -18,7 +18,7 @@ from config_utils import load_config | ||||
| from datasets     import get_datasets, SearchDataset | ||||
| from procedures   import prepare_seed, prepare_logger | ||||
| from log_utils    import AverageMeter, time_string, convert_secs2time | ||||
| from nas_201_api  import NASBench201API, NASBench301API | ||||
| from nats_bench   import create | ||||
| from models       import CellStructure, get_search_spaces | ||||
| # BOHB: Robust and Efficient Hyperparameter Optimization at Scale, ICML 2018 | ||||
| import ConfigSpace | ||||
| @@ -167,12 +167,7 @@ if __name__ == '__main__': | ||||
|   parser.add_argument('--rand_seed',          type=int,  default=-1, help='manual seed') | ||||
|   args = parser.parse_args() | ||||
|    | ||||
|   if args.search_space == 'tss': | ||||
|     api = NASBench201API(verbose=False) | ||||
|   elif args.search_space == 'sss': | ||||
|     api = NASBench301API(verbose=False) | ||||
|   else: | ||||
|     raise ValueError('Invalid search space : {:}'.format(args.search_space)) | ||||
|   api = create(None, args.search_space, verbose=False) | ||||
|  | ||||
|   args.save_dir = os.path.join('{:}-{:}'.format(args.save_dir, args.search_space), args.dataset, 'BOHB') | ||||
|   print('save-dir : {:}'.format(args.save_dir)) | ||||
|   | ||||
| @@ -21,7 +21,7 @@ from procedures   import prepare_seed, prepare_logger, save_checkpoint, copy_che | ||||
| from utils        import get_model_infos, obtain_accuracy | ||||
| from log_utils    import AverageMeter, time_string, convert_secs2time | ||||
| from models       import get_search_spaces | ||||
| from nas_201_api  import NASBench201API, NASBench301API | ||||
| from nats_bench   import create | ||||
| from regularized_ea import random_topology_func, random_size_func | ||||
|  | ||||
|  | ||||
| @@ -71,12 +71,7 @@ if __name__ == '__main__': | ||||
|   parser.add_argument('--rand_seed',          type=int,   default=-1,    help='manual seed') | ||||
|   args = parser.parse_args() | ||||
|    | ||||
|   if args.search_space == 'tss': | ||||
|     api = NASBench201API(verbose=False) | ||||
|   elif args.search_space == 'sss': | ||||
|     api = NASBench301API(verbose=False) | ||||
|   else: | ||||
|     raise ValueError('Invalid search space : {:}'.format(args.search_space)) | ||||
|   api = create(None, args.search_space, verbose=False) | ||||
|  | ||||
|   args.save_dir = os.path.join('{:}-{:}'.format(args.save_dir, args.search_space), args.dataset, 'RANDOM') | ||||
|   print('save-dir : {:}'.format(args.save_dir)) | ||||
|   | ||||
| @@ -23,8 +23,8 @@ from datasets     import get_datasets, SearchDataset | ||||
| from procedures   import prepare_seed, prepare_logger, save_checkpoint, copy_checkpoint, get_optim_scheduler | ||||
| from utils        import get_model_infos, obtain_accuracy | ||||
| from log_utils    import AverageMeter, time_string, convert_secs2time | ||||
| from nas_201_api  import NASBench201API, NASBench301API | ||||
| from models       import CellStructure, get_search_spaces | ||||
| from nats_bench   import create | ||||
|  | ||||
|  | ||||
| class Model(object): | ||||
| @@ -38,47 +38,6 @@ class Model(object): | ||||
|     return '{:}'.format(self.arch) | ||||
|    | ||||
|  | ||||
| # This function is to mimic the training and evaluatinig procedure for a single architecture `arch`. | ||||
| # The time_cost is calculated as the total training time for a few (e.g., 12 epochs) plus the evaluation time for one epoch. | ||||
| # For use_012_epoch_training = True, the architecture is trained for 12 epochs, with LR being decaded from 0.1 to 0. | ||||
| #       In this case, the LR schedular is converged. | ||||
| # For use_012_epoch_training = False, the architecture is planed to be trained for 200 epochs, but we early stop its procedure. | ||||
| #        | ||||
| def train_and_eval(arch, nas_bench, extra_info, dataname='cifar10-valid', use_012_epoch_training=True): | ||||
|  | ||||
|   if use_012_epoch_training and nas_bench is not None: | ||||
|     arch_index = nas_bench.query_index_by_arch( arch ) | ||||
|     assert arch_index >= 0, 'can not find this arch : {:}'.format(arch) | ||||
|     valid_acc, time_cost = info['valid-accuracy'], info['train-all-time'] + info['valid-per-time'] | ||||
|     #_, valid_acc = info.get_metrics('cifar10-valid', 'x-valid' , 25, True) # use the validation accuracy after 25 training epochs | ||||
|   elif not use_012_epoch_training and nas_bench is not None: | ||||
|     # Please contact me if you want to use the following logic, because it has some potential issues. | ||||
|     # Please use `use_012_epoch_training=False` for cifar10 only. | ||||
|     # It did return values for cifar100 and ImageNet16-120, but it has some potential issues. (Please email me for more details) | ||||
|     arch_index, nepoch = nas_bench.query_index_by_arch( arch ), 25 | ||||
|     assert arch_index >= 0, 'can not find this arch : {:}'.format(arch) | ||||
|     xoinfo = nas_bench.get_more_info(arch_index, 'cifar10-valid', iepoch=None, hp='12') | ||||
|     xocost = nas_bench.get_cost_info(arch_index, 'cifar10-valid', hp='200') | ||||
|     info = nas_bench.get_more_info(arch_index, dataname, nepoch, hp='200', is_random=True) # use the validation accuracy after 25 training epochs, which is used in our ICLR submission (not the camera ready). | ||||
|     cost = nas_bench.get_cost_info(arch_index, dataname, hp='200') | ||||
|     # The following codes are used to estimate the time cost. | ||||
|     # When we build NAS-Bench-201, architectures are trained on different machines and we can not use that time record. | ||||
|     # When we create checkpoints for converged_LR, we run all experiments on 1080Ti, and thus the time for each architecture can be fairly compared. | ||||
|     nums = {'ImageNet16-120-train': 151700, 'ImageNet16-120-valid': 3000, | ||||
|             'cifar10-valid-train' : 25000,  'cifar10-valid-valid' : 25000, | ||||
|             'cifar100-train'      : 50000,  'cifar100-valid'      : 5000} | ||||
|     estimated_train_cost = xoinfo['train-per-time'] / nums['cifar10-valid-train'] * nums['{:}-train'.format(dataname)] / xocost['latency'] * cost['latency'] * nepoch | ||||
|     estimated_valid_cost = xoinfo['valid-per-time'] / nums['cifar10-valid-valid'] * nums['{:}-valid'.format(dataname)] / xocost['latency'] * cost['latency'] | ||||
|     try: | ||||
|       valid_acc, time_cost = info['valid-accuracy'], estimated_train_cost + estimated_valid_cost | ||||
|     except: | ||||
|       valid_acc, time_cost = info['valtest-accuracy'], estimated_train_cost + estimated_valid_cost | ||||
|   else: | ||||
|     # train a model from scratch. | ||||
|     raise ValueError('NOT IMPLEMENT YET') | ||||
|   return valid_acc, time_cost | ||||
|  | ||||
|  | ||||
| def random_topology_func(op_names, max_nodes=4): | ||||
|   # Return a random architecture | ||||
|   def random_architecture(): | ||||
| @@ -239,12 +198,7 @@ if __name__ == '__main__': | ||||
|   parser.add_argument('--rand_seed',          type=int,   default=-1,    help='manual seed') | ||||
|   args = parser.parse_args() | ||||
|  | ||||
|   if args.search_space == 'tss': | ||||
|     api = NASBench201API(verbose=False) | ||||
|   elif args.search_space == 'sss': | ||||
|     api = NASBench301API(verbose=False) | ||||
|   else: | ||||
|     raise ValueError('Invalid search space : {:}'.format(args.search_space)) | ||||
|   api = create(None, args.search_space, verbose=False) | ||||
|  | ||||
|   args.save_dir = os.path.join('{:}-{:}'.format(args.save_dir, args.search_space), args.dataset, 'R-EA-SS{:}'.format(args.ea_sample_size)) | ||||
|   print('save-dir : {:}'.format(args.save_dir)) | ||||
|   | ||||
| @@ -24,8 +24,8 @@ from datasets     import get_datasets, SearchDataset | ||||
| from procedures   import prepare_seed, prepare_logger, save_checkpoint, copy_checkpoint, get_optim_scheduler | ||||
| from utils        import get_model_infos, obtain_accuracy | ||||
| from log_utils    import AverageMeter, time_string, convert_secs2time | ||||
| from nas_201_api  import NASBench201API, NASBench301API | ||||
| from models       import CellStructure, get_search_spaces | ||||
| from nats_bench   import create | ||||
|  | ||||
|  | ||||
| class PolicyTopology(nn.Module): | ||||
| @@ -192,12 +192,7 @@ if __name__ == '__main__': | ||||
|   parser.add_argument('--rand_seed',          type=int,   default=-1,    help='manual seed') | ||||
|   args = parser.parse_args() | ||||
|  | ||||
|   if args.search_space == 'tss': | ||||
|     api = NASBench201API(verbose=False) | ||||
|   elif args.search_space == 'sss': | ||||
|     api = NASBench301API(verbose=False) | ||||
|   else: | ||||
|     raise ValueError('Invalid search space : {:}'.format(args.search_space)) | ||||
|   api = create(None, args.search_space, verbose=False) | ||||
|  | ||||
|   args.save_dir = os.path.join('{:}-{:}'.format(args.save_dir, args.search_space), args.dataset, 'REINFORCE-{:}'.format(args.learning_rate)) | ||||
|   print('save-dir : {:}'.format(args.save_dir)) | ||||
|   | ||||
| @@ -39,7 +39,7 @@ from procedures   import prepare_seed, prepare_logger, save_checkpoint, copy_che | ||||
| from utils        import count_parameters_in_MB, obtain_accuracy | ||||
| from log_utils    import AverageMeter, time_string, convert_secs2time | ||||
| from models       import get_cell_based_tiny_net, get_search_spaces | ||||
| from nas_201_api  import NASBench201API as API | ||||
| from nats_bench   import create | ||||
|  | ||||
|  | ||||
| # The following three functions are used for DARTS-V2 | ||||
| @@ -364,7 +364,7 @@ def main(xargs): | ||||
|   logger.log('The parameters of the search model = {:.2f} MB'.format(params)) | ||||
|   logger.log('search-space : {:}'.format(search_space)) | ||||
|   if bool(xargs.use_api): | ||||
|     api = API(verbose=False) | ||||
|     api = create(None, 'topology', verbose=False) | ||||
|   else: | ||||
|     api = None | ||||
|   logger.log('{:} create API = {:} done'.format(time_string(), api)) | ||||
|   | ||||
| @@ -27,7 +27,7 @@ from procedures   import prepare_seed, prepare_logger, save_checkpoint, copy_che | ||||
| from utils        import count_parameters_in_MB, obtain_accuracy | ||||
| from log_utils    import AverageMeter, time_string, convert_secs2time | ||||
| from models       import get_cell_based_tiny_net, get_search_spaces | ||||
| from nas_201_api  import NASBench301API as API | ||||
| from nats_bench   import create | ||||
|  | ||||
|  | ||||
| # Ad-hoc for TuNAS | ||||
| @@ -176,7 +176,7 @@ def main(xargs): | ||||
|   logger.log('The parameters of the search model = {:.2f} MB'.format(params)) | ||||
|   logger.log('search-space : {:}'.format(search_space)) | ||||
|   if bool(xargs.use_api): | ||||
|     api = API(verbose=False) | ||||
|     api = create(None, 'size', verbose=False) | ||||
|   else: | ||||
|     api = None | ||||
|   logger.log('{:} create API = {:} done'.format(time_string(), api)) | ||||
| @@ -291,7 +291,7 @@ if __name__ == '__main__': | ||||
|   parser.add_argument('--rand_seed',          type=int,   help='manual seed') | ||||
|   args = parser.parse_args() | ||||
|   if args.rand_seed is None or args.rand_seed < 0: args.rand_seed = random.randint(1, 100000) | ||||
|   dirname = '{:}-affine{:}_BN{:}'.format(args.algo, args.affine, args.track_running_stats) | ||||
|   dirname = '{:}-affine{:}_BN{:}-AWD{:}'.format(args.algo, args.affine, args.track_running_stats, args.arch_weight_decay) | ||||
|   if args.overwite_epochs is not None: | ||||
|     dirname = dirname + '-E{:}'.format(args.overwite_epochs) | ||||
|   args.save_dir = os.path.join('{:}-{:}'.format(args.save_dir, args.search_space), args.dataset, dirname) | ||||
|   | ||||
| @@ -16,7 +16,7 @@ matplotlib.use('agg') | ||||
| import matplotlib.pyplot as plt | ||||
| lib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve() | ||||
| if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir)) | ||||
| from nas_201_api import NASBench201API, NASBench301API | ||||
| from nas_201_api import NASBench201API | ||||
| from log_utils import time_string | ||||
| from models import get_cell_based_tiny_net | ||||
| from utils import weight_watcher | ||||
|   | ||||
| @@ -3,9 +3,6 @@ | ||||
| ########################################################################################################################################################### | ||||
| # Before run these commands, the files must be properly put. | ||||
| # | ||||
| # python exps/experimental/test-ww-bench.py --base_path $HOME/.torch/NAS-Bench-201-v1_0-e61699 | ||||
| # python exps/experimental/test-ww-bench.py --base_path $HOME/.torch/NAS-Bench-201-v1_1-096897 --dataset cifar10-valid --use_12 1 --use_valid 1 | ||||
| # CUDA_VISIBLE_DEVICES='' OMP_NUM_THREADS=4 python exps/experimental/test-ww-bench.py --base_path $HOME/.torch/NAS-Bench-201-v1_1-096897 --dataset cifar10 | ||||
| # CUDA_VISIBLE_DEVICES='' OMP_NUM_THREADS=4 python exps/experimental/test-ww-bench.py --search_space sss --base_path $HOME/.torch/NAS-Bench-301-v1_0 --dataset cifar10 | ||||
| # CUDA_VISIBLE_DEVICES='' OMP_NUM_THREADS=4 python exps/experimental/test-ww-bench.py --search_space sss --base_path $HOME/.torch/NAS-Bench-301-v1_0 --dataset cifar100 | ||||
| # CUDA_VISIBLE_DEVICES='' OMP_NUM_THREADS=4 python exps/experimental/test-ww-bench.py --search_space sss --base_path $HOME/.torch/NAS-Bench-301-v1_0 --dataset ImageNet16-120 | ||||
| @@ -22,8 +19,8 @@ matplotlib.use('agg') | ||||
| import matplotlib.pyplot as plt | ||||
| lib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve() | ||||
| if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir)) | ||||
| from nas_201_api import NASBench201API, NASBench301API | ||||
| from log_utils import time_string | ||||
| from nats_bench import create | ||||
| from models import get_cell_based_tiny_net | ||||
| from utils import weight_watcher | ||||
|  | ||||
| @@ -52,8 +49,8 @@ def evaluate(api, weight_dir, data: str): | ||||
|     # compute the weight watcher results | ||||
|     config = api.get_net_config(arch_index, data) | ||||
|     net = get_cell_based_tiny_net(config) | ||||
|     meta_info = api.query_meta_info_by_index(arch_index, hp='200' if isinstance(api, NASBench201API) else '90') | ||||
|     params = meta_info.get_net_param(data, 888 if isinstance(api, NASBench201API) else 777) | ||||
|     meta_info = api.query_meta_info_by_index(arch_index, hp='200' if api.search_space_name == 'topology' else '90') | ||||
|     params = meta_info.get_net_param(data, 888 if api.search_space_name == 'topology' else 777) | ||||
|     with torch.no_grad(): | ||||
|       net.load_state_dict(params) | ||||
|       _, summary = weight_watcher.analyze(net, alphas=False) | ||||
| @@ -70,7 +67,7 @@ def evaluate(api, weight_dir, data: str): | ||||
|       ok += 1 | ||||
|       norms.append(cur_norm) | ||||
|     # query the accuracy | ||||
|     info = meta_info.get_metrics(data, 'ori-test', iepoch=None, is_random=888 if isinstance(api, NASBench201API) else 777) | ||||
|     info = meta_info.get_metrics(data, 'ori-test', iepoch=None, is_random=888 if api.search_space_name == 'topology' else 777) | ||||
|     accuracies.append(info['accuracy']) | ||||
|     del net, meta_info | ||||
|     # print the information | ||||
| @@ -81,9 +78,8 @@ def evaluate(api, weight_dir, data: str): | ||||
|  | ||||
|  | ||||
| def main(search_space, meta_file: str, weight_dir, save_dir, xdata): | ||||
|   API = NASBench201API if search_space == 'tss' else NASBench301API | ||||
|   save_dir.mkdir(parents=True, exist_ok=True) | ||||
|   api = API(meta_file, verbose=False) | ||||
|   api = create(meta_file, search_space, verbose=False) | ||||
|   datasets = ['cifar10-valid', 'cifar10', 'cifar100', 'ImageNet16-120'] | ||||
|   print(time_string() + ' ' + '='*50) | ||||
|   for data in datasets: | ||||
|   | ||||
| @@ -3,8 +3,8 @@ | ||||
| ############################################################### | ||||
| # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2020.06           # | ||||
| ############################################################### | ||||
| # Usage: python exps/experimental/vis-bench-algos.py --search_space tss | ||||
| # Usage: python exps/experimental/vis-bench-algos.py --search_space sss | ||||
| # Usage: python exps/experimental/vis-nats-bench-algos.py --search_space tss | ||||
| # Usage: python exps/experimental/vis-nats-bench-algos.py --search_space sss | ||||
| ############################################################### | ||||
| import os, gc, sys, time, torch, argparse | ||||
| import numpy as np | ||||
| @@ -22,7 +22,7 @@ import matplotlib.ticker as ticker | ||||
| lib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve() | ||||
| if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir)) | ||||
| from config_utils import dict2config, load_config | ||||
| from nas_201_api import NASBench201API, NASBench301API | ||||
| from nats_bench import create | ||||
| from log_utils import time_string | ||||
| 
 | ||||
| 
 | ||||
| @@ -48,18 +48,19 @@ def fetch_data(root_dir='./output/search', search_space='tss', dataset=None): | ||||
| 
 | ||||
| 
 | ||||
| def query_performance(api, data, dataset, ticket): | ||||
|   results, is_301 = [], isinstance(api, NASBench301API) | ||||
|   results, is_size_space = [], api.search_space_name == 'size' | ||||
|   for i, info in data.items(): | ||||
|     time_w_arch = sorted(info['time_w_arch'], key=lambda x: abs(x[0]-ticket)) | ||||
|     time_a, arch_a = time_w_arch[0] | ||||
|     time_b, arch_b = time_w_arch[1] | ||||
|     info_a = api.get_more_info(arch_a, dataset=dataset, hp=90 if is_301 else 200, is_random=False) | ||||
|     info_b = api.get_more_info(arch_b, dataset=dataset, hp=90 if is_301 else 200, is_random=False) | ||||
|     info_a = api.get_more_info(arch_a, dataset=dataset, hp=90 if is_size_space else 200, is_random=False) | ||||
|     info_b = api.get_more_info(arch_b, dataset=dataset, hp=90 if is_size_space else 200, is_random=False) | ||||
|     accuracy_a, accuracy_b = info_a['test-accuracy'], info_b['test-accuracy'] | ||||
|     interplate = (time_b-ticket) / (time_b-time_a) * accuracy_a + (ticket-time_a) / (time_b-time_a) * accuracy_b | ||||
|     results.append(interplate) | ||||
|   return sum(results) / len(results) | ||||
| 
 | ||||
| 
 | ||||
| y_min_s = {('cifar10', 'tss'): 90, | ||||
|            ('cifar10', 'sss'): 92, | ||||
|            ('cifar100', 'tss'): 65, | ||||
| @@ -74,6 +75,10 @@ y_max_s = {('cifar10', 'tss'): 94.5, | ||||
|            ('ImageNet16-120', 'tss'): 44, | ||||
|            ('ImageNet16-120', 'sss'): 46} | ||||
| 
 | ||||
| name2label = {'cifar10': 'CIFAR-10', | ||||
|               'cifar100': 'CIFAR-100', | ||||
|               'ImageNet16-120': 'ImageNet-16-120'} | ||||
| 
 | ||||
| def visualize_curve(api, vis_save_dir, search_space, max_time): | ||||
|   vis_save_dir = vis_save_dir.resolve() | ||||
|   vis_save_dir.mkdir(parents=True, exist_ok=True) | ||||
| @@ -99,8 +104,8 @@ def visualize_curve(api, vis_save_dir, search_space, max_time): | ||||
|       alg2accuracies[alg] = accuracies | ||||
|       ax.plot([x/100 for x in time_tickets], accuracies, c=colors[idx], label='{:}'.format(alg)) | ||||
|       ax.set_xlabel('Estimated wall-clock time (1e2 seconds)', fontsize=LabelSize) | ||||
|       ax.set_ylabel('Test accuracy on {:}'.format(dataset), fontsize=LabelSize) | ||||
|       ax.set_title('Searching results on {:}'.format(dataset), fontsize=LabelSize+4) | ||||
|       ax.set_ylabel('Test accuracy on {:}'.format(name2label[dataset]), fontsize=LabelSize) | ||||
|       ax.set_title('Searching results on {:}'.format(name2label[dataset]), fontsize=LabelSize+4) | ||||
|     ax.legend(loc=4, fontsize=LegendFontsize) | ||||
| 
 | ||||
|   fig, axs = plt.subplots(1, 3, figsize=figsize) | ||||
| @@ -123,10 +128,5 @@ if __name__ == '__main__': | ||||
| 
 | ||||
|   save_dir = Path(args.save_dir) | ||||
| 
 | ||||
|   if args.search_space == 'tss': | ||||
|     api = NASBench201API(verbose=False) | ||||
|   elif args.search_space == 'sss': | ||||
|     api = NASBench301API(verbose=False) | ||||
|   else: | ||||
|     raise ValueError('Invalid search space : {:}'.format(args.search_space)) | ||||
|   api = create(None, args.search_space, verbose=False) | ||||
|   visualize_curve(api, save_dir, args.search_space, args.max_time) | ||||
| @@ -3,8 +3,8 @@ | ||||
| ############################################################### | ||||
| # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2020.06           # | ||||
| ############################################################### | ||||
| # Usage: python exps/experimental/vis-bench-ws.py --search_space tss | ||||
| # Usage: python exps/experimental/vis-bench-ws.py --search_space sss | ||||
| # Usage: python exps/experimental/vis-nats-bench-ws.py --search_space tss | ||||
| # Usage: python exps/experimental/vis-nats-bench-ws.py --search_space sss | ||||
| ############################################################### | ||||
| import os, gc, sys, time, torch, argparse | ||||
| import numpy as np | ||||
| @@ -22,15 +22,16 @@ import matplotlib.ticker as ticker | ||||
| lib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve() | ||||
| if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir)) | ||||
| from config_utils import dict2config, load_config | ||||
| from nas_201_api import NASBench201API, NASBench301API | ||||
| from nats_bench import create | ||||
| from log_utils import time_string | ||||
| 
 | ||||
| 
 | ||||
| def fetch_data(root_dir='./output/search', search_space='tss', dataset=None): | ||||
|   ss_dir = '{:}-{:}'.format(root_dir, search_space) | ||||
|   alg2name, alg2path = OrderedDict(), OrderedDict() | ||||
|   seeds = [777, 888, 999] | ||||
|   print('\n[fetch data] from {:} on {:}'.format(search_space, dataset)) | ||||
|   if search_space == 'tss': | ||||
|     seeds = [777] | ||||
|     alg2name['GDAS'] = 'gdas-affine0_BN0-None' | ||||
|     alg2name['RSPS'] = 'random-affine0_BN0-None' | ||||
|     alg2name['DARTS (1st)'] = 'darts-v1-affine0_BN0-None' | ||||
| @@ -38,7 +39,6 @@ def fetch_data(root_dir='./output/search', search_space='tss', dataset=None): | ||||
|     alg2name['ENAS'] = 'enas-affine0_BN0-None' | ||||
|     alg2name['SETN'] = 'setn-affine0_BN0-None' | ||||
|   else: | ||||
|     seeds = [777, 888, 999] | ||||
|     alg2name['TAS'] = 'tas-affine0_BN0' | ||||
|     alg2name['FBNetV2'] = 'fbv2-affine0_BN0' | ||||
|     alg2name['TuNAS'] = 'tunas-affine0_BN0' | ||||
| @@ -46,13 +46,19 @@ def fetch_data(root_dir='./output/search', search_space='tss', dataset=None): | ||||
|     alg2path[alg] = os.path.join(ss_dir, dataset, name, 'seed-{:}-last-info.pth') | ||||
|   alg2data = OrderedDict() | ||||
|   for alg, path in alg2path.items(): | ||||
|     alg2data[alg] = [] | ||||
|     alg2data[alg], ok_num = [], 0 | ||||
|     for seed in seeds: | ||||
|       xpath = path.format(seed) | ||||
|       assert os.path.isfile(xpath), 'invalid path : {:}'.format(xpath) | ||||
|       if os.path.isfile(xpath): | ||||
|         ok_num += 1 | ||||
|       else: | ||||
|         print('This is an invalid path : {:}'.format(xpath)) | ||||
|         continue | ||||
|       data = torch.load(xpath, map_location=torch.device('cpu')) | ||||
|       data = torch.load(data['last_checkpoint'], map_location=torch.device('cpu')) | ||||
|       alg2data[alg].append(data['genotypes']) | ||||
|     print('This algorithm : {:} has {:} valid ckps.'.format(alg, ok_num)) | ||||
|     assert ok_num > 0, 'Must have at least 1 valid ckps.' | ||||
|   return alg2data | ||||
| 
 | ||||
| 
 | ||||
| @@ -95,7 +101,7 @@ def visualize_curve(api, vis_save_dir, search_space): | ||||
|       for iepoch in range(epochs+1): | ||||
|         structures, accs = [_[iepoch-1] for _ in data], [] | ||||
|         for structure in structures: | ||||
|           info = api.get_more_info(structure, dataset=dataset, hp=90 if isinstance(api, NASBench301API) else 200, is_random=False) | ||||
|           info = api.get_more_info(structure, dataset=dataset, hp=90 if api.search_space_name == 'size' else 200, is_random=False) | ||||
|           accs.append(info['test-accuracy']) | ||||
|         accuracies.append(sum(accs)/len(accs)) | ||||
|         xs.append(iepoch) | ||||
| @@ -124,12 +130,6 @@ if __name__ == '__main__': | ||||
|   args = parser.parse_args() | ||||
| 
 | ||||
|   save_dir = Path(args.save_dir) | ||||
|   alg2data = fetch_data(search_space='tss', dataset='cifar10') | ||||
| 
 | ||||
|   if args.search_space == 'tss': | ||||
|     api = NASBench201API(verbose=False) | ||||
|   elif args.search_space == 'sss': | ||||
|     api = NASBench301API(verbose=False) | ||||
|   else: | ||||
|     raise ValueError('Invalid search space : {:}'.format(args.search_space)) | ||||
|   api = create(None, args.search_space, verbose=False) | ||||
|   visualize_curve(api, save_dir, args.search_space) | ||||
| @@ -21,9 +21,9 @@ import matplotlib.ticker as ticker | ||||
| lib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve() | ||||
| if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir)) | ||||
| from config_utils import dict2config, load_config | ||||
| from nas_201_api import NASBench201API, NASBench301API | ||||
| from log_utils import time_string | ||||
| from models import get_cell_based_tiny_net | ||||
| from nats_bench import create | ||||
|  | ||||
|  | ||||
| def visualize_info(api, vis_save_dir, indicator): | ||||
| @@ -391,11 +391,11 @@ if __name__ == '__main__': | ||||
|   to_save_dir = Path(args.save_dir) | ||||
|  | ||||
|   datasets = ['cifar10', 'cifar100', 'ImageNet16-120'] | ||||
|   api201 = NASBench201API(None, verbose=True) | ||||
|   api201 = create(None, 'tss', verbose=True) | ||||
|   for xdata in datasets: | ||||
|     visualize_tss_info(api201, xdata, to_save_dir) | ||||
|  | ||||
|   api301 = NASBench301API(None, verbose=True) | ||||
|   api301 = create(None, 'size', verbose=True) | ||||
|   for xdata in datasets: | ||||
|     visualize_sss_info(api301, xdata, to_save_dir) | ||||
|  | ||||
|   | ||||
		Reference in New Issue
	
	Block a user