sa_nas_mobilenetv2.py 12.4 KB
Newer Older
C
ceci3 已提交
1 2 3 4 5 6 7 8 9 10 11
import sys
sys.path.append('..')
import numpy as np
import argparse
import ast
import time
import argparse
import ast
import logging
import paddle
import paddle.fluid as fluid
C
ceci3 已提交
12
from paddle.fluid.param_attr import ParamAttr
C
ceci3 已提交
13 14 15 16 17 18 19 20
from paddleslim.analysis import flops
from paddleslim.nas import SANAS
from paddleslim.common import get_logger
from optimizer import create_optimizer
import imagenet_reader

_logger = get_logger(__name__, level=logging.INFO)

C
update  
ceci3 已提交
21 22 23 24 25 26 27
reduce_rate = 0.85
init_temperature = 10.24
max_flops = 321208544
server_address = ""
port = 8909
retain_epoch = 5

C
ceci3 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40

def create_data_loader(image_shape):
    data_shape = [-1] + image_shape
    data = fluid.data(name='data', shape=data_shape, dtype='float32')
    label = fluid.data(name='label', shape=[-1, 1], dtype='int64')
    data_loader = fluid.io.DataLoader.from_generator(
        feed_list=[data, label],
        capacity=1024,
        use_double_buffer=True,
        iterable=True)
    return data_loader, data, label


C
ceci3 已提交
41 42 43 44 45 46 47 48 49
def build_program(main_program,
                  startup_program,
                  image_shape,
                  archs,
                  args,
                  is_test=False):
    with fluid.program_guard(main_program, startup_program):
        data_loader, data, label = create_data_loader(image_shape)
        output = archs(data)
C
update  
ceci3 已提交
50 51 52 53 54
        output = fluid.layers.fc(
            input=output,
            size=args.class_dim,
            param_attr=ParamAttr(name='mobilenetv2_fc_weights'),
            bias_attr=ParamAttr(name='mobilenetv2_fc_offset'))
C
ceci3 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67

        softmax_out = fluid.layers.softmax(input=output, use_cudnn=False)
        cost = fluid.layers.cross_entropy(input=softmax_out, label=label)
        avg_cost = fluid.layers.mean(cost)
        acc_top1 = fluid.layers.accuracy(input=softmax_out, label=label, k=1)
        acc_top5 = fluid.layers.accuracy(input=softmax_out, label=label, k=5)

        if is_test == False:
            optimizer = create_optimizer(args)
            optimizer.minimize(avg_cost)
    return data_loader, avg_cost, acc_top1, acc_top5


C
ceci3 已提交
68 69 70 71 72
def search_mobilenetv2(config, args, image_size, is_server=True):
    if is_server:
        ### start a server and a client
        sa_nas = SANAS(
            config,
C
update  
ceci3 已提交
73 74 75
            server_addr=("", port),
            init_temperature=init_temperature,
            reduce_rate=reduce_rate,
C
ceci3 已提交
76 77 78 79 80 81
            search_steps=args.search_steps,
            is_server=True)
    else:
        ### start a client
        sa_nas = SANAS(
            config,
C
update  
ceci3 已提交
82 83 84
            server_addr=(server_address, port),
            init_temperature=init_temperature,
            reduce_rate=reduce_rate,
C
ceci3 已提交
85 86
            search_steps=args.search_steps,
            is_server=False)
C
ceci3 已提交
87 88 89 90 91 92 93 94

    image_shape = [3, image_size, image_size]
    for step in range(args.search_steps):
        archs = sa_nas.next_archs()[0]

        train_program = fluid.Program()
        test_program = fluid.Program()
        startup_program = fluid.Program()
C
ceci3 已提交
95 96 97 98 99
        train_loader, avg_cost, acc_top1, acc_top5 = build_program(
            train_program, startup_program, image_shape, archs, args)

        current_flops = flops(train_program)
        print('step: {}, current_flops: {}'.format(step, current_flops))
C
update  
ceci3 已提交
100
        if current_flops > max_flops:
C
ceci3 已提交
101 102 103 104 105 106 107 108 109 110
            continue

        test_loader, test_avg_cost, test_acc_top1, test_acc_top5 = build_program(
            test_program,
            startup_program,
            image_shape,
            archs,
            args,
            is_test=True)
        test_program = test_program.clone(for_test=True)
C
ceci3 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

        place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()
        exe = fluid.Executor(place)
        exe.run(startup_program)

        if args.data == 'cifar10':
            train_reader = paddle.batch(
                paddle.reader.shuffle(
                    paddle.dataset.cifar.train10(cycle=False), buf_size=1024),
                batch_size=args.batch_size,
                drop_last=True)

            test_reader = paddle.batch(
                paddle.dataset.cifar.test10(cycle=False),
                batch_size=args.batch_size,
                drop_last=False)
        elif args.data == 'imagenet':
            train_reader = paddle.batch(
                imagenet_reader.train(),
                batch_size=args.batch_size,
                drop_last=True)
            test_reader = paddle.batch(
                imagenet_reader.val(),
                batch_size=args.batch_size,
                drop_last=False)

        train_loader.set_sample_list_generator(
            train_reader,
            places=fluid.cuda_places() if args.use_gpu else fluid.cpu_places())
C
ceci3 已提交
140 141
        test_loader.set_sample_list_generator(test_reader, places=place)

C
ceci3 已提交
142 143 144 145
        build_strategy = fluid.BuildStrategy()
        train_compiled_program = fluid.CompiledProgram(
            train_program).with_data_parallel(
                loss_name=avg_cost.name, build_strategy=build_strategy)
C
update  
ceci3 已提交
146
        for epoch_id in range(retain_epoch):
C
ceci3 已提交
147 148 149 150 151 152 153 154 155 156 157
            for batch_id, data in enumerate(train_loader()):
                fetches = [avg_cost.name]
                s_time = time.time()
                outs = exe.run(train_compiled_program,
                               feed=data,
                               fetch_list=fetches)[0]
                batch_time = time.time() - s_time
                if batch_id % 10 == 0:
                    _logger.info(
                        'TRAIN: steps: {}, epoch: {}, batch: {}, cost: {}, batch_time: {}ms'.
                        format(step, epoch_id, batch_id, outs[0], batch_time))
C
ceci3 已提交
158

C
ceci3 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171
        reward = []
        for batch_id, data in enumerate(test_loader()):
            test_fetches = [
                test_avg_cost.name, test_acc_top1.name, test_acc_top5.name
            ]
            batch_reward = exe.run(test_program,
                                   feed=data,
                                   fetch_list=test_fetches)
            reward_avg = np.mean(np.array(batch_reward), axis=1)
            reward.append(reward_avg)

            _logger.info(
                'TEST: step: {}, batch: {}, avg_cost: {}, acc_top1: {}, acc_top5: {}'.
C
ceci3 已提交
172 173
                format(step, batch_id, batch_reward[0], batch_reward[1],
                       batch_reward[2]))
C
ceci3 已提交
174 175

        finally_reward = np.mean(np.array(reward), axis=0)
C
ceci3 已提交
176
        _logger.info(
C
ceci3 已提交
177
            'FINAL TEST: avg_cost: {}, acc_top1: {}, acc_top5: {}'.format(
C
ceci3 已提交
178
                finally_reward[0], finally_reward[1], finally_reward[2]))
C
ceci3 已提交
179

C
ceci3 已提交
180
        sa_nas.reward(float(finally_reward[1]))
C
ceci3 已提交
181 182


C
update  
ceci3 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
def test_search_result(tokens, image_size, args, config):
    sa_nas = SANAS(
        config,
        server_addr=("", 8887),
        init_temperature=args.init_temperature,
        reduce_rate=args.reduce_rate,
        search_steps=args.search_steps,
        is_server=True)

    image_shape = [3, image_size, image_size]

    archs = sa_nas.tokens2arch(tokens)

    train_program = fluid.Program()
    test_program = fluid.Program()
    startup_program = fluid.Program()
    train_loader, avg_cost, acc_top1, acc_top5 = build_program(
        train_program, startup_program, image_shape, archs, args)

    current_flops = flops(train_program)
    print('current_flops: {}'.format(current_flops))
    test_loader, test_avg_cost, test_acc_top1, test_acc_top5 = build_program(
        test_program, startup_program, image_shape, archs, args, is_test=True)

    test_program = test_program.clone(for_test=True)

    place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()
    exe = fluid.Executor(place)
    exe.run(startup_program)

    if args.data == 'cifar10':
        train_reader = paddle.batch(
            paddle.reader.shuffle(
                paddle.dataset.cifar.train10(cycle=False), buf_size=1024),
            batch_size=args.batch_size,
            drop_last=True)

        test_reader = paddle.batch(
            paddle.dataset.cifar.test10(cycle=False),
            batch_size=args.batch_size,
            drop_last=False)
    elif args.data == 'imagenet':
        train_reader = paddle.batch(
            imagenet_reader.train(),
            batch_size=args.batch_size,
            drop_last=True)
        test_reader = paddle.batch(
            imagenet_reader.val(), batch_size=args.batch_size, drop_last=False)

    train_loader.set_sample_list_generator(
        train_reader,
        places=fluid.cuda_places() if args.use_gpu else fluid.cpu_places())
    test_loader.set_sample_list_generator(test_reader, places=place)

    build_strategy = fluid.BuildStrategy()
    train_compiled_program = fluid.CompiledProgram(
        train_program).with_data_parallel(
            loss_name=avg_cost.name, build_strategy=build_strategy)
    for epoch_id in range(retain_epoch):
        for batch_id, data in enumerate(train_loader()):
            fetches = [avg_cost.name]
            s_time = time.time()
            outs = exe.run(train_compiled_program,
                           feed=data,
                           fetch_list=fetches)[0]
            batch_time = time.time() - s_time
            if batch_id % 10 == 0:
                _logger.info(
                    'TRAIN: epoch: {}, batch: {}, cost: {}, batch_time: {}ms'.
                    format(epoch_id, batch_id, outs[0], batch_time))

        reward = []
        for batch_id, data in enumerate(test_loader()):
            test_fetches = [
                test_avg_cost.name, test_acc_top1.name, test_acc_top5.name
            ]
            batch_reward = exe.run(test_program,
                                   feed=data,
                                   fetch_list=test_fetches)
            reward_avg = np.mean(np.array(batch_reward), axis=1)
            reward.append(reward_avg)

            _logger.info(
                'TEST: batch: {}, avg_cost: {}, acc_top1: {}, acc_top5: {}'.
                format(batch_id, batch_reward[0], batch_reward[1],
                       batch_reward[2]))

        finally_reward = np.mean(np.array(reward), axis=0)
        _logger.info(
            'FINAL TEST: avg_cost: {}, acc_top1: {}, acc_top5: {}'.format(
                finally_reward[0], finally_reward[1], finally_reward[2]))


C
ceci3 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
if __name__ == '__main__':

    parser = argparse.ArgumentParser(
        description='SA NAS MobileNetV2 cifar10 argparase')
    parser.add_argument(
        '--use_gpu',
        type=ast.literal_eval,
        default=True,
        help='Whether to use GPU in train/test model.')
    parser.add_argument(
        '--batch_size', type=int, default=256, help='batch size.')
    parser.add_argument(
        '--data',
        type=str,
        default='cifar10',
        choices=['cifar10', 'imagenet'],
        help='server address.')
C
ceci3 已提交
293 294 295 296 297
    parser.add_argument(
        '--is_server',
        type=ast.literal_eval,
        default=True,
        help='Whether to start a server.')
C
ceci3 已提交
298 299 300 301 302 303 304 305
    parser.add_argument(
        '--search_steps',
        type=int,
        default=100,
        help='controller server number.')
    parser.add_argument(
        '--lr_strategy',
        type=str,
C
update  
ceci3 已提交
306
        default='cosine_decay',
C
ceci3 已提交
307 308 309 310
        help='learning rate decay strategy.')
    parser.add_argument('--lr', type=float, default=0.1, help='learning rate.')
    parser.add_argument(
        '--l2_decay', type=float, default=1e-4, help='learning rate decay.')
C
ceci3 已提交
311
    parser.add_argument(
C
update  
ceci3 已提交
312
        '--class_dim', type=int, default=100, help='classify number.')
C
ceci3 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    parser.add_argument(
        '--step_epochs',
        nargs='+',
        type=int,
        default=[30, 60, 90],
        help="piecewise decay step")
    parser.add_argument(
        '--momentum_rate',
        type=float,
        default=0.9,
        help='learning rate decay.')
    parser.add_argument(
        '--warm_up_epochs',
        type=float,
        default=5.0,
        help='learning rate decay.')
    parser.add_argument(
        '--num_epochs', type=int, default=120, help='learning rate decay.')
    parser.add_argument(
        '--decay_epochs', type=float, default=2.4, help='learning rate decay.')
    parser.add_argument(
        '--decay_rate', type=float, default=0.97, help='learning rate decay.')
    parser.add_argument(
        '--total_images',
        type=int,
        default=1281167,
        help='learning rate decay.')
    args = parser.parse_args()
    print(args)

    if args.data == 'cifar10':
        image_size = 32
        block_num = 3
    elif args.data == 'imagenet':
        image_size = 224
        block_num = 6
    else:
C
update  
ceci3 已提交
350
        raise NotImplementedError(
C
ceci3 已提交
351 352 353
            'data must in [cifar10, imagenet], but received: {}'.format(
                args.data))

C
ceci3 已提交
354
    config = [('MobileNetV2Space')]
C
ceci3 已提交
355

C
ceci3 已提交
356
    search_mobilenetv2(config, args, image_size, is_server=args.is_server)