main.py 16.2 KB
Newer Older
Y
Yibing Liu 已提交
1 2 3 4
"""
Deep Attention Matching Network
"""
import sys
Y
Yibing Liu 已提交
5
import os
Y
Yibing Liu 已提交
6
import six
Y
Yibing Liu 已提交
7 8 9 10 11
import numpy as np
import time
import multiprocessing
import paddle
import paddle.fluid as fluid
Y
Yibing Liu 已提交
12 13 14 15
import reader as reader
from util import mkdir
import evaluation as eva
import config
Y
Yibing Liu 已提交
16

Y
Yibing Liu 已提交
17 18 19 20 21
try:
    import cPickle as pickle  #python 2
except ImportError as e:
    import pickle  #python 3

Y
Yibing Liu 已提交
22
sys.path.append('../../models/dialogue_model_toolkit/deep_attention_matching/')
Y
Yibing Liu 已提交
23

Y
Yibing Liu 已提交
24
from net import Net
Y
Yibing Liu 已提交
25

Y
Yibing Liu 已提交
26
def evaluate(score_path, result_file_path):
Y
Yibing Liu 已提交
27 28 29
    """
    Evaluate both douban and ubuntu dataset
    """
Y
Yibing Liu 已提交
30
    if args.ext_eval:
Y
Yibing Liu 已提交
31
        result = eva.evaluate_douban(score_path)
Y
Yibing Liu 已提交
32
    else:
Y
Yibing Liu 已提交
33
        result = eva.evaluate_ubuntu(score_path)
Y
Yibing Liu 已提交
34 35 36
    #write evaluation result
    with open(result_file_path, 'w') as out_file:
        for p_at in result:
Y
Yibing Liu 已提交
37
            out_file.write(p_at + '\t' + str(result[p_at]) + '\n')
Y
Yibing Liu 已提交
38 39 40 41 42 43
    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):
Y
Yibing Liu 已提交
44 45 46
    """
    Test with feed
    """
Y
Yibing Liu 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
    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):
Y
Yibing Liu 已提交
70 71 72
    """
    Test with pyreader
    """
Y
Yibing Liu 已提交
73
    def data_provider():
Y
Yibing Liu 已提交
74 75 76
        """
        Data reader
        """
Y
Yibing Liu 已提交
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
        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 已提交
102
def train(args):
Y
Yibing Liu 已提交
103 104 105
    """
    Train Program
    """
Y
Yibing Liu 已提交
106 107 108
    if not os.path.exists(args.save_path):
        os.makedirs(args.save_path)

Y
Yibing Liu 已提交
109 110 111 112 113 114 115 116 117
    # 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 已提交
118 119
              args.emb_size, args.stack_num, args.channel1_num,
              args.channel2_num)
Y
Yibing Liu 已提交
120

Y
Yibing Liu 已提交
121 122
    train_program = fluid.Program()
    train_startup = fluid.Program()
Y
Yibing Liu 已提交
123 124 125
    if "CE_MODE_X" in os.environ:
        train_program.random_seed = 110
        train_startup.random_seed = 110
Y
Yibing Liu 已提交
126 127 128 129 130 131 132 133 134 135 136
    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
Y
Yibing Liu 已提交
137 138
            fluid.clip.set_gradient_clip(clip=fluid.clip.GradientClipByValue(
                max=1.0, min=-1.0))
Y
Yibing Liu 已提交
139 140 141 142 143 144 145 146

            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)
Y
Yibing Liu 已提交
147
            print("begin memory optimization ...")
Y
Yibing Liu 已提交
148
            print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
Y
Yibing Liu 已提交
149
            fluid.memory_optimize(train_program)
Y
Yibing Liu 已提交
150
            print("end memory optimization ...")
Y
Yibing Liu 已提交
151
            print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
Y
Yibing Liu 已提交
152 153 154

    test_program = fluid.Program()
    test_startup = fluid.Program()
Y
Yibing Liu 已提交
155 156 157
    if "CE_MODE_X" in os.environ:
        test_program.random_seed = 110
        test_startup.random_seed = 110
Y
Yibing Liu 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170
    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 已提交
171 172 173 174 175 176

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

    print("device count %d" % dev_count)
Y
Yibing Liu 已提交
180
    print("theoretical memory usage: ")
L
lujun 已提交
181 182 183
    print(
        fluid.contrib.memory_usage(
            program=train_program, batch_size=args.batch_size))
Y
Yibing Liu 已提交
184 185

    exe = fluid.Executor(place)
Y
Yibing Liu 已提交
186 187
    exe.run(train_startup)
    exe.run(test_startup)
Y
Yibing Liu 已提交
188 189 190 191 192 193 194 195 196 197 198

    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 已提交
199 200 201 202 203 204 205 206
        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 已提交
207 208
        dam.set_word_embedding(word_emb, place)
        print("finish init word embedding  ...")
Y
Yibing Liu 已提交
209 210

    print("start loading data ...")
Y
Yibing Liu 已提交
211 212 213 214 215
    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 已提交
216 217 218 219
    print("finish loading data ...")

    val_batches = reader.build_batches(val_data, data_conf)

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

Y
Yibing Liu 已提交
223 224
    print_step = max(1, batch_num // (dev_count * 100))
    save_step = max(1, batch_num // (dev_count * 10))
Y
Yibing Liu 已提交
225 226 227 228

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

Y
Yibing Liu 已提交
229
    def train_with_feed(step):
Y
Yibing Liu 已提交
230 231 232
        """
        Train on one epoch data by feeding
        """
Y
Yibing Liu 已提交
233
        ave_cost = 0.0
Y
Yibing Liu 已提交
234
        for it in six.moves.xrange(batch_num // dev_count):
Y
Yibing Liu 已提交
235
            feed_list = []
Y
Yibing Liu 已提交
236
            for dev in six.moves.xrange(dev_count):
Y
Yibing Liu 已提交
237
                index = it * dev_count + dev
Y
Yibing Liu 已提交
238 239
                batch_data = reader.make_one_batch_input(train_batches, index)
                feed_dict = dict(zip(dam.get_feed_names(), batch_data))
Y
Yibing Liu 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253
                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)
L
lujun 已提交
254 255 256
                print(
                    time.strftime('%Y-%m-%d %H:%M:%S',
                                  time.localtime(time.time())))
Y
Yibing Liu 已提交
257
                fluid.io.save_persistables(exe, save_path, train_program)
Y
Yibing Liu 已提交
258 259

                score_path = os.path.join(args.save_path, 'score.' + str(step))
Y
Yibing Liu 已提交
260 261 262 263
                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 已提交
264 265
                result_file_path = os.path.join(args.save_path,
                                                'result.' + str(step))
Y
Yibing Liu 已提交
266
                evaluate(score_path, result_file_path)
Y
Yibing Liu 已提交
267
        return step, np.array(cost[0]).mean()
Y
Yibing Liu 已提交
268 269

    def train_with_pyreader(step):
Y
Yibing Liu 已提交
270 271 272
        """
        Train on one epoch with pyreader
        """
Y
Yibing Liu 已提交
273
        def data_provider():
Y
Yibing Liu 已提交
274 275 276
            """
            Data reader
            """
Y
Yibing Liu 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
            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)
L
lujun 已提交
300 301 302
                    print(
                        time.strftime('%Y-%m-%d %H:%M:%S',
                                      time.localtime(time.time())))
Y
Yibing Liu 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
                    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
Y
Yibing Liu 已提交
318
        return step, np.array(cost[0]).mean()
Y
Yibing Liu 已提交
319 320

    # train over different epoches
Y
Yibing Liu 已提交
321
    global_step, train_time = 0, 0.0
Y
Yibing Liu 已提交
322
    for epoch in six.moves.xrange(args.num_scan_data):
Y
Yibing Liu 已提交
323 324
        shuffle_train = reader.unison_shuffle(
            train_data, seed=110 if ("CE_MODE_X" in os.environ) else None)
Y
Yibing Liu 已提交
325 326
        train_batches = reader.build_batches(shuffle_train, data_conf)

Y
Yibing Liu 已提交
327
        begin_time = time.time()
Y
Yibing Liu 已提交
328
        if args.use_pyreader:
Y
Yibing Liu 已提交
329
            global_step, last_cost = train_with_pyreader(global_step)
Y
Yibing Liu 已提交
330
        else:
Y
Yibing Liu 已提交
331
            global_step, last_cost = train_with_feed(global_step)
L
lujun 已提交
332 333 334

        pass_time_cost = time.time() - begin_time
        train_time += pass_time_cost
335
        print("Pass {0}, pass_time_cost {1}"
L
lujun 已提交
336
              .format(epoch, "%2.2f sec" % pass_time_cost))
Y
Yibing Liu 已提交
337 338 339 340
    # For internal continuous evaluation
    if "CE_MODE_X" in os.environ:
        print("kpis	train_cost	%f" % last_cost)
        print("kpis	train_duration	%f" % train_time)
Y
Yibing Liu 已提交
341 342


Y
Yibing Liu 已提交
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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
def test(args):
    """
    Test
    """
    if not os.path.exists(args.save_path):
        mkdir(args.save_path)
    if not os.path.exists(args.model_path):
        raise ValueError("Invalid model init path %s" % args.model_path)
    # 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,
              args.emb_size, args.stack_num, args.channel1_num,
              args.channel2_num)
    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))

    test_program = fluid.default_main_program().clone(for_test=True)
    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)

    print("begin memory optimization ...")
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    fluid.memory_optimize(fluid.default_main_program())
    print("end memory optimization ...")
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

    if args.use_cuda:
        place = fluid.CUDAPlace(0)
        dev_count = fluid.core.get_cuda_device_count()
    else:
        place = fluid.CPUPlace()
        #dev_count = multiprocessing.cpu_count()
        dev_count = 1

    exe = fluid.Executor(place)
    exe.run(fluid.default_startup_program())

    fluid.io.load_persistables(exe, args.model_path)

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

    print("start loading data ...")
    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")
    print("finish loading data ...")

    test_batches = reader.build_batches(test_data, data_conf)

    test_batch_num = len(test_batches["response"])

    print("test batch num: %d" % test_batch_num)

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

    score_path = os.path.join(args.save_path, 'score.txt')
    score_file = open(score_path, 'w')

    for it in six.moves.xrange(test_batch_num // dev_count):
        feed_list = []
        for dev in six.moves.xrange(dev_count):
            index = it * dev_count + dev
            batch_data = reader.make_one_batch_input(test_batches, index)
            feed_dict = dict(zip(dam.get_feed_names(), batch_data))
            feed_list.append(feed_dict)

        predicts = test_exe.run(feed=feed_list, fetch_list=[logits.name])

        scores = np.array(predicts[0])
        print("step = %d" % it)

        for dev in six.moves.xrange(dev_count):
            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(
                        test_batches["label"][index][i]) + '\n')

    score_file.close()

    #write evaluation result
    if args.ext_eval:
        result = eva.evaluate_douban(score_path)
    else:
        result = eva.evaluate_ubuntu(score_path)
    result_file_path = os.path.join(args.save_path, 'result.txt')
    with open(result_file_path, 'w') as out_file:
        for metric in result:
            out_file.write(metric + '\t' + str(result[metric]) + '\n')
    print('finish test')
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))


Y
Yibing Liu 已提交
458
if __name__ == '__main__':
Y
Yibing Liu 已提交
459 460 461 462 463 464 465
    args = config.parse_args()
    config.print_arguments(args)
    if args.do_train:
        train(args)

    if args.do_test:
        test(args)