train_and_evaluate.py 13.4 KB
Newer Older
Y
Yibing Liu 已提交
1
import os
Y
Yibing Liu 已提交
2
import six
Y
Yibing Liu 已提交
3 4 5 6 7 8 9
import numpy as np
import time
import argparse
import multiprocessing
import paddle
import paddle.fluid as fluid
import utils.reader as reader
Y
Yibing Liu 已提交
10
from utils.util import print_arguments, mkdir
Y
Yibing Liu 已提交
11

Y
Yibing Liu 已提交
12 13 14 15 16
try:
    import cPickle as pickle  #python 2
except ImportError as e:
    import pickle  #python 3

Y
Yibing Liu 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
from model import Net


#yapf: disable
def parse_args():
    parser = argparse.ArgumentParser("Training DAM.")
    parser.add_argument(
        '--batch_size',
        type=int,
        default=256,
        help='Batch size for training. (default: %(default)d)')
    parser.add_argument(
        '--num_scan_data',
        type=int,
        default=2,
        help='Number of pass for training. (default: %(default)d)')
    parser.add_argument(
        '--learning_rate',
        type=float,
        default=1e-3,
        help='Learning rate used to train. (default: %(default)f)')
    parser.add_argument(
        '--data_path',
        type=str,
Y
Yibing Liu 已提交
41
        default="data/data_small.pkl",
Y
Yibing Liu 已提交
42 43 44 45 46 47 48 49 50 51
        help='Path to training data. (default: %(default)s)')
    parser.add_argument(
        '--save_path',
        type=str,
        default="saved_models",
        help='Path to save trained models. (default: %(default)s)')
    parser.add_argument(
        '--use_cuda',
        action='store_true',
        help='If set, use cuda for training.')
Y
Yibing Liu 已提交
52 53 54 55
    parser.add_argument(
        '--use_pyreader',
        action='store_true',
        help='If set, use pyreader for reading data.')
Y
Yibing Liu 已提交
56 57 58 59
    parser.add_argument(
        '--ext_eval',
        action='store_true',
        help='If set, use MAP, MRR ect for evaluation.')
Y
Yibing Liu 已提交
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
    parser.add_argument(
        '--max_turn_num',
        type=int,
        default=9,
        help='Maximum number of utterances in context.')
    parser.add_argument(
        '--max_turn_len',
        type=int,
        default=50,
        help='Maximum length of setences in turns.')
    parser.add_argument(
        '--word_emb_init',
        type=str,
        default=None,
        help='Path to the initial word embedding.')
    parser.add_argument(
        '--vocab_size',
        type=int,
        default=434512,
        help='The size of vocabulary.')
    parser.add_argument(
        '--emb_size',
        type=int,
        default=200,
        help='The dimension of word embedding.')
    parser.add_argument(
        '--_EOS_',
        type=int,
        default=28270,
Y
Yibing Liu 已提交
89
        help='The id for the end of sentence in vocabulary.')
Y
Yibing Liu 已提交
90 91 92 93 94
    parser.add_argument(
        '--stack_num',
        type=int,
        default=5,
        help='The number of stacked attentive modules in network.')
Y
Yibing Liu 已提交
95 96 97 98 99 100 101 102 103 104
    parser.add_argument(
        '--channel1_num',
        type=int,
        default=32,
        help="The channels' number of the 1st conv3d layer's output.")
    parser.add_argument(
        '--channel2_num',
        type=int,
        default=16,
        help="The channels' number of the 2nd conv3d layer's output.")
Y
Yibing Liu 已提交
105 106 107 108 109 110 111
    args = parser.parse_args()
    return args


#yapf: enable


Y
Yibing Liu 已提交
112 113 114 115 116 117 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 175 176
def evaluate(score_path, result_file_path):
    if args.ext_eval:
        import utils.douban_evaluation as eva
    else:
        import utils.evaluation as eva
    #write evaluation result
    result = eva.evaluate(score_path)
    with open(result_file_path, 'w') as out_file:
        for p_at in result:
            out_file.write(str(p_at) + '\n')
    print('finish evaluation')
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))


def test_with_feed(exe, program, feed_names, fetch_list, score_path, batches,
                   batch_num, dev_count):
    score_file = open(score_path, 'w')
    for it in six.moves.xrange(batch_num // dev_count):
        feed_list = []
        for dev in six.moves.xrange(dev_count):
            val_index = it * dev_count + dev
            batch_data = reader.make_one_batch_input(batches, val_index)
            feed_dict = dict(zip(feed_names, batch_data))
            feed_list.append(feed_dict)

            predicts = exe.run(feed=feed_list, fetch_list=fetch_list)

            scores = np.array(predicts[0])
            for dev in six.moves.xrange(dev_count):
                val_index = it * dev_count + dev
                for i in six.moves.xrange(args.batch_size):
                    score_file.write(
                        str(scores[args.batch_size * dev + i][0]) + '\t' + str(
                            batches["label"][val_index][i]) + '\n')
    score_file.close()


def test_with_pyreader(exe, program, pyreader, fetch_list, score_path, batches,
                       batch_num, dev_count):
    def data_provider():
        for index in six.moves.xrange(batch_num):
            yield reader.make_one_batch_input(batches, index)

    score_file = open(score_path, 'w')
    pyreader.decorate_tensor_provider(data_provider)
    it = 0
    pyreader.start()
    while True:
        try:
            predicts = exe.run(fetch_list=fetch_list)

            scores = np.array(predicts[0])
            for dev in six.moves.xrange(dev_count):
                val_index = it * dev_count + dev
                for i in six.moves.xrange(args.batch_size):
                    score_file.write(
                        str(scores[args.batch_size * dev + i][0]) + '\t' + str(
                            batches["label"][val_index][i]) + '\n')
            it += 1
        except fluid.core.EOFException:
            pyreader.reset()
            break
    score_file.close()


Y
Yibing Liu 已提交
177
def train(args):
Y
Yibing Liu 已提交
178 179 180
    if not os.path.exists(args.save_path):
        os.makedirs(args.save_path)

Y
Yibing Liu 已提交
181 182 183 184 185 186 187 188 189
    # data data_config
    data_conf = {
        "batch_size": args.batch_size,
        "max_turn_num": args.max_turn_num,
        "max_turn_len": args.max_turn_len,
        "_EOS_": args._EOS_,
    }

    dam = Net(args.max_turn_num, args.max_turn_len, args.vocab_size,
Y
Yibing Liu 已提交
190 191
              args.emb_size, args.stack_num, args.channel1_num,
              args.channel2_num)
Y
Yibing Liu 已提交
192

Y
Yibing Liu 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    train_program = fluid.Program()
    train_startup = fluid.Program()
    with fluid.program_guard(train_program, train_startup):
        with fluid.unique_name.guard():
            if args.use_pyreader:
                train_pyreader = dam.create_py_reader(
                    capacity=10, name='train_reader')
            else:
                dam.create_data_layers()
            loss, logits = dam.create_network()
            loss.persistable = True
            logits.persistable = True
            # gradient clipping
            fluid.clip.set_gradient_clip(clip=fluid.clip.GradientClipByValue(
                max=1.0, min=-1.0))

            optimizer = fluid.optimizer.Adam(
                learning_rate=fluid.layers.exponential_decay(
                    learning_rate=args.learning_rate,
                    decay_steps=400,
                    decay_rate=0.9,
                    staircase=True))
            optimizer.minimize(loss)
            fluid.memory_optimize(train_program)

    test_program = fluid.Program()
    test_startup = fluid.Program()
    with fluid.program_guard(test_program, test_startup):
        with fluid.unique_name.guard():
            if args.use_pyreader:
                test_pyreader = dam.create_py_reader(
                    capacity=10, name='test_reader')
            else:
                dam.create_data_layers()

            loss, logits = dam.create_network()
            loss.persistable = True
            logits.persistable = True

    test_program = test_program.clone(for_test=True)
Y
Yibing Liu 已提交
233 234 235 236 237 238

    if args.use_cuda:
        place = fluid.CUDAPlace(0)
        dev_count = fluid.core.get_cuda_device_count()
    else:
        place = fluid.CPUPlace()
S
fix bug  
sneaxiy 已提交
239
        dev_count = int(os.environ.get('CPU_NUM', multiprocessing.cpu_count()))
Y
Yibing Liu 已提交
240 241

    print("device count %d" % dev_count)
Y
Yibing Liu 已提交
242 243 244
    print("theoretical memory usage: ")
    print(fluid.contrib.memory_usage(
        program=train_program, batch_size=args.batch_size))
Y
Yibing Liu 已提交
245 246

    exe = fluid.Executor(place)
Y
Yibing Liu 已提交
247 248
    exe.run(train_startup)
    exe.run(test_startup)
Y
Yibing Liu 已提交
249 250 251 252 253 254 255 256 257 258 259

    train_exe = fluid.ParallelExecutor(
        use_cuda=args.use_cuda, loss_name=loss.name, main_program=train_program)

    test_exe = fluid.ParallelExecutor(
        use_cuda=args.use_cuda,
        main_program=test_program,
        share_vars_from=train_exe)

    if args.word_emb_init is not None:
        print("start loading word embedding init ...")
Y
Yibing Liu 已提交
260 261 262 263 264 265 266 267
        if six.PY2:
            word_emb = np.array(pickle.load(open(args.word_emb_init,
                                                 'rb'))).astype('float32')
        else:
            word_emb = np.array(
                pickle.load(
                    open(args.word_emb_init, 'rb'), encoding="bytes")).astype(
                        'float32')
Y
Yibing Liu 已提交
268 269
        dam.set_word_embedding(word_emb, place)
        print("finish init word embedding  ...")
Y
Yibing Liu 已提交
270 271

    print("start loading data ...")
Y
Yibing Liu 已提交
272 273 274 275 276
    with open(args.data_path, 'rb') as f:
        if six.PY2:
            train_data, val_data, test_data = pickle.load(f)
        else:
            train_data, val_data, test_data = pickle.load(f, encoding="bytes")
Y
Yibing Liu 已提交
277 278 279 280
    print("finish loading data ...")

    val_batches = reader.build_batches(val_data, data_conf)

Y
Yibing Liu 已提交
281
    batch_num = len(train_data[six.b('y')]) // args.batch_size
Y
Yibing Liu 已提交
282 283
    val_batch_num = len(val_batches["response"])

Y
Yibing Liu 已提交
284 285
    print_step = max(1, batch_num // (dev_count * 100))
    save_step = max(1, batch_num // (dev_count * 10))
Y
Yibing Liu 已提交
286 287 288 289

    print("begin model training ...")
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

Y
Yibing Liu 已提交
290 291
    # train on one epoch data by feeding
    def train_with_feed(step):
Y
Yibing Liu 已提交
292
        ave_cost = 0.0
Y
Yibing Liu 已提交
293
        for it in six.moves.xrange(batch_num // dev_count):
Y
Yibing Liu 已提交
294
            feed_list = []
Y
Yibing Liu 已提交
295
            for dev in six.moves.xrange(dev_count):
Y
Yibing Liu 已提交
296
                index = it * dev_count + dev
Y
Yibing Liu 已提交
297 298
                batch_data = reader.make_one_batch_input(train_batches, index)
                feed_dict = dict(zip(dam.get_feed_names(), batch_data))
Y
Yibing Liu 已提交
299 300 301 302 303 304 305 306 307 308 309 310 311 312
                feed_list.append(feed_dict)

            cost = train_exe.run(feed=feed_list, fetch_list=[loss.name])

            ave_cost += np.array(cost[0]).mean()
            step = step + 1
            if step % print_step == 0:
                print("processed: [" + str(step * dev_count * 1.0 / batch_num) +
                      "] ave loss: [" + str(ave_cost / print_step) + "]")
                ave_cost = 0.0

            if (args.save_path is not None) and (step % save_step == 0):
                save_path = os.path.join(args.save_path, "step_" + str(step))
                print("Save model at step %d ... " % step)
Y
Yibing Liu 已提交
313 314
                print(time.strftime('%Y-%m-%d %H:%M:%S',
                                    time.localtime(time.time())))
Y
Yibing Liu 已提交
315
                fluid.io.save_persistables(exe, save_path, train_program)
Y
Yibing Liu 已提交
316 317

                score_path = os.path.join(args.save_path, 'score.' + str(step))
Y
Yibing Liu 已提交
318 319 320 321
                test_with_feed(test_exe, test_program,
                               dam.get_feed_names(), [logits.name], score_path,
                               val_batches, val_batch_num, dev_count)

Y
Yibing Liu 已提交
322 323
                result_file_path = os.path.join(args.save_path,
                                                'result.' + str(step))
Y
Yibing Liu 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
                evaluate(score_path, result_file_path)
        return step

    # train on one epoch with pyreader 
    def train_with_pyreader(step):
        def data_provider():
            for index in six.moves.xrange(batch_num):
                yield reader.make_one_batch_input(train_batches, index)

        train_pyreader.decorate_tensor_provider(data_provider)

        ave_cost = 0.0
        train_pyreader.start()
        while True:
            try:
                cost = train_exe.run(fetch_list=[loss.name])

                ave_cost += np.array(cost[0]).mean()
                step = step + 1
                if step % print_step == 0:
                    print("processed: [" + str(step * dev_count * 1.0 /
                                               batch_num) + "] ave loss: [" +
                          str(ave_cost / print_step) + "]")
                    ave_cost = 0.0

                if (args.save_path is not None) and (step % save_step == 0):
                    save_path = os.path.join(args.save_path,
                                             "step_" + str(step))
                    print("Save model at step %d ... " % step)
                    print(time.strftime('%Y-%m-%d %H:%M:%S',
                                        time.localtime(time.time())))
                    fluid.io.save_persistables(exe, save_path, train_program)

                    score_path = os.path.join(args.save_path,
                                              'score.' + str(step))
                    test_with_pyreader(test_exe, test_program, test_pyreader,
                                       [logits.name], score_path, val_batches,
                                       val_batch_num, dev_count)

                    result_file_path = os.path.join(args.save_path,
                                                    'result.' + str(step))
                    evaluate(score_path, result_file_path)

            except fluid.core.EOFException:
                train_pyreader.reset()
                break
        return step

    # train over different epoches
    global_step = 0
    for epoch in six.moves.xrange(args.num_scan_data):
        shuffle_train = reader.unison_shuffle(train_data)
        train_batches = reader.build_batches(shuffle_train, data_conf)

        if args.use_pyreader:
            global_step = train_with_pyreader(global_step)
        else:
            global_step = train_with_feed(global_step)
Y
Yibing Liu 已提交
382 383 384 385 386 387


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