train.py 7.0 KB
Newer Older
W
wangguanzhong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

F
FDInSky 已提交
15 16 17
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
18 19 20 21 22 23
import os, sys
# add python path of PadleDetection to sys.path
parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 2)))
if parent_path not in sys.path:
    sys.path.append(parent_path)

F
FDInSky 已提交
24 25 26 27 28
import time
# ignore numba warning
import warnings
warnings.filterwarnings('ignore')
import random
29
import datetime
F
FDInSky 已提交
30
import numpy as np
31
from collections import deque
W
wangxinxin08 已提交
32 33
import paddle
from paddle import fluid
F
FDInSky 已提交
34
from ppdet.core.workspace import load_config, merge_config, create
35
from ppdet.utils.stats import TrainingStats
F
FDInSky 已提交
36 37
from ppdet.utils.check import check_gpu, check_version, check_config
from ppdet.utils.cli import ArgsParser
W
wangguanzhong 已提交
38
from ppdet.utils.checkpoint import load_weight, load_pretrain_weight, save_model
G
Guanghua Yu 已提交
39
from paddle.distributed import ParallelEnv
40 41 42 43
import logging
FORMAT = '%(asctime)s-%(levelname)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger(__name__)
F
FDInSky 已提交
44 45 46 47 48


def parse_args():
    parser = ArgsParser()
    parser.add_argument(
W
wangguanzhong 已提交
49
        "--weight_type",
F
FDInSky 已提交
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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
        default='pretrain',
        type=str,
        help="Loading Checkpoints only support 'pretrain', 'finetune', 'resume'."
    )
    parser.add_argument(
        "--fp16",
        action='store_true',
        default=False,
        help="Enable mixed precision training.")
    parser.add_argument(
        "--loss_scale",
        default=8.,
        type=float,
        help="Mixed precision training loss scale.")
    parser.add_argument(
        "--eval",
        action='store_true',
        default=False,
        help="Whether to perform evaluation in train")
    parser.add_argument(
        "--output_eval",
        default=None,
        type=str,
        help="Evaluation directory, default is current directory.")
    parser.add_argument(
        "--use_tb",
        type=bool,
        default=False,
        help="whether to record the data to Tensorboard.")
    parser.add_argument(
        '--tb_log_dir',
        type=str,
        default="tb_log_dir/scalar",
        help='Tensorboard logging directory for scalar.')
    parser.add_argument(
        "--enable_ce",
        type=bool,
        default=False,
        help="If set True, enable continuous evaluation job."
        "This flag is only used for internal test.")
    parser.add_argument(
        "--use_gpu", action='store_true', default=False, help="data parallel")

    parser.add_argument(
        '--is_profiler',
        type=int,
        default=0,
        help='The switch of profiler tools. (used for benchmark)')

    args = parser.parse_args()
    return args


G
Guanghua Yu 已提交
103
def run(FLAGS, cfg, place):
F
FDInSky 已提交
104 105 106 107 108 109 110 111
    env = os.environ
    FLAGS.dist = 'PADDLE_TRAINER_ID' in env and 'PADDLE_TRAINERS_NUM' in env
    if FLAGS.dist:
        trainer_id = int(env['PADDLE_TRAINER_ID'])
        local_seed = (99 + trainer_id)
        random.seed(local_seed)
        np.random.seed(local_seed)

112
    if FLAGS.enable_ce:
F
FDInSky 已提交
113 114 115
        random.seed(0)
        np.random.seed(0)

G
Guanghua Yu 已提交
116
    if ParallelEnv().nranks > 1:
117 118
        paddle.distributed.init_parallel_env()

G
Guanghua Yu 已提交
119 120 121 122 123
    # Data 
    dataset = cfg.TrainDataset
    train_loader, step_per_epoch = create('TrainReader')(
        dataset, cfg['worker_num'], place)

F
FDInSky 已提交
124 125
    # Model
    main_arch = cfg.architecture
126
    model = create(cfg.architecture)
F
FDInSky 已提交
127 128

    # Optimizer
W
wangguanzhong 已提交
129
    lr = create('LearningRate')(step_per_epoch)
F
FDInSky 已提交
130 131 132
    optimizer = create('OptimizerBuilder')(lr, model.parameters())

    # Init Model & Optimzer   
W
wangguanzhong 已提交
133 134 135 136 137 138
    if FLAGS.weight_type == 'resume':
        load_weight(model, cfg.pretrain_weights, optimizer)
    else:
        load_pretrain_weight(model, cfg.pretrain_weights,
                             cfg.get('load_static_weights', False),
                             FLAGS.weight_type)
F
FDInSky 已提交
139

W
wangguanzhong 已提交
140
    # Parallel Model 
G
Guanghua Yu 已提交
141
    if ParallelEnv().nranks > 1:
142
        model = paddle.DataParallel(model)
W
wangguanzhong 已提交
143

G
Guanghua Yu 已提交
144
    # Run Train
F
FDInSky 已提交
145
    start_iter = 0
146
    time_stat = deque(maxlen=cfg.log_iter)
147 148
    start_time = time.time()
    end_time = time.time()
W
wangguanzhong 已提交
149 150
    # Run Train
    start_epoch = optimizer.state_dict()['LR_Scheduler']['last_epoch']
G
Guanghua Yu 已提交
151
    for e_id in range(int(cfg.epoch)):
W
wangguanzhong 已提交
152
        cur_eid = e_id + start_epoch
G
Guanghua Yu 已提交
153 154 155 156 157
        for iter_id, data in enumerate(train_loader):
            start_time = end_time
            end_time = time.time()
            time_stat.append(end_time - start_time)
            time_cost = np.mean(time_stat)
W
wangguanzhong 已提交
158 159
            eta_sec = (
                (cfg.epoch - cur_eid) * step_per_epoch - iter_id) * time_cost
G
Guanghua Yu 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
            eta = str(datetime.timedelta(seconds=int(eta_sec)))

            # Model Forward
            model.train()
            outputs = model(data, cfg['TrainReader']['inputs_def']['fields'],
                            'train')

            # Model Backward
            loss = outputs['loss']
            if ParallelEnv().nranks > 1:
                loss = model.scale_loss(loss)
                loss.backward()
                model.apply_collective_grads()
            else:
                loss.backward()
            optimizer.step()
            curr_lr = optimizer.get_lr()
            lr.step()
            optimizer.clear_grad()

            if ParallelEnv().nranks < 2 or ParallelEnv().local_rank == 0:
                # Log state 
W
wangguanzhong 已提交
182
                if e_id == 0 and iter_id == 0:
G
Guanghua Yu 已提交
183 184 185 186
                    train_stats = TrainingStats(cfg.log_iter, outputs.keys())
                train_stats.update(outputs)
                logs = train_stats.log()
                if iter_id % cfg.log_iter == 0:
W
wangguanzhong 已提交
187 188 189
                    ips = float(cfg['TrainReader']['batch_size']) / time_cost
                    strs = 'Epoch:{}: iter: {}, lr: {:.6f}, {}, eta: {}, batch_cost: {:.5f} sec, ips: {:.5f} images/sec'.format(
                        cur_eid, iter_id, curr_lr, logs, eta, time_cost, ips)
G
Guanghua Yu 已提交
190 191 192
                    logger.info(strs)

        # Save Stage 
W
wangguanzhong 已提交
193
        if ParallelEnv().local_rank == 0 and cur_eid % cfg.snapshot_epoch == 0:
G
Guanghua Yu 已提交
194
            cfg_name = os.path.basename(FLAGS.config).split('.')[0]
W
wangguanzhong 已提交
195
            save_name = str(cur_eid) if cur_eid + 1 != int(
G
Guanghua Yu 已提交
196 197
                cfg.epoch) else "model_final"
            save_dir = os.path.join(cfg.save_dir, cfg_name)
W
wangguanzhong 已提交
198
            save_model(model, optimizer, save_dir, save_name)
F
FDInSky 已提交
199 200 201


def main():
202 203 204 205 206 207 208 209
    FLAGS = parse_args()

    cfg = load_config(FLAGS.config)
    merge_config(FLAGS.opt)
    check_config(cfg)
    check_gpu(cfg.use_gpu)
    check_version()

G
Guanghua Yu 已提交
210 211 212 213
    place = 'gpu:{}'.format(ParallelEnv().dev_id) if cfg.use_gpu else 'cpu'
    place = paddle.set_device(place)

    run(FLAGS, cfg, place)
F
FDInSky 已提交
214 215 216 217


if __name__ == "__main__":
    main()