train.py 11.7 KB
Newer Older
R
ruri 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.

R
root 已提交
15 16 17
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
R
ruri 已提交
18

19 20 21
import os
import time
import sys
22
import logging
23

R
ruri 已提交
24
import numpy as np
25
import paddle
26
import paddle.fluid as fluid
27
from paddle.fluid import profiler
R
ruri 已提交
28 29
import reader
from utils import *
30
import models
R
ruri 已提交
31 32
from build_model import create_model

33 34 35
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

36

37
class TimeAverager(object):
W
wanghuancoder 已提交
38 39 40 41
    def __init__(self):
        self.reset()

    def reset(self):
42 43
        self._cnt = 0
        self._total_time = 0
W
wanghuancoder 已提交
44 45

    def record(self, usetime):
46 47
        self._cnt += 1
        self._total_time += usetime
W
wanghuancoder 已提交
48 49

    def get_average(self):
50
        if self._cnt == 0:
W
wanghuancoder 已提交
51
            return 0
52
        return self._total_time / self._cnt
W
wanghuancoder 已提交
53 54


R
ruri 已提交
55
def build_program(is_train, main_prog, startup_prog, args):
56
    """build program, and add backward op in program accroding to different mode
R
ruri 已提交
57

R
ruri 已提交
58 59
    Parameters:
        is_train: indicate train mode or test mode
R
ruri 已提交
60 61 62 63 64
        main_prog: main program
        startup_prog: strartup program
        args: arguments

    Returns : 
65 66
        train mode: [Loss, global_lr, data_loader]
        test mode: [Loss, data_loader]
R
ruri 已提交
67
    """
68 69 70
    if args.model.startswith('EfficientNet'):
        override_params = {"drop_connect_rate": args.drop_connect_rate}
        padding_type = args.padding_type
71
        use_se = args.use_se
R
ruri 已提交
72
        model = models.__dict__[args.model](is_test=not is_train,
73 74 75
                                            override_params=override_params,
                                            padding_type=padding_type,
                                            use_se=use_se)
76 77
    else:
        model = models.__dict__[args.model]()
R
ruri 已提交
78
    with fluid.program_guard(main_prog, startup_prog):
R
ruri 已提交
79
        if args.random_seed or args.enable_ce:
R
ruri 已提交
80 81
            main_prog.random_seed = args.random_seed
            startup_prog.random_seed = args.random_seed
R
ruri 已提交
82
        with fluid.unique_name.guard():
83
            data_loader, loss_out = create_model(model, args, is_train)
R
ruri 已提交
84
            # add backward op in program
R
ruri 已提交
85
            if is_train:
R
ruri 已提交
86 87 88
                optimizer = create_optimizer(args)
                avg_cost = loss_out[0]
                #XXX: fetch learning rate now, better implement is required here. 
R
root 已提交
89
                global_lr = optimizer._global_learning_rate()
R
ruri 已提交
90 91
                global_lr.persistable = True
                loss_out.append(global_lr)
R
ruri 已提交
92 93 94 95 96 97 98 99

                if args.use_fp16:
                    optimizer = fluid.contrib.mixed_precision.decorate(
                        optimizer,
                        init_loss_scaling=args.scale_loss,
                        use_dynamic_loss_scaling=args.use_dynamic_loss_scaling)

                optimizer.minimize(avg_cost)
100
                if args.use_ema:
101 102 103 104
                    global_steps = fluid.layers.learning_rate_scheduler._decay_step_counter(
                    )
                    ema = ExponentialMovingAverage(
                        args.ema_decay, thres_steps=global_steps)
105 106
                    ema.update()
                    loss_out.append(ema)
107
            loss_out.append(data_loader)
R
ruri 已提交
108
    return loss_out
R
ruri 已提交
109

R
ruri 已提交
110

R
ruri 已提交
111 112 113 114 115 116 117
def validate(args,
             test_iter,
             exe,
             test_prog,
             test_fetch_list,
             pass_id,
             train_batch_metrics_record,
118 119
             train_batch_time_record=None,
             train_prog=None):
120 121 122
    test_batch_time_record = []
    test_batch_metrics_record = []
    test_batch_id = 0
123

R
ruri 已提交
124 125 126 127 128 129 130 131 132 133
    if int(os.environ.get('PADDLE_TRAINERS_NUM', 1)) > 1:
        compiled_program = test_prog
    else:
        compiled_program = best_strategy_compiled(
            args,
            test_prog,
            test_fetch_list[0],
            exe,
            mode="val",
            share_prog=train_prog)
134 135
    for batch in test_iter:
        t1 = time.time()
136
        test_batch_metrics = exe.run(program=compiled_program,
137 138 139 140 141 142
                                     feed=batch,
                                     fetch_list=test_fetch_list)
        t2 = time.time()
        test_batch_elapse = t2 - t1
        test_batch_time_record.append(test_batch_elapse)

R
ruri 已提交
143
        test_batch_metrics_avg = np.mean(np.array(test_batch_metrics), axis=1)
144 145
        test_batch_metrics_record.append(test_batch_metrics_avg)

R
ruri 已提交
146
        print_info("batch", test_batch_metrics_avg, test_batch_elapse, pass_id,
147
                   test_batch_id, args.print_step, args.class_dim)
148 149
        sys.stdout.flush()
        test_batch_id += 1
150 151 152 153 154 155 156 157

    train_epoch_metrics_avg = np.mean(
        np.array(train_batch_metrics_record), axis=0)

    test_epoch_time_avg = np.mean(np.array(test_batch_time_record))
    test_epoch_metrics_avg = np.mean(
        np.array(test_batch_metrics_record), axis=0)

R
ruri 已提交
158 159 160 161
    print_info(
        "epoch",
        list(train_epoch_metrics_avg) + list(test_epoch_metrics_avg),
        test_epoch_time_avg,
162 163
        pass_id=pass_id,
        class_dim=args.class_dim)
R
ruri 已提交
164 165 166 167 168 169 170
    if args.enable_ce:
        device_num = fluid.core.get_cuda_device_count() if args.use_gpu else 1
        print_info(
            "ce",
            list(train_epoch_metrics_avg) + list(test_epoch_metrics_avg),
            train_batch_time_record,
            device_num=device_num)
R
ruri 已提交
171

172

R
ruri 已提交
173
def train(args):
R
ruri 已提交
174 175 176 177 178
    """Train model
    
    Args:
        args: all arguments.    
    """
R
ruri 已提交
179 180
    startup_prog = fluid.Program()
    train_prog = fluid.Program()
R
ruri 已提交
181 182 183 184 185
    train_out = build_program(
        is_train=True,
        main_prog=train_prog,
        startup_prog=startup_prog,
        args=args)
186
    train_data_loader = train_out[-1]
187 188 189 190 191
    if args.use_ema:
        train_fetch_vars = train_out[:-2]
        ema = train_out[-2]
    else:
        train_fetch_vars = train_out[:-1]
192 193

    train_fetch_list = [var.name for var in train_fetch_vars]
R
ruri 已提交
194

195 196 197 198 199 200 201 202 203
    if args.validate:
        test_prog = fluid.Program()
        test_out = build_program(
            is_train=False,
            main_prog=test_prog,
            startup_prog=startup_prog,
            args=args)
        test_data_loader = test_out[-1]
        test_fetch_vars = test_out[:-1]
204

205
        test_fetch_list = [var.name for var in test_fetch_vars]
R
ruri 已提交
206

207 208
        #Create test_prog and set layers' is_test params to True
        test_prog = test_prog.clone(for_test=True)
209

210 211
    gpu_id = int(os.environ.get('FLAGS_selected_gpus', 0))
    place = fluid.CUDAPlace(gpu_id) if args.use_gpu else fluid.CPUPlace()
212
    exe = fluid.Executor(place)
R
ruri 已提交
213
    exe.run(startup_prog)
214

215 216
    trainer_id = int(os.getenv("PADDLE_TRAINER_ID", 0))

R
ruri 已提交
217 218
    #init model by checkpoint or pretrianed model.
    init_model(exe, args, train_prog)
219
    num_trainers = int(os.environ.get('PADDLE_TRAINERS_NUM', 1))
220 221 222 223 224 225 226 227
    if args.use_dali:
        import dali
        train_iter = dali.train(settings=args)
        if trainer_id == 0:
            test_iter = dali.val(settings=args)
    else:
        imagenet_reader = reader.ImageNetReader(0 if num_trainers > 1 else None)
        train_reader = imagenet_reader.train(settings=args)
R
ruri 已提交
228 229 230 231 232 233 234 235 236 237 238
        if args.use_gpu:
            if num_trainers <= 1:
                places = fluid.framework.cuda_places()
            else:
                places = place
        else:
            if num_trainers <= 1:
                places = fluid.framework.cpu_places()
            else:
                places = place

239
        train_data_loader.set_sample_list_generator(train_reader, places)
240 241 242 243

        if args.validate:
            test_reader = imagenet_reader.val(settings=args)
            test_data_loader.set_sample_list_generator(test_reader, places)
R
ruri 已提交
244 245

    compiled_train_prog = best_strategy_compiled(args, train_prog,
246
                                                 train_fetch_vars[0], exe)
W
wanghuancoder 已提交
247

248 249
    #NOTE: this for benchmark
    total_batch_num = 0
250 251
    batch_cost_averager = TimeAverager()
    reader_cost_averager = TimeAverager()
R
ruri 已提交
252
    for pass_id in range(args.num_epochs):
253
        if num_trainers > 1 and not args.use_dali:
R
ruri 已提交
254 255
            imagenet_reader.set_shuffle_seed(pass_id + (
                args.random_seed if args.random_seed else 0))
256

R
ruri 已提交
257 258 259
        train_batch_id = 0
        train_batch_time_record = []
        train_batch_metrics_record = []
R
ruri 已提交
260

261 262
        if not args.use_dali:
            train_iter = train_data_loader()
263 264
            if args.validate:
                test_iter = test_data_loader()
265

266
        batch_start = time.time()
267
        for batch in train_iter:
268 269 270
            #NOTE: this is for benchmark
            if args.max_iter and total_batch_num == args.max_iter:
                return
271 272
            reader_cost_averager.record(time.time() - batch_start)

273 274
            train_batch_metrics = exe.run(compiled_train_prog,
                                          feed=batch,
R
ruri 已提交
275 276 277 278 279
                                          fetch_list=train_fetch_list)

            train_batch_metrics_avg = np.mean(
                np.array(train_batch_metrics), axis=1)
            train_batch_metrics_record.append(train_batch_metrics_avg)
280 281 282 283 284 285

            # Record the time for ce and benchmark
            train_batch_elapse = time.time() - batch_start
            train_batch_time_record.append(train_batch_elapse)
            batch_cost_averager.record(train_batch_elapse)

286
            if trainer_id == 0:
287
                ips = float(args.batch_size) / batch_cost_averager.get_average()
288 289 290
                print_info(
                    "batch",
                    train_batch_metrics_avg,
291
                    batch_cost_averager.get_average(),
292 293 294
                    pass_id,
                    train_batch_id,
                    args.print_step,
295 296
                    reader_cost=reader_cost_averager.get_average(),
                    ips=ips)
297
                sys.stdout.flush()
W
wanghuancoder 已提交
298
                if train_batch_id % args.print_step == 0:
299 300 301
                    batch_cost_averager.reset()
                    reader_cost_averager.reset()

302
            train_batch_id += 1
303
            total_batch_num = total_batch_num + 1
304 305 306
            batch_start = time.time()

            #NOTE: this for benchmark profiler
307 308 309 310 311
            if args.is_profiler and pass_id == 0 and train_batch_id == args.print_step:
                profiler.start_profiler("All")
            elif args.is_profiler and pass_id == 0 and train_batch_id == args.print_step + 5:
                profiler.stop_profiler("total", args.profiler_path)
                return
312 313 314

        if args.use_dali:
            train_iter.reset()
315

316
        if trainer_id == 0 and args.validate:
317
            if args.use_ema:
318
                logger.info('ExponentialMovingAverage validate start...')
319
                with ema.apply(exe):
R
ruri 已提交
320
                    validate(args, test_iter, exe, test_prog, test_fetch_list,
321 322
                             pass_id, train_batch_metrics_record,
                             compiled_train_prog)
323
                logger.info('ExponentialMovingAverage validate over!')
R
ruri 已提交
324

R
ruri 已提交
325
            validate(args, test_iter, exe, test_prog, test_fetch_list, pass_id,
326 327
                     train_batch_metrics_record, train_batch_time_record,
                     compiled_train_prog)
328

329 330
            if args.use_dali:
                test_iter.reset()
331

332
        if trainer_id == 0 and pass_id % args.save_step == 0:
333 334
            save_model(args, exe, train_prog, pass_id)

R
ruri 已提交
335

336
def main():
R
ruri 已提交
337
    args = parse_args()
338 339
    if int(os.getenv("PADDLE_TRAINER_ID", 0)) == 0:
        print_arguments(args)
R
ruri 已提交
340
    check_args(args)
341
    train(args)
342

343 344

if __name__ == '__main__':
L
Leo Chen 已提交
345 346
    import paddle
    paddle.enable_static()
347
    main()