train.py 5.0 KB
Newer Older
D
dengkaipeng 已提交
1
#  Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
D
dengkaipeng 已提交
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 27 28
#
#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
import sys
import numpy as np
import random
import time
import shutil
from utility import parse_args, print_arguments, SmoothedValue

import paddle
import paddle.fluid as fluid
import reader
D
dengkaipeng 已提交
29
from models.yolov3 import YOLOv3
D
dengkaipeng 已提交
30
from learning_rate import exponential_with_warmup_decay
T
tink2123 已提交
31
from config import cfg
D
dengkaipeng 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44


def train():

    if cfg.debug:
        fluid.default_startup_program().random_seed = 1000
        fluid.default_main_program().random_seed = 1000
        random.seed(0)
        np.random.seed(0)
        
    if not os.path.exists(cfg.model_save_dir):
        os.makedirs(cfg.model_save_dir)

D
dengkaipeng 已提交
45
    model = YOLOv3()
D
dengkaipeng 已提交
46
    model.build_model()
D
dengkaipeng 已提交
47
    input_size = cfg.input_size
D
dengkaipeng 已提交
48 49 50 51 52 53 54
    loss = model.loss()
    loss.persistable = True

    devices = os.getenv("CUDA_VISIBLE_DEVICES") or ""
    devices_num = len(devices.split(","))
    print("Found {} CUDA devices.".format(devices_num))

D
dengkaipeng 已提交
55
    learning_rate = cfg.learning_rate
D
dengkaipeng 已提交
56 57 58
    boundaries = cfg.lr_steps
    gamma = cfg.lr_gamma
    step_num = len(cfg.lr_steps)
D
dengkaipeng 已提交
59
    values = [learning_rate * (gamma**i) for i in range(step_num + 1)]
D
dengkaipeng 已提交
60 61 62 63 64 65 66

    optimizer = fluid.optimizer.Momentum(
        learning_rate=exponential_with_warmup_decay(
            learning_rate=learning_rate,
            boundaries=boundaries,
            values=values,
            warmup_iter=cfg.warm_up_iter,
D
dengkaipeng 已提交
67 68 69
            warmup_factor=cfg.warm_up_factor),
        regularization=fluid.regularizer.L2Decay(cfg.weight_decay),
        momentum=cfg.momentum)
D
dengkaipeng 已提交
70 71 72
    optimizer.minimize(loss)

    place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()
D
dengkaipeng 已提交
73 74
    exe = fluid.Executor(place)
    exe.run(fluid.default_startup_program())
D
dengkaipeng 已提交
75

D
dengkaipeng 已提交
76
    if cfg.pretrain:
D
dengkaipeng 已提交
77 78
        if not os.path.exists(cfg.pretrain):
            print("Pretrain weights not found: {}".format(cfg.pretrain))
D
dengkaipeng 已提交
79
        def if_exist(var):
D
dengkaipeng 已提交
80
            return os.path.exists(os.path.join(cfg.pretrain, var.name))
D
dengkaipeng 已提交
81
        fluid.io.load_vars(exe, cfg.pretrain, predicate=if_exist)
D
dengkaipeng 已提交
82

D
dengkaipeng 已提交
83 84 85
    compile_program = fluid.compiler.CompiledProgram(
            fluid.default_main_program()).with_data_parallel(
            loss_name=loss.name)
D
dengkaipeng 已提交
86

D
dengkaipeng 已提交
87
    random_sizes = [cfg.input_size]
D
dengkaipeng 已提交
88 89 90
    if cfg.random_shape:
        random_sizes = [32 * i for i in range(10, 20)]

91 92 93
    total_iter = cfg.max_iter - cfg.start_iter
    mixup_iter = total_iter - cfg.no_mixup_iter
    train_reader = reader.train(input_size, batch_size=cfg.batch_size, shuffle=True, total_iter=total_iter*devices_num, mixup_iter=mixup_iter*devices_num, random_sizes=random_sizes, use_multiprocessing=cfg.use_multiprocess)
D
dengkaipeng 已提交
94 95
    py_reader = model.py_reader
    py_reader.decorate_paddle_reader(train_reader)
D
dengkaipeng 已提交
96 97 98 99 100

    def save_model(postfix):
        model_path = os.path.join(cfg.model_save_dir, postfix)
        if os.path.isdir(model_path):
            shutil.rmtree(model_path)
D
dengkaipeng 已提交
101
        fluid.io.save_persistables(exe, model_path)
D
dengkaipeng 已提交
102 103 104

    fetch_list = [loss]

D
dengkaipeng 已提交
105 106 107 108 109 110 111 112
    py_reader.start()
    smoothed_loss = SmoothedValue()
    try:
        start_time = time.time()
        prev_start_time = start_time
        snapshot_loss = 0
        snapshot_time = 0
        for iter_id in range(cfg.start_iter, cfg.max_iter):
D
dengkaipeng 已提交
113
            prev_start_time = start_time
D
dengkaipeng 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
            start_time = time.time()
            losses = exe.run(compile_program, fetch_list=[v.name for v in fetch_list])
            smoothed_loss.add_value(np.mean(np.array(losses[0])))
            snapshot_loss += np.mean(np.array(losses[0]))
            snapshot_time += start_time - prev_start_time
            lr = np.array(fluid.global_scope().find_var('learning_rate')
                          .get_tensor())
            print("Iter {:d}, lr {:.6f}, loss {:.6f}, time {:.5f}".format(
                iter_id, lr[0],
                smoothed_loss.get_mean_value(), start_time - prev_start_time))
            sys.stdout.flush()
            if (iter_id + 1) % cfg.snapshot_iter == 0:
                save_model("model_iter{}".format(iter_id))
                print("Snapshot {} saved, average loss: {}, average time: {}".format(
                    iter_id + 1, snapshot_loss / float(cfg.snapshot_iter), 
                    snapshot_time / float(cfg.snapshot_iter)))
                snapshot_loss = 0
                snapshot_time = 0
    except fluid.core.EOFException:
        py_reader.reset()

D
dengkaipeng 已提交
135 136 137 138 139 140 141
    save_model('model_final')


if __name__ == '__main__':
    args = parse_args()
    print_arguments(args)
    train()