train_pair.py 10.8 KB
Newer Older
X
xiaoting 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2018 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.
K
kbChen 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys
import math
import time
import logging
import argparse
import functools
import threading
import subprocess
import numpy as np
import paddle
import paddle.fluid as fluid
import models
import reader
from losses import TripletLoss
from losses import QuadrupletLoss
from losses import EmlLoss
K
kbChen 已提交
35
from losses import NpairsLoss
K
kbChen 已提交
36
from utility import add_arguments, print_arguments
L
LielinJiang 已提交
37
from utility import fmt_time, recall_topk, get_gpu_num, check_cuda
K
kbChen 已提交
38 39 40 41 42 43 44 45 46 47 48

parser = argparse.ArgumentParser(description=__doc__)
add_arg = functools.partial(add_arguments, argparser=parser)
# yapf: disable
add_arg('model', str, "ResNet50", "Set the network to use.")
add_arg('embedding_size', int, 0, "Embedding size.")
add_arg('train_batch_size', int, 120, "Minibatch size.")
add_arg('test_batch_size', int, 50, "Minibatch size.")
add_arg('image_shape', str, "3,224,224", "input image size")
add_arg('class_dim', int, 11318, "Class number.")
add_arg('lr', float, 0.0001, "set learning rate.")
49
add_arg('lr_strategy', str, "piecewise_decay", "Set the learning rate decay strategy.")
K
kbChen 已提交
50 51 52 53 54 55 56 57 58 59 60 61
add_arg('lr_steps', str, "100000", "step of lr")
add_arg('total_iter_num', int, 100000, "total_iter_num")
add_arg('display_iter_step', int, 10, "display_iter_step.")
add_arg('test_iter_step', int, 5000, "test_iter_step.")
add_arg('save_iter_step', int, 5000, "save_iter_step.")
add_arg('use_gpu', bool, True, "Whether to use GPU or not.")
add_arg('pretrained_model', str, None, "Whether to use pretrained model.")
add_arg('checkpoint', str, None, "Whether to resume checkpoint.")
add_arg('model_save_dir', str, "output", "model save directory")
add_arg('loss_name', str, "triplet", "Set the loss type to use.")
add_arg('samples_each_class', int, 2, "samples_each_class.")
add_arg('margin', float, 0.1, "margin.")
K
kbChen 已提交
62
add_arg('npairs_reg_lambda', float, 0.01, "npairs reg lambda.")
K
kbChen 已提交
63 64 65 66
# yapf: enable

model_list = [m for m in dir(models) if "__" not in m]

67

K
kbChen 已提交
68 69 70
def optimizer_setting(params):
    ls = params["learning_strategy"]
    assert ls["name"] == "piecewise_decay", \
71
           "learning rate strategy must be {}, but got {}".format("piecewise_decay", lr["name"])
K
kbChen 已提交
72 73 74

    bd = [int(e) for e in ls["lr_steps"].split(',')]
    base_lr = params["lr"]
75
    lr = [base_lr * (0.1**i) for i in range(len(bd) + 1)]
K
kbChen 已提交
76 77 78 79 80 81 82 83 84
    optimizer = fluid.optimizer.Momentum(
        learning_rate=fluid.layers.piecewise_decay(
            boundaries=bd, values=lr),
        momentum=0.9,
        regularization=fluid.regularizer.L2Decay(1e-4))
    return optimizer


def net_config(image, label, model, args, is_train):
85 86
    assert args.model in model_list, "{} is not in lists: {}".format(args.model,
                                                                     model_list)
K
kbChen 已提交
87 88 89 90 91 92

    out = model.net(input=image, embedding_size=args.embedding_size)
    if not is_train:
        return None, out

    if args.loss_name == "triplet":
93
        metricloss = TripletLoss(margin=args.margin, )
K
kbChen 已提交
94 95
    elif args.loss_name == "quadruplet":
        metricloss = QuadrupletLoss(
96 97 98
            train_batch_size=args.train_batch_size,
            samples_each_class=args.samples_each_class,
            margin=args.margin, )
K
kbChen 已提交
99 100
    elif args.loss_name == "eml":
        metricloss = EmlLoss(
101 102
            train_batch_size=args.train_batch_size,
            samples_each_class=args.samples_each_class, )
K
kbChen 已提交
103 104
    elif args.loss_name == "npairs":
        metricloss = NpairsLoss(
105 106 107
            train_batch_size=args.train_batch_size,
            samples_each_class=args.samples_each_class,
            reg_lambda=args.npairs_reg_lambda, )
K
kbChen 已提交
108
    cost = metricloss.loss(out, label)
K
kbChen 已提交
109 110 111
    avg_cost = fluid.layers.mean(x=cost)
    return avg_cost, out

112

K
kbChen 已提交
113 114 115 116
def build_program(is_train, main_prog, startup_prog, args):
    image_shape = [int(m) for m in args.image_shape.split(",")]
    model = models.__dict__[args.model]()
    with fluid.program_guard(main_prog, startup_prog):
117
        queue_capacity = 64
S
suytingwan 已提交
118
        image = fluid.data(
119 120
            name='image', shape=[None] + image_shape, dtype='float32')
        label = fluid.data(name='label', shape=[None, 1], dtype='int64')
121
        loader = fluid.io.DataLoader.from_generator(
122 123 124 125
            feed_list=[image, label],
            capacity=queue_capacity,
            use_double_buffer=True,
            iterable=True)
K
kbChen 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

        with fluid.unique_name.guard():
            avg_cost, out = net_config(image, label, model, args, is_train)
            if is_train:
                params = model.params
                params["lr"] = args.lr
                params["learning_strategy"]["lr_steps"] = args.lr_steps
                params["learning_strategy"]["name"] = args.lr_strategy
                optimizer = optimizer_setting(params)
                optimizer.minimize(avg_cost)
                global_lr = optimizer._global_learning_rate()
    """            
    if not is_train:
        main_prog = main_prog.clone(for_test=True)
    """
    if is_train:
142
        return loader, avg_cost, global_lr, out, label
143
    else:
144
        return loader, out
K
kbChen 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159


def train_async(args):
    # parameters from arguments

    logging.debug('enter train')
    model_name = args.model
    checkpoint = args.checkpoint
    pretrained_model = args.pretrained_model
    model_save_dir = args.model_save_dir

    startup_prog = fluid.Program()
    train_prog = fluid.Program()
    tmp_prog = fluid.Program()

160
    train_loader, train_cost, global_lr, train_feas, train_label = build_program(
K
kbChen 已提交
161 162 163 164
        is_train=True,
        main_prog=train_prog,
        startup_prog=startup_prog,
        args=args)
165
    test_loader, test_feas = build_program(
K
kbChen 已提交
166 167 168 169 170 171
        is_train=False,
        main_prog=tmp_prog,
        startup_prog=startup_prog,
        args=args)
    test_prog = tmp_prog.clone(for_test=True)

172 173 174
    train_fetch_list = [
        global_lr.name, train_cost.name, train_feas.name, train_label.name
    ]
K
kbChen 已提交
175 176 177 178
    test_fetch_list = [test_feas.name]

    place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()
    exe = fluid.Executor(place)
179 180 181 182 183
    num_trainers = int(os.environ.get('PADDLE_TRAINERS_NUM', 1))
    if num_trainers <= 1 and args.use_gpu:
        places = fluid.framework.cuda_places()
    else:
        places = place
K
kbChen 已提交
184 185 186 187

    exe.run(startup_prog)

    if checkpoint is not None:
S
suytingwan 已提交
188
        fluid.load(program=train_prog, model_path=checkpoint, executor=exe)
K
kbChen 已提交
189 190

    if pretrained_model:
191 192
        fluid.load(
            program=train_prog, model_path=pretrained_model, executor=exe)
K
kbChen 已提交
193

194 195 196 197
    if args.use_gpu:
        devicenum = get_gpu_num()
    else:
        devicenum = int(os.environ.get('CPU_NUM', 1))
K
kbChen 已提交
198 199 200
    assert (args.train_batch_size % devicenum) == 0
    train_batch_size = args.train_batch_size / devicenum
    test_batch_size = args.test_batch_size
201

202
    train_loader.set_sample_generator(
203
        reader.train(args),
204 205 206 207 208 209 210 211 212
        batch_size=train_batch_size,
        drop_last=True,
        places=places)

    test_loader.set_sample_generator(
        reader.test(args),
        batch_size=test_batch_size,
        drop_last=False,
        places=place)
K
kbChen 已提交
213 214 215 216 217 218 219 220 221 222

    train_exe = fluid.ParallelExecutor(
        main_program=train_prog,
        use_cuda=args.use_gpu,
        loss_name=train_cost.name)

    totalruntime = 0
    iter_no = 0
    train_info = [0, 0, 0]
    while iter_no <= args.total_iter_num:
223 224
        for train_batch in train_loader():
            t1 = time.time()
225 226
            lr, loss, feas, label = train_exe.run(feed=train_batch,
                                                  fetch_list=train_fetch_list)
227 228 229 230 231 232 233 234 235 236 237
            t2 = time.time()
            period = t2 - t1
            lr = np.mean(np.array(lr))
            train_info[0] += np.mean(np.array(loss))
            train_info[1] += recall_topk(feas, label, k=1)
            train_info[2] += 1
            if iter_no % args.display_iter_step == 0:
                avgruntime = totalruntime / args.display_iter_step
                avg_loss = train_info[0] / train_info[2]
                avg_recall = train_info[1] / train_info[2]
                print("[%s] trainbatch %d, lr %.6f, loss %.6f, "\
K
kbChen 已提交
238 239
                    "recall %.4f, time %2.2f sec" % \
                    (fmt_time(), iter_no, lr, avg_loss, avg_recall, avgruntime))
240 241 242 243 244 245 246 247 248 249 250 251
                sys.stdout.flush()
                totalruntime = 0
            if iter_no % 1000 == 0:
                train_info = [0, 0, 0]

            totalruntime += period

            if iter_no % args.test_iter_step == 0 and iter_no != 0:
                f, l = [], []
                for batch_id, test_batch in enumerate(test_loader()):
                    t1 = time.time()
                    [feas] = exe.run(test_prog,
252 253
                                     feed=test_batch,
                                     fetch_list=test_fetch_list)
254 255 256 257 258 259 260 261 262 263

                    label = np.asarray(test_batch[0]['label'])
                    label = np.squeeze(label)
                    f.append(feas)
                    l.append(label)

                    t2 = time.time()
                    period = t2 - t1
                    if batch_id % 20 == 0:
                        print("[%s] testbatch %d, time %2.2f sec" % \
K
kbChen 已提交
264 265
                            (fmt_time(), batch_id, period))

266 267 268 269
                f = np.vstack(f)
                l = np.hstack(l)
                recall = recall_topk(f, l, k=1)
                print("[%s] test_img_num %d, trainbatch %d, test_recall %.5f" % \
K
kbChen 已提交
270
                    (fmt_time(), len(f), iter_no, recall))
271
                sys.stdout.flush()
K
kbChen 已提交
272

273 274
            if iter_no % args.save_iter_step == 0 and iter_no != 0:
                model_path = os.path.join(model_save_dir + '/' + model_name,
275
                                          str(iter_no))
276 277
                if not os.path.isdir(model_path):
                    os.makedirs(model_path)
S
suytingwan 已提交
278
                fluid.save(program=train_prog, model_path=model_path)
K
kbChen 已提交
279

280
            iter_no += 1
K
kbChen 已提交
281

282

K
kbChen 已提交
283 284 285 286 287 288 289
def initlogging():
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)
    loglevel = logging.DEBUG
    logging.basicConfig(
        level=loglevel,
        # logger.BASIC_FORMAT,
290
        format="%(levelname)s:%(filename)s[%(lineno)s] %(name)s:%(funcName)s->%(message)s",
K
kbChen 已提交
291 292
        datefmt='%a, %d %b %Y %H:%M:%S')

293

K
kbChen 已提交
294 295 296
def main():
    args = parser.parse_args()
    print_arguments(args)
L
LielinJiang 已提交
297
    check_cuda(args.use_gpu)
K
kbChen 已提交
298 299 300 301 302
    train_async(args)


if __name__ == '__main__':
    main()