├── .gitignore ├── .pre-commit-config.yaml ├── .style.yapf ├── .travis └── precommit.sh ├── AutoDL Design ├── README.md ├── __init__.py ├── autodl.py ├── autodl_agent.py ├── cifar │ └── dataset_maker.py ├── distribute_generator.py ├── img │ ├── cnn_net.png │ └── search_result.png ├── inception_train │ ├── models │ │ ├── __init__.py │ │ ├── inception.py │ │ ├── layers.py │ │ └── ops.py │ ├── nn.py │ ├── preprocess.py │ ├── reader.py │ ├── train.py │ └── utils.py ├── main.py ├── policy_model.py ├── reinforce_policy_gradient.py ├── run.sh ├── simple_main.py └── utils.py ├── LICENSE ├── LRC ├── README.md ├── README_cn.md ├── dataset │ └── download.sh ├── genotypes.py ├── labels.npz ├── learning_rate.py ├── model.py ├── operations.py ├── paddle_predict │ └── __init__.py ├── reader_cifar.py ├── run_cifar.sh ├── run_cifar_test.sh ├── test_mixup.py ├── train_mixup.py ├── utils.py └── voting.py ├── NAS-Models ├── .gitignore ├── README.md ├── README_CN.md ├── lib │ ├── models │ │ ├── __init__.py │ │ ├── genotypes.py │ │ ├── nas_net.py │ │ ├── operations.py │ │ └── resnet.py │ └── utils │ │ ├── __init__.py │ │ ├── data_utils.py │ │ ├── meter.py │ │ └── time_utils.py ├── scripts │ ├── base-train.sh │ └── train-nas.sh └── train_cifar.py └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | *.vs 3 | build/ 4 | build_doc/ 5 | *.user 6 | 7 | .vscode 8 | .idea 9 | .project 10 | .cproject 11 | .pydevproject 12 | .settings/ 13 | CMakeSettings.json 14 | Makefile 15 | .test_env/ 16 | third_party/ 17 | 18 | *~ 19 | bazel-* 20 | third_party/ 21 | 22 | build_* 23 | # clion workspace 24 | cmake-build-* 25 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | - repo: https://github.com/PaddlePaddle/mirrors-yapf.git 2 | sha: 0d79c0c469bab64f7229c9aca2b1186ef47f0e37 3 | hooks: 4 | - id: yapf 5 | files: \.py$ 6 | - repo: https://github.com/pre-commit/pre-commit-hooks 7 | sha: a11d9314b22d8f8c7556443875b731ef05965464 8 | hooks: 9 | - id: check-merge-conflict 10 | - id: check-symlinks 11 | - id: detect-private-key 12 | files: (?!.*paddle)^.*$ 13 | - id: end-of-file-fixer 14 | files: \.md$ 15 | - id: trailing-whitespace 16 | files: \.md$ 17 | - repo: https://github.com/Lucas-C/pre-commit-hooks 18 | sha: v1.0.1 19 | hooks: 20 | - id: forbid-crlf 21 | files: \.md$ 22 | - id: remove-crlf 23 | files: \.md$ 24 | - id: forbid-tabs 25 | files: \.md$ 26 | - id: remove-tabs 27 | files: \.md$ 28 | -------------------------------------------------------------------------------- /.style.yapf: -------------------------------------------------------------------------------- 1 | [style] 2 | based_on_style = pep8 3 | column_limit = 80 4 | -------------------------------------------------------------------------------- /.travis/precommit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | function abort(){ 3 | echo "Your commit does not fit PaddlePaddle code style" 1>&2 4 | echo "Please use pre-commit scripts to auto-format your code" 1>&2 5 | exit 1 6 | } 7 | 8 | trap 'abort' 0 9 | set -e 10 | cd `dirname $0` 11 | cd .. 12 | export PATH=/usr/bin:$PATH 13 | pre-commit install 14 | 15 | if ! pre-commit run -a ; then 16 | ls -lh 17 | git diff --exit-code 18 | exit 1 19 | fi 20 | 21 | trap : 0 22 | -------------------------------------------------------------------------------- /AutoDL Design/README.md: -------------------------------------------------------------------------------- 1 | # AutoDL Design 简介 2 | 3 | ## 目录 4 | - [安装](#安装) 5 | - [简介](#简介) 6 | - [数据准备](#数据准备) 7 | - [模型训练](#模型训练) 8 | 9 | ## 安装 10 | 在当前目录下运行样例代码需要PadddlePaddle Fluid的v.1.3.0或以上的版本。如果你的运行环境中的PaddlePaddle低于此版本,请根据安装文档中的说明来更新PaddlePaddle。 11 | * 安装Python2.7 12 | * 训练执行依赖[PARL](https://github.com/PaddlePaddle/PARL) 框架和[absl-py](https://github.com/abseil/abseil-py/tree/master/absl) 库,通过如下命令安装 13 | ``` 14 | pip install parl 15 | pip install absl-py 16 | ``` 17 | 18 | 19 | ## 简介 20 | [AutoDL](http://www.paddlepaddle.org/paddle/ModelAutoDL)是一种高效的自动搜索构建最佳网络结构的方法,通过增强学习在不断训练过程中得到定制化高质量的模型。系统由两部分组成,第一部分是网络结构的编码器,第二部分是网络结构的评测器。编码器通常以 RNN 的方式把网络结构进行编码,然后评测器把编码的结果拿去进行训练和评测,拿到包括准确率、模型大小在内的一些指标,反馈给编码器,编码器进行修改,再次编码,如此迭代。经过若干次迭代以后,最终得到一个设计好的模型。这里开源的AutoDl Design是基于PaddlePaddle框架的一种AutoDL技术实现。第二节介绍AutoDL Design的使用步骤。第三节介绍AutoDL Design的实现原理与示例。 21 | 22 | ## 数据准备 23 | * 克隆[PaddlePaddle/AutoDL](https://github.com/PaddlePaddle/AutoDL.git)到测试机,并进入AutoDL Design路径。 24 | * 下载[CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz)训练数据,并放入AutoDL Design/cifar路径下并解压,按如下命令执行`dataset_maker.py` 生成10类每类100张图片的pickle训练小数据集。 25 | ``` 26 | tar zxf cifar-10-python.tar.gz 27 | python dataset_maker.py 28 | ``` 29 | 30 | ## 模型训练 31 | AutoDL Design在训练过程中每次通过Agent的策略网络生成用于训练的Tokens和邻接矩阵Adj,然后Trainer通过Tokens和Adj进行CNN训练网络的组建与训练,训练20个epoch以后返回训练的acc值作为Reward返回给Agent,Agent收到Reward值以后更新策略,通过不断的迭代,最终可以自动搜索到效果不错的深度神经网络。 32 | ![图片](./img/cnn_net.png) 33 | 这里提供了如下两种测试的方法。 34 | 35 | ### 针对生成tokens个数的收敛性测试 36 | 由于CNN训练每次执行时间长,为了测试整体Agent框架的正确性,这里我们把生成tokens个数作为模拟CNN训练的返回Reward,最终自动搜索出来的网络可以使得tokens的个数越来越多。这里tokens向量总长度设置的是20。执行以下命令: 37 | ``` 38 | export FLAGS_fraction_of_gpu_memory_to_use=0.98 39 | export FLAGS_eager_delete_tensor_gb=0.0 40 | export FLAGS_fast_eager_deletion_mode=1 41 | CUDA_VISIBLE_DEVICES=0 python -u simple_main.py 42 | ``` 43 | 预期结果: 44 | 日志中 `average rewards`逐步向20收敛递增 45 | 46 | ``` 47 | Simple run target is 20 48 | mid=0, average rewards=2.500 49 | ... 50 | mid=450, average rewards=17.100 51 | mid=460, average rewards=17.000 52 | 53 | ``` 54 | 55 | ### AutoDL网络自动搜索训练 56 | 基于CIFAR-10小数据集上执行自动网络搜索策略,每次先执行Agent策略网络生成新的策略,然后Trainer根据生成的策略去进行模型的训练与Reward(即acc指标)结果的反馈,最终不断迭代搜索到准确率更高的模型网络结构。执行以下命令: 57 | ``` 58 | export FLAGS_fraction_of_gpu_memory_to_use=0.98 59 | export FLAGS_eager_delete_tensor_gb=0.0 60 | export FLAGS_fast_eager_deletion_mode=1 61 | CUDA_VISIBLE_DEVICES=0 python -u main.py 62 | ``` 63 | __注意:__ 这里训练需要使用两张卡来训练,Agent使用的卡为`CUDA_VISIBLE_DEVICES=0`(设置在启动`main.py`命令中);Trainer训练使用卡为`CUDA_VISIBLE_DEVICES=1`(设置在[autodl.py](https://github.com/PaddlePaddle/AutoDL/blob/master/AutoDL%20Design/autodl.py#L124)文件中) 64 | 65 | 预期结果: 66 | 日志中 `average accuracy`逐步增大 67 | 68 | ``` 69 | step = 0, average accuracy = 0.633 70 | step = 1, average accuracy = 0.688 71 | step = 2, average accuracy = 0.626 72 | step = 3, average accuracy = 0.682 73 | ...... 74 | step = 842, average accuracy = 0.823 75 | step = 843, average accuracy = 0.825 76 | step = 844, average accuracy = 0.808 77 | ...... 78 | ``` 79 | ### 结果展示 80 | 81 | ![图片](./img/search_result.png) 82 | 横坐标是迭代的step轮数,纵坐标是模型训练的acc指标,通过图中所示,通过不断的迭代搜索,使得自动构建模型的效果在不断增强。 83 | -------------------------------------------------------------------------------- /AutoDL Design/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PaddlePaddle/AutoDL/b3d3f7ce6de485879c952d02c2c4c95ebe1a2f0c/AutoDL Design/__init__.py -------------------------------------------------------------------------------- /AutoDL Design/autodl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | AutoDL definition 18 | """ 19 | 20 | from __future__ import absolute_import 21 | from __future__ import division 22 | from __future__ import print_function 23 | 24 | import os 25 | import sys 26 | import argparse 27 | import numpy as np 28 | import subprocess 29 | import paddle.fluid as fluid 30 | from reinforce_policy_gradient import ReinforcePolicyGradient 31 | from policy_model import PolicyModel 32 | from autodl_agent import AutoDLAgent 33 | import utils 34 | import collections 35 | 36 | 37 | class AutoDL(object): 38 | """ 39 | AutoDL class 40 | """ 41 | def __init__(self): 42 | """ 43 | init 44 | """ 45 | self.parse_args = self._init_parser() 46 | self.bl_decay = self.parse_args.bl_decay 47 | self.log_dir = self.parse_args.log_dir 48 | self.early_stop = self.parse_args.early_stop 49 | self.data_path = self.parse_args.data_path 50 | self.num_models = self.parse_args.num_models 51 | self.batch_size = self.parse_args.batch_size 52 | self.chunk_size= self.parse_args.chunk_size 53 | 54 | self._init_dir_path() 55 | self.model = PolicyModel(self.parse_args) 56 | algo_hyperparas = {'lr': self.parse_args.learning_rate} 57 | self.algorithm = ReinforcePolicyGradient(self.model, 58 | hyperparas=algo_hyperparas) 59 | self.autodl_agent = AutoDLAgent(self.algorithm, self.parse_args) 60 | self.total_reward = 0 61 | 62 | def _init_dir_path(self): 63 | """ 64 | init dir path 65 | """ 66 | utils.prepare(self.log_dir) 67 | utils.prepare(self.log_dir, "actions") 68 | utils.prepare(self.log_dir, "rewards") 69 | utils.prepare(self.log_dir, "checkpoints") 70 | 71 | def _init_parser(self): 72 | """ 73 | init parser 74 | """ 75 | parser = argparse.ArgumentParser(description='AutoDL Parser', 76 | prog='AutoDL') 77 | parser.add_argument('-v', '--version', action='version', 78 | version='%(prog)s 0.1') 79 | parser.add_argument('--num_nodes', dest="num_nodes", nargs="?", 80 | type=int, const=10, default=10, 81 | help="number of nodes") 82 | parser.add_argument('--num_tokens', dest="num_tokens", nargs="?", 83 | type=int, const=10, default=10, 84 | help="number of tokens") 85 | parser.add_argument('--learning_rate', dest="learning_rate", nargs="?", 86 | type=float, default=1e-3, 87 | help="learning rate") 88 | parser.add_argument('--batch_size', dest="batch_size", nargs="?", 89 | type=int, const=10, default=10, help="batch size") 90 | parser.add_argument('--num_models', dest="num_models", nargs="?", 91 | type=int, const=32000, default=32000, 92 | help="maximum number of models sampled") 93 | parser.add_argument('--early_stop', dest="early_stop", nargs="?", 94 | type=int, const=20, default=20, help="early stop") 95 | parser.add_argument('--log_dir', dest="log_dir", nargs="?", type=str, 96 | const="./log", default="./log", 97 | help="directory of log") 98 | parser.add_argument('--input_size', dest="input_size", nargs="?", 99 | type=int, const=10, default=10, help="input size") 100 | parser.add_argument('--hidden_size', dest="hidden_size", nargs="?", 101 | type=int, const=64, default=64, help="hidden size") 102 | parser.add_argument('--num_layers', dest="num_layers", nargs="?", 103 | type=int, const=2, default=2, help="num layers") 104 | parser.add_argument('--bl_decay', dest="bl_decay", nargs="?", 105 | type=float, const=0.9, default=0.9, 106 | help="base line decay") 107 | # inception train config 108 | parser.add_argument('--data_path', dest="data_path", nargs="?", 109 | type=str, default="./cifar/pickle-cifar-10", 110 | help="path of data files") 111 | parser.add_argument('--chunk_size', dest="chunk_size", nargs="?", 112 | type=int, const=100, default=100, 113 | help="chunk size") 114 | parse_args = parser.parse_args() 115 | return parse_args 116 | 117 | def supervisor(self, mid): 118 | """ 119 | execute cnn training 120 | sample cmd: python -u inception_train/train.py --mid=9 \ 121 | --early_stop=20 --data_path=./cifar/pickle-cifar-10 122 | """ 123 | tokens, adjvec = utils.load_action(mid, self.log_dir) 124 | cmd = ("CUDA_VISIBLE_DEVICES=1 python -u inception_train/train.py \ 125 | --mid=%d --early_stop=%d --logdir=%s --data_path=%s --chunk_size=%d") % \ 126 | (mid, self.early_stop, self.log_dir, self.data_path, self.chunk_size) 127 | print("cmd:{}".format(cmd)) 128 | while True: 129 | try: 130 | subprocess.check_call(cmd, shell=True) 131 | break 132 | except subprocess.CalledProcessError as e: 133 | print("[%s] training model #%d exits with exit code %d" % 134 | (utils.stime(), mid, e.returncode), file=sys.stderr) 135 | return 136 | 137 | def simple_run(self): 138 | """ 139 | simple run 140 | """ 141 | print("Simple run target is 20") 142 | mid = 0 143 | shadow = 0 144 | is_first = True 145 | while mid <= self.num_models: 146 | actions_to, actions_ad = self.autodl_agent.sample() 147 | rewards = np.count_nonzero(actions_to == 1, axis=1).astype("int32") 148 | # moving average 149 | current_mean_reward = np.mean(rewards) 150 | if is_first: 151 | shadow = current_mean_reward 152 | is_first = False 153 | else: 154 | shadow = shadow * self.bl_decay \ 155 | + current_mean_reward * (1 - self.bl_decay) 156 | self.autodl_agent.learn((np.array(actions_to).astype("int32"), 157 | np.array(actions_ad).astype("int32")), 158 | rewards - shadow) 159 | 160 | if mid % 10 == 0: 161 | print('mid=%d, average rewards=%.3f' % (mid, np.mean(rewards))) 162 | mid += 1 163 | 164 | def run(self): 165 | """ 166 | run 167 | """ 168 | rewards = [] 169 | mid = 0 170 | while mid <= self.num_models: 171 | actions_to, actions_ad = self.autodl_agent.sample() 172 | 173 | for action in zip(actions_to, actions_ad): 174 | utils.dump_action(mid, action, self.log_dir) 175 | self.supervisor(mid) 176 | current_reward = utils.load_reward(mid, self.log_dir) 177 | if not np.isnan(current_reward): 178 | rewards.append(current_reward.item()) 179 | mid += 1 180 | 181 | if len(rewards) % self.batch_size == 0: 182 | print("[%s] step = %d, average accuracy = %.3f" % 183 | (utils.stime(), self.autodl_agent.global_step, 184 | np.mean(rewards))) 185 | rewards_array = np.array(rewards).astype("float32") 186 | if self.total_reward == 0: 187 | self.total_reward = rewards_array.mean() 188 | else: 189 | self.total_reward = self.total_reward * self.bl_decay \ 190 | + (1 - self.bl_decay) * rewards_array.mean() 191 | rewards_array = rewards_array - self.total_reward 192 | self.autodl_agent.learn([actions_to.astype("int32"), 193 | actions_ad.astype("int32")], 194 | rewards_array ** 3) 195 | rewards = [] 196 | -------------------------------------------------------------------------------- /AutoDL Design/autodl_agent.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | AutoDL Agent Definition 18 | """ 19 | 20 | from __future__ import absolute_import 21 | from __future__ import division 22 | from __future__ import print_function 23 | 24 | import os 25 | import sys 26 | import numpy as np 27 | import paddle.fluid as fluid 28 | import paddle.fluid.layers as layers 29 | from parl.framework.agent_base import Agent 30 | 31 | 32 | class AutoDLAgent(Agent): 33 | """ 34 | AutoDLAgent 35 | """ 36 | def __init__(self, algorithm, parse_args): 37 | """ 38 | init 39 | """ 40 | self.global_step = 0 41 | self.parse_args = parse_args 42 | self.num_nodes = self.parse_args.num_nodes 43 | self.batch_size = self.parse_args.batch_size 44 | super(AutoDLAgent, self).__init__(algorithm) 45 | self.inputs_data = np.zeros([self.batch_size, 46 | 1]).astype('int32') 47 | 48 | def build_program(self): 49 | """ 50 | build program 51 | """ 52 | self.predict_program = fluid.Program() 53 | self.train_program = fluid.Program() 54 | with fluid.program_guard(self.predict_program): 55 | self.predict_inputs = layers.data( 56 | name='input', 57 | append_batch_size=False, 58 | shape=[self.batch_size, 1], 59 | dtype='int32') 60 | self.predict_tokens, self.predict_adjvec = self.alg.define_predict( 61 | self.predict_inputs) 62 | 63 | with fluid.program_guard(self.train_program): 64 | self.train_inputs = layers.data( 65 | name='input', 66 | append_batch_size=False, 67 | shape=[self.batch_size, 1], 68 | dtype='int32') 69 | self.actions_to = layers.data( 70 | name='actions_to', 71 | append_batch_size=False, 72 | shape=[self.batch_size, 73 | self.num_nodes * 2], 74 | dtype='int32') 75 | self.actions_ad = layers.data( 76 | name='actions_ad', 77 | append_batch_size=False, 78 | shape=[self.batch_size, 79 | self.num_nodes * (self.num_nodes - 1)], 80 | dtype='int32') 81 | self.rewards = layers.data( 82 | name='rewards', 83 | append_batch_size=False, 84 | shape=[self.batch_size], 85 | dtype='float32') 86 | self.cost = self.alg.define_learn( 87 | obs=self.train_inputs, reward=self.rewards, 88 | action=[self.actions_to, self.actions_ad]) 89 | 90 | def sample(self): 91 | """ 92 | sample 93 | """ 94 | feed_dict = {'input': self.inputs_data} 95 | [actions_to, actions_ad] = self.fluid_executor.run( 96 | self.predict_program, feed=feed_dict, 97 | fetch_list=[self.predict_tokens, self.predict_adjvec]) 98 | return actions_to, actions_ad 99 | 100 | def learn(self, actions, reward): 101 | """ 102 | learn 103 | """ 104 | (actions_to, actions_ad) = actions 105 | feed_dict = {'input': self.inputs_data, 'actions_to': actions_to, 106 | 'actions_ad': actions_ad, 'rewards': reward} 107 | cost = self.fluid_executor.run( 108 | self.train_program, feed=feed_dict, fetch_list=[self.cost])[0] 109 | self.global_step += 1 110 | return cost 111 | -------------------------------------------------------------------------------- /AutoDL Design/cifar/dataset_maker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | Generate pkl files from cifar10 18 | """ 19 | import os 20 | import cPickle as pickle 21 | import random 22 | import numpy as np 23 | import sys 24 | import argparse 25 | 26 | 27 | def init_parser(): 28 | """ 29 | init_parser 30 | """ 31 | parser = argparse.ArgumentParser(description='Data generator') 32 | parser.add_argument('--chunk_size', dest="chunk_size", nargs="?", 33 | type=int, default=100, 34 | help="size of chunk") 35 | parser.add_argument('--input_dir', dest="input_dir", nargs="?", 36 | type=str, default='./cifar-10-batches-py', 37 | help="path of input") 38 | parser.add_argument('--output_dir', dest="output_dir", nargs="?", 39 | type=str, default='./pickle-cifar-10', 40 | help="path of output") 41 | parse_args, unknown_flags = parser.parse_known_args() 42 | return parse_args 43 | 44 | 45 | def get_file_names(input_dir): 46 | """ 47 | get all file names located in dir_path 48 | """ 49 | sub_name = 'data_batch' 50 | files = os.listdir(input_dir) 51 | names = [each_item for each_item in files if sub_name in each_item] 52 | return names 53 | 54 | 55 | def check_output_dir(output_dir): 56 | """ 57 | check exist of output dir 58 | """ 59 | if not os.path.exists(output_dir): 60 | os.makedirs(output_dir) 61 | 62 | 63 | def get_datasets(input_dir, chunk_size): 64 | """ 65 | get image datasets 66 | chunk_size is the number of each class 67 | """ 68 | total_size = chunk_size * 10 69 | names = get_file_names(parse_args.input_dir) 70 | img_count = 0 71 | datasets = [] 72 | class_map = {i: 0 for i in range(10)} 73 | for name in names: 74 | print("Reading file " + name) 75 | batch = pickle.load(open(input_dir + "/" + name, 'rb')) 76 | data = batch['data'] 77 | labels = batch.get('labels', batch.get('fine_labels', None)) 78 | assert labels is not None 79 | data_tuples = zip(data, labels) 80 | for data in data_tuples: 81 | if class_map[data[1]] < chunk_size: 82 | datasets.append(data) 83 | class_map[data[1]] += 1 84 | img_count += 1 85 | if img_count >= total_size: 86 | random.shuffle(datasets) 87 | for k, v in class_map.items(): 88 | print("label:{} count:{}".format(k, v)) 89 | return np.array(datasets) 90 | random.shuffle(datasets) 91 | return np.array(datasets) 92 | 93 | 94 | def dump_pkl(datasets, output_dir): 95 | """ 96 | dump_pkl 97 | """ 98 | chunk_size = parse_args.chunk_size 99 | for i in range(10): 100 | sub_dataset = datasets[i * chunk_size:(i + 1) * chunk_size, :] 101 | sub_dataset.dump(output_dir + "/" + 'data_batch_' + str(i) + '.pkl') 102 | 103 | 104 | if __name__ == "__main__": 105 | parse_args = init_parser() 106 | check_output_dir(parse_args.output_dir) 107 | datasets = get_datasets(parse_args.input_dir, parse_args.chunk_size) 108 | dump_pkl(datasets, parse_args.output_dir) 109 | -------------------------------------------------------------------------------- /AutoDL Design/distribute_generator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | Implementation of binomial and multinomial distribution 18 | """ 19 | 20 | import paddle.fluid as fluid 21 | import functools 22 | import numpy as np 23 | 24 | 25 | def create_tmp_var(name, dtype, shape, program=None): 26 | """ 27 | Create variable which is used to store the py_func result 28 | """ 29 | if program is None: 30 | return fluid.default_main_program().current_block().create_var( 31 | name=fluid.unique_name.generate(name), 32 | dtype=dtype, shape=shape) 33 | else: 34 | return program.current_block().create_var( 35 | name=fluid.unique_name.generate(name), 36 | dtype=dtype, shape=shape) 37 | 38 | 39 | def sigmoid(x): 40 | """ 41 | Sigmoid 42 | """ 43 | return (1 / (1 + np.exp(-x))) 44 | 45 | 46 | def softmax(x): 47 | """ 48 | Compute softmax values for each sets of scores in x. 49 | """ 50 | e_x = np.exp(x - np.max(x)) 51 | return e_x / e_x.sum() 52 | 53 | 54 | def py_func_bernoulli(input): 55 | """ 56 | Binormial python function definition 57 | """ 58 | prob_array = sigmoid(np.array(input)) 59 | sample = np.random.binomial(1, prob_array) 60 | return sample 61 | 62 | 63 | def bernoulli(input_logits, output_shape, program=None): 64 | """ 65 | Bernoulli 66 | """ 67 | # the output_shape is the same as input_logits 68 | samples_var = create_tmp_var(name='binomial_result_var', 69 | dtype='float32', shape=output_shape, 70 | program=program) 71 | fluid.layers.py_func(func=py_func_bernoulli, x=input_logits, 72 | out=samples_var, backward_func=None, 73 | skip_vars_in_backward_input=None) 74 | return samples_var 75 | 76 | 77 | def py_func_multinomial(logits, num_samples_var): 78 | """ 79 | Multinomial python function definition 80 | Input: 81 | input: list of [logits_array, num_samples_int] 82 | """ 83 | def generate(x, prob_array): 84 | """ 85 | Sample multinomial 86 | """ 87 | sample = np.random.multinomial(1, prob_array) 88 | ret = np.argmax(sample) 89 | return ret 90 | 91 | num_samples = int(np.array(num_samples_var)[0]) 92 | logits_array = np.array(logits) 93 | if len(logits_array.shape) != 2: 94 | raise Exception("Shape must be rank 2 but is rank {} \ 95 | for 'multinomial/Multinomial' (op: 'Multinomial') \ 96 | with input shapes:{}".format(len(logits_array.shape), 97 | logits_array.shape)) 98 | ret = np.array([]) 99 | for logits in logits_array: 100 | prob = softmax(logits) 101 | func = functools.partial(generate, prob_array=prob) 102 | sample = np.zeros(num_samples) 103 | sample = np.array(list(map(func, sample))) 104 | ret = np.append(ret, sample) 105 | ret = ret.reshape(-1, num_samples).astype("int32") 106 | return ret 107 | 108 | 109 | def multinomial(input_logits, output_shape, num_samples, program=None): 110 | """ 111 | Multinomial 112 | input_logits's dimension is [M * D] 113 | output_shape's dimension is [M * num_samples] 114 | """ 115 | samples_var = create_tmp_var(name='multinomial_result_var', 116 | dtype='int32', shape=output_shape, 117 | program=program) 118 | num_samples_var = fluid.layers.fill_constant(shape=[1], value=num_samples, 119 | dtype='int32') 120 | fluid.layers.py_func(func=py_func_multinomial, 121 | x=[input_logits, num_samples_var], 122 | out=samples_var, backward_func=None, 123 | skip_vars_in_backward_input=None) 124 | return samples_var 125 | -------------------------------------------------------------------------------- /AutoDL Design/img/cnn_net.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PaddlePaddle/AutoDL/b3d3f7ce6de485879c952d02c2c4c95ebe1a2f0c/AutoDL Design/img/cnn_net.png -------------------------------------------------------------------------------- /AutoDL Design/img/search_result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PaddlePaddle/AutoDL/b3d3f7ce6de485879c952d02c2c4c95ebe1a2f0c/AutoDL Design/img/search_result.png -------------------------------------------------------------------------------- /AutoDL Design/inception_train/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PaddlePaddle/AutoDL/b3d3f7ce6de485879c952d02c2c4c95ebe1a2f0c/AutoDL Design/inception_train/models/__init__.py -------------------------------------------------------------------------------- /AutoDL Design/inception_train/models/inception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | Inception Definition 18 | """ 19 | 20 | from __future__ import absolute_import 21 | from __future__ import division 22 | from __future__ import print_function 23 | 24 | import paddle.fluid as fluid 25 | from absl import flags 26 | import numpy as np 27 | import models.layers as layers 28 | import models.ops as _ops 29 | 30 | FLAGS = flags.FLAGS 31 | 32 | flags.DEFINE_integer("num_stages", 3, "number of stages") 33 | flags.DEFINE_integer("num_cells", 3, "number of cells per stage") 34 | flags.DEFINE_integer("width", 64, "network width") 35 | flags.DEFINE_integer("ratio", 4, "compression ratio") 36 | 37 | num_classes = 10 38 | 39 | ops = [ 40 | _ops.conv_1x1, 41 | _ops.conv_3x3, 42 | _ops.conv_5x5, 43 | _ops.dilated_3x3, 44 | _ops.conv_1x3_3x1, 45 | _ops.conv_1x5_5x1, 46 | _ops.maxpool_3x3, 47 | _ops.maxpool_5x5, 48 | _ops.avgpool_3x3, 49 | _ops.avgpool_5x5, 50 | ] 51 | 52 | 53 | def net(inputs, output, tokens, adjvec): 54 | """ 55 | create net 56 | """ 57 | num_nodes = len(tokens) // 2 58 | 59 | def slice(vec): 60 | """ 61 | slice vec 62 | """ 63 | mat = np.zeros([num_nodes, num_nodes]) 64 | 65 | def pos(x): 66 | """ 67 | pos 68 | """ 69 | return x * (x - 1) // 2 70 | for i in range(1, num_nodes): 71 | mat[0:i, i] = vec[pos(i):pos(i + 1)] 72 | return mat 73 | 74 | normal_to, reduce_to = np.split(tokens, 2) 75 | normal_ad, reduce_ad = map(slice, np.split(adjvec, 2)) 76 | 77 | x = layers.conv(inputs, FLAGS.width, (3, 3)) 78 | 79 | c = 1 80 | for _ in range(FLAGS.num_cells): 81 | x = cell(x, normal_to, normal_ad) 82 | c += 1 83 | for _ in range(1, FLAGS.num_stages): 84 | x = cell(x, reduce_to, reduce_ad, downsample=True) 85 | c += 1 86 | for _ in range(1, FLAGS.num_cells): 87 | x = cell(x, normal_to, normal_ad) 88 | c += 1 89 | 90 | x = layers.bn_relu(x) 91 | x = layers.global_avgpool(x) 92 | x = layers.dropout(x) 93 | logits = layers.fully_connected(x, num_classes) 94 | x = fluid.layers.softmax_with_cross_entropy(logits, output, 95 | numeric_stable_mode=True) 96 | loss = fluid.layers.reduce_mean(x) 97 | accuracy = fluid.layers.accuracy(input=logits, label=output) 98 | return loss, accuracy 99 | 100 | 101 | def cell(inputs, tokens, adjmat, downsample=False, name=None): 102 | """ 103 | cell 104 | """ 105 | filters = inputs.shape[1] 106 | d = filters // FLAGS.ratio 107 | 108 | num_nodes, tensors = len(adjmat), [] 109 | for n in range(num_nodes): 110 | func = ops[tokens[n]] 111 | idx, = np.nonzero(adjmat[:, n]) 112 | if len(idx) == 0: 113 | x = layers.bn_relu(inputs) 114 | x = layers.conv(x, d, (1, 1)) 115 | x = layers.bn_relu(x) 116 | x = func(x, downsample) 117 | else: 118 | x = fluid.layers.sums([tensors[i] for i in idx]) 119 | x = layers.bn_relu(x) 120 | x = func(x) 121 | tensors.append(x) 122 | 123 | free_ends, = np.where(~adjmat.any(axis=1)) 124 | tensors = [tensors[i] for i in free_ends] 125 | filters = filters * 2 if downsample else filters 126 | x = fluid.layers.concat(tensors, axis=1) 127 | x = layers.conv(x, filters, (1, 1)) 128 | return x 129 | -------------------------------------------------------------------------------- /AutoDL Design/inception_train/models/layers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | Layers Definition 18 | """ 19 | 20 | from __future__ import absolute_import 21 | from __future__ import division 22 | from __future__ import print_function 23 | 24 | import operator 25 | import numpy as np 26 | import paddle.fluid as fluid 27 | from absl import flags 28 | 29 | FLAGS = flags.FLAGS 30 | 31 | flags.DEFINE_float("weight_decay", 0.0001, 32 | "weight decay") 33 | flags.DEFINE_float("bn_decay", 0.9, 34 | "batch norm decay") 35 | flags.DEFINE_float("relu_leakiness", 0.1, 36 | "relu leakiness") 37 | flags.DEFINE_float("dropout_rate", 0.5, 38 | "dropout rate") 39 | 40 | 41 | def calc_padding(img_width, stride, dilation, filter_width): 42 | """ 43 | calculate pixels to padding in order to keep input/output size same. 44 | """ 45 | filter_width = dilation * (filter_width - 1) + 1 46 | if img_width % stride == 0: 47 | pad_along_width = max(filter_width - stride, 0) 48 | else: 49 | pad_along_width = max(filter_width - (img_width % stride), 0) 50 | return pad_along_width // 2, pad_along_width - pad_along_width // 2 51 | 52 | 53 | def conv(inputs, 54 | filters, 55 | kernel, 56 | strides=None, 57 | dilation=None, 58 | num_groups=1, 59 | conv_param=None, 60 | name=None): 61 | """ 62 | normal conv layer 63 | """ 64 | if strides is None: 65 | strides = (1, 1) 66 | if dilation is None: 67 | dilation = (1, 1) 68 | if isinstance(kernel, (tuple, list)): 69 | n = operator.mul(*kernel) * inputs.shape[1] 70 | else: 71 | n = kernel * kernel * inputs.shape[1] 72 | 73 | # pad input 74 | padding = (0, 0, 0, 0) \ 75 | + calc_padding(inputs.shape[2], strides[0], dilation[0], kernel[0]) \ 76 | + calc_padding(inputs.shape[3], strides[1], dilation[1], kernel[1]) 77 | if sum(padding) > 0: 78 | inputs = fluid.layers.pad(inputs, padding, 0) 79 | 80 | param_attr = fluid.param_attr.ParamAttr( 81 | initializer=fluid.initializer.TruncatedNormal( 82 | 0.0, scale=np.sqrt(2.0 / n)), 83 | regularizer=fluid.regularizer.L2Decay(FLAGS.weight_decay)) 84 | 85 | return fluid.layers.conv2d( 86 | inputs, 87 | filters, 88 | kernel, 89 | stride=strides, 90 | padding=0, 91 | dilation=dilation, 92 | groups=num_groups, 93 | param_attr=param_attr if conv_param is None else conv_param, 94 | use_cudnn=False if num_groups == inputs.shape[1] == filters else True, 95 | name=name) 96 | 97 | 98 | def sep(inputs, filters, kernel, strides=None, dilation=None, name=None): 99 | """ 100 | Separable convolution layer 101 | """ 102 | if strides is None: 103 | strides = (1, 1) 104 | if dilation is None: 105 | dilation = (1, 1) 106 | if isinstance(kernel, (tuple, list)): 107 | n_depth = operator.mul(*kernel) 108 | else: 109 | n_depth = kernel * kernel 110 | n_point = inputs.shape[1] 111 | 112 | if isinstance(strides, (tuple, list)): 113 | multiplier = strides[0] 114 | else: 115 | multiplier = strides 116 | 117 | depthwise_param = fluid.param_attr.ParamAttr( 118 | initializer=fluid.initializer.TruncatedNormal( 119 | 0.0, scale=np.sqrt(2.0 / n_depth)), 120 | regularizer=fluid.regularizer.L2Decay(FLAGS.weight_decay)) 121 | 122 | pointwise_param = fluid.param_attr.ParamAttr( 123 | initializer=fluid.initializer.TruncatedNormal( 124 | 0.0, scale=np.sqrt(2.0 / n_point)), 125 | regularizer=fluid.regularizer.L2Decay(FLAGS.weight_decay)) 126 | 127 | depthwise_conv = conv( 128 | inputs=inputs, 129 | kernel=kernel, 130 | filters=int(filters * multiplier), 131 | strides=strides, 132 | dilation=dilation, 133 | num_groups=int(filters * multiplier), 134 | conv_param=depthwise_param, 135 | name='depthwise_' + name) 136 | 137 | return conv( 138 | inputs=depthwise_conv, 139 | kernel=(1, 1), 140 | filters=int(filters * multiplier), 141 | strides=(1, 1), 142 | dilation=dilation, 143 | conv_param=pointwise_param, 144 | name='pointwise_' + name) 145 | 146 | 147 | def maxpool(inputs, kernel, strides=None, name=None): 148 | """ 149 | maxpool 150 | """ 151 | if strides is None: 152 | strides = (1, 1) 153 | padding = (0, 0, 0, 0) \ 154 | + calc_padding(inputs.shape[2], strides[0], 1, kernel[0]) \ 155 | + calc_padding(inputs.shape[3], strides[1], 1, kernel[1]) 156 | if sum(padding) > 0: 157 | inputs = fluid.layers.pad(inputs, padding, 0) 158 | 159 | return fluid.layers.pool2d( 160 | inputs, kernel, 'max', strides, pool_padding=0, 161 | ceil_mode=False, name=name) 162 | 163 | 164 | def avgpool(inputs, kernel, strides=None, name=None): 165 | """ 166 | avgpool 167 | """ 168 | if strides is None: 169 | strides = (1, 1) 170 | padding_pixel = (0, 0, 0, 0) 171 | padding_pixel += calc_padding(inputs.shape[2], strides[0], 1, kernel[0]) 172 | padding_pixel += calc_padding(inputs.shape[3], strides[1], 1, kernel[1]) 173 | 174 | if padding_pixel[4] == padding_pixel[5] and padding_pixel[ 175 | 6] == padding_pixel[7]: 176 | # same padding pixel num on all sides. 177 | return fluid.layers.pool2d( 178 | inputs, 179 | kernel, 180 | 'avg', 181 | strides, 182 | pool_padding=(padding_pixel[4], padding_pixel[6]), 183 | ceil_mode=False) 184 | elif padding_pixel[4] + 1 == padding_pixel[5] \ 185 | and padding_pixel[6] + 1 == padding_pixel[7] \ 186 | and strides == (1, 1): 187 | # different padding size: first pad then crop. 188 | x = fluid.layers.pool2d( 189 | inputs, 190 | kernel, 191 | 'avg', 192 | strides, 193 | pool_padding=(padding_pixel[5], padding_pixel[7]), 194 | ceil_mode=False) 195 | x_shape = x.shape 196 | return fluid.layers.crop( 197 | x, 198 | shape=(-1, x_shape[1], x_shape[2] - 1, x_shape[3] - 1), 199 | offsets=(0, 0, 1, 1), name=name) 200 | else: 201 | # not support. use padding-zero and pool2d. 202 | print("Warning: use zero-padding in avgpool") 203 | outputs = fluid.layers.pad(inputs, padding_pixel, 0) 204 | return fluid.layers.pool2d( 205 | outputs, kernel, 'avg', strides, pool_padding=0, 206 | ceil_mode=False, name=name) 207 | 208 | 209 | def global_avgpool(inputs, name=None): 210 | """ 211 | global avgpool 212 | """ 213 | return fluid.layers.reduce_mean(inputs, dim=[2, 3], name=name) 214 | 215 | 216 | def fully_connected(inputs, units, name=None): 217 | """ 218 | fully connected 219 | """ 220 | n = inputs.shape[1] 221 | param_attr = fluid.param_attr.ParamAttr( 222 | initializer=fluid.initializer.TruncatedNormal( 223 | 0.0, scale=np.sqrt(2.0 / n)), 224 | regularizer=fluid.regularizer.L2Decay(FLAGS.weight_decay)) 225 | 226 | return fluid.layers.fc(inputs, 227 | units, 228 | param_attr=param_attr) 229 | 230 | 231 | def batch_norm(inputs, name=None): 232 | """ 233 | batch norm 234 | """ 235 | param_attr = fluid.param_attr.ParamAttr( 236 | regularizer=fluid.regularizer.L2Decay(FLAGS.weight_decay)) 237 | bias_attr = fluid.param_attr.ParamAttr( 238 | regularizer=fluid.regularizer.L2Decay(FLAGS.weight_decay)) 239 | 240 | return fluid.layers.batch_norm( 241 | inputs, momentum=FLAGS.bn_decay, epsilon=0.001, 242 | param_attr=param_attr, 243 | bias_attr=bias_attr) 244 | 245 | 246 | def relu(inputs, name=None): 247 | """ 248 | relu 249 | """ 250 | if FLAGS.relu_leakiness: 251 | return fluid.layers.leaky_relu(inputs, FLAGS.relu_leakiness, name=name) 252 | return fluid.layers.relu(inputs, name=name) 253 | 254 | 255 | def bn_relu(inputs, name=None): 256 | """ 257 | batch norm + rely layer 258 | """ 259 | output = batch_norm(inputs) 260 | return fluid.layers.relu(output, name=name) 261 | 262 | 263 | def dropout(inputs, name=None): 264 | """ 265 | dropout layer 266 | """ 267 | return fluid.layers.dropout(inputs, dropout_prob=FLAGS.dropout_rate, 268 | dropout_implementation='upscale_in_train', 269 | name=name) 270 | -------------------------------------------------------------------------------- /AutoDL Design/inception_train/models/ops.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | Base Ops Definition 18 | """ 19 | 20 | from __future__ import absolute_import 21 | from __future__ import division 22 | from __future__ import print_function 23 | 24 | import models.layers as layers 25 | 26 | 27 | def conv_1x1(inputs, downsample=False): 28 | """ 29 | conv_1x1 30 | """ 31 | return conv_base(inputs, (1, 1), downsample=downsample) 32 | 33 | 34 | def conv_2x2(inputs, downsample=False): 35 | """ 36 | conv_2x2 37 | """ 38 | return conv_base(inputs, (2, 2), downsample=downsample) 39 | 40 | 41 | def conv_3x3(inputs, downsample=False): 42 | """ 43 | conv_3x3 44 | """ 45 | return conv_base(inputs, (3, 3), downsample=downsample) 46 | 47 | 48 | def conv_4x4(inputs, downsample=False): 49 | """ 50 | conv_4x4 51 | """ 52 | return conv_base(inputs, (4, 4), downsample=downsample) 53 | 54 | 55 | def conv_5x5(inputs, downsample=False): 56 | """ 57 | conv_5x5 58 | """ 59 | return conv_base(inputs, (5, 5), downsample=downsample) 60 | 61 | 62 | def dilated_2x2(inputs, downsample=False): 63 | """ 64 | dilated_2x2 65 | """ 66 | return conv_base(inputs, (2, 2), (2, 2), downsample) 67 | 68 | 69 | def dilated_3x3(inputs, downsample=False): 70 | """ 71 | dilated_3x3 72 | """ 73 | return conv_base(inputs, (3, 3), (2, 2), downsample) 74 | 75 | 76 | def conv_1x2_2x1(inputs, downsample=False): 77 | """ 78 | conv_1x2_2x1 79 | """ 80 | return pair_base(inputs, 2, downsample) 81 | 82 | 83 | def conv_1x3_3x1(inputs, downsample=False): 84 | """ 85 | conv_1x3_3x1 86 | """ 87 | return pair_base(inputs, 3, downsample) 88 | 89 | 90 | def conv_1x4_4x1(inputs, downsample=False): 91 | """ 92 | conv_1x4_4x1 93 | """ 94 | return pair_base(inputs, 4, downsample) 95 | 96 | 97 | def conv_1x5_5x1(inputs, downsample=False): 98 | """ 99 | conv_1x5_5x1 100 | """ 101 | return pair_base(inputs, 5, downsample) 102 | 103 | 104 | def sep_2x2(inputs, downsample=False): 105 | """ 106 | sep_2x2 107 | """ 108 | return sep_base(inputs, (2, 2), downsample=downsample) 109 | 110 | 111 | def sep_3x3(inputs, downsample=False): 112 | """ 113 | sep_3x3 114 | """ 115 | return sep_base(inputs, (3, 3), downsample=downsample) 116 | 117 | 118 | def sep_4x4(inputs, downsample=False): 119 | """ 120 | sep_4x4 121 | """ 122 | return sep_base(inputs, (4, 4), downsample=downsample) 123 | 124 | 125 | def sep_5x5(inputs, downsample=False): 126 | """ 127 | sep_5x5 128 | """ 129 | return sep_base(inputs, (5, 5), downsample=downsample) 130 | 131 | 132 | def maxpool_2x2(inputs, downsample=False): 133 | """ 134 | maxpool_2x2 135 | """ 136 | return maxpool_base(inputs, (2, 2), downsample) 137 | 138 | 139 | def maxpool_3x3(inputs, downsample=False): 140 | """ 141 | maxpool_3x3 142 | """ 143 | return maxpool_base(inputs, (3, 3), downsample) 144 | 145 | 146 | def maxpool_4x4(inputs, downsample=False): 147 | """ 148 | maxpool_4x4 149 | """ 150 | return maxpool_base(inputs, (4, 4), downsample) 151 | 152 | 153 | def maxpool_5x5(inputs, downsample=False): 154 | """ 155 | maxpool_5x5 156 | """ 157 | return maxpool_base(inputs, (5, 5), downsample) 158 | 159 | 160 | def avgpool_2x2(inputs, downsample=False): 161 | """ 162 | avgpool_2x2 163 | """ 164 | return avgpool_base(inputs, (2, 2), downsample) 165 | 166 | 167 | def avgpool_3x3(inputs, downsample=False): 168 | """ 169 | avgpool_3x3 170 | """ 171 | return avgpool_base(inputs, (3, 3), downsample) 172 | 173 | 174 | def avgpool_4x4(inputs, downsample=False): 175 | """ 176 | avgpool_4x4 177 | """ 178 | return avgpool_base(inputs, (4, 4), downsample) 179 | 180 | 181 | def avgpool_5x5(inputs, downsample=False): 182 | """ 183 | avgpool_5x5 184 | """ 185 | return avgpool_base(inputs, (5, 5), downsample) 186 | 187 | 188 | def conv_base(inputs, kernel, dilation=None, downsample=False): 189 | """ 190 | conv_base 191 | """ 192 | if dilation is None: 193 | dilation = (1, 1) 194 | filters = inputs.shape[1] 195 | if downsample: 196 | output = layers.conv(inputs, filters * 2, kernel, (2, 2)) 197 | else: 198 | output = layers.conv(inputs, filters, kernel, dilation=dilation) 199 | return output 200 | 201 | 202 | def pair_base(inputs, kernel, downsample=False): 203 | """ 204 | pair_base 205 | """ 206 | filters = inputs.shape[1] 207 | if downsample: 208 | output = layers.conv(inputs, filters, (1, kernel), (1, 2)) 209 | output = layers.conv(output, filters, (kernel, 1), (2, 1)) 210 | output = layers.conv(output, filters * 2, (1, 1)) 211 | else: 212 | output = layers.conv(inputs, filters, (1, kernel)) 213 | output = layers.conv(output, filters, (kernel, 1)) 214 | return output 215 | 216 | 217 | def sep_base(inputs, kernel, dilation=None, downsample=False): 218 | """ 219 | sep_base 220 | """ 221 | if dilation is None: 222 | dilation = (1, 1) 223 | filters = inputs.shape[1] 224 | if downsample: 225 | output = layers.sep(inputs, filters * 2, kernel, (2, 2)) 226 | else: 227 | output = layers.sep(inputs, filters, kernel, dilation=dilation) 228 | return output 229 | 230 | 231 | def maxpool_base(inputs, kernel, downsample=False): 232 | """ 233 | maxpool_base 234 | """ 235 | if downsample: 236 | filters = inputs.shape[1] 237 | output = layers.maxpool(inputs, kernel, (2, 2)) 238 | output = layers.conv(output, filters * 2, (1, 1)) 239 | else: 240 | output = layers.maxpool(inputs, kernel) 241 | return output 242 | 243 | 244 | def avgpool_base(inputs, kernel, downsample=False): 245 | """ 246 | avgpool_base 247 | """ 248 | if downsample: 249 | filters = inputs.shape[1] 250 | output = layers.avgpool(inputs, kernel, (2, 2)) 251 | output = layers.conv(output, filters * 2, (1, 1)) 252 | else: 253 | output = layers.avgpool(inputs, kernel) 254 | return output 255 | -------------------------------------------------------------------------------- /AutoDL Design/inception_train/nn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | Network Definition 18 | """ 19 | 20 | from __future__ import absolute_import 21 | from __future__ import division 22 | from __future__ import print_function 23 | 24 | import cPickle as cp 25 | import paddle.fluid as fluid 26 | import paddle.fluid.layers.ops as ops 27 | import paddle.fluid as fluid 28 | from paddle.fluid.layers.learning_rate_scheduler import _decay_step_counter 29 | import math 30 | from models import inception 31 | from absl import flags 32 | 33 | FLAGS = flags.FLAGS 34 | 35 | flags.DEFINE_float("lr_max", 0.1, 36 | "initial learning rate") 37 | flags.DEFINE_float("lr_min", 0.0001, 38 | "limiting learning rate") 39 | flags.DEFINE_integer("batch_size", 128, 40 | "batch size") 41 | flags.DEFINE_integer("T_0", 200, 42 | "number of epochs") 43 | flags.DEFINE_integer("chunk_size", 100, 44 | "chunk size") 45 | 46 | 47 | class CIFARModel(object): 48 | """ 49 | CIFARModel class 50 | """ 51 | def __init__(self, tokens, adjvec, im_shape): 52 | """ 53 | CIFARModel init 54 | """ 55 | chunk_size = FLAGS.chunk_size 56 | self.batch_size = FLAGS.batch_size 57 | self.tokens = tokens 58 | self.adjvec = adjvec 59 | self.im_shape = im_shape 60 | max_step = chunk_size * 9 * FLAGS.T_0 // FLAGS.batch_size 61 | test_batch = chunk_size // FLAGS.batch_size 62 | 63 | def cosine_decay(): 64 | """ 65 | Applies cosine decay to the learning rate. 66 | """ 67 | global_step = _decay_step_counter() 68 | frac = (1 + ops.cos(global_step / max_step * math.pi)) / 2 69 | return FLAGS.lr_min + (FLAGS.lr_max - FLAGS.lr_min) * frac 70 | 71 | self.lr_strategy = cosine_decay 72 | 73 | def fn_model(self, py_reader): 74 | """ 75 | fn model 76 | """ 77 | self.image, self.label = fluid.layers.read_file(py_reader) 78 | self.loss, self.accuracy = inception.net( 79 | self.image, self.label, self.tokens, self.adjvec) 80 | return self.loss, self.accuracy 81 | 82 | def build_input(self, image_shape, is_train): 83 | """ 84 | build_input 85 | """ 86 | name = 'train_reader' if is_train else 'test_reader' 87 | py_reader = fluid.layers.py_reader( 88 | capacity=64, 89 | shapes=[[-1] + image_shape, [-1, 1]], 90 | lod_levels=[0, 0], 91 | dtypes=["float32", "int64"], 92 | use_double_buffer=True, 93 | name=name) 94 | return py_reader 95 | 96 | def build_program(self, main_prog, startup_prog, is_train): 97 | """ 98 | build_program 99 | """ 100 | out = [] 101 | with fluid.program_guard(main_prog, startup_prog): 102 | py_reader = self.build_input(self.im_shape, is_train) 103 | if is_train: 104 | with fluid.unique_name.guard(): 105 | loss, accuracy = self.fn_model(py_reader) 106 | optimizer = fluid.optimizer.Momentum( 107 | learning_rate=self.lr_strategy(), 108 | momentum=0.9, 109 | use_nesterov=True) 110 | optimizer.minimize(loss) 111 | out = [py_reader, loss, accuracy] 112 | else: 113 | with fluid.unique_name.guard(): 114 | loss, accuracy = self.fn_model(py_reader) 115 | out = [py_reader, loss, accuracy] 116 | return out 117 | -------------------------------------------------------------------------------- /AutoDL Design/inception_train/preprocess.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | Data preprocess 18 | """ 19 | 20 | from __future__ import absolute_import 21 | from __future__ import division 22 | from __future__ import print_function 23 | 24 | from absl import flags 25 | from PIL import Image 26 | from PIL import ImageOps 27 | from PIL import ImageEnhance 28 | import numpy as np 29 | 30 | FLAGS = flags.FLAGS 31 | 32 | flags.DEFINE_boolean("random_flip_left_right", True, 33 | "random flip left and right") 34 | flags.DEFINE_boolean("random_flip_up_down", False, 35 | "random flip up and down") 36 | flags.DEFINE_boolean("random_brightness", False, 37 | "randomly adjust brightness") 38 | image_size = 32 39 | 40 | 41 | def augmentation(sample, is_training): 42 | """ 43 | augmentation 44 | """ 45 | image_array = sample.reshape(3, image_size, image_size) 46 | rgb_array = np.transpose(image_array, (1, 2, 0)) 47 | img = Image.fromarray(rgb_array, 'RGB') 48 | 49 | if is_training: 50 | # pad and crop 51 | img = ImageOps.expand(img, (4, 4, 4, 4), fill=0) # pad to 40 * 40 * 3 52 | left_top = np.random.randint(9, size=2) # rand 0 - 8 53 | img = img.crop((left_top[0], left_top[1], left_top[0] + image_size, 54 | left_top[1] + image_size)) 55 | 56 | if FLAGS.random_flip_left_right: 57 | if np.random.randint(2): 58 | img = img.transpose(Image.FLIP_LEFT_RIGHT) 59 | if FLAGS.random_flip_up_down: 60 | if np.random.randint(2): 61 | img = img.transpose(Image.FLIP_TOP_BOTTOM) 62 | if FLAGS.random_brightness: 63 | delta = np.random.uniform(-0.3, 0.3) + 1. 64 | img = ImageEnhance.Brightness(img).enhance(delta) 65 | 66 | img = np.array(img).astype(np.float32) 67 | 68 | # per_image_standardization 69 | img_float = img / 255.0 70 | num_pixels = img_float.size 71 | img_mean = img_float.mean() 72 | img_std = img_float.std() 73 | scale = np.maximum(np.sqrt(num_pixels), img_std) 74 | img = (img_float - img_mean) / scale 75 | 76 | img = np.transpose(img, (2, 0, 1)) 77 | return img 78 | -------------------------------------------------------------------------------- /AutoDL Design/inception_train/reader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rig hts Reserved 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | # Based on: 18 | # -------------------------------------------------------- 19 | # DARTS 20 | # Copyright (c) 2018, Hanxiao Liu. 21 | # Licensed under the Apache License, Version 2.0; 22 | # -------------------------------------------------------- 23 | """ 24 | CIFAR-10 dataset. 25 | This module will download dataset from 26 | https://www.cs.toronto.edu/~kriz/cifar.html and parse train/test set into 27 | paddle reader creators. 28 | The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, 29 | with 6000 images per class. There are 50000 training images 30 | and 10000 test images. 31 | """ 32 | 33 | import numpy as np 34 | try: 35 | import cPickle as pickle 36 | except ImportError: 37 | import pickle 38 | import random 39 | import utils 40 | import paddle.fluid as fluid 41 | import os 42 | from preprocess import augmentation 43 | 44 | 45 | def reader_creator_filepath(filename, sub_name, is_training, 46 | batch_size, data_list): 47 | """ 48 | reader creator 49 | """ 50 | dataset = [] 51 | for name in data_list: 52 | print("Reading file " + name) 53 | file_path = os.path.join(filename, name) 54 | batch_data = pickle.load(open(file_path)) 55 | dataset.append(batch_data) 56 | datasets = np.concatenate(dataset) 57 | if is_training: 58 | np.random.shuffle(dataset) 59 | 60 | def read_batch(datasets, is_training): 61 | """ 62 | read batch 63 | """ 64 | for sample, label in datasets: 65 | im = augmentation(sample, is_training) 66 | yield im, [int(label)] 67 | 68 | def reader(): 69 | """ 70 | get reader 71 | """ 72 | batch_data = [] 73 | batch_label = [] 74 | for data, label in read_batch(datasets, is_training): 75 | batch_data.append(data) 76 | batch_label.append(label) 77 | if len(batch_data) == batch_size: 78 | batch_data = np.array(batch_data, dtype='float32') 79 | batch_label = np.array(batch_label, dtype='int64') 80 | batch_out = [[batch_data, batch_label]] 81 | yield batch_out 82 | batch_data = [] 83 | batch_label = [] 84 | if len(batch_data) != 0: 85 | batch_data = np.array(batch_data, dtype='float32') 86 | batch_label = np.array(batch_label, dtype='int64') 87 | batch_out = [[batch_data, batch_label]] 88 | yield batch_out 89 | batch_data = [] 90 | batch_label = [] 91 | return reader 92 | 93 | 94 | def train10(data, batch_size, data_list): 95 | """ 96 | CIFAR-10 training set creator. 97 | It returns a reader creator, each sample in the reader is image pixels in 98 | [0, 1] and label in [0, 9]. 99 | :return: Training reader creator 100 | :rtype: callable 101 | """ 102 | return reader_creator_filepath(data, 'data_batch', True, 103 | batch_size, data_list) 104 | 105 | 106 | def test10(data, batch_size, data_list): 107 | """ 108 | CIFAR-10 test set creator. 109 | It returns a reader creator, each sample in the reader is image pixels in 110 | [0, 1] and label in [0, 9]. 111 | :return: Test reader creator. 112 | :rtype: callable 113 | """ 114 | return reader_creator_filepath(data, 'test_batch', False, 115 | batch_size, data_list) 116 | -------------------------------------------------------------------------------- /AutoDL Design/inception_train/train.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | Trainer Definition 18 | """ 19 | 20 | from __future__ import absolute_import 21 | from __future__ import division 22 | from __future__ import print_function 23 | import numpy as np 24 | import reader 25 | import sys 26 | import os 27 | import time 28 | import paddle.fluid as fluid 29 | import utils 30 | import cPickle as cp 31 | from absl import flags 32 | from absl import app 33 | from nn import CIFARModel 34 | 35 | FLAGS = flags.FLAGS 36 | flags.DEFINE_string("data_path", 37 | "./cifar/pickle-cifar-10", 38 | "data path") 39 | flags.DEFINE_string("logdir", "log", 40 | "logging directory") 41 | flags.DEFINE_integer("mid", 0, 42 | "model id") 43 | flags.DEFINE_integer("early_stop", 20, 44 | "early stop") 45 | 46 | image_size = 32 47 | 48 | 49 | def main(_): 50 | """ 51 | main 52 | """ 53 | image_shape = [3, image_size, image_size] 54 | files = os.listdir(FLAGS.data_path) 55 | names = [each_item for each_item in files] 56 | np.random.shuffle(names) 57 | train_list = names[:9] 58 | test_list = names[-1] 59 | tokens, adjvec = utils.load_action(FLAGS.mid) 60 | 61 | model = CIFARModel(tokens, adjvec, image_shape) 62 | 63 | place = fluid.CUDAPlace(0) 64 | exe = fluid.Executor(place) 65 | 66 | startup = fluid.Program() 67 | train_prog = fluid.Program() 68 | test_prog = fluid.Program() 69 | train_vars = model.build_program(train_prog, startup, True) 70 | test_vars = model.build_program(test_prog, startup, False) 71 | exe.run(startup) 72 | 73 | train_accuracy, epoch_id = train(model, FLAGS.early_stop, 74 | train_prog, train_vars, exe, train_list) 75 | if epoch_id < FLAGS.early_stop: 76 | utils.dump_reward(FLAGS.mid, train_accuracy) 77 | else: 78 | test_accuracy = test(model, test_prog, test_vars, exe, [test_list]) 79 | utils.dump_reward(FLAGS.mid, test_accuracy) 80 | 81 | 82 | def train(model, epoch_num, train_prog, train_vars, exe, data_list): 83 | """ 84 | train 85 | """ 86 | train_py_reader, loss_train, acc_train = train_vars 87 | exec_strategy = fluid.ExecutionStrategy() 88 | exec_strategy.num_threads = 1 89 | build_strategy = fluid.BuildStrategy() 90 | build_strategy.memory_optimize = False 91 | build_strategy.enable_inplace = True 92 | train_exe = fluid.ParallelExecutor( 93 | main_program=train_prog, 94 | use_cuda=True, 95 | loss_name=loss_train.name, 96 | exec_strategy=exec_strategy, 97 | build_strategy=build_strategy) 98 | 99 | train_reader = reader.train10(FLAGS.data_path, FLAGS.batch_size, data_list) 100 | train_py_reader.decorate_paddle_reader(train_reader) 101 | 102 | train_fetch_list = [loss_train, acc_train] 103 | epoch_start_time = time.time() 104 | for epoch_id in range(epoch_num): 105 | train_py_reader.start() 106 | epoch_end_time = time.time() 107 | if epoch_id > 0: 108 | print("Epoch {}, total time {}".format(epoch_id - 1, epoch_end_time 109 | - epoch_start_time)) 110 | epoch_start_time = epoch_end_time 111 | epoch_end_time 112 | start_time = time.time() 113 | step_id = 0 114 | try: 115 | while True: 116 | prev_start_time = start_time 117 | start_time = time.time() 118 | loss_v, acc_v = train_exe.run( 119 | fetch_list=[v.name for v in train_fetch_list]) 120 | if np.isnan(np.array(loss_v).mean()): 121 | format_str = "[%s] jobs done, step = %d, loss = nan" 122 | print(format_str % (utils.stime(), step_id)) 123 | return np.array(acc_v).mean(), epoch_id 124 | print("Epoch {}, Step {}, loss {}, acc {}, time {}".format( 125 | epoch_id, step_id, np.array(loss_v).mean(), 126 | np.array(acc_v).mean(), start_time - prev_start_time)) 127 | step_id += 1 128 | sys.stdout.flush() 129 | except fluid.core.EOFException: 130 | train_py_reader.reset() 131 | return np.array(acc_v).mean(), epoch_id 132 | 133 | 134 | def test(model, test_prog, test_vars, exe, data_list): 135 | """ 136 | test 137 | """ 138 | test_py_reader, loss_test, acc_test = test_vars 139 | test_prog = test_prog.clone(for_test=True) 140 | objs = utils.AvgrageMeter() 141 | 142 | test_reader = reader.test10(FLAGS.data_path, FLAGS.batch_size, data_list) 143 | test_py_reader.decorate_paddle_reader(test_reader) 144 | 145 | test_py_reader.start() 146 | test_fetch_list = [acc_test] 147 | test_start_time = time.time() 148 | step_id = 0 149 | try: 150 | while True: 151 | prev_test_start_time = test_start_time 152 | test_start_time = time.time() 153 | acc_v, = exe.run( 154 | test_prog, fetch_list=test_fetch_list) 155 | objs.update(np.array(acc_v), np.array(acc_v).shape[0]) 156 | step_id += 1 157 | except fluid.core.EOFException: 158 | test_py_reader.reset() 159 | print("test acc {0}".format(objs.avg)) 160 | return objs.avg 161 | 162 | 163 | if __name__ == '__main__': 164 | app.run(main) 165 | -------------------------------------------------------------------------------- /AutoDL Design/inception_train/utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | """ 12 | Utils Definition 13 | """ 14 | 15 | import os 16 | import pickle 17 | import time 18 | from absl import flags 19 | 20 | FLAGS = flags.FLAGS 21 | 22 | 23 | def stime(): 24 | """ 25 | stime 26 | """ 27 | return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) 28 | 29 | 30 | def load_action(mid): 31 | """ 32 | load action by mid 33 | """ 34 | filename = os.path.join(FLAGS.logdir, "actions", "%d.pkl" % mid) 35 | return pickle.load(open(filename, "rb")) 36 | 37 | 38 | def dump_action(mid, action): 39 | """ 40 | dump action 41 | """ 42 | filename = os.path.join(FLAGS.logdir, "actions", "%d.pkl" % mid) 43 | pickle.dump(action, open(filename, "wb")) 44 | 45 | 46 | def dump_reward(mid, reward): 47 | """ 48 | dump reward 49 | """ 50 | filename = os.path.join(FLAGS.logdir, "rewards", "%d.pkl" % mid) 51 | pickle.dump(reward, open(filename, "wb")) 52 | 53 | 54 | class AvgrageMeter(object): 55 | """ 56 | AvgrageMeter for test 57 | """ 58 | def __init__(self): 59 | """ 60 | init 61 | """ 62 | self.reset() 63 | 64 | def reset(self): 65 | """ 66 | reset 67 | """ 68 | self.avg = 0 69 | self.sum = 0 70 | self.cnt = 0 71 | 72 | def update(self, val, n=1): 73 | """ 74 | update 75 | """ 76 | self.sum += val * n 77 | self.cnt += n 78 | self.avg = self.sum / self.cnt 79 | -------------------------------------------------------------------------------- /AutoDL Design/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | AutoDL main definition 18 | """ 19 | from __future__ import absolute_import 20 | from __future__ import division 21 | from __future__ import print_function 22 | 23 | import os 24 | import sys 25 | import traceback 26 | import autodl 27 | 28 | if __name__ == "__main__": 29 | try: 30 | autodl_exe = autodl.AutoDL() 31 | autodl_exe.run() 32 | except Exception as e: 33 | print(str(e)) 34 | traceback.print_exc() 35 | -------------------------------------------------------------------------------- /AutoDL Design/policy_model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | PolicyModel definition 18 | """ 19 | 20 | from __future__ import absolute_import 21 | from __future__ import division 22 | from __future__ import print_function 23 | 24 | import os 25 | import sys 26 | import numpy as np 27 | import paddle.fluid as fluid 28 | from parl.framework.model_base import Model 29 | import distribute_generator 30 | 31 | 32 | class LstmUnit(object): 33 | """ 34 | implemetation of lstm unit 35 | """ 36 | def __init__(self, input_size, hidden_size, num_layers=1, 37 | init_scale=0.1): 38 | """ 39 | init 40 | """ 41 | self.weight_1_arr = [] 42 | self.bias_1_arr = [] 43 | for i in range(num_layers): 44 | weight_1 = fluid.layers.create_parameter( 45 | [input_size + hidden_size, hidden_size * 4], 46 | dtype="float32", 47 | name="fc_weight1_" + str(i), 48 | default_initializer=fluid.initializer.UniformInitializer( 49 | low=-init_scale, 50 | high=init_scale)) 51 | input_size = hidden_size 52 | self.weight_1_arr.append(weight_1) 53 | bias_1 = fluid.layers.create_parameter( 54 | [hidden_size * 4], 55 | dtype="float32", 56 | name="fc_bias1_" + str(i), 57 | default_initializer=fluid.initializer.Constant(0.0)) 58 | self.bias_1_arr.append(bias_1) 59 | 60 | self.num_layers = num_layers 61 | self.hidden_size = hidden_size 62 | 63 | def lstm_step(self, inputs, hidden, cell): 64 | """ 65 | lstm step 66 | """ 67 | hidden_array = [] 68 | cell_array = [] 69 | for i in range(self.num_layers): 70 | hidden_temp = fluid.layers.slice(hidden, axes=[0], starts=[i], 71 | ends=[i + 1]) 72 | hidden_temp = fluid.layers.reshape(hidden_temp, 73 | shape=[-1, self.hidden_size]) 74 | hidden_array.append(hidden_temp) 75 | 76 | cell_temp = fluid.layers.slice(cell, axes=[0], starts=[i], 77 | ends=[i + 1]) 78 | cell_temp = fluid.layers.reshape(cell_temp, 79 | shape=[-1, self.hidden_size]) 80 | cell_array.append(cell_temp) 81 | 82 | last_hidden_array = [] 83 | step_input = inputs 84 | for k in range(self.num_layers): 85 | pre_hidden = hidden_array[k] 86 | pre_cell = cell_array[k] 87 | weight = self.weight_1_arr[k] 88 | bias = self.bias_1_arr[k] 89 | 90 | nn = fluid.layers.concat([step_input, pre_hidden], 1) 91 | gate_input = fluid.layers.matmul(x=nn, y=weight) 92 | 93 | gate_input = fluid.layers.elementwise_add(gate_input, bias) 94 | i, j, f, o = fluid.layers.split(gate_input, num_or_sections=4, 95 | dim=-1) 96 | 97 | c = pre_cell * fluid.layers.sigmoid(f) + fluid.layers.sigmoid(i) \ 98 | * fluid.layers.tanh(j) 99 | m = fluid.layers.tanh(c) * fluid.layers.sigmoid(o) 100 | 101 | hidden_array[k] = m 102 | cell_array[k] = c 103 | step_input = m 104 | 105 | last_hidden = fluid.layers.concat(hidden_array, axis=0) 106 | last_hidden = fluid.layers.reshape(last_hidden, shape=[ 107 | self.num_layers, -1, self.hidden_size]) 108 | 109 | last_cell = fluid.layers.concat(cell_array, axis=0) 110 | last_cell = fluid.layers.reshape( 111 | last_cell, 112 | shape=[self.num_layers, -1, self.hidden_size]) 113 | return step_input, last_hidden, last_cell 114 | 115 | def __call__(self, inputs, hidden, cell): 116 | """ 117 | lstm step call 118 | """ 119 | return self.lstm_step(inputs, hidden, cell) 120 | 121 | 122 | class PolicyModel(Model): 123 | """ 124 | PolicyModel 125 | """ 126 | def __init__(self, parser_args): 127 | """ 128 | construct rnn net 129 | """ 130 | self.parser_args = parser_args 131 | 132 | def policy(self, inputs): 133 | """ 134 | policy function is used by `define_predict` in PolicyGradient 135 | """ 136 | [tokens, softmax, adjvec, sigmoid] = self.build_rnn(inputs) 137 | return [tokens, softmax, adjvec, sigmoid] 138 | 139 | def build_rnn(self, inputs): 140 | """ 141 | build rnn net 142 | """ 143 | batch_size = self.parser_args.batch_size 144 | input_size = self.parser_args.input_size 145 | hidden_size = self.parser_args.hidden_size 146 | num_layers = self.parser_args.num_layers 147 | num_nodes = self.parser_args.num_nodes 148 | num_tokens = self.parser_args.num_tokens 149 | 150 | depth = max(num_nodes - 1, num_tokens) 151 | lstm_unit = LstmUnit(input_size, hidden_size, num_layers) 152 | 153 | def encode_token(inp): 154 | """ 155 | encode token 156 | """ 157 | token = fluid.layers.assign(inp) 158 | token.stop_gradient = True 159 | token = fluid.layers.one_hot(token, depth) 160 | return token 161 | 162 | def encode_adj(adj, step): 163 | """ 164 | encode adj 165 | """ 166 | adj = fluid.layers.cast(adj, dtype='float32') 167 | adj_pad = fluid.layers.pad(x=adj, paddings=[0, 0, 0, depth - step], 168 | pad_value=0.0) 169 | return adj_pad 170 | 171 | def decode_token(hidden): 172 | """ 173 | decode token 174 | """ 175 | initiallizer = fluid.initializer.TruncatedNormalInitializer( 176 | scale=np.sqrt(2.0 / self.parser_args.hidden_size)) 177 | param_attr = fluid.ParamAttr(initializer=initiallizer) 178 | logits = fluid.layers.fc(hidden, num_tokens, param_attr=param_attr) 179 | temper = 5.0 180 | tanh_c = 2.5 181 | logits = fluid.layers.tanh(logits / temper) * tanh_c 182 | token = distribute_generator.multinomial(logits, 183 | [batch_size, 1], 1) 184 | return token, fluid.layers.unsqueeze(logits, axes=[1]) 185 | 186 | def decode_adj(hidden, step): 187 | """ 188 | decode adj 189 | """ 190 | initiallizer = fluid.initializer.TruncatedNormalInitializer( 191 | scale=np.sqrt(2.0 / self.parser_args.hidden_size)) 192 | param_attr = fluid.ParamAttr(initializer=initiallizer) 193 | logits = fluid.layers.fc(hidden, step, param_attr=param_attr) 194 | temper = 5.0 195 | tanh_c = 2.5 196 | logits = fluid.layers.tanh(logits / temper) * tanh_c 197 | adj = distribute_generator.bernoulli(logits, 198 | output_shape=logits.shape) 199 | return adj, logits 200 | 201 | tokens = [] 202 | softmax = [] 203 | adjvec = [] 204 | sigmoid = [] 205 | 206 | def rnn_block(hidden, last_hidden, last_cell): 207 | """ 208 | rnn block 209 | """ 210 | last_output, last_hidden, last_cell = lstm_unit( 211 | hidden, last_hidden, last_cell) 212 | token, logits = decode_token(last_output) 213 | tokens.append(token) 214 | softmax.append(logits) 215 | 216 | for step in range(1, num_nodes): 217 | token_vec = encode_token(token) 218 | last_output, last_hidden, last_cell = lstm_unit( 219 | token_vec, last_hidden, last_cell) 220 | adj, logits = decode_adj(last_output, step) 221 | adjvec.append(adj) 222 | sigmoid.append(logits) 223 | adj_vec = encode_adj(adj, step) 224 | last_output, last_hidden, last_cell = lstm_unit( 225 | adj_vec, last_hidden, last_cell) 226 | token, logits = decode_token(last_output) 227 | tokens.append(token) 228 | softmax.append(logits) 229 | return token, last_hidden, last_cell 230 | init_hidden = fluid.layers.fill_constant( 231 | shape=[num_layers, batch_size, hidden_size], 232 | value=0.0, dtype='float32') 233 | init_cell = fluid.layers.fill_constant( 234 | shape=[num_layers, batch_size, hidden_size], 235 | value=0.0, dtype='float32') 236 | 237 | hidden = encode_adj(inputs, 1) 238 | token, last_hidden, last_cell = rnn_block(hidden, init_hidden, 239 | init_cell) 240 | hidden = encode_token(token) 241 | token, last_hidden, last_cell = rnn_block(hidden, last_hidden, 242 | last_cell) 243 | token_out = fluid.layers.concat(tokens, axis=1) 244 | softmax_out = fluid.layers.concat(softmax, axis=1) 245 | adjvec_out = fluid.layers.concat(adjvec, axis=1) 246 | sigmoid_out = fluid.layers.concat(sigmoid, axis=1) 247 | return [token_out, softmax_out, adjvec_out, sigmoid_out] 248 | -------------------------------------------------------------------------------- /AutoDL Design/reinforce_policy_gradient.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | AutoDL definition 18 | """ 19 | import paddle.fluid as fluid 20 | from parl.framework.algorithm_base import Algorithm 21 | import paddle.fluid.layers as layers 22 | import os 23 | import sys 24 | 25 | 26 | class ReinforcePolicyGradient(Algorithm): 27 | """ 28 | Implement REINFORCE policy gradient for autoDL 29 | """ 30 | def __init__(self, model, hyperparas): 31 | """ 32 | """ 33 | Algorithm.__init__(self, model, hyperparas) 34 | self.model = model 35 | self.lr = hyperparas['lr'] 36 | 37 | def define_predict(self, obs): 38 | """ 39 | use policy model self.model to predict the action probability 40 | obs is `inputs` 41 | """ 42 | with fluid.unique_name.guard(): 43 | [tokens, softmax, adjvec, sigmoid] = self.model.policy(obs) 44 | return tokens, adjvec 45 | 46 | def define_learn(self, obs, action, reward): 47 | """ 48 | update policy model self.model with policy gradient algorithm 49 | obs is `inputs` 50 | """ 51 | tokens = action[0] 52 | adjvec = action[1] 53 | with fluid.unique_name.guard(): 54 | [_, softmax, _, sigmoid] = self.model.policy(obs) 55 | reshape_softmax = layers.reshape( 56 | softmax, 57 | [-1, self.model.parser_args.num_tokens]) 58 | reshape_tokens = layers.reshape(tokens, [-1, 1]) 59 | reshape_tokens.stop_gradient = True 60 | raw_neglogp_to = layers.softmax_with_cross_entropy( 61 | soft_label=False, 62 | logits=reshape_softmax, 63 | label=fluid.layers.cast(x=reshape_tokens, dtype="int64")) 64 | 65 | action_to_shape_sec = self.model.parser_args.num_nodes * 2 66 | neglogp_to = layers.reshape(fluid.layers.cast( 67 | raw_neglogp_to, dtype="float32"), 68 | [-1, action_to_shape_sec]) 69 | 70 | adjvec = layers.cast(x=adjvec, dtype='float32') 71 | neglogp_ad = layers.sigmoid_cross_entropy_with_logits( 72 | x=sigmoid, label=adjvec) 73 | 74 | neglogp = layers.elementwise_add( 75 | x=layers.reduce_sum(neglogp_to, dim=1), 76 | y=layers.reduce_sum(neglogp_ad, dim=1)) 77 | reward = layers.cast(reward, dtype="float32") 78 | cost = layers.reduce_mean( 79 | fluid.layers.elementwise_mul(x=neglogp, y=reward)) 80 | optimizer = fluid.optimizer.Adam(learning_rate=self.lr) 81 | train_op = optimizer.minimize(cost) 82 | return cost 83 | -------------------------------------------------------------------------------- /AutoDL Design/run.sh: -------------------------------------------------------------------------------- 1 | export FLAGS_fraction_of_gpu_memory_to_use=0.98 2 | export FLAGS_eager_delete_tensor_gb=0.0 3 | export FLAGS_fast_eager_deletion_mode=1 4 | CUDA_VISIBLE_DEVICES=0 python -u main.py > main.log 2>&1 & 5 | -------------------------------------------------------------------------------- /AutoDL Design/simple_main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | AutoDL main definition 18 | """ 19 | from __future__ import absolute_import 20 | from __future__ import division 21 | from __future__ import print_function 22 | 23 | import os 24 | import sys 25 | import traceback 26 | import autodl 27 | 28 | if __name__ == "__main__": 29 | try: 30 | autodl_exe = autodl.AutoDL() 31 | autodl_exe.simple_run() 32 | except Exception as e: 33 | print(str(e)) 34 | traceback.print_exc() 35 | -------------------------------------------------------------------------------- /AutoDL Design/utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | AutoDL definition 18 | """ 19 | 20 | import os 21 | import time 22 | import pickle 23 | 24 | 25 | def stime(): 26 | """ 27 | stime 28 | """ 29 | return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) 30 | 31 | 32 | def prepare(log_dir, category=""): 33 | """ 34 | prepare directory 35 | """ 36 | subdir = os.path.join(log_dir, category) 37 | if not os.path.exists(subdir): 38 | os.mkdir(subdir) 39 | 40 | 41 | def dump_action(mid, action, log_dir): 42 | """ 43 | dump action 44 | """ 45 | filename = os.path.join(log_dir, "actions", "%d.pkl" % mid) 46 | pickle.dump(action, open(filename, "wb")) 47 | 48 | 49 | def load_action(mid, log_dir): 50 | """ 51 | load action 52 | """ 53 | filename = os.path.join(log_dir, "actions", "%d.pkl" % mid) 54 | return pickle.load(open(filename, "rb")) 55 | 56 | 57 | def dump_reward(mid, reward, log_dir): 58 | """ 59 | dump reward 60 | """ 61 | filename = os.path.join(log_dir, "rewards", "%d.pkl" % mid) 62 | pickle.dump(reward, open(filename, "wb")) 63 | 64 | 65 | def load_reward(mid, log_dir): 66 | """ 67 | load reward 68 | """ 69 | filename = os.path.join(log_dir, "rewards", "%d.pkl" % mid) 70 | return pickle.load(open(filename, "rb")) 71 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LRC/README.md: -------------------------------------------------------------------------------- 1 | # LRC Local Rademachar Complexity Regularization 2 | Regularization of Deep Neural Networks(DNNs) for the sake of improving their generalization capability is important and chllenging. This directory contains image classification model based on a novel regularizer rooted in Local Rademacher Complexity (LRC). We appreciate the contribution by [DARTS](https://arxiv.org/abs/1806.09055) for our research. The regularization by LRC and DARTS are combined in this model to reach accuracy of 98.01% on CIFAR-10 dataset. Code accompanying the paper 3 | > [An Empirical Study on Regularization of Deep Neural Networks by Local Rademacher Complexity](https://arxiv.org/abs/1902.00873)\ 4 | > Yingzhen Yang, Xingjian Li, Jun Huan.\ 5 | > _arXiv:1902.00873_. 6 | 7 | --- 8 | # Table of Contents 9 | 10 | - [Introduction of algorithm](#introduction-of-algorithm) 11 | - [Installation](#installation) 12 | - [Data preparation](#data-preparation) 13 | - [Training](#training) 14 | - [Testing](#testing) 15 | - [Experimental result](#experimental-result) 16 | - [Reference](#reference) 17 | 18 | ## Introduction of algorithm 19 | 20 | Rademacher complexity is well known as a distribution-free complexity measure of function class and LRC focus on a restricted function class which leads to sharper convergence rates and potential better generalization. Our LRC based regularizer is developed by estimating the complexity of the function class centered at the minimizer of the empirical loss of DNNs. 21 | 22 | ## Installation 23 | 24 | Running sample code in this directory requires PaddelPaddle Fluid v.1.3.0 and later. If the PaddlePaddle on your device is lower than this version, please follow the instructions in [installation document](http://www.paddlepaddle.org/documentation/docs/zh/1.3/beginners_guide/install/index_cn.html#paddlepaddle) and make an update. 25 | 26 | ## Data preparation 27 | 28 | When you want to use the cifar-10 dataset for the first time, you can download the dataset as: 29 | 30 | sh ./dataset/download.sh 31 | 32 | Please make sure your environment has an internet connection. 33 | 34 | The dataset will be downloaded to `dataset/cifar/cifar-10-batches-py` in the same directory as the `train.py`. If automatic download fails, you can download cifar-10-python.tar.gz from https://www.cs.toronto.edu/~kriz/cifar.html and decompress it to the location mentioned above. 35 | 36 | 37 | ## Training 38 | 39 | After data preparation, one can start the training step by: 40 | 41 | sh run_cifar.sh 42 | 43 | - Set ```export CUDA_VISIBLE_DEVICES=0``` to specifiy one GPU to train. 44 | - For more help on arguments: 45 | 46 | python train_mixup.py --help 47 | 48 | **data reader introduction:** 49 | 50 | * Data reader is defined in `reader_cifar.py`. 51 | * Reshape the images to 32 * 32. 52 | * In training stage, images are padding to 40 * 40 and cropped randomly to the original size. 53 | * In training stage, images are horizontally random flipped. 54 | * Images are standardized to (0, 1). 55 | * In training stage, cutout images randomly. 56 | * Shuffle the order of the input images during training. 57 | 58 | **model configuration:** 59 | 60 | * Use momentum optimizer with momentum=0.9. 61 | * Total epoch is 600. 62 | * Use global L2 norm to clip gradient. 63 | * Other configurations are set in `run_cifar.sh` 64 | 65 | ## Tesing 66 | 67 | one can start the testing step by: 68 | 69 | sh run_cifar_test.sh 70 | 71 | - Set ```export CUDA_VISIBLE_DEVICES=0``` to specifiy one GPU to train. 72 | - For more help on arguments: 73 | 74 | python test_mixup.py --help 75 | 76 | After obtaining six models, one can get ensembled model by: 77 | 78 | python voting.py 79 | 80 | ## Experimental result 81 | 82 | Experimental result is shown as below: 83 | 84 | | Model | based lr | batch size | model id | acc-1 | 85 | | :--------------- | :--------: | :------------: | :------------------: |------: | 86 | | [model_0](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_0.tar.gz) | 0.01 | 64 | 0 | 97.12% | 87 | | [model_1](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_1.tar.gz) | 0.02 | 80 | 0 | 97.34% | 88 | | [model_2](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_2.tar.gz) | 0.015 | 80 | 1 | 97.31% | 89 | | [model_3](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_3.tar.gz) | 0.02 | 80 | 1 | 97.52% | 90 | | [model_4](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_4.tar.gz) | 0.03 | 80 | 1 | 97.30% | 91 | | [model_5](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_5.tar.gz) | 0.015 | 64 | 2 | 97.32% | 92 | 93 | ensembled model acc-1=98.01% 94 | 95 | ## Reference 96 | 97 | - DARTS: Differentiable Architecture Search [`paper`](https://arxiv.org/abs/1806.09055) 98 | - Differentiable architecture search in PyTorch [`code`](https://github.com/quark0/darts) 99 | -------------------------------------------------------------------------------- /LRC/README_cn.md: -------------------------------------------------------------------------------- 1 | # LRC 局部Rademachar复杂度正则化 2 | 为了在深度神经网络中提升泛化能力,正则化的选择十分重要也具有挑战性。本目录包括了一种基于局部rademacher复杂度的新型正则(LRC)的图像分类模型。十分感谢[DARTS](https://arxiv.org/abs/1806.09055)模型对本研究提供的帮助。该模型将LRC正则和DARTS网络相结合,在CIFAR-10数据集中得到了98.01%的准确率。代码和文章一同发布 3 | > [An Empirical Study on Regularization of Deep Neural Networks by Local Rademacher Complexity](https://arxiv.org/abs/1902.00873)\ 4 | > Yingzhen Yang, Xingjian Li, Jun Huan.\ 5 | > _arXiv:1902.00873_. 6 | 7 | --- 8 | # 内容 9 | 10 | - [算法简介](#算法简介) 11 | - [安装](#安装) 12 | - [数据准备](#数据准备) 13 | - [模型训练](#模型训练) 14 | - [模型测试](#模型测试) 15 | - [实验结果](#实验结果) 16 | - [引用](#引用) 17 | 18 | ## 算法简介 19 | 20 | 局部拉德马赫复杂度方法借鉴了已有的局部拉德马赫复杂度方法,仅考虑在经验损失函数的极小值点附近的一个球内的拉德马赫复杂度。采用最近的拉德马赫复杂度的估计方法,对折页损失函数 (Hinge Loss) 和交叉熵(cross entropy)推得了这个固定值的表达式,并且将其称之为局部拉德马赫正则化项,并加在经验损失函数上。将正则化方法作用在混合和模型集成之后,得到了CIFAR-10上目前最好的准确率。 21 | 22 | ## 安装 23 | 24 | 在当前目录下运行样例代码需要PadddlePaddle Fluid的v.1.3.0或以上的版本。如果你的运行环境中的PaddlePaddle低于此版本,请根据[安装文档](http://www.paddlepaddle.org/documentation/docs/zh/1.3/beginners_guide/install/index_cn.html#paddlepaddle)中的说明来更新PaddlePaddle。 25 | 26 | ## 数据准备 27 | 28 | 第一次使用CIFAR-10数据集时,您可以通过如果命令下载: 29 | 30 | sh ./dataset/download.sh 31 | 32 | 请确保您的环境有互联网连接。数据会下载到`train.py`同目录下的`dataset/cifar/cifar-10-batches-py`。如果下载失败,您可以自行从 https://www.cs.toronto.edu/~kriz/cifar.html 上下载cifar-10-python.tar.gz并解压到上述位置。 33 | 34 | ## 模型训练 35 | 36 | 数据准备好后,可以通过如下命令开始训练: 37 | 38 | sh run_cifar.sh 39 | 40 | - 在```run_cifar.sh```中通过设置 ```export CUDA_VISIBLE_DEVICES=0```指定GPU卡号进行训练。 41 | - 可选参数见: 42 | 43 | python train_mixup.py --help 44 | 45 | **数据读取器说明:** 46 | 47 | * 数据读取器定义在`reader_cifar.py`中 48 | * 输入图像尺寸统一变换为32 * 32 49 | * 训练时将图像填充为40 * 40然后随机剪裁为原输入图像大小 50 | * 训练时图像随机水平翻转 51 | * 对图像每个像素做归一化处理 52 | * 训练时对图像做随机遮挡 53 | * 训练时对输入图像做随机洗牌 54 | 55 | **模型配置:** 56 | 57 | * 采用momentum优化算法训练,momentum=0.9 58 | * 总共训练600轮 59 | * 对梯度采用全局L2范数裁剪 60 | * 其余模型配置在run_cifar.sh中 61 | 62 | ## 模型测试 63 | 64 | 可以通过如下命令开始测试: 65 | 66 | sh run_cifar_test.sh 67 | 68 | - 在```run_cifar_test.sh```中通过设置 ```export CUDA_VISIBLE_DEVICES=0```指定GPU卡号进行训练。 69 | - 可选参数见: 70 | 71 | python test_mixup.py --help 72 | 73 | 得到六个模型后运行如下脚本得到融合模型: 74 | 75 | python voting.py 76 | 77 | 78 | ## 实验结果 79 | 80 | 下表为模型评估结果: 81 | 82 | | 模型 | 初始学习率 | 批量大小 | 模型编号 | acc-1 | 83 | | :--------------- | :--------: | :------------: | :------------------: |------: | 84 | | [model_0](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_0.tar.gz) | 0.01 | 64 | 0 | 97.12% | 85 | | [model_1](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_1.tar.gz) | 0.02 | 80 | 0 | 97.34% | 86 | | [model_2](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_2.tar.gz) | 0.015 | 80 | 1 | 97.31% | 87 | | [model_3](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_3.tar.gz) | 0.02 | 80 | 1 | 97.52% | 88 | | [model_4](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_4.tar.gz) | 0.03 | 80 | 1 | 97.30% | 89 | | [model_5](https://paddlemodels.bj.bcebos.com/autodl/lrc_model_5.tar.gz) | 0.015 | 64 | 2 | 97.32% | 90 | 91 | 融合模型acc-1=98.01% 92 | 93 | ## 引用 94 | 95 | - DARTS: Differentiable Architecture Search [`论文`](https://arxiv.org/abs/1806.09055) 96 | - Differentiable Architecture Search in PyTorch [`代码`](https://github.com/quark0/darts) 97 | -------------------------------------------------------------------------------- /LRC/dataset/download.sh: -------------------------------------------------------------------------------- 1 | DIR="$( cd "$(dirname "$0")" ; pwd -P )" 2 | cd "$DIR" 3 | mkdir cifar 4 | cd cifar 5 | # Download the data. 6 | echo "Downloading..." 7 | wget https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz 8 | # Extract the data. 9 | echo "Extracting..." 10 | tar zvxf cifar-10-python.tar.gz 11 | -------------------------------------------------------------------------------- /LRC/genotypes.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # Based on: 16 | # -------------------------------------------------------- 17 | # DARTS 18 | # Copyright (c) 2018, Hanxiao Liu. 19 | # Licensed under the Apache License, Version 2.0; 20 | # -------------------------------------------------------- 21 | 22 | from collections import namedtuple 23 | 24 | Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat') 25 | 26 | PRIMITIVES = [ 27 | 'none', 'max_pool_3x3', 'avg_pool_3x3', 'skip_connect', 'sep_conv_3x3', 28 | 'sep_conv_5x5', 'dil_conv_3x3', 'dil_conv_5x5' 29 | ] 30 | 31 | NASNet = Genotype( 32 | normal=[ 33 | ('sep_conv_5x5', 1), 34 | ('sep_conv_3x3', 0), 35 | ('sep_conv_5x5', 0), 36 | ('sep_conv_3x3', 0), 37 | ('avg_pool_3x3', 1), 38 | ('skip_connect', 0), 39 | ('avg_pool_3x3', 0), 40 | ('avg_pool_3x3', 0), 41 | ('sep_conv_3x3', 1), 42 | ('skip_connect', 1), 43 | ], 44 | normal_concat=[2, 3, 4, 5, 6], 45 | reduce=[ 46 | ('sep_conv_5x5', 1), 47 | ('sep_conv_7x7', 0), 48 | ('max_pool_3x3', 1), 49 | ('sep_conv_7x7', 0), 50 | ('avg_pool_3x3', 1), 51 | ('sep_conv_5x5', 0), 52 | ('skip_connect', 3), 53 | ('avg_pool_3x3', 2), 54 | ('sep_conv_3x3', 2), 55 | ('max_pool_3x3', 1), 56 | ], 57 | reduce_concat=[4, 5, 6], ) 58 | 59 | AmoebaNet = Genotype( 60 | normal=[ 61 | ('avg_pool_3x3', 0), 62 | ('max_pool_3x3', 1), 63 | ('sep_conv_3x3', 0), 64 | ('sep_conv_5x5', 2), 65 | ('sep_conv_3x3', 0), 66 | ('avg_pool_3x3', 3), 67 | ('sep_conv_3x3', 1), 68 | ('skip_connect', 1), 69 | ('skip_connect', 0), 70 | ('avg_pool_3x3', 1), 71 | ], 72 | normal_concat=[4, 5, 6], 73 | reduce=[ 74 | ('avg_pool_3x3', 0), 75 | ('sep_conv_3x3', 1), 76 | ('max_pool_3x3', 0), 77 | ('sep_conv_7x7', 2), 78 | ('sep_conv_7x7', 0), 79 | ('avg_pool_3x3', 1), 80 | ('max_pool_3x3', 0), 81 | ('max_pool_3x3', 1), 82 | ('conv_7x1_1x7', 0), 83 | ('sep_conv_3x3', 5), 84 | ], 85 | reduce_concat=[3, 4, 6]) 86 | 87 | DARTS_V1 = Genotype( 88 | normal=[('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('skip_connect', 0), 89 | ('sep_conv_3x3', 1), ('skip_connect', 0), ('sep_conv_3x3', 1), 90 | ('sep_conv_3x3', 0), ('skip_connect', 2)], 91 | normal_concat=[2, 3, 4, 5], 92 | reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('skip_connect', 2), 93 | ('max_pool_3x3', 0), ('max_pool_3x3', 0), ('skip_connect', 2), 94 | ('skip_connect', 2), ('avg_pool_3x3', 0)], 95 | reduce_concat=[2, 3, 4, 5]) 96 | DARTS_V2 = Genotype( 97 | normal=[('sep_conv_3x3', 0), ('sep_conv_3x3', 1), ('sep_conv_3x3', 0), 98 | ('sep_conv_3x3', 1), ('sep_conv_3x3', 1), ('skip_connect', 0), 99 | ('skip_connect', 0), ('dil_conv_3x3', 2)], 100 | normal_concat=[2, 3, 4, 5], 101 | reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('skip_connect', 2), 102 | ('max_pool_3x3', 1), ('max_pool_3x3', 0), ('skip_connect', 2), 103 | ('skip_connect', 2), ('max_pool_3x3', 1)], 104 | reduce_concat=[2, 3, 4, 5]) 105 | 106 | MY_DARTS = Genotype( 107 | normal=[('sep_conv_3x3', 0), ('skip_connect', 1), ('skip_connect', 0), 108 | ('dil_conv_5x5', 1), ('skip_connect', 0), ('sep_conv_3x3', 1), 109 | ('skip_connect', 0), ('sep_conv_3x3', 1)], 110 | normal_concat=range(2, 6), 111 | reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('max_pool_3x3', 0), 112 | ('skip_connect', 2), ('max_pool_3x3', 0), ('skip_connect', 2), 113 | ('skip_connect', 2), ('skip_connect', 3)], 114 | reduce_concat=range(2, 6)) 115 | 116 | MY_DARTS_list = [ 117 | Genotype( 118 | normal=[('sep_conv_3x3', 0), ('skip_connect', 1), ('sep_conv_3x3', 0), 119 | ('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('sep_conv_3x3', 1), 120 | ('skip_connect', 0), ('sep_conv_3x3', 2)], 121 | normal_concat=range(2, 6), 122 | reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('skip_connect', 2), 123 | ('max_pool_3x3', 0), ('skip_connect', 3), ('avg_pool_3x3', 1), 124 | ('skip_connect', 2), ('skip_connect', 3)], 125 | reduce_concat=range(2, 6)), 126 | Genotype( 127 | normal=[('sep_conv_3x3', 0), ('sep_conv_3x3', 1), ('skip_connect', 0), 128 | ('dil_conv_3x3', 2), ('skip_connect', 0), ('sep_conv_3x3', 1), 129 | ('skip_connect', 0), ('skip_connect', 1)], 130 | normal_concat=range(2, 6), 131 | reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('skip_connect', 2), 132 | ('dil_conv_3x3', 0), ('skip_connect', 3), ('skip_connect', 2), 133 | ('skip_connect', 3), ('skip_connect', 2)], 134 | reduce_concat=range(2, 6)), 135 | Genotype( 136 | normal=[('sep_conv_3x3', 0), ('skip_connect', 1), ('skip_connect', 0), 137 | ('dil_conv_5x5', 1), ('skip_connect', 0), ('sep_conv_3x3', 1), 138 | ('skip_connect', 0), ('sep_conv_3x3', 1)], 139 | normal_concat=range(2, 6), 140 | reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('max_pool_3x3', 0), 141 | ('skip_connect', 2), ('max_pool_3x3', 0), ('skip_connect', 2), 142 | ('skip_connect', 2), ('skip_connect', 3)], 143 | reduce_concat=range(2, 6)) 144 | ] 145 | 146 | DARTS = MY_DARTS_list[0] 147 | -------------------------------------------------------------------------------- /LRC/labels.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PaddlePaddle/AutoDL/b3d3f7ce6de485879c952d02c2c4c95ebe1a2f0c/LRC/labels.npz -------------------------------------------------------------------------------- /LRC/learning_rate.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # Based on: 16 | # -------------------------------------------------------- 17 | # DARTS 18 | # Copyright (c) 2018, Hanxiao Liu. 19 | # Licensed under the Apache License, Version 2.0; 20 | # -------------------------------------------------------- 21 | 22 | from __future__ import absolute_import 23 | from __future__ import division 24 | from __future__ import print_function 25 | import paddle 26 | import paddle.fluid as fluid 27 | import paddle.fluid.layers.ops as ops 28 | from paddle.fluid.layers.learning_rate_scheduler import _decay_step_counter 29 | import math 30 | 31 | 32 | def cosine_decay(learning_rate, num_epoch, steps_one_epoch): 33 | """Applies cosine decay to the learning rate. 34 | lr = 0.5 * (math.cos(epoch * (math.pi / 120)) + 1) 35 | """ 36 | global_step = _decay_step_counter() 37 | 38 | decayed_lr = learning_rate * \ 39 | (ops.cos(fluid.layers.floor(global_step / steps_one_epoch) \ 40 | * math.pi / num_epoch) + 1)/2 41 | return decayed_lr 42 | 43 | 44 | def cosine_with_warmup_decay(learning_rate, lr_min, steps_one_epoch, 45 | warmup_epochs, total_epoch, num_gpu): 46 | global_step = _decay_step_counter() 47 | epoch_idx = fluid.layers.floor(global_step / steps_one_epoch) 48 | 49 | lr = fluid.layers.create_global_var( 50 | shape=[1], 51 | value=0.0, 52 | dtype='float32', 53 | persistable=True, 54 | name="learning_rate") 55 | 56 | warmup_epoch_var = fluid.layers.fill_constant( 57 | shape=[1], dtype='float32', value=float(warmup_epochs), force_cpu=True) 58 | num_gpu_var = fluid.layers.fill_constant( 59 | shape=[1], dtype='float32', value=float(num_gpu), force_cpu=True) 60 | batch_idx = global_step - steps_one_epoch * epoch_idx 61 | 62 | with fluid.layers.control_flow.Switch() as switch: 63 | with switch.case(epoch_idx < warmup_epoch_var): 64 | epoch_ = (batch_idx + 1) / steps_one_epoch 65 | factor = 1 / num_gpu_var * ( 66 | epoch_ * (num_gpu_var - 1) / warmup_epoch_var + 1) 67 | decayed_lr = learning_rate * factor * num_gpu_var 68 | fluid.layers.assign(decayed_lr, lr) 69 | epoch_ = (batch_idx + 1) / steps_one_epoch 70 | m = epoch_ / total_epoch 71 | frac = (1 + ops.cos(math.pi * m)) / 2 72 | cosine_lr = (lr_min + (learning_rate - lr_min) * frac) * num_gpu_var 73 | with switch.default(): 74 | fluid.layers.assign(cosine_lr, lr) 75 | 76 | return lr 77 | -------------------------------------------------------------------------------- /LRC/operations.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 2 | # 3 | #Licensed under the Apache License, Version 2.0 (the "License"); 4 | #you may not use this file except in compliance with the License. 5 | #You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | #Unless required by applicable law or agreed to in writing, software 10 | #distributed under the License is distributed on an "AS IS" BASIS, 11 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | #See the License for the specific language governing permissions and 13 | #limitations under the License. 14 | # 15 | # Based on: 16 | # -------------------------------------------------------- 17 | # DARTS 18 | # Copyright (c) 2018, Hanxiao Liu. 19 | # Licensed under the Apache License, Version 2.0; 20 | # -------------------------------------------------------- 21 | from __future__ import absolute_import 22 | from __future__ import division 23 | from __future__ import print_function 24 | import os 25 | import sys 26 | import numpy as np 27 | import time 28 | import paddle 29 | import paddle.fluid as fluid 30 | from paddle.fluid.param_attr import ParamAttr 31 | from paddle.fluid.initializer import Xavier 32 | from paddle.fluid.initializer import Normal 33 | from paddle.fluid.initializer import Constant 34 | 35 | OPS = { 36 | 'none' : lambda input, C, stride, name, affine: Zero(input, stride, name), 37 | 'avg_pool_3x3' : lambda input, C, stride, name, affine: fluid.layers.pool2d(input, 3, 'avg', pool_stride=stride, pool_padding=1, name=name), 38 | 'max_pool_3x3' : lambda input, C, stride, name, affine: fluid.layers.pool2d(input, 3, 'max', pool_stride=stride, pool_padding=1, name=name), 39 | 'skip_connect' : lambda input,C, stride, name, affine: Identity(input, name) if stride == 1 else FactorizedReduce(input, C, name=name, affine=affine), 40 | 'sep_conv_3x3' : lambda input,C, stride, name, affine: SepConv(input, C, C, 3, stride, 1, name=name, affine=affine), 41 | 'sep_conv_5x5' : lambda input,C, stride, name, affine: SepConv(input, C, C, 5, stride, 2, name=name, affine=affine), 42 | 'sep_conv_7x7' : lambda input,C, stride, name, affine: SepConv(input, C, C, 7, stride, 3, name=name, affine=affine), 43 | 'dil_conv_3x3' : lambda input,C, stride, name, affine: DilConv(input, C, C, 3, stride, 2, 2, name=name, affine=affine), 44 | 'dil_conv_5x5' : lambda input,C, stride, name, affine: DilConv(input, C, C, 5, stride, 4, 2, name=name, affine=affine), 45 | 'conv_7x1_1x7' : lambda input,C, stride, name, affine: SevenConv(input, C, name=name, affine=affine) 46 | } 47 | 48 | 49 | def ReLUConvBN(input, C_out, kernel_size, stride, padding, name='', 50 | affine=True): 51 | relu_a = fluid.layers.relu(input) 52 | conv2d_a = fluid.layers.conv2d( 53 | relu_a, 54 | C_out, 55 | kernel_size, 56 | stride, 57 | padding, 58 | param_attr=ParamAttr( 59 | initializer=Xavier( 60 | uniform=False, fan_in=0), 61 | name=name + 'op.1.weight'), 62 | bias_attr=False) 63 | if affine: 64 | reluconvbn_out = fluid.layers.batch_norm( 65 | conv2d_a, 66 | param_attr=ParamAttr( 67 | initializer=Constant(1.), name=name + 'op.2.weight'), 68 | bias_attr=ParamAttr( 69 | initializer=Constant(0.), name=name + 'op.2.bias'), 70 | moving_mean_name=name + 'op.2.running_mean', 71 | moving_variance_name=name + 'op.2.running_var') 72 | else: 73 | reluconvbn_out = fluid.layers.batch_norm( 74 | conv2d_a, 75 | param_attr=ParamAttr( 76 | initializer=Constant(1.), 77 | learning_rate=0., 78 | name=name + 'op.2.weight'), 79 | bias_attr=ParamAttr( 80 | initializer=Constant(0.), 81 | learning_rate=0., 82 | name=name + 'op.2.bias'), 83 | moving_mean_name=name + 'op.2.running_mean', 84 | moving_variance_name=name + 'op.2.running_var') 85 | return reluconvbn_out 86 | 87 | 88 | def DilConv(input, 89 | C_in, 90 | C_out, 91 | kernel_size, 92 | stride, 93 | padding, 94 | dilation, 95 | name='', 96 | affine=True): 97 | relu_a = fluid.layers.relu(input) 98 | conv2d_a = fluid.layers.conv2d( 99 | relu_a, 100 | C_in, 101 | kernel_size, 102 | stride, 103 | padding, 104 | dilation, 105 | groups=C_in, 106 | param_attr=ParamAttr( 107 | initializer=Xavier( 108 | uniform=False, fan_in=0), 109 | name=name + 'op.1.weight'), 110 | bias_attr=False, 111 | use_cudnn=False) 112 | conv2d_b = fluid.layers.conv2d( 113 | conv2d_a, 114 | C_out, 115 | 1, 116 | param_attr=ParamAttr( 117 | initializer=Xavier( 118 | uniform=False, fan_in=0), 119 | name=name + 'op.2.weight'), 120 | bias_attr=False) 121 | if affine: 122 | dilconv_out = fluid.layers.batch_norm( 123 | conv2d_b, 124 | param_attr=ParamAttr( 125 | initializer=Constant(1.), name=name + 'op.3.weight'), 126 | bias_attr=ParamAttr( 127 | initializer=Constant(0.), name=name + 'op.3.bias'), 128 | moving_mean_name=name + 'op.3.running_mean', 129 | moving_variance_name=name + 'op.3.running_var') 130 | else: 131 | dilconv_out = fluid.layers.batch_norm( 132 | conv2d_b, 133 | param_attr=ParamAttr( 134 | initializer=Constant(1.), 135 | learning_rate=0., 136 | name=name + 'op.3.weight'), 137 | bias_attr=ParamAttr( 138 | initializer=Constant(0.), 139 | learning_rate=0., 140 | name=name + 'op.3.bias'), 141 | moving_mean_name=name + 'op.3.running_mean', 142 | moving_variance_name=name + 'op.3.running_var') 143 | return dilconv_out 144 | 145 | 146 | def SepConv(input, 147 | C_in, 148 | C_out, 149 | kernel_size, 150 | stride, 151 | padding, 152 | name='', 153 | affine=True): 154 | relu_a = fluid.layers.relu(input) 155 | conv2d_a = fluid.layers.conv2d( 156 | relu_a, 157 | C_in, 158 | kernel_size, 159 | stride, 160 | padding, 161 | groups=C_in, 162 | param_attr=ParamAttr( 163 | initializer=Xavier( 164 | uniform=False, fan_in=0), 165 | name=name + 'op.1.weight'), 166 | bias_attr=False, 167 | use_cudnn=False) 168 | conv2d_b = fluid.layers.conv2d( 169 | conv2d_a, 170 | C_in, 171 | 1, 172 | param_attr=ParamAttr( 173 | initializer=Xavier( 174 | uniform=False, fan_in=0), 175 | name=name + 'op.2.weight'), 176 | bias_attr=False) 177 | if affine: 178 | bn_a = fluid.layers.batch_norm( 179 | conv2d_b, 180 | param_attr=ParamAttr( 181 | initializer=Constant(1.), name=name + 'op.3.weight'), 182 | bias_attr=ParamAttr( 183 | initializer=Constant(0.), name=name + 'op.3.bias'), 184 | moving_mean_name=name + 'op.3.running_mean', 185 | moving_variance_name=name + 'op.3.running_var') 186 | else: 187 | bn_a = fluid.layers.batch_norm( 188 | conv2d_b, 189 | param_attr=ParamAttr( 190 | initializer=Constant(1.), 191 | learning_rate=0., 192 | name=name + 'op.3.weight'), 193 | bias_attr=ParamAttr( 194 | initializer=Constant(0.), 195 | learning_rate=0., 196 | name=name + 'op.3.bias'), 197 | moving_mean_name=name + 'op.3.running_mean', 198 | moving_variance_name=name + 'op.3.running_var') 199 | 200 | relu_b = fluid.layers.relu(bn_a) 201 | conv2d_d = fluid.layers.conv2d( 202 | relu_b, 203 | C_in, 204 | kernel_size, 205 | 1, 206 | padding, 207 | groups=C_in, 208 | param_attr=ParamAttr( 209 | initializer=Xavier( 210 | uniform=False, fan_in=0), 211 | name=name + 'op.5.weight'), 212 | bias_attr=False, 213 | use_cudnn=False) 214 | conv2d_e = fluid.layers.conv2d( 215 | conv2d_d, 216 | C_out, 217 | 1, 218 | param_attr=ParamAttr( 219 | initializer=Xavier( 220 | uniform=False, fan_in=0), 221 | name=name + 'op.6.weight'), 222 | bias_attr=False) 223 | if affine: 224 | sepconv_out = fluid.layers.batch_norm( 225 | conv2d_e, 226 | param_attr=ParamAttr( 227 | initializer=Constant(1.), name=name + 'op.7.weight'), 228 | bias_attr=ParamAttr( 229 | initializer=Constant(0.), name=name + 'op.7.bias'), 230 | moving_mean_name=name + 'op.7.running_mean', 231 | moving_variance_name=name + 'op.7.running_var') 232 | else: 233 | sepconv_out = fluid.layers.batch_norm( 234 | conv2d_e, 235 | param_attr=ParamAttr( 236 | initializer=Constant(1.), 237 | learning_rate=0., 238 | name=name + 'op.7.weight'), 239 | bias_attr=ParamAttr( 240 | initializer=Constant(0.), 241 | learning_rate=0., 242 | name=name + 'op.7.bias'), 243 | moving_mean_name=name + 'op.7.running_mean', 244 | moving_variance_name=name + 'op.7.running_var') 245 | return sepconv_out 246 | 247 | 248 | def SevenConv(input, C_out, stride, name='', affine=True): 249 | relu_a = fluid.layers.relu(input) 250 | conv2d_a = fluid.layers.conv2d( 251 | relu_a, 252 | C_out, (1, 7), (1, stride), (0, 3), 253 | param_attr=ParamAttr( 254 | initializer=Xavier( 255 | uniform=False, fan_in=0), 256 | name=name + 'op.1.weight'), 257 | bias_attr=False) 258 | conv2d_b = fluid.layers.conv2d( 259 | conv2d_a, 260 | C_out, (7, 1), (stride, 1), (3, 0), 261 | param_attr=ParamAttr( 262 | initializer=Xavier( 263 | uniform=False, fan_in=0), 264 | name=name + 'op.2.weight'), 265 | bias_attr=False) 266 | if affine: 267 | out = fluid.layers.batch_norm( 268 | conv2d_b, 269 | param_attr=ParamAttr( 270 | initializer=Constant(1.), name=name + 'op.3.weight'), 271 | bias_attr=ParamAttr( 272 | initializer=Constant(0.), name=name + 'op.3.bias'), 273 | moving_mean_name=name + 'op.3.running_mean', 274 | moving_variance_name=name + 'op.3.running_var') 275 | else: 276 | out = fluid.layers.batch_norm( 277 | conv2d_b, 278 | param_attr=ParamAttr( 279 | initializer=Constant(1.), 280 | learning_rate=0., 281 | name=name + 'op.3.weight'), 282 | bias_attr=ParamAttr( 283 | initializer=Constant(0.), 284 | learning_rate=0., 285 | name=name + 'op.3.bias'), 286 | moving_mean_name=name + 'op.3.running_mean', 287 | moving_variance_name=name + 'op.3.running_var') 288 | 289 | 290 | def Identity(input, name=''): 291 | return input 292 | 293 | 294 | def Zero(input, stride, name=''): 295 | ones = np.ones(input.shape[-2:]) 296 | ones[::stride, ::stride] = 0 297 | ones = fluid.layers.assign(ones) 298 | return input * ones 299 | 300 | 301 | def FactorizedReduce(input, C_out, name='', affine=True): 302 | relu_a = fluid.layers.relu(input) 303 | conv2d_a = fluid.layers.conv2d( 304 | relu_a, 305 | C_out // 2, 306 | 1, 307 | 2, 308 | param_attr=ParamAttr( 309 | initializer=Xavier( 310 | uniform=False, fan_in=0), 311 | name=name + 'conv_1.weight'), 312 | bias_attr=False) 313 | h_end = relu_a.shape[2] 314 | w_end = relu_a.shape[3] 315 | slice_a = fluid.layers.slice( 316 | input=relu_a, axes=[2, 3], starts=[1, 1], ends=[h_end, w_end]) 317 | conv2d_b = fluid.layers.conv2d( 318 | slice_a, 319 | C_out // 2, 320 | 1, 321 | 2, 322 | param_attr=ParamAttr( 323 | initializer=Xavier( 324 | uniform=False, fan_in=0), 325 | name=name + 'conv_2.weight'), 326 | bias_attr=False) 327 | out = fluid.layers.concat([conv2d_a, conv2d_b], axis=1) 328 | if affine: 329 | out = fluid.layers.batch_norm( 330 | out, 331 | param_attr=ParamAttr( 332 | initializer=Constant(1.), name=name + 'bn.weight'), 333 | bias_attr=ParamAttr( 334 | initializer=Constant(0.), name=name + 'bn.bias'), 335 | moving_mean_name=name + 'bn.running_mean', 336 | moving_variance_name=name + 'bn.running_var') 337 | else: 338 | out = fluid.layers.batch_norm( 339 | out, 340 | param_attr=ParamAttr( 341 | initializer=Constant(1.), 342 | learning_rate=0., 343 | name=name + 'bn.weight'), 344 | bias_attr=ParamAttr( 345 | initializer=Constant(0.), 346 | learning_rate=0., 347 | name=name + 'bn.bias'), 348 | moving_mean_name=name + 'bn.running_mean', 349 | moving_variance_name=name + 'bn.running_var') 350 | return out 351 | -------------------------------------------------------------------------------- /LRC/paddle_predict/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PaddlePaddle/AutoDL/b3d3f7ce6de485879c952d02c2c4c95ebe1a2f0c/LRC/paddle_predict/__init__.py -------------------------------------------------------------------------------- /LRC/reader_cifar.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 PaddlePaddle Authors. All Rig hts Reserved 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # Based on: 16 | # -------------------------------------------------------- 17 | # DARTS 18 | # Copyright (c) 2018, Hanxiao Liu. 19 | # Licensed under the Apache License, Version 2.0; 20 | # -------------------------------------------------------- 21 | """ 22 | CIFAR-10 dataset. 23 | This module will download dataset from 24 | https://www.cs.toronto.edu/~kriz/cifar.html and parse train/test set into 25 | paddle reader creators. 26 | The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, 27 | with 6000 images per class. There are 50000 training images and 10000 test images. 28 | """ 29 | 30 | from PIL import Image 31 | from PIL import ImageOps 32 | import numpy as np 33 | 34 | try: 35 | import cPickle as pickle 36 | except: 37 | import pickle 38 | import random 39 | import utils 40 | import paddle.fluid as fluid 41 | import time 42 | import os 43 | import functools 44 | import paddle.reader 45 | 46 | __all__ = ['train10', 'test10'] 47 | 48 | image_size = 32 49 | image_depth = 3 50 | half_length = 8 51 | 52 | CIFAR_MEAN = [0.49139968, 0.48215827, 0.44653124] 53 | CIFAR_STD = [0.24703233, 0.24348505, 0.26158768] 54 | 55 | 56 | def generate_reshape_label(label, batch_size, CIFAR_CLASSES=10): 57 | reshape_label = np.zeros((batch_size, 1), dtype='int32') 58 | reshape_non_label = np.zeros( 59 | (batch_size * (CIFAR_CLASSES - 1), 1), dtype='int32') 60 | num = 0 61 | for i in range(batch_size): 62 | label_i = label[i] 63 | reshape_label[i] = label_i + i * CIFAR_CLASSES 64 | for j in range(CIFAR_CLASSES): 65 | if label_i != j: 66 | reshape_non_label[num] = \ 67 | j + i * CIFAR_CLASSES 68 | num += 1 69 | return reshape_label, reshape_non_label 70 | 71 | 72 | def generate_bernoulli_number(batch_size, CIFAR_CLASSES=10): 73 | rcc_iters = 50 74 | rad_var = np.zeros((rcc_iters, batch_size, CIFAR_CLASSES - 1)) 75 | for i in range(rcc_iters): 76 | bernoulli_num = np.random.binomial(size=batch_size, n=1, p=0.5) 77 | bernoulli_map = np.array([]) 78 | ones = np.ones((CIFAR_CLASSES - 1, 1)) 79 | for batch_id in range(batch_size): 80 | num = bernoulli_num[batch_id] 81 | var_id = 2 * ones * num - 1 82 | bernoulli_map = np.append(bernoulli_map, var_id) 83 | rad_var[i] = bernoulli_map.reshape((batch_size, CIFAR_CLASSES - 1)) 84 | return rad_var.astype('float32') 85 | 86 | 87 | def preprocess(sample, is_training, args): 88 | 89 | image_array = sample.reshape(3, image_size, image_size) 90 | rgb_array = np.transpose(image_array, (1, 2, 0)) 91 | img = Image.fromarray(rgb_array, 'RGB') 92 | 93 | if is_training: 94 | # pad and ramdom crop 95 | img = ImageOps.expand(img, (4, 4, 4, 4), fill=0) # pad to 40 * 40 * 3 96 | left_top = np.random.randint(9, size=2) # rand 0 - 8 97 | img = img.crop((left_top[0], left_top[1], left_top[0] + image_size, 98 | left_top[1] + image_size)) 99 | if np.random.randint(2): 100 | img = img.transpose(Image.FLIP_LEFT_RIGHT) 101 | 102 | img = np.array(img).astype(np.float32) 103 | 104 | # per_image_standardization 105 | img_float = img / 255.0 106 | img = (img_float - CIFAR_MEAN) / CIFAR_STD 107 | 108 | if is_training and args.cutout: 109 | center = np.random.randint(image_size, size=2) 110 | offset_width = max(0, center[0] - half_length) 111 | offset_height = max(0, center[1] - half_length) 112 | target_width = min(center[0] + half_length, image_size) 113 | target_height = min(center[1] + half_length, image_size) 114 | 115 | for i in range(offset_height, target_height): 116 | for j in range(offset_width, target_width): 117 | img[i][j][:] = 0.0 118 | 119 | img = np.transpose(img, (2, 0, 1)) 120 | return img 121 | 122 | 123 | def reader_creator_filepath(filename, sub_name, is_training, args): 124 | files = os.listdir(filename) 125 | names = [each_item for each_item in files if sub_name in each_item] 126 | names.sort() 127 | datasets = [] 128 | for name in names: 129 | print("Reading file " + name) 130 | try: 131 | batch = pickle.load(open(filename + name, 'rb'), encode='latin1') 132 | except TypeError: 133 | batch = pickle.load(open(filename + name, 'rb')) 134 | data = batch['data'] 135 | labels = batch.get('labels', batch.get('fine_labels', None)) 136 | assert labels is not None 137 | dataset = zip(data, labels) 138 | datasets.extend(dataset) 139 | 140 | if is_training: 141 | random.shuffle(datasets) 142 | 143 | def read_batch(datasets, args): 144 | for sample, label in datasets: 145 | im = preprocess(sample, is_training, args) 146 | yield im, [int(label)] 147 | 148 | def reader(): 149 | batch_data = [] 150 | batch_label = [] 151 | for data, label in read_batch(datasets, args): 152 | batch_data.append(data) 153 | batch_label.append(label) 154 | if len(batch_data) == args.batch_size: 155 | batch_data = np.array(batch_data, dtype='float32') 156 | batch_label = np.array(batch_label, dtype='int64') 157 | if is_training: 158 | flatten_label, flatten_non_label = \ 159 | generate_reshape_label(batch_label, args.batch_size) 160 | rad_var = generate_bernoulli_number(args.batch_size) 161 | mixed_x, y_a, y_b, lam = utils.mixup_data( 162 | batch_data, batch_label, args.batch_size, 163 | args.mix_alpha) 164 | batch_out = [[mixed_x, y_a, y_b, lam, flatten_label, \ 165 | flatten_non_label, rad_var]] 166 | yield batch_out 167 | else: 168 | batch_out = [[batch_data, batch_label]] 169 | yield batch_out 170 | batch_data = [] 171 | batch_label = [] 172 | if len(batch_data) != 0: 173 | batch_data = np.array(batch_data, dtype='float32') 174 | batch_label = np.array(batch_label, dtype='int64') 175 | if is_training: 176 | flatten_label, flatten_non_label = \ 177 | generate_reshape_label(batch_label, len(batch_data)) 178 | rad_var = generate_bernoulli_number(len(batch_data)) 179 | mixed_x, y_a, y_b, lam = utils.mixup_data( 180 | batch_data, batch_label, len(batch_data), args.mix_alpha) 181 | batch_out = [[mixed_x, y_a, y_b, lam, flatten_label, \ 182 | flatten_non_label, rad_var]] 183 | yield batch_out 184 | else: 185 | batch_out = [[batch_data, batch_label]] 186 | yield batch_out 187 | batch_data = [] 188 | batch_label = [] 189 | 190 | return reader 191 | 192 | 193 | def train10(args): 194 | """ 195 | CIFAR-10 training set creator. 196 | It returns a reader creator, each sample in the reader is image pixels in 197 | [0, 1] and label in [0, 9]. 198 | :return: Training reader creator 199 | :rtype: callable 200 | """ 201 | 202 | return reader_creator_filepath(args.data, 'data_batch', True, args) 203 | 204 | 205 | def test10(args): 206 | """ 207 | CIFAR-10 test set creator. 208 | It returns a reader creator, each sample in the reader is image pixels in 209 | [0, 1] and label in [0, 9]. 210 | :return: Test reader creator. 211 | :rtype: callable 212 | """ 213 | return reader_creator_filepath(args.data, 'test_batch', False, args) 214 | -------------------------------------------------------------------------------- /LRC/run_cifar.sh: -------------------------------------------------------------------------------- 1 | export FLAGS_fraction_of_gpu_memory_to_use=0.9 2 | export FLAGS_eager_delete_tensor_gb=0.0 3 | export FLAGS_fast_eager_deletion_mode=1 4 | 5 | nohup env CUDA_VISIBLE_DEVICES=0 python -u train_mixup.py --batch_size=64 --auxiliary --mix_alpha=0.9 --model_id=0 --cutout --lrc_loss_lambda=0.5 --weight_decay=0.0002 --learning_rate=0.01 --save_model_path=model_0 > lrc_model_0.log 2>&1 & 6 | nohup env CUDA_VISIBLE_DEVICES=1 python -u train_mixup.py --batch_size=64 --auxiliary --mix_alpha=0.6 --model_id=0 --cutout --lrc_loss_lambda=0.5 --weight_decay=0.0002 --learning_rate=0.02 --save_model_path=model_1 > lrc_model_1.log 2>&1 & 7 | nohup env CUDA_VISIBLE_DEVICES=2 python -u train_mixup.py --batch_size=80 --auxiliary --mix_alpha=0.5 --model_id=1 --cutout --lrc_loss_lambda=0.5 --weight_decay=0.0002 --learning_rate=0.015 --save_model_path=model_2 > lrc_model_2.log 2>&1 & 8 | nohup env CUDA_VISIBLE_DEVICES=3 python -u train_mixup.py --batch_size=80 --auxiliary --mix_alpha=0.6 --model_id=1 --cutout --lrc_loss_lambda=0.5 --weight_decay=0.0002 --learning_rate=0.02 --save_model_path=model_3 > lrc_model_3.log 2>&1 & 9 | nohup env CUDA_VISIBLE_DEVICES=4 python -u train_mixup.py --batch_size=80 --auxiliary --mix_alpha=0.8 --model_id=1 --cutout --lrc_loss_lambda=0.5 --weight_decay=0.0002 --learning_rate=0.03 --save_model_path=model_4 > lrc_model_4.log 2>&1 & 10 | nohup env CUDA_VISIBLE_DEVICES=5 python -u train_mixup.py --batch_size=64 --auxiliary --mix_alpha=0.5 --model_id=2 --cutout --lrc_loss_lambda=0.5 --weight_decay=0.0002 --learning_rate=0.015 --save_model_path=model_5 > lrc_model_5.log 2>&1 & 11 | 12 | -------------------------------------------------------------------------------- /LRC/run_cifar_test.sh: -------------------------------------------------------------------------------- 1 | export FLAGS_fraction_of_gpu_memory_to_use=0.6 2 | nohup env CUDA_VISIBLE_DEVICES=0 python -u test_mixup.py --batch_size=64 --auxiliary --model_id=0 --pretrained_model=model_0/final/ --dump_path=paddle_predict/prob_test_0.pkl > lrc_test_0.log 2>&1 & 3 | nohup env CUDA_VISIBLE_DEVICES=1 python -u test_mixup.py --batch_size=64 --auxiliary --model_id=0 --pretrained_model=model_1/final/ --dump_path=paddle_predict/prob_test_1.pkl > lrc_test_1.log 2>&1 & 4 | nohup env CUDA_VISIBLE_DEVICES=2 python -u test_mixup.py --batch_size=80 --auxiliary --model_id=1 --pretrained_model=model_2/final/ --dump_path=paddle_predict/prob_test_2.pkl > lrc_test_2.log 2>&1 & 5 | nohup env CUDA_VISIBLE_DEVICES=3 python -u test_mixup.py --batch_size=80 --auxiliary --model_id=1 --pretrained_model=model_3/final/ --dump_path=paddle_predict/prob_test_3.pkl > lrc_test_3.log 2>&1 & 6 | nohup env CUDA_VISIBLE_DEVICES=4 python -u test_mixup.py --batch_size=80 --auxiliary --model_id=1 --pretrained_model=model_4/final/ --dump_path=paddle_predict/prob_test_4.pkl > lrc_test_4.log 2>&1 & 7 | nohup env CUDA_VISIBLE_DEVICES=5 python -u test_mixup.py --batch_size=64 --auxiliary --model_id=2 --pretrained_model=model_5/final/ --dump_path=paddle_predict/prob_test_5.pkl > lrc_test_5.log 2>&1 & 8 | 9 | -------------------------------------------------------------------------------- /LRC/test_mixup.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 2 | # 3 | #Licensed under the Apache License, Version 2.0 (the "License"); 4 | #you may not use this file except in compliance with the License. 5 | #You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | #Unless required by applicable law or agreed to in writing, software 10 | #distributed under the License is distributed on an "AS IS" BASIS, 11 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | #See the License for the specific language governing permissions and 13 | #limitations under the License. 14 | # 15 | # Based on: 16 | # -------------------------------------------------------- 17 | # DARTS 18 | # Copyright (c) 2018, Hanxiao Liu. 19 | # Licensed under the Apache License, Version 2.0; 20 | # -------------------------------------------------------- 21 | 22 | from __future__ import absolute_import 23 | from __future__ import division 24 | from __future__ import print_function 25 | from learning_rate import cosine_decay 26 | import numpy as np 27 | import argparse 28 | from model import NetworkCIFAR as Network 29 | import reader_cifar as reader 30 | import sys 31 | import os 32 | import time 33 | import logging 34 | import genotypes 35 | import paddle.fluid as fluid 36 | import shutil 37 | import utils 38 | 39 | parser = argparse.ArgumentParser("cifar") 40 | # yapf: disable 41 | parser.add_argument('--data', type=str, default='./dataset/cifar/cifar-10-batches-py/', help='location of the data corpus') 42 | parser.add_argument('--batch_size', type=int, default=96, help='batch size') 43 | parser.add_argument('--model_id', type=int, help='model id') 44 | parser.add_argument('--report_freq', type=float, default=50, help='report frequency') 45 | parser.add_argument( '--init_channels', type=int, default=36, help='num of init channels') 46 | parser.add_argument( '--layers', type=int, default=20, help='total number of layers') 47 | parser.add_argument('--auxiliary', action='store_true', default=False, help='use auxiliary tower') 48 | parser.add_argument('--auxiliary_weight', type=float, default=0.4, help='weight for auxiliary loss') 49 | parser.add_argument('--drop_path_prob', type=float, default=0.2, help='drop path probability') 50 | parser.add_argument('--pretrained_model', type=str, default='/model_0/final/', help='pretrained model to load') 51 | parser.add_argument('--arch', type=str, default='DARTS', help='which architecture to use') 52 | parser.add_argument('--dump_path', type=str, default='prob_test_0.pkl', help='dump path') 53 | # yapf: enable 54 | 55 | args = parser.parse_args() 56 | 57 | CIFAR_CLASSES = 10 58 | dataset_train_size = 50000 59 | image_size = 32 60 | genotypes.DARTS = genotypes.MY_DARTS_list[args.model_id] 61 | print(genotypes.DARTS) 62 | 63 | 64 | def main(): 65 | image_shape = [3, image_size, image_size] 66 | devices = os.getenv("CUDA_VISIBLE_DEVICES") or "" 67 | devices_num = len(devices.split(",")) 68 | logging.info("args = %s", args) 69 | genotype = eval("genotypes.%s" % args.arch) 70 | model = Network(args.init_channels, CIFAR_CLASSES, args.layers, 71 | args.auxiliary, genotype) 72 | test(model, args, image_shape) 73 | 74 | 75 | def build_program(args, is_train, model, im_shape): 76 | out = [] 77 | py_reader = model.build_input(im_shape, is_train) 78 | prob, acc_1, acc_5 = model.test_model(py_reader, args.init_channels) 79 | out = [py_reader, prob, acc_1, acc_5] 80 | return out 81 | 82 | 83 | def test(model, args, im_shape): 84 | 85 | test_py_reader, prob, acc_1, acc_5 = build_program(args, False, model, 86 | im_shape) 87 | 88 | test_prog = fluid.default_main_program().clone(for_test=True) 89 | 90 | place = fluid.CUDAPlace(0) 91 | exe = fluid.Executor(place) 92 | exe.run(fluid.default_startup_program()) 93 | 94 | # yapf: disable 95 | if args.pretrained_model: 96 | def if_exist(var): 97 | return os.path.exists(os.path.join(args.pretrained_model, var.name)) 98 | fluid.io.load_vars(exe, args.pretrained_model, predicate=if_exist) 99 | 100 | # yapf: enable 101 | 102 | exec_strategy = fluid.ExecutionStrategy() 103 | exec_strategy.num_threads = 1 104 | compile_program = fluid.compiler.CompiledProgram( 105 | test_prog).with_data_parallel(exec_strategy=exec_strategy) 106 | test_reader = reader.test10(args) 107 | test_py_reader.decorate_paddle_reader(test_reader) 108 | 109 | test_fetch_list = [prob, acc_1, acc_5] 110 | prob = [] 111 | top1 = utils.AvgrageMeter() 112 | top5 = utils.AvgrageMeter() 113 | test_py_reader.start() 114 | test_start_time = time.time() 115 | step_id = 0 116 | try: 117 | while True: 118 | prev_test_start_time = test_start_time 119 | test_start_time = time.time() 120 | prob_v, acc_1_v, acc_5_v = exe.run(compile_program, 121 | test_prog, 122 | fetch_list=test_fetch_list) 123 | prob.append(list(np.array(prob_v))) 124 | top1.update(np.array(acc_1_v), np.array(prob_v).shape[0]) 125 | top5.update(np.array(acc_5_v), np.array(prob_v).shape[0]) 126 | if step_id % args.report_freq == 0: 127 | print('prob shape:', np.array(prob_v).shape) 128 | print("Step {}, acc_1 {}, acc_5 {}, time {}".format( 129 | step_id, 130 | np.array(acc_1_v), 131 | np.array(acc_5_v), test_start_time - prev_test_start_time)) 132 | step_id += 1 133 | except fluid.core.EOFException: 134 | test_py_reader.reset() 135 | np.concatenate(prob).dump(args.dump_path) 136 | print("top1 {0}, top5 {1}".format(top1.avg, top5.avg)) 137 | 138 | 139 | if __name__ == '__main__': 140 | main() 141 | -------------------------------------------------------------------------------- /LRC/train_mixup.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 2 | # 3 | #Licensed under the Apache License, Version 2.0 (the "License"); 4 | #you may not use this file except in compliance with the License. 5 | #You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | #Unless required by applicable law or agreed to in writing, software 10 | #distributed under the License is distributed on an "AS IS" BASIS, 11 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | #See the License for the specific language governing permissions and 13 | #limitations under the License. 14 | # 15 | # Based on: 16 | # -------------------------------------------------------- 17 | # DARTS 18 | # Copyright (c) 2018, Hanxiao Liu. 19 | # Licensed under the Apache License, Version 2.0; 20 | # -------------------------------------------------------- 21 | 22 | from __future__ import absolute_import 23 | from __future__ import division 24 | from __future__ import print_function 25 | from learning_rate import cosine_decay 26 | import numpy as np 27 | import argparse 28 | from model import NetworkCIFAR as Network 29 | import reader_cifar as reader 30 | import sys 31 | import os 32 | import time 33 | import logging 34 | import genotypes 35 | import paddle.fluid as fluid 36 | import shutil 37 | import utils 38 | import math 39 | 40 | parser = argparse.ArgumentParser("cifar") 41 | # yapf: disable 42 | parser.add_argument('--data', type=str, default='./dataset/cifar/cifar-10-batches-py/', help='location of the data corpus') 43 | parser.add_argument('--batch_size', type=int, default=96, help='batch size') 44 | parser.add_argument('--pretrained_model', type=str, default=None, help='pretrained model to load') 45 | parser.add_argument('--model_id', type=int, help='model id') 46 | parser.add_argument('--learning_rate', type=float, default=0.025, help='init learning rate') 47 | parser.add_argument('--momentum', type=float, default=0.9, help='momentum') 48 | parser.add_argument('--weight_decay', type=float, default=3e-4, help='weight decay') 49 | parser.add_argument('--report_freq', type=float, default=50, help='report frequency') 50 | parser.add_argument('--epochs', type=int, default=600, help='num of training epochs') 51 | parser.add_argument('--init_channels', type=int, default=36, help='num of init channels') 52 | parser.add_argument('--layers', type=int, default=20, help='total number of layers') 53 | parser.add_argument('--save_model_path', type=str, default='saved_models', help='path to save the model') 54 | parser.add_argument('--auxiliary', action='store_true', default=False, help='use auxiliary tower') 55 | parser.add_argument('--auxiliary_weight', type=float, default=0.4, help='weight for auxiliary loss') 56 | parser.add_argument('--cutout', action='store_true', default=False, help='use cutout') 57 | parser.add_argument('--cutout_length', type=int, default=16, help='cutout length') 58 | parser.add_argument('--drop_path_prob', type=float, default=0.2, help='drop path probability') 59 | parser.add_argument('--arch', type=str, default='DARTS', help='which architecture to use') 60 | parser.add_argument('--grad_clip', type=float, default=5, help='gradient clipping') 61 | parser.add_argument('--lr_exp_decay', action='store_true', default=False, help='use exponential_decay learning_rate') 62 | parser.add_argument('--mix_alpha', type=float, default=0.5, help='mixup alpha') 63 | parser.add_argument('--lrc_loss_lambda', default=0, type=float, help='lrc_loss_lambda') 64 | # yapf: enable 65 | 66 | args = parser.parse_args() 67 | 68 | CIFAR_CLASSES = 10 69 | dataset_train_size = 50000. 70 | image_size = 32 71 | genotypes.DARTS = genotypes.MY_DARTS_list[args.model_id] 72 | 73 | 74 | def main(): 75 | image_shape = [3, image_size, image_size] 76 | devices = os.getenv("CUDA_VISIBLE_DEVICES") or "" 77 | devices_num = len(devices.split(",")) 78 | logging.info("args = %s", args) 79 | genotype = eval("genotypes.%s" % args.arch) 80 | model = Network(args.init_channels, CIFAR_CLASSES, args.layers, 81 | args.auxiliary, genotype) 82 | 83 | steps_one_epoch = math.ceil(dataset_train_size / 84 | (devices_num * args.batch_size)) 85 | train(model, args, image_shape, steps_one_epoch) 86 | 87 | 88 | def build_program(main_prog, startup_prog, args, is_train, model, im_shape, 89 | steps_one_epoch): 90 | out = [] 91 | with fluid.program_guard(main_prog, startup_prog): 92 | py_reader = model.build_input(im_shape, is_train) 93 | if is_train: 94 | with fluid.unique_name.guard(): 95 | loss = model.train_model(py_reader, args.init_channels, 96 | args.auxiliary, args.auxiliary_weight, 97 | args.lrc_loss_lambda) 98 | optimizer = fluid.optimizer.Momentum( 99 | learning_rate=cosine_decay(args.learning_rate, args.epochs, 100 | steps_one_epoch), 101 | regularization=fluid.regularizer.L2Decay(args.weight_decay), 102 | momentum=args.momentum) 103 | optimizer.minimize(loss) 104 | out = [py_reader, loss] 105 | else: 106 | with fluid.unique_name.guard(): 107 | prob, acc_1, acc_5 = model.test_model(py_reader, 108 | args.init_channels) 109 | out = [py_reader, prob, acc_1, acc_5] 110 | return out 111 | 112 | 113 | def train(model, args, im_shape, steps_one_epoch): 114 | startup_prog = fluid.Program() 115 | train_prog = fluid.Program() 116 | test_prog = fluid.Program() 117 | 118 | train_py_reader, loss_train = build_program( 119 | train_prog, startup_prog, args, True, model, im_shape, steps_one_epoch) 120 | 121 | test_py_reader, prob, acc_1, acc_5 = build_program( 122 | test_prog, startup_prog, args, False, model, im_shape, steps_one_epoch) 123 | 124 | test_prog = test_prog.clone(for_test=True) 125 | 126 | place = fluid.CUDAPlace(0) 127 | exe = fluid.Executor(place) 128 | exe.run(startup_prog) 129 | 130 | if args.pretrained_model: 131 | 132 | def if_exist(var): 133 | return os.path.exists(os.path.join(args.pretrained_model, var.name)) 134 | 135 | fluid.io.load_vars( 136 | exe, 137 | args.pretrained_model, 138 | main_program=train_prog, 139 | predicate=if_exist) 140 | 141 | exec_strategy = fluid.ExecutionStrategy() 142 | exec_strategy.num_threads = 1 143 | build_strategy = fluid.BuildStrategy() 144 | build_strategy.memory_optimize = False 145 | build_strategy.enable_inplace = True 146 | 147 | compile_program = fluid.compiler.CompiledProgram( 148 | train_prog).with_data_parallel( 149 | loss_name=loss_train.name, 150 | build_strategy=build_strategy, 151 | exec_strategy=exec_strategy) 152 | 153 | train_reader = reader.train10(args) 154 | test_reader = reader.test10(args) 155 | train_py_reader.decorate_paddle_reader(train_reader) 156 | test_py_reader.decorate_paddle_reader(test_reader) 157 | 158 | fluid.clip.set_gradient_clip( 159 | fluid.clip.GradientClipByGlobalNorm(args.grad_clip), program=train_prog) 160 | train_fetch_list = [loss_train] 161 | 162 | def save_model(postfix, main_prog): 163 | model_path = os.path.join(args.save_model_path, postfix) 164 | if os.path.isdir(model_path): 165 | shutil.rmtree(model_path) 166 | fluid.io.save_persistables(exe, model_path, main_program=main_prog) 167 | 168 | def test(epoch_id): 169 | test_fetch_list = [prob, acc_1, acc_5] 170 | top1 = utils.AvgrageMeter() 171 | top5 = utils.AvgrageMeter() 172 | test_py_reader.start() 173 | test_start_time = time.time() 174 | step_id = 0 175 | try: 176 | while True: 177 | prev_test_start_time = test_start_time 178 | test_start_time = time.time() 179 | prob_v, acc_1_v, acc_5_v = exe.run(test_prog, 180 | fetch_list=test_fetch_list) 181 | top1.update(np.array(acc_1_v), np.array(prob_v).shape[0]) 182 | top5.update(np.array(acc_5_v), np.array(prob_v).shape[0]) 183 | if step_id % args.report_freq == 0: 184 | print("Epoch {}, Step {}, acc_1 {}, acc_5 {}, time {}". 185 | format(epoch_id, step_id, 186 | np.array(acc_1_v), 187 | np.array(acc_5_v), test_start_time - 188 | prev_test_start_time)) 189 | step_id += 1 190 | except fluid.core.EOFException: 191 | test_py_reader.reset() 192 | print("Epoch {0}, top1 {1}, top5 {2}".format(epoch_id, top1.avg, 193 | top5.avg)) 194 | 195 | epoch_start_time = time.time() 196 | for epoch_id in range(args.epochs): 197 | model.drop_path_prob = args.drop_path_prob * epoch_id / args.epochs 198 | train_py_reader.start() 199 | epoch_end_time = time.time() 200 | if epoch_id > 0: 201 | print("Epoch {}, total time {}".format(epoch_id - 1, epoch_end_time 202 | - epoch_start_time)) 203 | epoch_start_time = epoch_end_time 204 | epoch_end_time 205 | start_time = time.time() 206 | step_id = 0 207 | try: 208 | while True: 209 | prev_start_time = start_time 210 | start_time = time.time() 211 | loss_v, = exe.run( 212 | compile_program, 213 | fetch_list=[v.name for v in train_fetch_list]) 214 | print("Epoch {}, Step {}, loss {}, time {}".format(epoch_id, step_id, \ 215 | np.array(loss_v).mean(), start_time-prev_start_time)) 216 | step_id += 1 217 | sys.stdout.flush() 218 | except fluid.core.EOFException: 219 | train_py_reader.reset() 220 | if epoch_id % 50 == 0: 221 | save_model(str(epoch_id), train_prog) 222 | if epoch_id == args.epochs - 1: 223 | save_model('final', train_prog) 224 | test(epoch_id) 225 | 226 | 227 | if __name__ == '__main__': 228 | main() 229 | -------------------------------------------------------------------------------- /LRC/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # Based on: 16 | # -------------------------------------------------------- 17 | # DARTS 18 | # Copyright (c) 2018, Hanxiao Liu. 19 | # Licensed under the Apache License, Version 2.0; 20 | # -------------------------------------------------------- 21 | 22 | import os 23 | import sys 24 | import time 25 | import math 26 | import numpy as np 27 | 28 | 29 | def mixup_data(x, y, batch_size, alpha=1.0): 30 | '''Compute the mixup data. Return mixed inputs, pairs of targets, and lambda''' 31 | if alpha > 0.: 32 | lam = np.random.beta(alpha, alpha) 33 | else: 34 | lam = 1. 35 | index = np.random.permutation(batch_size) 36 | 37 | mixed_x = lam * x + (1 - lam) * x[index, :] 38 | y_a, y_b = y, y[index] 39 | return mixed_x.astype('float32'), y_a.astype('int64'),\ 40 | y_b.astype('int64'), np.array(lam, dtype='float32') 41 | 42 | 43 | class AvgrageMeter(object): 44 | def __init__(self): 45 | self.reset() 46 | 47 | def reset(self): 48 | self.avg = 0 49 | self.sum = 0 50 | self.cnt = 0 51 | 52 | def update(self, val, n=1): 53 | self.sum += val * n 54 | self.cnt += n 55 | self.avg = self.sum / self.cnt 56 | -------------------------------------------------------------------------------- /LRC/voting.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | try: 3 | import cPickle as pickle 4 | except ImportError: 5 | import pickle 6 | import sys, os 7 | 8 | model_path = 'paddle_predict' 9 | fl = os.listdir(model_path) 10 | labels = np.load('labels.npz')['arr_0'] 11 | pred = np.zeros((10000, 10)) 12 | fl.sort() 13 | i = 0 14 | for f in fl: 15 | if 'init' in f: 16 | continue 17 | print(f) 18 | pred += pickle.load(open(os.path.join(model_path, f))) 19 | print(np.mean(np.argmax(pred, axis=1) == labels)) 20 | i += 1 21 | -------------------------------------------------------------------------------- /NAS-Models/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.whl 3 | snapshots 4 | -------------------------------------------------------------------------------- /NAS-Models/README.md: -------------------------------------------------------------------------------- 1 | # Image Classification based on NAS-Searched Models 2 | 3 | This directory contains 10 image classification models. 4 | Nine of them are automatically searched models using different Neural Architecture Search (NAS) algorithms, and the other is the residual network. 5 | We provide codes and scripts to train these models on both CIFAR-10 and CIFAR-100. 6 | We use the standard data augmentation, i.e., random crop, random flip, and normalization. 7 | 8 | Please find the Chinese documentation (中文文档) in `README_CN.md`. 9 | 10 | --- 11 | ## Table of Contents 12 | - [Installation](#installation) 13 | - [Data Preparation](#data-preparation) 14 | - [Training Models](#training-models) 15 | - [Project Structure](#project-structure) 16 | - [Citation](#citation) 17 | 18 | 19 | ### Installation 20 | This project has the following requirements: 21 | - Python = 3.6 22 | - PadddlePaddle Fluid >= v0.15.0 23 | - numpy, tarfile, cPickle, PIL 24 | 25 | 26 | ### Data Preparation 27 | Please download [CIFAR-10](https://dataset.bj.bcebos.com/cifar/cifar-10-python.tar.gz) and [CIFAR-100](https://dataset.bj.bcebos.com/cifar/cifar-100-python.tar.gz) before running the codes. 28 | Note that the MD5 of CIFAR-10-Python compressed file is `c58f30108f718f92721af3b95e74349a` and the MD5 of CIFAR-100-Python compressed file is `eb9058c3a382ffc7106e4002c42a8d85`. 29 | Please save the file into `${TORCH_HOME}/cifar.python`. 30 | After data preparation, there should be two files `${TORCH_HOME}/cifar.python/cifar-10-python.tar.gz` and `${TORCH_HOME}/cifar.python/cifar-100-python.tar.gz`. 31 | 32 | 33 | ### Training Models 34 | 35 | After setting up the environment and preparing the data, you can train the model. The main function entrance is `train_cifar.py`. We also provide some scripts for easy usage. 36 | ``` 37 | bash ./scripts/base-train.sh 0 cifar-10 ResNet110 38 | bash ./scripts/train-nas.sh 0 cifar-10 GDAS_V1 39 | bash ./scripts/train-nas.sh 0 cifar-10 GDAS_V2 40 | bash ./scripts/train-nas.sh 0 cifar-10 SETN 41 | bash ./scripts/train-nas.sh 0 cifar-10 NASNet 42 | bash ./scripts/train-nas.sh 0 cifar-10 ENASNet 43 | bash ./scripts/train-nas.sh 0 cifar-10 AmoebaNet 44 | bash ./scripts/train-nas.sh 0 cifar-10 PNASNet 45 | bash ./scripts/train-nas.sh 0 cifar-100 SETN 46 | ``` 47 | The first argument is the GPU-ID to train your program, the second argument is the dataset name (`cifar-10` or `cifar-100`), and the last one is the model name. 48 | Please use `./scripts/base-train.sh` for ResNet and use `./scripts/train-nas.sh` for NAS-searched models. 49 | 50 | 51 | ### Project Structure 52 | ``` 53 | . 54 | ├──train_cifar.py [Training CNN models] 55 | ├──lib [Library for dataset, models, and others] 56 | │ └──models 57 | │ ├──__init__.py [Import useful Classes and Functions in models] 58 | │ ├──resnet.py [Define the ResNet models] 59 | │ ├──operations.py [Define the atomic operation in NAS search space] 60 | │ ├──genotypes.py [Define the topological structure of different NAS-searched models] 61 | │ └──nas_net.py [Define the macro structure of NAS models] 62 | │ └──utils 63 | │ ├──__init__.py [Import useful Classes and Functions in utils] 64 | │ ├──meter.py [Define the AverageMeter class to count the accuracy and loss] 65 | │ ├──time_utils.py [Define some functions to print date or convert seconds into hours] 66 | │ └──data_utils.py [Define data augmentation functions and dataset reader for CIFAR] 67 | └──scripts [Scripts for running] 68 | ``` 69 | 70 | 71 | ### Citation 72 | If you find that this project helps your research, please consider citing some of these papers: 73 | ``` 74 | @inproceedings{dong2019one, 75 | title = {One-Shot Neural Architecture Search via Self-Evaluated Template Network}, 76 | author = {Dong, Xuanyi and Yang, Yi}, 77 | booktitle = {Proceedings of the IEEE International Conference on Computer Vision (ICCV)}, 78 | year = {2019} 79 | } 80 | @inproceedings{dong2019search, 81 | title = {Searching for A Robust Neural Architecture in Four GPU Hours}, 82 | author = {Dong, Xuanyi and Yang, Yi}, 83 | booktitle = {Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, 84 | pages = {1761--1770}, 85 | year = {2019} 86 | } 87 | @inproceedings{liu2018darts, 88 | title = {Darts: Differentiable architecture search}, 89 | author = {Liu, Hanxiao and Simonyan, Karen and Yang, Yiming}, 90 | booktitle = {International Conference on Learning Representations (ICLR)}, 91 | year = {2018} 92 | } 93 | @inproceedings{pham2018efficient, 94 | title = {Efficient Neural Architecture Search via Parameter Sharing}, 95 | author = {Pham, Hieu and Guan, Melody and Zoph, Barret and Le, Quoc and Dean, Jeff}, 96 | booktitle = {International Conference on Machine Learning (ICML)}, 97 | pages = {4092--4101}, 98 | year = {2018} 99 | } 100 | @inproceedings{liu2018progressive, 101 | title = {Progressive neural architecture search}, 102 | author = {Liu, Chenxi and Zoph, Barret and Neumann, Maxim and Shlens, Jonathon and Hua, Wei and Li, Li-Jia and Fei-Fei, Li and Yuille, Alan and Huang, Jonathan and Murphy, Kevin}, 103 | booktitle = {Proceedings of the European Conference on Computer Vision (ECCV)}, 104 | pages = {19--34}, 105 | year = {2018} 106 | } 107 | @inproceedings{zoph2018learning, 108 | title = {Learning transferable architectures for scalable image recognition}, 109 | author = {Zoph, Barret and Vasudevan, Vijay and Shlens, Jonathon and Le, Quoc V}, 110 | booktitle = {Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, 111 | pages = {8697--8710}, 112 | year = {2018} 113 | } 114 | @inproceedings{real2019regularized, 115 | title = {Regularized evolution for image classifier architecture search}, 116 | author = {Real, Esteban and Aggarwal, Alok and Huang, Yanping and Le, Quoc V}, 117 | booktitle = {Proceedings of the AAAI Conference on Artificial Intelligence (AAAI)}, 118 | pages = {4780--4789}, 119 | year = {2019} 120 | } 121 | ``` 122 | -------------------------------------------------------------------------------- /NAS-Models/README_CN.md: -------------------------------------------------------------------------------- 1 | # 基于神经网络搜索的图片分类 2 | 3 | 该项目包含了10种图片分类模型。其中的九种模型是由不同的神经网络搜索(NAS)算法自动搜索出来的,另外一种是ResNet模型。 4 | 我们提供了代码和训练脚本来在CIFAR-10和CIFAR-100数据集上训练和测试这些模型。 5 | 在训练过程中,我们使用了标准的数据增强技术,即随机裁剪,随机翻转,和归一化。 6 | 7 | --- 8 | ## 内容概括 9 | - [安装说明](#安装说明) 10 | - [数据准备](#数据准备) 11 | - [训练模型](#训练模型) 12 | - [项目文件结构介绍](#项目文件结构) 13 | - [引用](#引用) 14 | 15 | 16 | ### 安装说明 17 | 这个项目依赖于以下一些软件包: 18 | - Python = 3.6 19 | - PadddlePaddle Fluid >= v0.15.0 20 | - numpy, tarfile, cPickle, PIL 21 | 22 | 23 | ### 数据准备 24 | 请在运行代码前下载 [CIFAR-10](https://dataset.bj.bcebos.com/cifar/cifar-10-python.tar.gz) 和 [CIFAR-100](https://dataset.bj.bcebos.com/cifar/cifar-100-python.tar.gz)。 25 | 请注意CIFAR-10-Python压缩文件的MD5值是`c58f30108f718f92721af3b95e74349a`,CIFAR-100-Python压缩文件的MD5值是`eb9058c3a382ffc7106e4002c42a8d85`。 26 | 请将这两个下载文件保存在`${TORCH_HOME}/cifar.python`路径下。在数据准备之后,应该有两个文件:`${TORCH_HOME}/cifar.python/cifar-10-python.tar.gz`和`${TORCH_HOME}/cifar.python/cifar-100-python.tar.gz`。 27 | 28 | 29 | ### Training Models 30 | 31 | 在设置好环境和准备好数据之后,您可以开始训练模型了。训练的主要入口文件是在`train_cifar.py`中,我们提供了方便的脚本可以直接训练,如下: 32 | ``` 33 | bash ./scripts/base-train.sh 0 cifar-10 ResNet110 34 | bash ./scripts/train-nas.sh 0 cifar-10 GDAS_V1 35 | bash ./scripts/train-nas.sh 0 cifar-10 GDAS_V2 36 | bash ./scripts/train-nas.sh 0 cifar-10 SETN 37 | bash ./scripts/train-nas.sh 0 cifar-10 NASNet 38 | bash ./scripts/train-nas.sh 0 cifar-10 ENASNet 39 | bash ./scripts/train-nas.sh 0 cifar-10 AmoebaNet 40 | bash ./scripts/train-nas.sh 0 cifar-10 PNASNet 41 | bash ./scripts/train-nas.sh 0 cifar-100 SETN 42 | ``` 43 | 第一个参数指定在哪块GPU上运行该的程序(GPU-ID),第二个参数指定数据集名称(`cifar-10`或`cifar-100`),第三个参数是指定了模型名称。 44 | 如果您要训练ResNet模型,请使用`./scripts/base-train.sh`;如果您要训练NAS搜索出的模型,请使用`./scripts/train-nas.sh`。 45 | 46 | 47 | ### 项目文件结构 48 | ``` 49 | . 50 | ├──train_cifar.py [训练卷积神经网络模型的文件] 51 | ├──lib [数据集,模型,及其他相关库] 52 | │ └──models 53 | │ ├──__init__.py [引用一些模型相关的函数和类] 54 | │ ├──resnet.py [定义ResNet模型] 55 | │ ├──operations.py [定义了NAS搜索空间中的一些原子级操作] 56 | │ ├──genotypes.py [定义了不同的NAS搜索出的模型的拓扑结构] 57 | │ └──nas_net.py [定义了NAS模型的宏观结构] 58 | │ └──utils 59 | │ ├──__init__.py [引用一些辅助模块] 60 | │ ├──meter.py [定义了AverageMeter类来统计模型的准确率和损失函数值] 61 | │ ├──time_utils.py [定义了打印时间和转换时间度量的函数] 62 | │ └──data_utils.py [定义了数据集相关的读取和数据增强相关的函数] 63 | └──scripts [运行脚本] 64 | ``` 65 | 66 | 67 | ### 引用 68 | 如果您发现这个项目对您的研究有帮助,请考虑引用下面的某些论文: 69 | ``` 70 | @inproceedings{dong2019one, 71 | title = {One-Shot Neural Architecture Search via Self-Evaluated Template Network}, 72 | author = {Dong, Xuanyi and Yang, Yi}, 73 | booktitle = {Proceedings of the IEEE International Conference on Computer Vision (ICCV)}, 74 | year = {2019} 75 | } 76 | @inproceedings{dong2019search, 77 | title = {Searching for A Robust Neural Architecture in Four GPU Hours}, 78 | author = {Dong, Xuanyi and Yang, Yi}, 79 | booktitle = {Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, 80 | pages = {1761--1770}, 81 | year = {2019} 82 | } 83 | @inproceedings{liu2018darts, 84 | title = {Darts: Differentiable architecture search}, 85 | author = {Liu, Hanxiao and Simonyan, Karen and Yang, Yiming}, 86 | booktitle = {International Conference on Learning Representations (ICLR)}, 87 | year = {2018} 88 | } 89 | @inproceedings{pham2018efficient, 90 | title = {Efficient Neural Architecture Search via Parameter Sharing}, 91 | author = {Pham, Hieu and Guan, Melody and Zoph, Barret and Le, Quoc and Dean, Jeff}, 92 | booktitle = {International Conference on Machine Learning (ICML)}, 93 | pages = {4092--4101}, 94 | year = {2018} 95 | } 96 | @inproceedings{liu2018progressive, 97 | title = {Progressive neural architecture search}, 98 | author = {Liu, Chenxi and Zoph, Barret and Neumann, Maxim and Shlens, Jonathon and Hua, Wei and Li, Li-Jia and Fei-Fei, Li and Yuille, Alan and Huang, Jonathan and Murphy, Kevin}, 99 | booktitle = {Proceedings of the European Conference on Computer Vision (ECCV)}, 100 | pages = {19--34}, 101 | year = {2018} 102 | } 103 | @inproceedings{zoph2018learning, 104 | title = {Learning transferable architectures for scalable image recognition}, 105 | author = {Zoph, Barret and Vasudevan, Vijay and Shlens, Jonathon and Le, Quoc V}, 106 | booktitle = {Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, 107 | pages = {8697--8710}, 108 | year = {2018} 109 | } 110 | @inproceedings{real2019regularized, 111 | title = {Regularized evolution for image classifier architecture search}, 112 | author = {Real, Esteban and Aggarwal, Alok and Huang, Yanping and Le, Quoc V}, 113 | booktitle = {Proceedings of the AAAI Conference on Artificial Intelligence (AAAI)}, 114 | pages = {4780--4789}, 115 | year = {2019} 116 | } 117 | ``` 118 | -------------------------------------------------------------------------------- /NAS-Models/lib/models/__init__.py: -------------------------------------------------------------------------------- 1 | from .genotypes import Networks 2 | from .nas_net import NASCifarNet 3 | from .resnet import resnet_cifar 4 | -------------------------------------------------------------------------------- /NAS-Models/lib/models/genotypes.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | 3 | Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat') 4 | 5 | # Learning Transferable Architectures for Scalable Image Recognition, CVPR 2018 6 | NASNet = Genotype( 7 | normal=[ 8 | (('sep_conv_5x5', 1), ('sep_conv_3x3', 0)), 9 | (('sep_conv_5x5', 0), ('sep_conv_3x3', 0)), 10 | (('avg_pool_3x3', 1), ('skip_connect', 0)), 11 | (('avg_pool_3x3', 0), ('avg_pool_3x3', 0)), 12 | (('sep_conv_3x3', 1), ('skip_connect', 1)), 13 | ], 14 | normal_concat=[2, 3, 4, 5, 6], 15 | reduce=[ 16 | (('sep_conv_5x5', 1), ('sep_conv_7x7', 0)), 17 | (('max_pool_3x3', 1), ('sep_conv_7x7', 0)), 18 | (('avg_pool_3x3', 1), ('sep_conv_5x5', 0)), 19 | (('skip_connect', 3), ('avg_pool_3x3', 2)), 20 | (('sep_conv_3x3', 2), ('max_pool_3x3', 1)), 21 | ], 22 | reduce_concat=[4, 5, 6], ) 23 | 24 | # Progressive Neural Architecture Search, ECCV 2018 25 | PNASNet = Genotype( 26 | normal=[ 27 | (('sep_conv_5x5', 0), ('max_pool_3x3', 0)), 28 | (('sep_conv_7x7', 1), ('max_pool_3x3', 1)), 29 | (('sep_conv_5x5', 1), ('sep_conv_3x3', 1)), 30 | (('sep_conv_3x3', 4), ('max_pool_3x3', 1)), 31 | (('sep_conv_3x3', 0), ('skip_connect', 1)), 32 | ], 33 | normal_concat=[2, 3, 4, 5, 6], 34 | reduce=[ 35 | (('sep_conv_5x5', 0), ('max_pool_3x3', 0)), 36 | (('sep_conv_7x7', 1), ('max_pool_3x3', 1)), 37 | (('sep_conv_5x5', 1), ('sep_conv_3x3', 1)), 38 | (('sep_conv_3x3', 4), ('max_pool_3x3', 1)), 39 | (('sep_conv_3x3', 0), ('skip_connect', 1)), 40 | ], 41 | reduce_concat=[2, 3, 4, 5, 6], ) 42 | 43 | # Regularized Evolution for Image Classifier Architecture Search, AAAI 2019 44 | AmoebaNet = Genotype( 45 | normal=[ 46 | (('avg_pool_3x3', 0), ('max_pool_3x3', 1)), 47 | (('sep_conv_3x3', 0), ('sep_conv_5x5', 2)), 48 | (('sep_conv_3x3', 0), ('avg_pool_3x3', 3)), 49 | (('sep_conv_3x3', 1), ('skip_connect', 1)), 50 | (('skip_connect', 0), ('avg_pool_3x3', 1)), 51 | ], 52 | normal_concat=[4, 5, 6], 53 | reduce=[ 54 | (('avg_pool_3x3', 0), ('sep_conv_3x3', 1)), 55 | (('max_pool_3x3', 0), ('sep_conv_7x7', 2)), 56 | (('sep_conv_7x7', 0), ('avg_pool_3x3', 1)), 57 | (('max_pool_3x3', 0), ('max_pool_3x3', 1)), 58 | (('conv_7x1_1x7', 0), ('sep_conv_3x3', 5)), 59 | ], 60 | reduce_concat=[3, 4, 6]) 61 | 62 | # Efficient Neural Architecture Search via Parameter Sharing, ICML 2018 63 | ENASNet = Genotype( 64 | normal=[ 65 | (('sep_conv_3x3', 1), ('skip_connect', 1)), 66 | (('sep_conv_5x5', 1), ('skip_connect', 0)), 67 | (('avg_pool_3x3', 0), ('sep_conv_3x3', 1)), 68 | (('sep_conv_3x3', 0), ('avg_pool_3x3', 1)), 69 | (('sep_conv_5x5', 1), ('avg_pool_3x3', 0)), 70 | ], 71 | normal_concat=[2, 3, 4, 5, 6], 72 | reduce=[ 73 | (('sep_conv_5x5', 0), ('sep_conv_3x3', 1)), # 2 74 | (('sep_conv_3x3', 1), ('avg_pool_3x3', 1)), # 3 75 | (('sep_conv_3x3', 1), ('avg_pool_3x3', 1)), # 4 76 | (('avg_pool_3x3', 1), ('sep_conv_5x5', 4)), # 5 77 | (('sep_conv_3x3', 5), ('sep_conv_5x5', 0)), 78 | ], 79 | reduce_concat=[2, 3, 4, 5, 6], ) 80 | 81 | # DARTS: Differentiable Architecture Search, ICLR 2019 82 | DARTS_V1 = Genotype( 83 | normal=[ 84 | (('sep_conv_3x3', 1), ('sep_conv_3x3', 0)), # step 1 85 | (('skip_connect', 0), ('sep_conv_3x3', 1)), # step 2 86 | (('skip_connect', 0), ('sep_conv_3x3', 1)), # step 3 87 | (('sep_conv_3x3', 0), ('skip_connect', 2)) # step 4 88 | ], 89 | normal_concat=[2, 3, 4, 5], 90 | reduce=[ 91 | (('max_pool_3x3', 0), ('max_pool_3x3', 1)), # step 1 92 | (('skip_connect', 2), ('max_pool_3x3', 0)), # step 2 93 | (('max_pool_3x3', 0), ('skip_connect', 2)), # step 3 94 | (('skip_connect', 2), ('avg_pool_3x3', 0)) # step 4 95 | ], 96 | reduce_concat=[2, 3, 4, 5], ) 97 | 98 | # DARTS: Differentiable Architecture Search, ICLR 2019 99 | DARTS_V2 = Genotype( 100 | normal=[ 101 | (('sep_conv_3x3', 0), ('sep_conv_3x3', 1)), # step 1 102 | (('sep_conv_3x3', 0), ('sep_conv_3x3', 1)), # step 2 103 | (('sep_conv_3x3', 1), ('skip_connect', 0)), # step 3 104 | (('skip_connect', 0), ('dil_conv_3x3', 2)) # step 4 105 | ], 106 | normal_concat=[2, 3, 4, 5], 107 | reduce=[ 108 | (('max_pool_3x3', 0), ('max_pool_3x3', 1)), # step 1 109 | (('skip_connect', 2), ('max_pool_3x3', 1)), # step 2 110 | (('max_pool_3x3', 0), ('skip_connect', 2)), # step 3 111 | (('skip_connect', 2), ('max_pool_3x3', 1)) # step 4 112 | ], 113 | reduce_concat=[2, 3, 4, 5], ) 114 | 115 | # One-Shot Neural Architecture Search via Self-Evaluated Template Network, ICCV 2019 116 | SETN = Genotype( 117 | normal=[(('skip_connect', 0), ('sep_conv_5x5', 1)), ( 118 | ('sep_conv_5x5', 0), ('sep_conv_3x3', 1)), ( 119 | ('sep_conv_5x5', 1), ('sep_conv_5x5', 3)), (('max_pool_3x3', 1), 120 | ('conv_3x1_1x3', 4))], 121 | normal_concat=[2, 3, 4, 5], 122 | reduce=[(('sep_conv_3x3', 0), ('sep_conv_5x5', 1)), ( 123 | ('avg_pool_3x3', 0), ('sep_conv_5x5', 1)), ( 124 | ('avg_pool_3x3', 0), ('sep_conv_5x5', 1)), (('avg_pool_3x3', 0), 125 | ('skip_connect', 1))], 126 | reduce_concat=[2, 3, 4, 5], ) 127 | 128 | # Searching for A Robust Neural Architecture in Four GPU Hours, CVPR 2019 129 | GDAS_V1 = Genotype( 130 | normal=[(('skip_connect', 0), ('skip_connect', 1)), ( 131 | ('skip_connect', 0), ('sep_conv_5x5', 2)), ( 132 | ('sep_conv_3x3', 3), ('skip_connect', 0)), (('sep_conv_5x5', 4), 133 | ('sep_conv_3x3', 3))], 134 | normal_concat=[2, 3, 4, 5], 135 | reduce=[(('sep_conv_5x5', 0), ('sep_conv_3x3', 1)), ( 136 | ('sep_conv_5x5', 2), ('sep_conv_5x5', 1)), ( 137 | ('dil_conv_5x5', 2), ('sep_conv_3x3', 1)), (('sep_conv_5x5', 0), 138 | ('sep_conv_5x5', 1))], 139 | reduce_concat=[2, 3, 4, 5], ) 140 | 141 | Networks = { 142 | 'DARTS_V1': DARTS_V1, 143 | 'DARTS_V2': DARTS_V2, 144 | 'DARTS': DARTS_V2, 145 | 'NASNet': NASNet, 146 | 'ENASNet': ENASNet, 147 | 'AmoebaNet': AmoebaNet, 148 | 'GDAS_V1': GDAS_V1, 149 | 'PNASNet': PNASNet, 150 | 'SETN': SETN, 151 | } 152 | -------------------------------------------------------------------------------- /NAS-Models/lib/models/nas_net.py: -------------------------------------------------------------------------------- 1 | import paddle 2 | import paddle.fluid as fluid 3 | from .operations import OPS 4 | 5 | 6 | def AuxiliaryHeadCIFAR(inputs, C, class_num): 7 | print('AuxiliaryHeadCIFAR : inputs-shape : {:}'.format(inputs.shape)) 8 | temp = fluid.layers.relu(inputs) 9 | temp = fluid.layers.pool2d( 10 | temp, pool_size=5, pool_stride=3, pool_padding=0, pool_type='avg') 11 | temp = fluid.layers.conv2d( 12 | temp, 13 | filter_size=1, 14 | num_filters=128, 15 | stride=1, 16 | padding=0, 17 | act=None, 18 | bias_attr=False) 19 | temp = fluid.layers.batch_norm(input=temp, act='relu', bias_attr=None) 20 | temp = fluid.layers.conv2d( 21 | temp, 22 | filter_size=1, 23 | num_filters=768, 24 | stride=2, 25 | padding=0, 26 | act=None, 27 | bias_attr=False) 28 | temp = fluid.layers.batch_norm(input=temp, act='relu', bias_attr=None) 29 | print('AuxiliaryHeadCIFAR : last---shape : {:}'.format(temp.shape)) 30 | predict = fluid.layers.fc(input=temp, size=class_num, act='softmax') 31 | return predict 32 | 33 | 34 | def InferCell(name, inputs_prev_prev, inputs_prev, genotype, C_prev_prev, 35 | C_prev, C, reduction, reduction_prev): 36 | print( 37 | '[{:}] C_prev_prev={:} C_prev={:}, C={:}, reduction_prev={:}, reduction={:}'. 38 | format(name, C_prev_prev, C_prev, C, reduction_prev, reduction)) 39 | print('inputs_prev_prev : {:}'.format(inputs_prev_prev.shape)) 40 | print('inputs_prev : {:}'.format(inputs_prev.shape)) 41 | inputs_prev_prev = OPS['skip_connect'](inputs_prev_prev, C_prev_prev, C, 2 42 | if reduction_prev else 1) 43 | inputs_prev = OPS['skip_connect'](inputs_prev, C_prev, C, 1) 44 | print('inputs_prev_prev : {:}'.format(inputs_prev_prev.shape)) 45 | print('inputs_prev : {:}'.format(inputs_prev.shape)) 46 | if reduction: step_ops, concat = genotype.reduce, genotype.reduce_concat 47 | else: step_ops, concat = genotype.normal, genotype.normal_concat 48 | states = [inputs_prev_prev, inputs_prev] 49 | for istep, operations in enumerate(step_ops): 50 | op_a, op_b = operations 51 | # the first operation 52 | #print ('-->>[{:}/{:}] [{:}] + [{:}]'.format(istep, len(step_ops), op_a, op_b)) 53 | stride = 2 if reduction and op_a[1] < 2 else 1 54 | tensor1 = OPS[op_a[0]](states[op_a[1]], C, C, stride) 55 | stride = 2 if reduction and op_b[1] < 2 else 1 56 | tensor2 = OPS[op_b[0]](states[op_b[1]], C, C, stride) 57 | state = fluid.layers.elementwise_add(x=tensor1, y=tensor2, act=None) 58 | assert tensor1.shape == tensor2.shape, 'invalid shape {:} vs. {:}'.format( 59 | tensor1.shape, tensor2.shape) 60 | print('-->>[{:}/{:}] tensor={:} from {:} + {:}'.format( 61 | istep, len(step_ops), state.shape, tensor1.shape, tensor2.shape)) 62 | states.append(state) 63 | states_to_cat = [states[x] for x in concat] 64 | outputs = fluid.layers.concat(states_to_cat, axis=1) 65 | print('-->> output-shape : {:} from concat={:}'.format(outputs.shape, 66 | concat)) 67 | return outputs 68 | 69 | 70 | # NASCifarNet(inputs, 36, 6, 3, 10, 'xxx', True) 71 | def NASCifarNet(ipt, C, N, stem_multiplier, class_num, genotype, auxiliary): 72 | # cifar head module 73 | C_curr = stem_multiplier * C 74 | stem = fluid.layers.conv2d( 75 | ipt, 76 | filter_size=3, 77 | num_filters=C_curr, 78 | stride=1, 79 | padding=1, 80 | act=None, 81 | bias_attr=False) 82 | stem = fluid.layers.batch_norm(input=stem, act=None, bias_attr=None) 83 | print('stem-shape : {:}'.format(stem.shape)) 84 | # N + 1 + N + 1 + N cells 85 | layer_channels = [C] * N + [C * 2] + [C * 2] * N + [C * 4] + [C * 4] * N 86 | layer_reductions = [False] * N + [True] + [False] * N + [True] + [False] * N 87 | C_prev_prev, C_prev, C_curr = C_curr, C_curr, C 88 | reduction_prev = False 89 | auxiliary_pred = None 90 | 91 | cell_results = [stem, stem] 92 | for index, (C_curr, 93 | reduction) in enumerate(zip(layer_channels, layer_reductions)): 94 | xstr = '{:02d}/{:02d}'.format(index, len(layer_channels)) 95 | cell_result = InferCell(xstr, cell_results[-2], cell_results[-1], 96 | genotype, C_prev_prev, C_prev, C_curr, 97 | reduction, reduction_prev) 98 | reduction_prev = reduction 99 | C_prev_prev, C_prev = C_prev, cell_result.shape[1] 100 | cell_results.append(cell_result) 101 | if auxiliary and reduction and C_curr == C * 4: 102 | auxiliary_pred = AuxiliaryHeadCIFAR(cell_result, C_prev, class_num) 103 | 104 | global_P = fluid.layers.pool2d( 105 | input=cell_results[-1], pool_size=8, pool_type='avg', pool_stride=1) 106 | predicts = fluid.layers.fc(input=global_P, size=class_num, act='softmax') 107 | print('predict-shape : {:}'.format(predicts.shape)) 108 | if auxiliary_pred is None: 109 | return predicts 110 | else: 111 | return [predicts, auxiliary_pred] 112 | -------------------------------------------------------------------------------- /NAS-Models/lib/models/operations.py: -------------------------------------------------------------------------------- 1 | import paddle 2 | import paddle.fluid as fluid 3 | 4 | OPS = { 5 | 'none': lambda inputs, C_in, C_out, stride: ZERO(inputs, stride), 6 | 'avg_pool_3x3': 7 | lambda inputs, C_in, C_out, stride: POOL_3x3(inputs, C_in, C_out, stride, 'avg'), 8 | 'max_pool_3x3': 9 | lambda inputs, C_in, C_out, stride: POOL_3x3(inputs, C_in, C_out, stride, 'max'), 10 | 'skip_connect': 11 | lambda inputs, C_in, C_out, stride: Identity(inputs, C_in, C_out, stride), 12 | 'sep_conv_3x3': 13 | lambda inputs, C_in, C_out, stride: SepConv(inputs, C_in, C_out, 3, stride, 1), 14 | 'sep_conv_5x5': 15 | lambda inputs, C_in, C_out, stride: SepConv(inputs, C_in, C_out, 5, stride, 2), 16 | 'sep_conv_7x7': 17 | lambda inputs, C_in, C_out, stride: SepConv(inputs, C_in, C_out, 7, stride, 3), 18 | 'dil_conv_3x3': 19 | lambda inputs, C_in, C_out, stride: DilConv(inputs, C_in, C_out, 3, stride, 2, 2), 20 | 'dil_conv_5x5': 21 | lambda inputs, C_in, C_out, stride: DilConv(inputs, C_in, C_out, 5, stride, 4, 2), 22 | 'conv_3x1_1x3': 23 | lambda inputs, C_in, C_out, stride: Conv313(inputs, C_in, C_out, stride), 24 | 'conv_7x1_1x7': 25 | lambda inputs, C_in, C_out, stride: Conv717(inputs, C_in, C_out, stride), 26 | } 27 | 28 | 29 | def ReLUConvBN(inputs, C_in, C_out, kernel, stride, padding): 30 | temp = fluid.layers.relu(inputs) 31 | temp = fluid.layers.conv2d( 32 | temp, 33 | filter_size=kernel, 34 | num_filters=C_out, 35 | stride=stride, 36 | padding=padding, 37 | act=None, 38 | bias_attr=False) 39 | temp = fluid.layers.batch_norm(input=temp, act=None, bias_attr=None) 40 | return temp 41 | 42 | 43 | def ZERO(inputs, stride): 44 | if stride == 1: 45 | return inputs * 0 46 | elif stride == 2: 47 | return fluid.layers.pool2d( 48 | inputs, 49 | filter_size=2, 50 | pool_stride=2, 51 | pool_padding=0, 52 | pool_type='avg') * 0 53 | else: 54 | raise ValueError('invalid stride of {:} not [1, 2]'.format(stride)) 55 | 56 | 57 | def Identity(inputs, C_in, C_out, stride): 58 | if C_in == C_out and stride == 1: 59 | return inputs 60 | elif stride == 1: 61 | return ReLUConvBN(inputs, C_in, C_out, 1, 1, 0) 62 | else: 63 | temp1 = fluid.layers.relu(inputs) 64 | temp2 = fluid.layers.pad2d( 65 | input=temp1, paddings=[0, 1, 0, 1], mode='reflect') 66 | temp2 = fluid.layers.slice( 67 | temp2, 68 | axes=[0, 1, 2, 3], 69 | starts=[0, 0, 1, 1], 70 | ends=[999, 999, 999, 999]) 71 | temp1 = fluid.layers.conv2d( 72 | temp1, 73 | filter_size=1, 74 | num_filters=C_out // 2, 75 | stride=stride, 76 | padding=0, 77 | act=None, 78 | bias_attr=False) 79 | temp2 = fluid.layers.conv2d( 80 | temp2, 81 | filter_size=1, 82 | num_filters=C_out - C_out // 2, 83 | stride=stride, 84 | padding=0, 85 | act=None, 86 | bias_attr=False) 87 | temp = fluid.layers.concat([temp1, temp2], axis=1) 88 | return fluid.layers.batch_norm(input=temp, act=None, bias_attr=None) 89 | 90 | 91 | def POOL_3x3(inputs, C_in, C_out, stride, mode): 92 | if C_in == C_out: 93 | xinputs = inputs 94 | else: 95 | xinputs = ReLUConvBN(inputs, C_in, C_out, 1, 1, 0) 96 | return fluid.layers.pool2d( 97 | xinputs, 98 | pool_size=3, 99 | pool_stride=stride, 100 | pool_padding=1, 101 | pool_type=mode) 102 | 103 | 104 | def SepConv(inputs, C_in, C_out, kernel, stride, padding): 105 | temp = fluid.layers.relu(inputs) 106 | temp = fluid.layers.conv2d( 107 | temp, 108 | filter_size=kernel, 109 | num_filters=C_in, 110 | stride=stride, 111 | padding=padding, 112 | act=None, 113 | bias_attr=False) 114 | temp = fluid.layers.conv2d( 115 | temp, 116 | filter_size=1, 117 | num_filters=C_in, 118 | stride=1, 119 | padding=0, 120 | act=None, 121 | bias_attr=False) 122 | temp = fluid.layers.batch_norm(input=temp, act='relu', bias_attr=None) 123 | temp = fluid.layers.conv2d( 124 | temp, 125 | filter_size=kernel, 126 | num_filters=C_in, 127 | stride=1, 128 | padding=padding, 129 | act=None, 130 | bias_attr=False) 131 | temp = fluid.layers.conv2d( 132 | temp, 133 | filter_size=1, 134 | num_filters=C_out, 135 | stride=1, 136 | padding=0, 137 | act=None, 138 | bias_attr=False) 139 | temp = fluid.layers.batch_norm(input=temp, act=None, bias_attr=None) 140 | return temp 141 | 142 | 143 | def DilConv(inputs, C_in, C_out, kernel, stride, padding, dilation): 144 | temp = fluid.layers.relu(inputs) 145 | temp = fluid.layers.conv2d( 146 | temp, 147 | filter_size=kernel, 148 | num_filters=C_in, 149 | stride=stride, 150 | padding=padding, 151 | dilation=dilation, 152 | act=None, 153 | bias_attr=False) 154 | temp = fluid.layers.conv2d( 155 | temp, 156 | filter_size=1, 157 | num_filters=C_out, 158 | stride=1, 159 | padding=0, 160 | act=None, 161 | bias_attr=False) 162 | temp = fluid.layers.batch_norm(input=temp, act=None, bias_attr=None) 163 | return temp 164 | 165 | 166 | def Conv313(inputs, C_in, C_out, stride): 167 | temp = fluid.layers.relu(inputs) 168 | temp = fluid.layers.conv2d( 169 | temp, 170 | filter_size=(1, 3), 171 | num_filters=C_out, 172 | stride=(1, stride), 173 | padding=(0, 1), 174 | act=None, 175 | bias_attr=False) 176 | temp = fluid.layers.conv2d( 177 | temp, 178 | filter_size=(3, 1), 179 | num_filters=C_out, 180 | stride=(stride, 1), 181 | padding=(1, 0), 182 | act=None, 183 | bias_attr=False) 184 | temp = fluid.layers.batch_norm(input=temp, act=None, bias_attr=None) 185 | return temp 186 | 187 | 188 | def Conv717(inputs, C_in, C_out, stride): 189 | temp = fluid.layers.relu(inputs) 190 | temp = fluid.layers.conv2d( 191 | temp, 192 | filter_size=(1, 7), 193 | num_filters=C_out, 194 | stride=(1, stride), 195 | padding=(0, 3), 196 | act=None, 197 | bias_attr=False) 198 | temp = fluid.layers.conv2d( 199 | temp, 200 | filter_size=(7, 1), 201 | num_filters=C_out, 202 | stride=(stride, 1), 203 | padding=(3, 0), 204 | act=None, 205 | bias_attr=False) 206 | temp = fluid.layers.batch_norm(input=temp, act=None, bias_attr=None) 207 | return temp 208 | -------------------------------------------------------------------------------- /NAS-Models/lib/models/resnet.py: -------------------------------------------------------------------------------- 1 | import paddle 2 | import paddle.fluid as fluid 3 | 4 | 5 | def conv_bn_layer(input, 6 | ch_out, 7 | filter_size, 8 | stride, 9 | padding, 10 | act='relu', 11 | bias_attr=False): 12 | tmp = fluid.layers.conv2d( 13 | input=input, 14 | filter_size=filter_size, 15 | num_filters=ch_out, 16 | stride=stride, 17 | padding=padding, 18 | act=None, 19 | bias_attr=bias_attr) 20 | return fluid.layers.batch_norm(input=tmp, act=act) 21 | 22 | 23 | def shortcut(input, ch_in, ch_out, stride): 24 | if stride == 2: 25 | temp = fluid.layers.pool2d( 26 | input, pool_size=2, pool_type='avg', pool_stride=2) 27 | temp = fluid.layers.conv2d( 28 | temp, 29 | filter_size=1, 30 | num_filters=ch_out, 31 | stride=1, 32 | padding=0, 33 | act=None, 34 | bias_attr=None) 35 | return temp 36 | elif ch_in != ch_out: 37 | return conv_bn_layer(input, ch_out, 1, stride, 0, None, None) 38 | else: 39 | return input 40 | 41 | 42 | def basicblock(input, ch_in, ch_out, stride): 43 | tmp = conv_bn_layer(input, ch_out, 3, stride, 1) 44 | tmp = conv_bn_layer(tmp, ch_out, 3, 1, 1, act=None, bias_attr=True) 45 | short = shortcut(input, ch_in, ch_out, stride) 46 | return fluid.layers.elementwise_add(x=tmp, y=short, act='relu') 47 | 48 | 49 | def layer_warp(block_func, input, ch_in, ch_out, count, stride): 50 | tmp = block_func(input, ch_in, ch_out, stride) 51 | for i in range(1, count): 52 | tmp = block_func(tmp, ch_out, ch_out, 1) 53 | return tmp 54 | 55 | 56 | def resnet_cifar(ipt, depth, class_num): 57 | # depth should be one of 20, 32, 44, 56, 110, 1202 58 | assert (depth - 2) % 6 == 0 59 | n = (depth - 2) // 6 60 | print('[resnet] depth : {:}, class_num : {:}'.format(depth, class_num)) 61 | conv1 = conv_bn_layer(ipt, ch_out=16, filter_size=3, stride=1, padding=1) 62 | print('conv-1 : shape = {:}'.format(conv1.shape)) 63 | res1 = layer_warp(basicblock, conv1, 16, 16, n, 1) 64 | print('res--1 : shape = {:}'.format(res1.shape)) 65 | res2 = layer_warp(basicblock, res1, 16, 32, n, 2) 66 | print('res--2 : shape = {:}'.format(res2.shape)) 67 | res3 = layer_warp(basicblock, res2, 32, 64, n, 2) 68 | print('res--3 : shape = {:}'.format(res3.shape)) 69 | pool = fluid.layers.pool2d( 70 | input=res3, pool_size=8, pool_type='avg', pool_stride=1) 71 | print('pool : shape = {:}'.format(pool.shape)) 72 | predict = fluid.layers.fc(input=pool, size=class_num, act='softmax') 73 | print('predict: shape = {:}'.format(predict.shape)) 74 | return predict 75 | -------------------------------------------------------------------------------- /NAS-Models/lib/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .meter import AverageMeter 2 | from .time_utils import time_for_file, time_string, time_string_short, time_print, convert_size2str, convert_secs2time 3 | from .data_utils import reader_creator 4 | -------------------------------------------------------------------------------- /NAS-Models/lib/utils/data_utils.py: -------------------------------------------------------------------------------- 1 | import random, tarfile 2 | import numpy, six 3 | from six.moves import cPickle as pickle 4 | from PIL import Image, ImageOps 5 | 6 | 7 | def train_cifar_augmentation(image): 8 | # flip 9 | if random.random() < 0.5: image1 = image.transpose(Image.FLIP_LEFT_RIGHT) 10 | else: image1 = image 11 | # random crop 12 | image2 = ImageOps.expand(image1, border=4, fill=0) 13 | i = random.randint(0, 40 - 32) 14 | j = random.randint(0, 40 - 32) 15 | image3 = image2.crop((j, i, j + 32, i + 32)) 16 | # to numpy 17 | image3 = numpy.array(image3) / 255.0 18 | mean = numpy.array([x / 255 for x in [125.3, 123.0, 113.9]]).reshape(1, 1, 19 | 3) 20 | std = numpy.array([x / 255 for x in [63.0, 62.1, 66.7]]).reshape(1, 1, 3) 21 | return (image3 - mean) / std 22 | 23 | 24 | def valid_cifar_augmentation(image): 25 | image3 = numpy.array(image) / 255.0 26 | mean = numpy.array([x / 255 for x in [125.3, 123.0, 113.9]]).reshape(1, 1, 27 | 3) 28 | std = numpy.array([x / 255 for x in [63.0, 62.1, 66.7]]).reshape(1, 1, 3) 29 | return (image3 - mean) / std 30 | 31 | 32 | def reader_creator(filename, sub_name, is_train, cycle=False): 33 | def read_batch(batch): 34 | data = batch[six.b('data')] 35 | labels = batch.get( 36 | six.b('labels'), batch.get(six.b('fine_labels'), None)) 37 | assert labels is not None 38 | for sample, label in six.moves.zip(data, labels): 39 | sample = sample.reshape(3, 32, 32) 40 | sample = sample.transpose((1, 2, 0)) 41 | image = Image.fromarray(sample) 42 | if is_train: 43 | ximage = train_cifar_augmentation(image) 44 | else: 45 | ximage = valid_cifar_augmentation(image) 46 | ximage = ximage.transpose((2, 0, 1)) 47 | yield ximage.astype(numpy.float32), int(label) 48 | 49 | def reader(): 50 | with tarfile.open(filename, mode='r') as f: 51 | names = (each_item.name for each_item in f 52 | if sub_name in each_item.name) 53 | 54 | while True: 55 | for name in names: 56 | if six.PY2: 57 | batch = pickle.load(f.extractfile(name)) 58 | else: 59 | batch = pickle.load( 60 | f.extractfile(name), encoding='bytes') 61 | for item in read_batch(batch): 62 | yield item 63 | if not cycle: 64 | break 65 | 66 | return reader 67 | -------------------------------------------------------------------------------- /NAS-Models/lib/utils/meter.py: -------------------------------------------------------------------------------- 1 | import time, sys 2 | import numpy as np 3 | 4 | 5 | class AverageMeter(object): 6 | """Computes and stores the average and current value""" 7 | 8 | def __init__(self): 9 | self.reset() 10 | 11 | def reset(self): 12 | self.val = 0.0 13 | self.avg = 0.0 14 | self.sum = 0.0 15 | self.count = 0.0 16 | 17 | def update(self, val, n=1): 18 | self.val = val 19 | self.sum += val * n 20 | self.count += n 21 | self.avg = self.sum / self.count 22 | 23 | def __repr__(self): 24 | return ('{name}(val={val}, avg={avg}, count={count})'.format( 25 | name=self.__class__.__name__, **self.__dict__)) 26 | -------------------------------------------------------------------------------- /NAS-Models/lib/utils/time_utils.py: -------------------------------------------------------------------------------- 1 | import time, sys 2 | import numpy as np 3 | 4 | 5 | def time_for_file(): 6 | ISOTIMEFORMAT = '%d-%h-at-%H-%M-%S' 7 | return '{}'.format(time.strftime(ISOTIMEFORMAT, time.gmtime(time.time()))) 8 | 9 | 10 | def time_string(): 11 | ISOTIMEFORMAT = '%Y-%m-%d %X' 12 | string = '[{}]'.format( 13 | time.strftime(ISOTIMEFORMAT, time.gmtime(time.time()))) 14 | return string 15 | 16 | 17 | def time_string_short(): 18 | ISOTIMEFORMAT = '%Y%m%d' 19 | string = '{}'.format(time.strftime(ISOTIMEFORMAT, time.gmtime(time.time()))) 20 | return string 21 | 22 | 23 | def time_print(string, is_print=True): 24 | if (is_print): 25 | print('{} : {}'.format(time_string(), string)) 26 | 27 | 28 | def convert_size2str(torch_size): 29 | dims = len(torch_size) 30 | string = '[' 31 | for idim in range(dims): 32 | string = string + ' {}'.format(torch_size[idim]) 33 | return string + ']' 34 | 35 | 36 | def convert_secs2time(epoch_time, return_str=False): 37 | need_hour = int(epoch_time / 3600) 38 | need_mins = int((epoch_time - 3600 * need_hour) / 60) 39 | need_secs = int(epoch_time - 3600 * need_hour - 60 * need_mins) 40 | if return_str: 41 | str = '[{:02d}:{:02d}:{:02d}]'.format(need_hour, need_mins, need_secs) 42 | return str 43 | else: 44 | return need_hour, need_mins, need_secs 45 | 46 | 47 | def print_log(print_string, log): 48 | #if isinstance(log, Logger): log.log('{:}'.format(print_string)) 49 | if hasattr(log, 'log'): log.log('{:}'.format(print_string)) 50 | else: 51 | print("{:}".format(print_string)) 52 | if log is not None: 53 | log.write('{:}\n'.format(print_string)) 54 | log.flush() 55 | -------------------------------------------------------------------------------- /NAS-Models/scripts/base-train.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # bash ./scripts/base-train.sh 0 cifar-10 ResNet110 3 | echo script name: $0 4 | echo $# arguments 5 | if [ "$#" -ne 3 ] ;then 6 | echo "Input illegal number of parameters " $# 7 | echo "Need 3 parameters for GPU and dataset and the-model-name" 8 | exit 1 9 | fi 10 | if [ "$TORCH_HOME" = "" ]; then 11 | echo "Must set TORCH_HOME envoriment variable for data dir saving" 12 | exit 1 13 | else 14 | echo "TORCH_HOME : $TORCH_HOME" 15 | fi 16 | 17 | GPU=$1 18 | dataset=$2 19 | model=$3 20 | 21 | save_dir=snapshots/${dataset}-${model} 22 | 23 | export FLAGS_fraction_of_gpu_memory_to_use="0.005" 24 | export FLAGS_free_idle_memory=True 25 | 26 | CUDA_VISIBLE_DEVICES=${GPU} python train_cifar.py \ 27 | --data_path $TORCH_HOME/cifar.python/${dataset}-python.tar.gz \ 28 | --log_dir ${save_dir} \ 29 | --dataset ${dataset} \ 30 | --model_name ${model} \ 31 | --lr 0.1 --epochs 300 --batch_size 256 --step_each_epoch 196 32 | -------------------------------------------------------------------------------- /NAS-Models/scripts/train-nas.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # bash ./scripts/base-train.sh 0 cifar-10 ResNet110 3 | echo script name: $0 4 | echo $# arguments 5 | if [ "$#" -ne 3 ] ;then 6 | echo "Input illegal number of parameters " $# 7 | echo "Need 3 parameters for GPU and dataset and the-model-name" 8 | exit 1 9 | fi 10 | if [ "$TORCH_HOME" = "" ]; then 11 | echo "Must set TORCH_HOME envoriment variable for data dir saving" 12 | exit 1 13 | else 14 | echo "TORCH_HOME : $TORCH_HOME" 15 | fi 16 | 17 | GPU=$1 18 | dataset=$2 19 | model=$3 20 | 21 | save_dir=snapshots/${dataset}-${model} 22 | 23 | export FLAGS_fraction_of_gpu_memory_to_use="0.005" 24 | export FLAGS_free_idle_memory=True 25 | 26 | CUDA_VISIBLE_DEVICES=${GPU} python train_cifar.py \ 27 | --data_path $TORCH_HOME/cifar.python/${dataset}-python.tar.gz \ 28 | --log_dir ${save_dir} \ 29 | --dataset ${dataset} \ 30 | --model_name ${model} \ 31 | --lr 0.025 --epochs 600 --batch_size 96 --step_each_epoch 521 32 | -------------------------------------------------------------------------------- /NAS-Models/train_cifar.py: -------------------------------------------------------------------------------- 1 | import os, sys, numpy as np, argparse 2 | from pathlib import Path 3 | import paddle.fluid as fluid 4 | import math, time, paddle 5 | import paddle.fluid.layers.ops as ops 6 | #from tb_paddle import SummaryWriter 7 | 8 | lib_dir = (Path(__file__).parent / 'lib').resolve() 9 | if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir)) 10 | from models import resnet_cifar, NASCifarNet, Networks 11 | from utils import AverageMeter, time_for_file, time_string, convert_secs2time 12 | from utils import reader_creator 13 | 14 | 15 | def inference_program(model_name, num_class): 16 | # The image is 32 * 32 with RGB representation. 17 | data_shape = [3, 32, 32] 18 | images = fluid.layers.data(name='pixel', shape=data_shape, dtype='float32') 19 | 20 | if model_name == 'ResNet20': 21 | predict = resnet_cifar(images, 20, num_class) 22 | elif model_name == 'ResNet32': 23 | predict = resnet_cifar(images, 32, num_class) 24 | elif model_name == 'ResNet110': 25 | predict = resnet_cifar(images, 110, num_class) 26 | else: 27 | predict = NASCifarNet(images, 36, 6, 3, num_class, Networks[model_name], 28 | True) 29 | return predict 30 | 31 | 32 | def train_program(predict): 33 | label = fluid.layers.data(name='label', shape=[1], dtype='int64') 34 | if isinstance(predict, (list, tuple)): 35 | predict, aux_predict = predict 36 | x_losses = fluid.layers.cross_entropy(input=predict, label=label) 37 | aux_losses = fluid.layers.cross_entropy(input=aux_predict, label=label) 38 | x_loss = fluid.layers.mean(x_losses) 39 | aux_loss = fluid.layers.mean(aux_losses) 40 | loss = x_loss + aux_loss * 0.4 41 | accuracy = fluid.layers.accuracy(input=predict, label=label) 42 | else: 43 | losses = fluid.layers.cross_entropy(input=predict, label=label) 44 | loss = fluid.layers.mean(losses) 45 | accuracy = fluid.layers.accuracy(input=predict, label=label) 46 | return [loss, accuracy] 47 | 48 | 49 | # For training test cost 50 | def evaluation(program, reader, fetch_list, place): 51 | feed_var_list = [ 52 | program.global_block().var('pixel'), program.global_block().var('label') 53 | ] 54 | feeder_test = fluid.DataFeeder(feed_list=feed_var_list, place=place) 55 | test_exe = fluid.Executor(place) 56 | losses, accuracies = AverageMeter(), AverageMeter() 57 | for tid, test_data in enumerate(reader()): 58 | loss, acc = test_exe.run(program=program, 59 | feed=feeder_test.feed(test_data), 60 | fetch_list=fetch_list) 61 | losses.update(float(loss), len(test_data)) 62 | accuracies.update(float(acc) * 100, len(test_data)) 63 | return losses.avg, accuracies.avg 64 | 65 | 66 | def cosine_decay_with_warmup(learning_rate, step_each_epoch, epochs=120): 67 | """Applies cosine decay to the learning rate. 68 | lr = 0.05 * (math.cos(epoch * (math.pi / 120)) + 1) 69 | decrease lr for every mini-batch and start with warmup. 70 | """ 71 | from paddle.fluid.layers.learning_rate_scheduler import _decay_step_counter 72 | global_step = _decay_step_counter() 73 | lr = fluid.layers.tensor.create_global_var( 74 | shape=[1], 75 | value=0.0, 76 | dtype='float32', 77 | persistable=True, 78 | name="learning_rate") 79 | 80 | warmup_epoch = fluid.layers.fill_constant( 81 | shape=[1], dtype='float32', value=float(5), force_cpu=True) 82 | 83 | epoch = ops.floor(global_step / step_each_epoch) 84 | with fluid.layers.control_flow.Switch() as switch: 85 | with switch.case(epoch < warmup_epoch): 86 | decayed_lr = learning_rate * (global_step / 87 | (step_each_epoch * warmup_epoch)) 88 | fluid.layers.tensor.assign(input=decayed_lr, output=lr) 89 | with switch.default(): 90 | decayed_lr = learning_rate * \ 91 | (ops.cos((global_step - warmup_epoch * step_each_epoch) * (math.pi / (epochs * step_each_epoch))) + 1)/2 92 | fluid.layers.tensor.assign(input=decayed_lr, output=lr) 93 | return lr 94 | 95 | 96 | def main(xargs): 97 | 98 | save_dir = Path(xargs.log_dir) / time_for_file() 99 | save_dir.mkdir(parents=True, exist_ok=True) 100 | 101 | print('save dir : {:}'.format(save_dir)) 102 | print('xargs : {:}'.format(xargs)) 103 | 104 | if xargs.dataset == 'cifar-10': 105 | train_data = reader_creator(xargs.data_path, 'data_batch', True, False) 106 | test__data = reader_creator(xargs.data_path, 'test_batch', False, False) 107 | class_num = 10 108 | print('create cifar-10 dataset') 109 | elif xargs.dataset == 'cifar-100': 110 | train_data = reader_creator(xargs.data_path, 'train', True, False) 111 | test__data = reader_creator(xargs.data_path, 'test', False, False) 112 | class_num = 100 113 | print('create cifar-100 dataset') 114 | else: 115 | raise ValueError('invalid dataset : {:}'.format(xargs.dataset)) 116 | 117 | train_reader = paddle.batch( 118 | paddle.reader.shuffle( 119 | train_data, buf_size=5000), 120 | batch_size=xargs.batch_size) 121 | 122 | # Reader for testing. A separated data set for testing. 123 | test_reader = paddle.batch(test__data, batch_size=xargs.batch_size) 124 | 125 | place = fluid.CUDAPlace(0) 126 | 127 | main_program = fluid.default_main_program() 128 | star_program = fluid.default_startup_program() 129 | 130 | # programs 131 | predict = inference_program(xargs.model_name, class_num) 132 | [loss, accuracy] = train_program(predict) 133 | print('training program setup done') 134 | test_program = main_program.clone(for_test=True) 135 | print('testing program setup done') 136 | 137 | #infer_writer = SummaryWriter( str(save_dir / 'infer') ) 138 | #infer_writer.add_paddle_graph(fluid_program=fluid.default_main_program(), verbose=True) 139 | #infer_writer.close() 140 | #print(test_program.to_string(True)) 141 | 142 | #learning_rate = fluid.layers.cosine_decay(learning_rate=xargs.lr, step_each_epoch=xargs.step_each_epoch, epochs=xargs.epochs) 143 | #learning_rate = fluid.layers.cosine_decay(learning_rate=0.1, step_each_epoch=196, epochs=300) 144 | learning_rate = cosine_decay_with_warmup(xargs.lr, xargs.step_each_epoch, 145 | xargs.epochs) 146 | optimizer = fluid.optimizer.Momentum( 147 | learning_rate=learning_rate, 148 | momentum=0.9, 149 | regularization=fluid.regularizer.L2Decay(0.0005), 150 | use_nesterov=True) 151 | optimizer.minimize(loss) 152 | 153 | exe = fluid.Executor(place) 154 | 155 | feed_var_list_loop = [ 156 | main_program.global_block().var('pixel'), 157 | main_program.global_block().var('label') 158 | ] 159 | feeder = fluid.DataFeeder(feed_list=feed_var_list_loop, place=place) 160 | exe.run(star_program) 161 | 162 | start_time, epoch_time = time.time(), AverageMeter() 163 | for iepoch in range(xargs.epochs): 164 | losses, accuracies, steps = AverageMeter(), AverageMeter(), 0 165 | for step_id, train_data in enumerate(train_reader()): 166 | tloss, tacc, xlr = exe.run( 167 | main_program, 168 | feed=feeder.feed(train_data), 169 | fetch_list=[loss, accuracy, learning_rate]) 170 | tloss, tacc, xlr = float(tloss), float(tacc) * 100, float(xlr) 171 | steps += 1 172 | losses.update(tloss, len(train_data)) 173 | accuracies.update(tacc, len(train_data)) 174 | if step_id % 100 == 0: 175 | print( 176 | '{:} [{:03d}/{:03d}] [{:03d}] lr = {:.7f}, loss = {:.4f} ({:.4f}), accuracy = {:.2f} ({:.2f}), error={:.2f}'. 177 | format(time_string( 178 | ), iepoch, xargs.epochs, step_id, xlr, tloss, losses.avg, 179 | tacc, accuracies.avg, 100 - accuracies.avg)) 180 | test_loss, test_acc = evaluation(test_program, test_reader, 181 | [loss, accuracy], place) 182 | need_time = 'Time Left: {:}'.format( 183 | convert_secs2time(epoch_time.avg * (xargs.epochs - iepoch), True)) 184 | print( 185 | '{:}x[{:03d}/{:03d}] {:} train-loss = {:.4f}, train-accuracy = {:.2f}, test-loss = {:.4f}, test-accuracy = {:.2f} test-error = {:.2f} [{:} steps per epoch]\n'. 186 | format(time_string(), iepoch, xargs.epochs, need_time, losses.avg, 187 | accuracies.avg, test_loss, test_acc, 100 - test_acc, steps)) 188 | if isinstance(predict, list): 189 | fluid.io.save_inference_model( 190 | str(save_dir / 'inference_model'), ["pixel"], predict, exe) 191 | else: 192 | fluid.io.save_inference_model( 193 | str(save_dir / 'inference_model'), ["pixel"], [predict], exe) 194 | # measure elapsed time 195 | epoch_time.update(time.time() - start_time) 196 | start_time = time.time() 197 | 198 | print('finish training and evaluation with {:} epochs in {:}'.format( 199 | xargs.epochs, convert_secs2time(epoch_time.sum, True))) 200 | 201 | 202 | if __name__ == '__main__': 203 | parser = argparse.ArgumentParser( 204 | description='Train.', 205 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 206 | parser.add_argument('--log_dir', type=str, help='Save dir.') 207 | parser.add_argument('--dataset', type=str, help='The dataset name.') 208 | parser.add_argument('--data_path', type=str, help='The dataset path.') 209 | parser.add_argument('--model_name', type=str, help='The model name.') 210 | parser.add_argument('--lr', type=float, help='The learning rate.') 211 | parser.add_argument('--batch_size', type=int, help='The batch size.') 212 | parser.add_argument('--step_each_epoch', type=int, help='The batch size.') 213 | parser.add_argument('--epochs', type=int, help='The total training epochs.') 214 | args = parser.parse_args() 215 | main(args) 216 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introduction to AutoDL Design 2 | 3 | ## Content 4 | - [Installation](#Installation) 5 | - [Introduction](#Introduction) 6 | - [Data Preparation](#Data-Preparation) 7 | - [Model Training](#Model-Training) 8 | 9 | ## Installation 10 | Running demo code in the current directory requires PadddlePaddle Fluid v.1.3.0 or above. If your runtime environment does not meet this requirement, please update PaddlePaddle according to the documents. 11 | * Install Python2.7 12 | * Install dependencies [PARL](https://github.com/PaddlePaddle/PARL) framework and [absl-py](https://github.com/abseil/abseil-py/tree/master/absl) library,as follows: 13 | ``` 14 | pip install parl 15 | pip install absl-py 16 | ``` 17 | 18 | 19 | ## Introduction 20 | [AutoDL](http://www.paddlepaddle.org/paddle/ModelAutoDL) is an efficient automated neural architecture design method. It designs quality customized neural architecture via reinforcement learning. The system consists of two components: an encoder of the neural architecture, and a critic of the model performance. The encoder encodes neural architecture using a recurrent neural network, and the critic evaluates the sampled architecture in terms of accuracy, number of model parameters, etc., which are fed back to the encoder. The encoder updates its parameters accordingly, and samples a new batch of architectures. After several iterations, the encoder is trained to converge and finds a quality architecture. The open-sourced AutoDl Design is one implementation of AutoDL technique. Section 2 presents the usage of AutoDL. Section 3 presents the framework and examples. 21 | 22 | ## Data Preparation 23 | * Clone [PaddlePaddle/AutoDL](https://github.com/PaddlePaddle/AutoDL.git) to local machine,and enter the path of AutoDL Design. 24 | * Download [CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz) training data, unzip to AutoDL Design/cifar, and generate a dataset of 10 classes and 100 images per class using `dataset_maker.py` 25 | ``` 26 | tar zxf cifar-10-python.tar.gz 27 | python dataset_maker.py 28 | ``` 29 | 30 | ## Model Training 31 | In the training process, AutoDLa Design agent generates tokens and adjacency matrices used for training, and the trainer uses these tokens and matrices to construct and train convolutional neural networks. The validation accuracy after 20 epochs are used as feed back for the agent, and the agent updates its policy accordingly. After several iterations, the agent learns to find a quality deep neural network. 32 | ![Picture](./AutoDL%20Design/img/cnn_net.png) 33 | Here we provide the following test on the method. 34 | 35 | ### Test on the convergence of the number of tokens produced 36 | Due to the long training time of CNN, to test the validity of agent framework, we use the number of "correct" tokens produced as a pseudo reward. The agent will learn to produce more "correct" tokens per step. The total length of tokens is set at 20. 37 | ``` 38 | export FLAGS_fraction_of_gpu_memory_to_use=0.98 39 | export FLAGS_eager_delete_tensor_gb=0.0 40 | export FLAGS_fast_eager_deletion_mode=1 41 | CUDA_VISIBLE_DEVICES=0 python -u simple_main.py 42 | ``` 43 | Expected results: 44 | In the log, `average rewards` gradually converges to 20: 45 | 46 | ``` 47 | Simple run target is 20 48 | mid=0, average rewards=2.500 49 | ... 50 | mid=450, average rewards=17.100 51 | mid=460, average rewards=17.000 52 | 53 | ``` 54 | 55 | ### Training AutoDL to design CNN 56 | Train AutoDL Design on the small scale dataset prepared in the previous section: 57 | ``` 58 | export FLAGS_fraction_of_gpu_memory_to_use=0.98 59 | export FLAGS_eager_delete_tensor_gb=0.0 60 | export FLAGS_fast_eager_deletion_mode=1 61 | CUDA_VISIBLE_DEVICES=0 python -u main.py 62 | ``` 63 | __Note:__ It requires two GPUs for training, GPU used by the Agent is set by `CUDA_VISIBLE_DEVICES=0`(in `main.py`);Trainer uses GPU set by `CUDA_VISIBLE_DEVICES=1`(in [autodl.py](https://github.com/PaddlePaddle/AutoDL/blob/master/AutoDL%20Design/autodl.py#L124)) 64 | 65 | Expected results: 66 | In the log, `average accuracy` gradually increases: 67 | 68 | ``` 69 | step = 0, average accuracy = 0.633 70 | step = 1, average accuracy = 0.688 71 | step = 2, average accuracy = 0.626 72 | step = 3, average accuracy = 0.682 73 | ...... 74 | step = 842, average accuracy = 0.823 75 | step = 843, average accuracy = 0.825 76 | step = 844, average accuracy = 0.808 77 | ...... 78 | ``` 79 | ### Results 80 | 81 | ![Picture](./AutoDL%20Design/img/search_result.png) 82 | The x-axis is the number of steps, and the y-axis is validation accuracy of the sampled models. The average performance of the sampled models improves over time. 83 | 84 | --------------------------------------------------------------------------------