train.py 16.8 KB
Newer Older
R
root 已提交
1 2 3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
4 5 6 7
import os
import numpy as np
import time
import sys
R
root 已提交
8 9
import functools
import math
10
import paddle
11
import paddle.fluid as fluid
12
import paddle.dataset.flowers as flowers
13 14
import reader
import argparse
R
ruri 已提交
15 16 17 18
import functools
import subprocess
import utils
from utils.learning_rate import cosine_decay
T
typhoonzero 已提交
19
from utils.fp16_utils import create_master_params_grads, master_param_to_train_param
20
from utility import add_arguments, print_arguments
R
root 已提交
21 22

IMAGENET1000 = 1281167
23 24 25

parser = argparse.ArgumentParser(description=__doc__)
add_arg = functools.partial(add_arguments, argparser=parser)
26 27 28 29 30 31 32 33 34 35 36 37 38 39
# yapf: disable
add_arg('batch_size',       int,   256,                  "Minibatch size.")
add_arg('use_gpu',          bool,  True,                 "Whether to use GPU or not.")
add_arg('total_images',     int,   1281167,              "Training image number.")
add_arg('num_epochs',       int,   120,                  "number of epochs.")
add_arg('class_dim',        int,   1000,                 "Class number.")
add_arg('image_shape',      str,   "3,224,224",          "input image size")
add_arg('model_save_dir',   str,   "output",             "model save directory")
add_arg('with_mem_opt',     bool,  True,                 "Whether to use memory optimization or not.")
add_arg('pretrained_model', str,   None,                 "Whether to use pretrained model.")
add_arg('checkpoint',       str,   None,                 "Whether to resume checkpoint.")
add_arg('lr',               float, 0.1,                  "set learning rate.")
add_arg('lr_strategy',      str,   "piecewise_decay",    "Set the learning rate decay strategy.")
add_arg('model',            str,   "SE_ResNeXt50_32x4d", "Set the network to use.")
40
add_arg('enable_ce',        bool,  False,                "If set True, enable continuous evaluation job.")
M
minqiyang 已提交
41
add_arg('data_dir',         str,   "./data/ILSVRC2012",  "The ImageNet dataset root dir.")
R
root 已提交
42
add_arg('model_category',   str,   "models",        "Whether to use models_name or not, valid value:'models','models_name'." )
T
typhoonzero 已提交
43
add_arg('fp16',             bool,  False,                "Enable half precision training with fp16." )
T
update  
typhoonzero 已提交
44
add_arg('scale_loss',       float, 1.0,                  "Scale loss for fp16." )
R
root 已提交
45 46
add_arg('l2_decay',         float, 1e-4,                 "L2_decay parameter.")
add_arg('momentum_rate',    float, 0.9,                  "momentum_rate.")
T
typhoonzero 已提交
47
# yapf: enable
48

R
ruri 已提交
49

R
root 已提交
50
def set_models(model_category):
R
ruri 已提交
51
    global models
R
root 已提交
52 53 54 55 56
    assert model_category in ["models", "models_name"
                              ], "{} is not in lists: {}".format(
                                  model_category, ["models", "models_name"])
    if model_category == "models_name":
        import models_name as models
R
ruri 已提交
57
    else:
R
root 已提交
58
        import models as models
59 60 61 62


def optimizer_setting(params):
    ls = params["learning_strategy"]
R
root 已提交
63 64
    l2_decay = params["l2_decay"]
    momentum_rate = params["momentum_rate"]
65 66
    if ls["name"] == "piecewise_decay":
        if "total_images" not in params:
R
root 已提交
67
            total_images = IMAGENET1000
Y
Yibing Liu 已提交
68
        else:
69 70 71
            total_images = params["total_images"]
        batch_size = ls["batch_size"]
        step = int(total_images / batch_size + 1)
D
Dang Qingqing 已提交
72

73 74 75 76
        bd = [step * e for e in ls["epochs"]]
        base_lr = params["lr"]
        lr = []
        lr = [base_lr * (0.1**i) for i in range(len(bd) + 1)]
77
        optimizer = fluid.optimizer.Momentum(
78 79
            learning_rate=fluid.layers.piecewise_decay(
                boundaries=bd, values=lr),
R
root 已提交
80 81
            momentum=momentum_rate,
            regularization=fluid.regularizer.L2Decay(l2_decay))
R
ruri 已提交
82

83 84
    elif ls["name"] == "cosine_decay":
        if "total_images" not in params:
R
root 已提交
85
            total_images = IMAGENET1000
86 87 88
        else:
            total_images = params["total_images"]
        batch_size = ls["batch_size"]
R
root 已提交
89 90
        l2_decay = params["l2_decay"]
        momentum_rate = params["momentum_rate"]
91 92 93 94 95
        step = int(total_images / batch_size + 1)

        lr = params["lr"]
        num_epochs = params["num_epochs"]

96 97
        optimizer = fluid.optimizer.Momentum(
            learning_rate=cosine_decay(
98
                learning_rate=lr, step_each_epoch=step, epochs=num_epochs),
R
root 已提交
99 100 101
            momentum=momentum_rate,
            regularization=fluid.regularizer.L2Decay(l2_decay))
    elif ls["name"] == "linear_decay":
R
ruri 已提交
102
        if "total_images" not in params:
R
root 已提交
103
            total_images = IMAGENET1000
R
ruri 已提交
104 105 106 107
        else:
            total_images = params["total_images"]
        batch_size = ls["batch_size"]
        num_epochs = params["num_epochs"]
R
root 已提交
108
        start_lr = params["lr"]
R
root 已提交
109 110 111 112 113 114
        l2_decay = params["l2_decay"]
        momentum_rate = params["momentum_rate"]
        end_lr = 0
        total_step = int((total_images / batch_size) * num_epochs)
        lr = fluid.layers.polynomial_decay(
            start_lr, total_step, end_lr, power=1)
R
ruri 已提交
115
        optimizer = fluid.optimizer.Momentum(
R
root 已提交
116 117 118
            learning_rate=lr,
            momentum=momentum_rate,
            regularization=fluid.regularizer.L2Decay(l2_decay))
119
    else:
120
        lr = params["lr"]
R
root 已提交
121 122
        l2_decay = params["l2_decay"]
        momentum_rate = params["momentum_rate"]
123
        optimizer = fluid.optimizer.Momentum(
124
            learning_rate=lr,
R
root 已提交
125 126
            momentum=momentum_rate,
            regularization=fluid.regularizer.L2Decay(l2_decay))
127

128
    return optimizer
129

R
root 已提交
130

R
ruri 已提交
131 132
def net_config(image, label, model, args):
    model_list = [m for m in dir(models) if "__" not in m]
R
root 已提交
133 134
    assert args.model in model_list, "{} is not lists: {}".format(args.model,
                                                                  model_list)
135

136 137 138
    class_dim = args.class_dim
    model_name = args.model

139 140
    if args.enable_ce:
        assert model_name == "SE_ResNeXt50_32x4d"
D
Dang Qingqing 已提交
141
        model.params["dropout_seed"] = 100
R
root 已提交
142
        class_dim = 102
143

R
root 已提交
144
    if model_name == "GoogleNet":
145 146 147 148 149 150 151 152 153 154 155
        out0, out1, out2 = model.net(input=image, class_dim=class_dim)
        cost0 = fluid.layers.cross_entropy(input=out0, label=label)
        cost1 = fluid.layers.cross_entropy(input=out1, label=label)
        cost2 = fluid.layers.cross_entropy(input=out2, label=label)
        avg_cost0 = fluid.layers.mean(x=cost0)
        avg_cost1 = fluid.layers.mean(x=cost1)
        avg_cost2 = fluid.layers.mean(x=cost2)

        avg_cost = avg_cost0 + 0.3 * avg_cost1 + 0.3 * avg_cost2
        acc_top1 = fluid.layers.accuracy(input=out0, label=label, k=1)
        acc_top5 = fluid.layers.accuracy(input=out0, label=label, k=5)
Y
Yibing Liu 已提交
156
    else:
R
root 已提交
157 158 159
        out = model.net(input=image, class_dim=class_dim)
        cost, pred = fluid.layers.softmax_with_cross_entropy(
            out, label, return_softmax=True)
T
typhoonzero 已提交
160
        if args.scale_loss > 1:
T
update  
typhoonzero 已提交
161
            avg_cost = fluid.layers.mean(x=cost) * float(args.scale_loss)
T
typhoonzero 已提交
162
        else:
T
update  
typhoonzero 已提交
163
            avg_cost = fluid.layers.mean(x=cost)
164

T
update  
typhoonzero 已提交
165 166
        acc_top1 = fluid.layers.accuracy(input=pred, label=label, k=1)
        acc_top5 = fluid.layers.accuracy(input=pred, label=label, k=5)
167

R
ruri 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    return avg_cost, acc_top1, acc_top5


def build_program(is_train, main_prog, startup_prog, args):
    image_shape = [int(m) for m in args.image_shape.split(",")]
    model_name = args.model
    model_list = [m for m in dir(models) if "__" not in m]
    assert model_name in model_list, "{} is not in lists: {}".format(args.model,
                                                                     model_list)
    model = models.__dict__[model_name]()
    with fluid.program_guard(main_prog, startup_prog):
        py_reader = fluid.layers.py_reader(
            capacity=16,
            shapes=[[-1] + image_shape, [-1, 1]],
            lod_levels=[0, 0],
            dtypes=["float32", "int64"],
            use_double_buffer=True)
        with fluid.unique_name.guard():
            image, label = fluid.layers.read_file(py_reader)
T
typhoonzero 已提交
187
            if args.fp16:
T
update  
typhoonzero 已提交
188
                image = fluid.layers.cast(image, "float16")
R
ruri 已提交
189 190 191 192 193 194 195 196 197 198 199
            avg_cost, acc_top1, acc_top5 = net_config(image, label, model, args)
            avg_cost.persistable = True
            acc_top1.persistable = True
            acc_top5.persistable = True
            if is_train:
                params = model.params
                params["total_images"] = args.total_images
                params["lr"] = args.lr
                params["num_epochs"] = args.num_epochs
                params["learning_strategy"]["batch_size"] = args.batch_size
                params["learning_strategy"]["name"] = args.lr_strategy
R
root 已提交
200 201
                params["l2_decay"] = args.l2_decay
                params["momentum_rate"] = args.momentum_rate
R
ruri 已提交
202 203

                optimizer = optimizer_setting(params)
T
typhoonzero 已提交
204
                if args.fp16:
T
typhoonzero 已提交
205
                    params_grads = optimizer.backward(avg_cost)
T
typhoonzero 已提交
206 207
                    master_params_grads = create_master_params_grads(
                        params_grads, main_prog, startup_prog, args.scale_loss)
T
update  
typhoonzero 已提交
208
                    optimizer.apply_gradients(master_params_grads)
R
root 已提交
209 210
                    master_param_to_train_param(master_params_grads,
                                                params_grads, main_prog)
T
typhoonzero 已提交
211 212
                else:
                    optimizer.minimize(avg_cost)
R
root 已提交
213
                global_lr = optimizer._global_learning_rate()
R
ruri 已提交
214

R
root 已提交
215 216 217 218
    if is_train:
        return py_reader, avg_cost, acc_top1, acc_top5, global_lr
    else:
        return py_reader, avg_cost, acc_top1, acc_top5
R
ruri 已提交
219 220 221 222 223 224 225 226 227


def train(args):
    # parameters from arguments
    model_name = args.model
    checkpoint = args.checkpoint
    pretrained_model = args.pretrained_model
    with_memory_optimization = args.with_mem_opt
    model_save_dir = args.model_save_dir
228

R
ruri 已提交
229 230 231 232 233 234 235
    startup_prog = fluid.Program()
    train_prog = fluid.Program()
    test_prog = fluid.Program()
    if args.enable_ce:
        startup_prog.random_seed = 1000
        train_prog.random_seed = 1000

R
root 已提交
236
    train_py_reader, train_cost, train_acc1, train_acc5, global_lr = build_program(
R
ruri 已提交
237 238 239 240 241 242 243 244 245 246
        is_train=True,
        main_prog=train_prog,
        startup_prog=startup_prog,
        args=args)
    test_py_reader, test_cost, test_acc1, test_acc5 = build_program(
        is_train=False,
        main_prog=test_prog,
        startup_prog=startup_prog,
        args=args)
    test_prog = test_prog.clone(for_test=True)
247

248
    if with_memory_optimization:
R
ruri 已提交
249 250
        fluid.memory_optimize(train_prog)
        fluid.memory_optimize(test_prog)
251

252
    place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()
253
    exe = fluid.Executor(place)
R
ruri 已提交
254
    exe.run(startup_prog)
255

256
    if checkpoint is not None:
R
ruri 已提交
257
        fluid.io.load_persistables(exe, checkpoint, main_program=train_prog)
258

259 260 261 262 263
    if pretrained_model:

        def if_exist(var):
            return os.path.exists(os.path.join(pretrained_model, var.name))

R
ruri 已提交
264 265
        fluid.io.load_vars(
            exe, pretrained_model, main_program=train_prog, predicate=if_exist)
266

R
ruri 已提交
267 268 269 270
    visible_device = os.getenv('CUDA_VISIBLE_DEVICES')
    if visible_device:
        device_num = len(visible_device.split(','))
    else:
R
root 已提交
271 272
        device_num = subprocess.check_output(
            ['nvidia-smi', '-L']).decode().count('\n')
273

R
ruri 已提交
274
    train_batch_size = args.batch_size / device_num
K
kolinwei 已提交
275
    test_batch_size = 16
276
    if not args.enable_ce:
R
ruri 已提交
277 278
        train_reader = paddle.batch(
            reader.train(), batch_size=train_batch_size, drop_last=True)
279 280 281 282 283 284
        test_reader = paddle.batch(reader.val(), batch_size=test_batch_size)
    else:
        # use flowers dataset for CE and set use_xmap False to avoid disorder data
        # but it is time consuming. For faster speed, need another dataset.
        import random
        random.seed(0)
D
Dang Qingqing 已提交
285
        np.random.seed(0)
286
        train_reader = paddle.batch(
R
ruri 已提交
287 288 289
            flowers.train(use_xmap=False),
            batch_size=train_batch_size,
            drop_last=True)
290 291 292
        test_reader = paddle.batch(
            flowers.test(use_xmap=False), batch_size=test_batch_size)

R
ruri 已提交
293 294
    train_py_reader.decorate_paddle_reader(train_reader)
    test_py_reader.decorate_paddle_reader(test_reader)
L
Luo Tao 已提交
295
    train_exe = fluid.ParallelExecutor(
R
ruri 已提交
296 297 298 299
        main_program=train_prog,
        use_cuda=bool(args.use_gpu),
        loss_name=train_cost.name)

R
root 已提交
300 301 302
    train_fetch_list = [
        train_cost.name, train_acc1.name, train_acc5.name, global_lr.name
    ]
R
ruri 已提交
303
    test_fetch_list = [test_cost.name, test_acc1.name, test_acc5.name]
304

R
ruri 已提交
305
    params = models.__dict__[args.model]().params
306
    for pass_id in range(params["num_epochs"]):
R
ruri 已提交
307 308 309

        train_py_reader.start()

310 311
        train_info = [[], [], []]
        test_info = [[], [], []]
312
        train_time = []
R
ruri 已提交
313 314 315 316
        batch_id = 0
        try:
            while True:
                t1 = time.time()
R
root 已提交
317 318
                loss, acc1, acc5, lr = train_exe.run(
                    fetch_list=train_fetch_list)
R
root 已提交
319

R
ruri 已提交
320 321 322 323 324 325 326 327
                t2 = time.time()
                period = t2 - t1
                loss = np.mean(np.array(loss))
                acc1 = np.mean(np.array(acc1))
                acc5 = np.mean(np.array(acc5))
                train_info[0].append(loss)
                train_info[1].append(acc1)
                train_info[2].append(acc5)
R
root 已提交
328
                lr = np.mean(np.array(lr))
R
ruri 已提交
329
                train_time.append(period)
R
root 已提交
330

R
ruri 已提交
331 332
                if batch_id % 10 == 0:
                    print("Pass {0}, trainbatch {1}, loss {2}, \
R
root 已提交
333 334 335
                        acc1 {3}, acc5 {4}, lr{5}, time {6}"
                          .format(pass_id, batch_id, loss, acc1, acc5, "%.5f" %
                                  lr, "%2.2f sec" % period))
R
ruri 已提交
336 337 338 339
                    sys.stdout.flush()
                batch_id += 1
        except fluid.core.EOFException:
            train_py_reader.reset()
340 341 342 343

        train_loss = np.array(train_info[0]).mean()
        train_acc1 = np.array(train_info[1]).mean()
        train_acc5 = np.array(train_info[2]).mean()
R
root 已提交
344 345
        train_speed = np.array(train_time).mean() / (train_batch_size *
                                                     device_num)
R
ruri 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

        test_py_reader.start()

        test_batch_id = 0
        try:
            while True:
                t1 = time.time()
                loss, acc1, acc5 = exe.run(program=test_prog,
                                           fetch_list=test_fetch_list)
                t2 = time.time()
                period = t2 - t1
                loss = np.mean(loss)
                acc1 = np.mean(acc1)
                acc5 = np.mean(acc5)
                test_info[0].append(loss)
                test_info[1].append(acc1)
                test_info[2].append(acc5)
                if test_batch_id % 10 == 0:
                    print("Pass {0},testbatch {1},loss {2}, \
                        acc1 {3},acc5 {4},time {5}"
                          .format(pass_id, test_batch_id, loss, acc1, acc5,
                                  "%2.2f sec" % period))
                    sys.stdout.flush()
                test_batch_id += 1
        except fluid.core.EOFException:
            test_py_reader.reset()

        test_loss = np.array(test_info[0]).mean()
        test_acc1 = np.array(test_info[1]).mean()
        test_acc5 = np.array(test_info[2]).mean()
376

377
        print("End pass {0}, train_loss {1}, train_acc1 {2}, train_acc5 {3}, "
R
ruri 已提交
378 379 380
              "test_loss {4}, test_acc1 {5}, test_acc5 {6}".format(
                  pass_id, train_loss, train_acc1, train_acc5, test_loss,
                  test_acc1, test_acc5))
381 382
        sys.stdout.flush()

383
        model_path = os.path.join(model_save_dir + '/' + model_name,
384
                                  str(pass_id))
385 386
        if not os.path.isdir(model_path):
            os.makedirs(model_path)
R
ruri 已提交
387
        fluid.io.save_persistables(exe, model_path, main_program=train_prog)
388

389 390
        # This is for continuous evaluation only
        if args.enable_ce and pass_id == args.num_epochs - 1:
R
ruri 已提交
391
            if device_num == 1:
D
Dang Qingqing 已提交
392
                # Use the mean cost/acc for training
393 394 395 396 397 398 399 400 401
                print("kpis	train_cost	%s" % train_loss)
                print("kpis	train_acc_top1	%s" % train_acc1)
                print("kpis	train_acc_top5	%s" % train_acc5)
                # Use the mean cost/acc for testing
                print("kpis	test_cost	%s" % test_loss)
                print("kpis	test_acc_top1	%s" % test_acc1)
                print("kpis	test_acc_top5	%s" % test_acc5)
                print("kpis	train_speed	%s" % train_speed)
            else:
D
Dang Qingqing 已提交
402
                # Use the mean cost/acc for training
R
ruri 已提交
403 404 405 406 407
                print("kpis	train_cost_card%s	%s" % (device_num, train_loss))
                print("kpis	train_acc_top1_card%s	%s" %
                      (device_num, train_acc1))
                print("kpis	train_acc_top5_card%s	%s" %
                      (device_num, train_acc5))
408
                # Use the mean cost/acc for testing
R
ruri 已提交
409 410 411 412
                print("kpis	test_cost_card%s	%s" % (device_num, test_loss))
                print("kpis	test_acc_top1_card%s	%s" % (device_num, test_acc1))
                print("kpis	test_acc_top5_card%s	%s" % (device_num, test_acc5))
                print("kpis	train_speed_card%s	%s" % (device_num, train_speed))
413

414

415
def main():
416
    args = parser.parse_args()
R
root 已提交
417
    set_models(args.model_category)
418
    print_arguments(args)
419
    train(args)
420

421 422 423

if __name__ == '__main__':
    main()