train.py 7.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#  Copyright (c) 2018 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
J
jerrywgz 已提交
18
import os
19
import sys
J
jerrywgz 已提交
20
import numpy as np
21
import time
J
jerrywgz 已提交
22
import shutil
J
jerrywgz 已提交
23 24
from utility import parse_args, print_arguments, SmoothedValue, TrainingStats, now_time
import collections
J
jerrywgz 已提交
25 26 27 28

import paddle
import paddle.fluid as fluid
import reader
29 30
import models.model_builder as model_builder
import models.resnet as resnet
J
jerrywgz 已提交
31
from learning_rate import exponential_with_warmup_decay
J
jerrywgz 已提交
32
from config import cfg
J
jerrywgz 已提交
33 34


J
jerrywgz 已提交
35
def train():
36
    learning_rate = cfg.learning_rate
J
jerrywgz 已提交
37
    image_shape = [3, cfg.TRAIN.max_size, cfg.TRAIN.max_size]
J
jerrywgz 已提交
38

39
    if cfg.enable_ce:
J
jerrywgz 已提交
40 41 42 43 44 45 46 47
        fluid.default_startup_program().random_seed = 1000
        fluid.default_main_program().random_seed = 1000
        import random
        random.seed(0)
        np.random.seed(0)

    devices = os.getenv("CUDA_VISIBLE_DEVICES") or ""
    devices_num = len(devices.split(","))
J
jerrywgz 已提交
48
    total_batch_size = devices_num * cfg.TRAIN.im_per_batch
J
jerrywgz 已提交
49

Z
zhengya01 已提交
50 51 52
    use_random = True
    if cfg.enable_ce:
        use_random = False
53
    model = model_builder.RCNN(
54 55 56
        add_conv_body_func=resnet.add_ResNet50_conv4_body,
        add_roi_box_head_func=resnet.add_ResNet_roi_conv5_head,
        use_pyreader=cfg.use_pyreader,
Z
zhengya01 已提交
57
        use_random=use_random)
58
    model.build_model(image_shape)
J
jerrywgz 已提交
59 60 61
    losses, keys = model.loss()
    loss = losses[0]
    fetch_list = losses
J
jerrywgz 已提交
62

J
jerrywgz 已提交
63 64
    boundaries = cfg.lr_steps
    gamma = cfg.lr_gamma
65
    step_num = len(cfg.lr_steps)
J
jerrywgz 已提交
66
    values = [learning_rate * (gamma**i) for i in range(step_num + 1)]
J
jerrywgz 已提交
67

J
jerrywgz 已提交
68 69 70 71 72 73
    lr = exponential_with_warmup_decay(
        learning_rate=learning_rate,
        boundaries=boundaries,
        values=values,
        warmup_iter=cfg.warm_up_iter,
        warmup_factor=cfg.warm_up_factor)
J
jerrywgz 已提交
74
    optimizer = fluid.optimizer.Momentum(
J
jerrywgz 已提交
75
        learning_rate=lr,
J
jerrywgz 已提交
76 77
        regularization=fluid.regularizer.L2Decay(cfg.weight_decay),
        momentum=cfg.momentum)
J
jerrywgz 已提交
78
    optimizer.minimize(loss)
J
jerrywgz 已提交
79
    fetch_list = fetch_list + [lr]
J
jerrywgz 已提交
80

J
jerrywgz 已提交
81 82
    fluid.memory_optimize(
        fluid.default_main_program(), skip_opt_set=set(fetch_list))
J
jerrywgz 已提交
83

84
    place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()
J
jerrywgz 已提交
85 86 87
    exe = fluid.Executor(place)
    exe.run(fluid.default_startup_program())

88
    if cfg.pretrained_model:
J
jerrywgz 已提交
89

J
jerrywgz 已提交
90
        def if_exist(var):
91
            return os.path.exists(os.path.join(cfg.pretrained_model, var.name))
J
jerrywgz 已提交
92

J
jerrywgz 已提交
93
        fluid.io.load_vars(exe, cfg.pretrained_model, predicate=if_exist)
J
jerrywgz 已提交
94

95
    if cfg.parallel:
J
jerrywgz 已提交
96
        train_exe = fluid.ParallelExecutor(
97 98
            use_cuda=bool(cfg.use_gpu), loss_name=loss.name)

Z
zhengya01 已提交
99 100 101
    shuffle = True
    if cfg.enable_ce:
        shuffle = False
102
    if cfg.use_pyreader:
J
jerrywgz 已提交
103
        train_reader = reader.train(
J
jerrywgz 已提交
104 105 106
            batch_size=cfg.TRAIN.im_per_batch,
            total_batch_size=total_batch_size,
            padding_total=cfg.TRAIN.padding_minibatch,
Z
zhengya01 已提交
107
            shuffle=shuffle)
108 109 110
        py_reader = model.py_reader
        py_reader.decorate_paddle_reader(train_reader)
    else:
J
jerrywgz 已提交
111 112
        train_reader = reader.train(
            batch_size=total_batch_size, shuffle=shuffle)
113
        feeder = fluid.DataFeeder(place=place, feed_list=model.feeds())
J
jerrywgz 已提交
114 115

    def save_model(postfix):
116
        model_path = os.path.join(cfg.model_save_dir, postfix)
J
jerrywgz 已提交
117 118 119 120
        if os.path.isdir(model_path):
            shutil.rmtree(model_path)
        fluid.io.save_persistables(exe, model_path)

J
jerrywgz 已提交
121
    def train_loop_pyreader():
122
        py_reader.start()
J
jerrywgz 已提交
123
        train_stats = TrainingStats(cfg.log_window, keys)
124 125 126
        try:
            start_time = time.time()
            prev_start_time = start_time
127
            for iter_id in range(cfg.max_iter):
128 129
                prev_start_time = start_time
                start_time = time.time()
J
jerrywgz 已提交
130 131 132 133
                outs = train_exe.run(fetch_list=[v.name for v in fetch_list])
                stats = {k: np.array(v).mean() for k, v in zip(keys, outs[:-1])}
                train_stats.update(stats)
                logs = train_stats.log()
134 135
                strs = '{}, iter: {}, lr: {:.5f}, {}, time: {:.3f}'.format(
                    now_time(), iter_id,
J
jerrywgz 已提交
136 137
                    np.mean(outs[-1]), logs, start_time - prev_start_time)
                print(strs)
138
                sys.stdout.flush()
J
jerrywgz 已提交
139
                if (iter_id + 1) % cfg.TRAIN.snapshot_iter == 0:
140
                    save_model("model_iter{}".format(iter_id))
J
jerrywgz 已提交
141 142 143
            end_time = time.time()
            total_time = end_time - start_time
            last_loss = np.array(outs[0]).mean()
Z
zhengya01 已提交
144 145 146 147 148
            if cfg.enable_ce:
                gpu_num = devices_num
                epoch_idx = iter_id + 1
                loss = last_loss
                print("kpis\teach_pass_duration_card%s\t%s" %
J
jerrywgz 已提交
149 150 151
                      (gpu_num, total_time / epoch_idx))
                print("kpis\ttrain_loss_card%s\t%s" % (gpu_num, loss))
        except (StopIteration, fluid.core.EOFException):
152
            py_reader.reset()
J
jerrywgz 已提交
153

J
jerrywgz 已提交
154
    def train_loop():
J
jerrywgz 已提交
155 156
        start_time = time.time()
        prev_start_time = start_time
J
jerrywgz 已提交
157
        start = start_time
J
jerrywgz 已提交
158
        train_stats = TrainingStats(cfg.log_window, keys)
159
        for iter_id, data in enumerate(train_reader()):
J
jerrywgz 已提交
160 161
            prev_start_time = start_time
            start_time = time.time()
J
jerrywgz 已提交
162 163 164 165 166
            outs = train_exe.run(fetch_list=[v.name for v in fetch_list],
                                 feed=feeder.feed(data))
            stats = {k: np.array(v).mean() for k, v in zip(keys, outs[:-1])}
            train_stats.update(stats)
            logs = train_stats.log()
167 168
            strs = '{}, iter: {}, lr: {:.5f}, {}, time: {:.3f}'.format(
                now_time(), iter_id,
J
jerrywgz 已提交
169 170
                np.mean(outs[-1]), logs, start_time - prev_start_time)
            print(strs)
171
            sys.stdout.flush()
J
jerrywgz 已提交
172
            if (iter_id + 1) % cfg.TRAIN.snapshot_iter == 0:
173 174 175
                save_model("model_iter{}".format(iter_id))
            if (iter_id + 1) == cfg.max_iter:
                break
J
jerrywgz 已提交
176 177 178
        end_time = time.time()
        total_time = end_time - start_time
        last_loss = np.array(outs[0]).mean()
Z
zhengya01 已提交
179 180 181 182 183 184
        # only for ce
        if cfg.enable_ce:
            gpu_num = devices_num
            epoch_idx = iter_id + 1
            loss = last_loss
            print("kpis\teach_pass_duration_card%s\t%s" %
J
jerrywgz 已提交
185 186
                  (gpu_num, total_time / epoch_idx))
            print("kpis\ttrain_loss_card%s\t%s" % (gpu_num, loss))
Z
zhengya01 已提交
187

188
        return np.mean(every_pass_loss)
J
jerrywgz 已提交
189

190
    if cfg.use_pyreader:
J
jerrywgz 已提交
191
        train_loop_pyreader()
192
    else:
J
jerrywgz 已提交
193
        train_loop()
194
    save_model('model_final')
J
jerrywgz 已提交
195

J
jerrywgz 已提交
196

J
jerrywgz 已提交
197
if __name__ == '__main__':
J
jerrywgz 已提交
198
    args = parse_args()
J
jerrywgz 已提交
199
    print_arguments(args)
J
jerrywgz 已提交
200
    train()