train.py 19.4 KB
Newer Older
W
wuzewu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# coding: utf8
# 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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
# GPU memory garbage collection optimization flags
os.environ['FLAGS_eager_delete_tensor_gb'] = "0.0"

import sys
import argparse
import pprint
X
xiegegege 已提交
27
import random
W
wuzewu 已提交
28 29 30 31 32 33
import shutil
import functools

import paddle
import numpy as np
import paddle.fluid as fluid
H
hysunflower 已提交
34
from paddle.fluid import profiler
W
wuzewu 已提交
35 36 37 38 39 40 41 42 43 44

from utils.config import cfg
from utils.timer import Timer, calculate_eta
from metrics import ConfusionMatrix
from reader import SegDataset
from models.model_builder import build_model
from models.model_builder import ModelPhase
from models.model_builder import parse_shape_from_file
from eval import evaluate
from vis import visualize
45
from utils import dist_utils
W
wuzewu 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79


def parse_args():
    parser = argparse.ArgumentParser(description='PaddleSeg training')
    parser.add_argument(
        '--cfg',
        dest='cfg_file',
        help='Config file for training (and optionally testing)',
        default=None,
        type=str)
    parser.add_argument(
        '--use_gpu',
        dest='use_gpu',
        help='Use gpu or cpu',
        action='store_true',
        default=False)
    parser.add_argument(
        '--use_mpio',
        dest='use_mpio',
        help='Use multiprocess I/O or not',
        action='store_true',
        default=False)
    parser.add_argument(
        '--log_steps',
        dest='log_steps',
        help='Display logging information at every log_steps',
        default=10,
        type=int)
    parser.add_argument(
        '--debug',
        dest='debug',
        help='debug mode, display detail information of training',
        action='store_true')
    parser.add_argument(
80 81 82
        '--use_vdl',
        dest='use_vdl',
        help='whether to record the data during training to VisualDL',
W
wuzewu 已提交
83 84
        action='store_true')
    parser.add_argument(
85 86 87
        '--vdl_log_dir',
        dest='vdl_log_dir',
        help='VisualDL logging directory',
W
wuzewu 已提交
88 89 90 91 92 93 94 95 96 97 98 99
        default=None,
        type=str)
    parser.add_argument(
        '--do_eval',
        dest='do_eval',
        help='Evaluation models result on every new checkpoint',
        action='store_true')
    parser.add_argument(
        'opts',
        help='See utils/config.py for all options',
        default=None,
        nargs=argparse.REMAINDER)
X
xiegegege 已提交
100 101 102 103 104 105
    parser.add_argument(
        '--enable_ce',
        dest='enable_ce',
        help='If set True, enable continuous evaluation job.'
        'This flag is only used for internal test.',
        action='store_true')
106

H
hysunflower 已提交
107 108 109 110 111 112 113 114 115 116
    # NOTE: This for benchmark
    parser.add_argument(
        '--is_profiler',
        help='the profiler switch.(used for benchmark)',
        default=0,
        type=int)
    parser.add_argument(
        '--profiler_path',
        help='the profiler output file path.(used for benchmark)',
        default='./seg.profiler',
117
        type=str)
W
wuzewu 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    return parser.parse_args()


def save_vars(executor, dirname, program=None, vars=None):
    """
    Temporary resolution for Win save variables compatability.
    Will fix in PaddlePaddle v1.5.2
    """

    save_program = fluid.Program()
    save_block = save_program.global_block()

    for each_var in vars:
        # NOTE: don't save the variable which type is RAW
        if each_var.type == fluid.core.VarDesc.VarType.RAW:
            continue
        new_var = save_block.create_var(
            name=each_var.name,
            shape=each_var.shape,
            dtype=each_var.dtype,
            type=each_var.type,
            lod_level=each_var.lod_level,
            persistable=True)
        file_path = os.path.join(dirname, new_var.name)
        file_path = os.path.normpath(file_path)
        save_block.append_op(
            type='save',
            inputs={'X': [new_var]},
            outputs={},
            attrs={'file_path': file_path})

    executor.run(save_program)


def save_checkpoint(exe, program, ckpt_name):
    """
    Save checkpoint for evaluation or resume training
    """
    ckpt_dir = os.path.join(cfg.TRAIN.MODEL_SAVE_DIR, str(ckpt_name))
    print("Save model checkpoint to {}".format(ckpt_dir))
    if not os.path.isdir(ckpt_dir):
        os.makedirs(ckpt_dir)

    save_vars(
        exe,
        ckpt_dir,
        program,
        vars=list(filter(fluid.io.is_persistable, program.list_vars())))

    return ckpt_dir


def load_checkpoint(exe, program):
    """
    Load checkpoiont from pretrained model directory for resume training
    """

W
wuzewu 已提交
175 176
    print('Resume model training from:', cfg.TRAIN.RESUME_MODEL_DIR)
    if not os.path.exists(cfg.TRAIN.RESUME_MODEL_DIR):
W
wuzewu 已提交
177
        raise ValueError("TRAIN.PRETRAIN_MODEL {} not exist!".format(
W
wuzewu 已提交
178
            cfg.TRAIN.RESUME_MODEL_DIR))
W
wuzewu 已提交
179 180

    fluid.io.load_persistables(
W
wuzewu 已提交
181
        exe, cfg.TRAIN.RESUME_MODEL_DIR, main_program=program)
W
wuzewu 已提交
182

W
wuzewu 已提交
183
    model_path = cfg.TRAIN.RESUME_MODEL_DIR
W
wuzewu 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    # Check is path ended by path spearator
    if model_path[-1] == os.sep:
        model_path = model_path[0:-1]
    epoch_name = os.path.basename(model_path)
    # If resume model is final model
    if epoch_name == 'final':
        begin_epoch = cfg.SOLVER.NUM_EPOCHS
    # If resume model path is end of digit, restore epoch status
    elif epoch_name.isdigit():
        epoch = int(epoch_name)
        begin_epoch = epoch + 1
    else:
        raise ValueError("Resume model path is not valid!")
    print("Model checkpoint loaded successfully!")

    return begin_epoch


W
wuyefeilin 已提交
202 203 204 205 206 207 208
def update_best_model(ckpt_dir):
    best_model_dir = os.path.join(cfg.TRAIN.MODEL_SAVE_DIR, 'best_model')
    if os.path.exists(best_model_dir):
        shutil.rmtree(best_model_dir)
    shutil.copytree(ckpt_dir, best_model_dir)


209 210 211
def print_info(*msg):
    if cfg.TRAINER_ID == 0:
        print(*msg)
W
wuzewu 已提交
212

W
wuzewu 已提交
213

W
wuzewu 已提交
214 215 216
def train(cfg):
    startup_prog = fluid.Program()
    train_prog = fluid.Program()
X
xiegegege 已提交
217 218 219
    if args.enable_ce:
        startup_prog.random_seed = 1000
        train_prog.random_seed = 1000
W
wuzewu 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    drop_last = True

    dataset = SegDataset(
        file_list=cfg.DATASET.TRAIN_FILE_LIST,
        mode=ModelPhase.TRAIN,
        shuffle=True,
        data_dir=cfg.DATASET.DATA_DIR)

    def data_generator():
        if args.use_mpio:
            data_gen = dataset.multiprocess_generator(
                num_processes=cfg.DATALOADER.NUM_WORKERS,
                max_queue_size=cfg.DATALOADER.BUF_SIZE)
        else:
            data_gen = dataset.generator()

        batch_data = []
        for b in data_gen:
            batch_data.append(b)
239
            if len(batch_data) == (cfg.BATCH_SIZE // cfg.NUM_TRAINERS):
W
wuzewu 已提交
240 241 242 243 244 245 246 247 248 249
                for item in batch_data:
                    yield item[0], item[1], item[2]
                batch_data = []
        # If use sync batch norm strategy, drop last batch if number of samples
        # in batch_data is less then cfg.BATCH_SIZE to avoid NCCL hang issues
        if not cfg.TRAIN.SYNC_BATCH_NORM:
            for item in batch_data:
                yield item[0], item[1], item[2]

    # Get device environment
250 251 252 253
    # places = fluid.cuda_places() if args.use_gpu else fluid.cpu_places()
    # place = places[0]
    gpu_id = int(os.environ.get('FLAGS_selected_gpus', 0))
    place = fluid.CUDAPlace(gpu_id) if args.use_gpu else fluid.CPUPlace()
W
wuzewu 已提交
254
    places = fluid.cuda_places() if args.use_gpu else fluid.cpu_places()
255

W
wuzewu 已提交
256
    # Get number of GPU
257 258
    dev_count = cfg.NUM_TRAINERS if cfg.NUM_TRAINERS > 1 else len(places)
    print_info("#Device count: {}".format(dev_count))
W
wuzewu 已提交
259 260 261 262 263 264 265

    # Make sure BATCH_SIZE can divided by GPU cards
    assert cfg.BATCH_SIZE % dev_count == 0, (
        'BATCH_SIZE:{} not divisble by number of GPUs:{}'.format(
            cfg.BATCH_SIZE, dev_count))
    # If use multi-gpu training mode, batch data will allocated to each GPU evenly
    batch_size_per_dev = cfg.BATCH_SIZE // dev_count
266
    print_info("batch_size_per_dev: {}".format(batch_size_per_dev))
W
wuzewu 已提交
267

268
    data_loader, avg_loss, lr, pred, grts, masks = build_model(
W
wuzewu 已提交
269
        train_prog, startup_prog, phase=ModelPhase.TRAIN)
270
    data_loader.set_sample_generator(
W
wuzewu 已提交
271 272 273 274 275 276 277 278 279 280 281
        data_generator, batch_size=batch_size_per_dev, drop_last=drop_last)

    exe = fluid.Executor(place)
    exe.run(startup_prog)

    exec_strategy = fluid.ExecutionStrategy()
    # Clear temporary variables every 100 iteration
    if args.use_gpu:
        exec_strategy.num_threads = fluid.core.get_cuda_device_count()
    exec_strategy.num_iteration_per_drop_scope = 100
    build_strategy = fluid.BuildStrategy()
282 283 284 285 286

    if cfg.NUM_TRAINERS > 1 and args.use_gpu:
        dist_utils.prepare_for_multi_process(exe, build_strategy, train_prog)
        exec_strategy.num_threads = 1

W
wuzewu 已提交
287 288 289
    if cfg.TRAIN.SYNC_BATCH_NORM and args.use_gpu:
        if dev_count > 1:
            # Apply sync batch norm strategy
290
            print_info("Sync BatchNorm strategy is effective.")
W
wuzewu 已提交
291 292
            build_strategy.sync_batch_norm = True
        else:
W
wuzewu 已提交
293 294 295
            print_info(
                "Sync BatchNorm strategy will not be effective if GPU device"
                " count <= 1")
W
wuzewu 已提交
296 297 298 299 300 301 302
    compiled_train_prog = fluid.CompiledProgram(train_prog).with_data_parallel(
        loss_name=avg_loss.name,
        exec_strategy=exec_strategy,
        build_strategy=build_strategy)

    # Resume training
    begin_epoch = cfg.SOLVER.BEGIN_EPOCH
W
wuzewu 已提交
303
    if cfg.TRAIN.RESUME_MODEL_DIR:
W
wuzewu 已提交
304 305
        begin_epoch = load_checkpoint(exe, train_prog)
    # Load pretrained model
W
wuzewu 已提交
306
    elif os.path.exists(cfg.TRAIN.PRETRAINED_MODEL_DIR):
307
        print_info('Pretrained model dir: ', cfg.TRAIN.PRETRAINED_MODEL_DIR)
W
wuzewu 已提交
308
        load_vars = []
W
wuzewu 已提交
309
        load_fail_vars = []
W
wuzewu 已提交
310 311 312 313 314 315

        def var_shape_matched(var, shape):
            """
            Check whehter persitable variable shape is match with current network
            """
            var_exist = os.path.exists(
W
wuzewu 已提交
316
                os.path.join(cfg.TRAIN.PRETRAINED_MODEL_DIR, var.name))
W
wuzewu 已提交
317 318
            if var_exist:
                var_shape = parse_shape_from_file(
W
wuzewu 已提交
319
                    os.path.join(cfg.TRAIN.PRETRAINED_MODEL_DIR, var.name))
W
wuzewu 已提交
320 321
                return var_shape == shape
            return False
W
wuzewu 已提交
322 323 324 325 326 327 328

        for x in train_prog.list_vars():
            if isinstance(x, fluid.framework.Parameter):
                shape = tuple(fluid.global_scope().find_var(
                    x.name).get_tensor().shape())
                if var_shape_matched(x, shape):
                    load_vars.append(x)
W
wuzewu 已提交
329 330
                else:
                    load_fail_vars.append(x)
331 332 333

        fluid.io.load_vars(
            exe, dirname=cfg.TRAIN.PRETRAINED_MODEL_DIR, vars=load_vars)
W
wuzewu 已提交
334
        for var in load_vars:
335
            print_info("Parameter[{}] loaded sucessfully!".format(var.name))
W
wuzewu 已提交
336
        for var in load_fail_vars:
W
wuzewu 已提交
337 338 339
            print_info(
                "Parameter[{}] don't exist or shape does not match current network, skip"
                " to load it.".format(var.name))
340
        print_info("{}/{} pretrained parameters loaded successfully!".format(
W
wuzewu 已提交
341 342
            len(load_vars),
            len(load_vars) + len(load_fail_vars)))
W
wuzewu 已提交
343
    else:
W
wuzewu 已提交
344 345 346
        print_info(
            'Pretrained model dir {} not exists, training from scratch...'.
            format(cfg.TRAIN.PRETRAINED_MODEL_DIR))
W
wuzewu 已提交
347 348 349 350 351 352 353 354 355 356

    fetch_list = [avg_loss.name, lr.name]
    if args.debug:
        # Fetch more variable info and use streaming confusion matrix to
        # calculate IoU results if in debug mode
        np.set_printoptions(
            precision=4, suppress=True, linewidth=160, floatmode="fixed")
        fetch_list.extend([pred.name, grts.name, masks.name])
        cm = ConfusionMatrix(cfg.DATASET.NUM_CLASSES, streaming=True)

357 358 359
    if args.use_vdl:
        if not args.vdl_log_dir:
            print_info("Please specify the log directory by --vdl_log_dir.")
W
wuzewu 已提交
360 361
            exit(1)

362 363
        from visualdl import LogWriter
        log_writer = LogWriter(args.vdl_log_dir)
W
wuzewu 已提交
364

365 366
    # trainer_id = int(os.getenv("PADDLE_TRAINER_ID", 0))
    # num_trainers = int(os.environ.get('PADDLE_TRAINERS_NUM', 1))
367
    step = 0
W
wuzewu 已提交
368 369 370 371 372 373
    all_step = cfg.DATASET.TRAIN_TOTAL_IMAGES // cfg.BATCH_SIZE
    if cfg.DATASET.TRAIN_TOTAL_IMAGES % cfg.BATCH_SIZE and drop_last != True:
        all_step += 1
    all_step *= (cfg.SOLVER.NUM_EPOCHS - begin_epoch + 1)

    avg_loss = 0.0
W
wuyefeilin 已提交
374 375
    best_mIoU = 0.0

W
wuzewu 已提交
376 377 378 379 380 381 382
    timer = Timer()
    timer.start()
    if begin_epoch > cfg.SOLVER.NUM_EPOCHS:
        raise ValueError(
            ("begin epoch[{}] is larger than cfg.SOLVER.NUM_EPOCHS[{}]").format(
                begin_epoch, cfg.SOLVER.NUM_EPOCHS))

W
wuzewu 已提交
383
    if args.use_mpio:
384
        print_info("Use multiprocess reader")
W
wuzewu 已提交
385
    else:
386
        print_info("Use multi-thread reader")
W
wuzewu 已提交
387

W
wuzewu 已提交
388
    for epoch in range(begin_epoch, cfg.SOLVER.NUM_EPOCHS + 1):
389
        data_loader.start()
W
wuzewu 已提交
390 391 392 393 394 395 396 397 398 399 400
        while True:
            try:
                if args.debug:
                    # Print category IoU and accuracy to check whether the
                    # traning process is corresponed to expectation
                    loss, lr, pred, grts, masks = exe.run(
                        program=compiled_train_prog,
                        fetch_list=fetch_list,
                        return_numpy=True)
                    cm.calculate(pred, grts, masks)
                    avg_loss += np.mean(np.array(loss))
401
                    step += 1
W
wuzewu 已提交
402

403
                    if step % args.log_steps == 0:
W
wuzewu 已提交
404 405 406 407 408
                        speed = args.log_steps / timer.elapsed_time()
                        avg_loss /= args.log_steps
                        category_acc, mean_acc = cm.accuracy()
                        category_iou, mean_iou = cm.mean_iou()

409
                        print_info((
W
wuzewu 已提交
410
                            "epoch={} step={} lr={:.5f} loss={:.4f} acc={:.5f} mIoU={:.5f} step/sec={:.3f} | ETA {}"
411
                        ).format(epoch, step, lr[0], avg_loss, mean_acc,
W
wuzewu 已提交
412
                                 mean_iou, speed,
413
                                 calculate_eta(all_step - step, speed)))
414 415
                        print_info("Category IoU: ", category_iou)
                        print_info("Category Acc: ", category_acc)
416
                        if args.use_vdl:
W
wuzewu 已提交
417
                            log_writer.add_scalar('Train/mean_iou', mean_iou,
418
                                                  step)
W
wuzewu 已提交
419
                            log_writer.add_scalar('Train/mean_acc', mean_acc,
420
                                                  step)
W
wuzewu 已提交
421
                            log_writer.add_scalar('Train/loss', avg_loss,
422
                                                  step)
W
wuzewu 已提交
423
                            log_writer.add_scalar('Train/lr', lr[0],
424
                                                  step)
W
wuzewu 已提交
425
                            log_writer.add_scalar('Train/step/sec', speed,
426
                                                  step)
W
wuzewu 已提交
427 428 429 430 431 432 433 434 435 436 437
                        sys.stdout.flush()
                        avg_loss = 0.0
                        cm.zero_matrix()
                        timer.restart()
                else:
                    # If not in debug mode, avoid unnessary log and calculate
                    loss, lr = exe.run(
                        program=compiled_train_prog,
                        fetch_list=fetch_list,
                        return_numpy=True)
                    avg_loss += np.mean(np.array(loss))
438
                    step += 1
W
wuzewu 已提交
439

440
                    if step % args.log_steps == 0 and cfg.TRAINER_ID == 0:
W
wuzewu 已提交
441 442 443 444
                        avg_loss /= args.log_steps
                        speed = args.log_steps / timer.elapsed_time()
                        print((
                            "epoch={} step={} lr={:.5f} loss={:.4f} step/sec={:.3f} | ETA {}"
445 446 447
                        ).format(epoch, step, lr[0], avg_loss, speed,
                                 calculate_eta(all_step - step, speed)))
                        if args.use_vdl:
W
wuzewu 已提交
448
                            log_writer.add_scalar('Train/loss', avg_loss,
449
                                                  step)
W
wuzewu 已提交
450
                            log_writer.add_scalar('Train/lr', lr[0],
451
                                                  step)
W
wuzewu 已提交
452
                            log_writer.add_scalar('Train/speed', speed,
453
                                                  step)
W
wuzewu 已提交
454 455 456
                        sys.stdout.flush()
                        avg_loss = 0.0
                        timer.restart()
457

H
hysunflower 已提交
458
                    # NOTE : used for benchmark, profiler tools
459
                    if args.is_profiler and epoch == 1 and step == args.log_steps:
H
hysunflower 已提交
460
                        profiler.start_profiler("All")
461
                    elif args.is_profiler and epoch == 1 and step == args.log_steps + 5:
H
hysunflower 已提交
462 463
                        profiler.stop_profiler("total", args.profiler_path)
                        return
W
wuzewu 已提交
464 465

            except fluid.core.EOFException:
466
                data_loader.reset()
W
wuzewu 已提交
467 468 469 470
                break
            except Exception as e:
                print(e)

W
wuyefeilin 已提交
471 472
        if (epoch % cfg.TRAIN.SNAPSHOT_EPOCH == 0
                or epoch == cfg.SOLVER.NUM_EPOCHS) and cfg.TRAINER_ID == 0:
W
wuzewu 已提交
473 474 475 476 477 478 479 480 481
            ckpt_dir = save_checkpoint(exe, train_prog, epoch)

            if args.do_eval:
                print("Evaluation start")
                _, mean_iou, _, mean_acc = evaluate(
                    cfg=cfg,
                    ckpt_dir=ckpt_dir,
                    use_gpu=args.use_gpu,
                    use_mpio=args.use_mpio)
482
                if args.use_vdl:
W
wuzewu 已提交
483
                    log_writer.add_scalar('Evaluate/mean_iou', mean_iou,
484
                                          step)
W
wuzewu 已提交
485
                    log_writer.add_scalar('Evaluate/mean_acc', mean_acc,
486
                                          step)
W
wuzewu 已提交
487

W
wuyefeilin 已提交
488 489 490 491 492 493 494 495
                if mean_iou > best_mIoU:
                    best_mIoU = mean_iou
                    update_best_model(ckpt_dir)
                    print_info("Save best model {} to {}, mIoU = {:.4f}".format(
                        ckpt_dir,
                        os.path.join(cfg.TRAIN.MODEL_SAVE_DIR, 'best_model'),
                        mean_iou))

496 497
            # Use VisualDL to visualize results
            if args.use_vdl and cfg.DATASET.VIS_FILE_LIST is not None:
W
wuzewu 已提交
498 499 500 501 502 503 504 505 506
                visualize(
                    cfg=cfg,
                    use_gpu=args.use_gpu,
                    vis_file_list=cfg.DATASET.VIS_FILE_LIST,
                    vis_dir="visual",
                    ckpt_dir=ckpt_dir,
                    log_writer=log_writer)

    # save final model
507 508
    if cfg.TRAINER_ID == 0:
        save_checkpoint(exe, train_prog, 'final')
W
wuzewu 已提交
509 510 511 512 513


def main(args):
    if args.cfg_file is not None:
        cfg.update_from_file(args.cfg_file)
514
    if args.opts:
W
wuzewu 已提交
515
        cfg.update_from_list(args.opts)
X
xiegegege 已提交
516 517 518
    if args.enable_ce:
        random.seed(0)
        np.random.seed(0)
519 520 521 522

    cfg.TRAINER_ID = int(os.getenv("PADDLE_TRAINER_ID", 0))
    cfg.NUM_TRAINERS = int(os.environ.get('PADDLE_TRAINERS_NUM', 1))

W
wuzewu 已提交
523
    cfg.check_and_infer()
524
    print_info(pprint.pformat(cfg))
W
wuzewu 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538
    train(cfg)


if __name__ == '__main__':
    args = parse_args()
    if fluid.core.is_compiled_with_cuda() != True and args.use_gpu == True:
        print(
            "You can not set use_gpu = True in the model because you are using paddlepaddle-cpu."
        )
        print(
            "Please: 1. Install paddlepaddle-gpu to run your models on GPU or 2. Set use_gpu=False to run models on CPU."
        )
        sys.exit(1)
    main(args)