run.py 26.0 KB
Newer Older
X
xuezhong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#   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

import numpy as np
import time
import os
import random
import json
X
xuezhong 已提交
24
import six
25
import multiprocessing
X
xuezhong 已提交
26 27 28 29 30 31 32 33 34 35 36

import paddle
import paddle.fluid as fluid
import paddle.fluid.framework as framework
from paddle.fluid.executor import Executor

import sys
if sys.version[0] == '2':
    reload(sys)
    sys.setdefaultencoding("utf-8")
sys.path.append('..')
Y
Yibing Liu 已提交
37 38
sys.path.append('../../models/reading_comprehension/')

X
xuezhong 已提交
39 40

from args import *
Y
Yibing Liu 已提交
41
import bidaf_model as rc_model
X
xuezhong 已提交
42 43 44 45 46
from dataset import BRCDataset
import logging
import pickle
from utils import normalize
from utils import compute_bleu_rouge
X
xuezhong 已提交
47
from vocab import Vocab
X
xuezhong 已提交
48

Q
qiuxuezhong 已提交
49

X
xuezhong 已提交
50 51
def prepare_batch_input(insts, args):
    batch_size = len(insts['raw_data'])
X
xuezhong 已提交
52 53 54 55
    inst_num = len(insts['passage_num'])
    if batch_size != inst_num:
        print("data error %d, %d" % (batch_size, inst_num))
        return None
X
xuezhong 已提交
56 57
    new_insts = []

X
xuezhong 已提交
58
    passage_idx = 0
X
xuezhong 已提交
59
    for i in range(batch_size):
X
xuezhong 已提交
60
        p_len = 0
X
xuezhong 已提交
61 62 63
        p_id = []
        p_ids = []
        q_ids = []
X
xuezhong 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76
        q_id = []
        p_id_r = []
        p_ids_r = []
        q_ids_r = []
        q_id_r = []

        for j in range(insts['passage_num'][i]):
            p_ids.append(insts['passage_token_ids'][passage_idx + j])
            p_id = p_id + insts['passage_token_ids'][passage_idx + j]
            q_ids.append(insts['question_token_ids'][passage_idx + j])
            q_id = q_id + insts['question_token_ids'][passage_idx + j]

        passage_idx += insts['passage_num'][i]
X
xuezhong 已提交
77 78 79 80 81 82 83 84 85 86
        p_len = len(p_id)

        def _get_label(idx, ref_len):
            ret = [0.0] * ref_len
            if idx >= 0 and idx < ref_len:
                ret[idx] = 1.0
            return [[x] for x in ret]

        start_label = _get_label(insts['start_id'][i], p_len)
        end_label = _get_label(insts['end_id'][i], p_len)
X
xuezhong 已提交
87
        new_inst = [q_ids, start_label, end_label, p_ids, q_id]
X
xuezhong 已提交
88 89 90 91
        new_insts.append(new_inst)
    return new_insts


X
xuezhong 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
def batch_reader(batch_list, args):
    res = []
    for batch in batch_list:
        res.append(prepare_batch_input(batch, args))
    return res


def read_multiple(reader, count, clip_last=True):
    """
    Stack data from reader for multi-devices.
    """

    def __impl__():
        res = []
        for item in reader():
            res.append(item)
            if len(res) == count:
                yield res
                res = []
        if len(res) == count:
            yield res
        elif not clip_last:
            data = []
            for item in res:
                data += item
            if len(data) > count:
                inst_num_per_part = len(data) // count
                yield [
                    data[inst_num_per_part * i:inst_num_per_part * (i + 1)]
                    for i in range(count)
                ]

    return __impl__


X
xuezhong 已提交
127 128 129 130 131 132 133 134 135 136
def LodTensor_Array(lod_tensor):
    lod = lod_tensor.lod()
    array = np.array(lod_tensor)
    new_array = []
    for i in range(len(lod[0]) - 1):
        new_array.append(array[lod[0][i]:lod[0][i + 1]])
    return new_array


def print_para(train_prog, train_exe, logger, args):
X
xuezhong 已提交
137
    """Print para info for debug purpose"""
X
xuezhong 已提交
138 139 140 141 142 143 144 145
    if args.para_print:
        param_list = train_prog.block(0).all_parameters()
        param_name_list = [p.name for p in param_list]
        num_sum = 0
        for p_name in param_name_list:
            p_array = np.array(train_exe.scope.find_var(p_name).get_tensor())
            param_num = np.prod(p_array.shape)
            num_sum = num_sum + param_num
Q
qiuxuezhong 已提交
146 147 148 149 150
            logger.info(
                "param: {0},  mean={1}  max={2}  min={3}  num={4} {5}".format(
                    p_name,
                    p_array.mean(),
                    p_array.max(), p_array.min(), p_array.shape, param_num))
X
xuezhong 已提交
151 152 153
        logger.info("total param num: {0}".format(num_sum))


X
xuezhong 已提交
154
def find_best_answer_for_passage(start_probs, end_probs, passage_len):
X
xuezhong 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    """
    Finds the best answer with the maximum start_prob * end_prob from a single passage
    """
    if passage_len is None:
        passage_len = len(start_probs)
    else:
        passage_len = min(len(start_probs), passage_len)
    best_start, best_end, max_prob = -1, -1, 0
    for start_idx in range(passage_len):
        for ans_len in range(args.max_a_len):
            end_idx = start_idx + ans_len
            if end_idx >= passage_len:
                continue
            prob = start_probs[start_idx] * end_probs[end_idx]
            if prob > max_prob:
                best_start = start_idx
                best_end = end_idx
                max_prob = prob
    return (best_start, best_end), max_prob


X
xuezhong 已提交
176 177
def find_best_answer_for_inst(sample, start_prob, end_prob, inst_lod,
                              para_prior_scores=(0.44, 0.23, 0.15, 0.09, 0.07)):
X
xuezhong 已提交
178 179 180 181 182 183 184 185
    """
    Finds the best answer for a sample given start_prob and end_prob for each position.
    This will call find_best_answer_for_passage because there are multiple passages in a sample
    """
    best_p_idx, best_span, best_score = None, None, 0
    for p_idx, passage in enumerate(sample['passages']):
        if p_idx >= args.max_p_num:
            continue
X
xuezhong 已提交
186 187 188 189 190 191
        if len(start_prob) != len(end_prob):
            logger.info('error: {}'.format(sample['question']))
            continue
        passage_start = inst_lod[p_idx] - inst_lod[0]
        passage_end = inst_lod[p_idx + 1] - inst_lod[0]
        passage_len = passage_end - passage_start
X
xuezhong 已提交
192 193
        passage_len = min(args.max_p_len, len(passage['passage_tokens']))
        answer_span, score = find_best_answer_for_passage(
X
xuezhong 已提交
194 195
            start_prob[passage_start:passage_end],
            end_prob[passage_start:passage_end], passage_len)
X
xuezhong 已提交
196 197 198 199
        if para_prior_scores is not None:
            # the Nth prior score = the Number of training samples whose gold answer comes
            #  from the Nth paragraph / the number of the training samples
            score *= para_prior_scores[p_idx]
X
xuezhong 已提交
200 201 202 203 204 205 206 207 208
        if score > best_score:
            best_score = score
            best_p_idx = p_idx
            best_span = answer_span
    if best_p_idx is None or best_span is None:
        best_answer = ''
    else:
        best_answer = ''.join(sample['passages'][best_p_idx]['passage_tokens'][
            best_span[0]:best_span[1] + 1])
X
xuezhong 已提交
209
    return best_answer, best_span
X
xuezhong 已提交
210 211


X
xuezhong 已提交
212 213
def validation(inference_program, avg_cost, s_probs, e_probs, match, feed_order,
               place, dev_count, vocab, brc_data, logger, args):
X
xuezhong 已提交
214
    """
X
xuezhong 已提交
215
    do inference with given inference_program
X
xuezhong 已提交
216 217
    """
    parallel_executor = fluid.ParallelExecutor(
Q
qiuxuezhong 已提交
218 219
        main_program=inference_program,
        use_cuda=bool(args.use_gpu),
X
xuezhong 已提交
220
        loss_name=avg_cost.name)
Q
qiuxuezhong 已提交
221
    print_para(inference_program, parallel_executor, logger, args)
X
xuezhong 已提交
222 223 224 225

    # Use test set as validation each pass
    total_loss = 0.0
    count = 0
X
xuezhong 已提交
226 227
    n_batch_cnt = 0
    n_batch_loss = 0.0
X
xuezhong 已提交
228 229 230 231 232 233 234
    pred_answers, ref_answers = [], []
    val_feed_list = [
        inference_program.global_block().var(var_name)
        for var_name in feed_order
    ]
    val_feeder = fluid.DataFeeder(val_feed_list, place)
    pad_id = vocab.get_id(vocab.pad_token)
X
xuezhong 已提交
235 236
    dev_reader = lambda:brc_data.gen_mini_batches('dev', args.batch_size, pad_id, shuffle=False)
    dev_reader = read_multiple(dev_reader, dev_count)
X
xuezhong 已提交
237

X
xuezhong 已提交
238 239
    for batch_id, batch_list in enumerate(dev_reader(), 1):
        feed_data = batch_reader(batch_list, args)
X
xuezhong 已提交
240
        val_fetch_outs = parallel_executor.run(
X
xuezhong 已提交
241 242
            feed=list(val_feeder.feed_parallel(feed_data, dev_count)),
            fetch_list=[avg_cost.name, s_probs.name, e_probs.name, match.name],
Q
qiuxuezhong 已提交
243
            return_numpy=False)
X
xuezhong 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
        total_loss += np.array(val_fetch_outs[0]).sum()
        start_probs_m = LodTensor_Array(val_fetch_outs[1])
        end_probs_m = LodTensor_Array(val_fetch_outs[2])
        match_lod = val_fetch_outs[3].lod()
        count += len(np.array(val_fetch_outs[0]))

        n_batch_cnt += len(np.array(val_fetch_outs[0]))
        n_batch_loss += np.array(val_fetch_outs[0]).sum()
        log_every_n_batch = args.log_interval
        if log_every_n_batch > 0 and batch_id % log_every_n_batch == 0:
            logger.info('Average dev loss from batch {} to {} is {}'.format(
                batch_id - log_every_n_batch + 1, batch_id, "%.10f" % (
                    n_batch_loss / n_batch_cnt)))
            n_batch_loss = 0.0
            n_batch_cnt = 0
X
xuezhong 已提交
259
        batch_offset = 0
X
xuezhong 已提交
260 261 262
        for idx, batch in enumerate(batch_list):
            #one batch
            batch_size = len(batch['raw_data'])
X
xuezhong 已提交
263
            batch_range = match_lod[0][batch_offset:batch_offset + batch_size +
X
xuezhong 已提交
264 265 266
                                       1]
            batch_lod = [[batch_range[x], batch_range[x + 1]]
                         for x in range(len(batch_range[:-1]))]
X
xuezhong 已提交
267 268 269 270
            start_prob_batch = start_probs_m[batch_offset:batch_offset +
                                             batch_size + 1]
            end_prob_batch = end_probs_m[batch_offset:batch_offset + batch_size
                                         + 1]
X
xuezhong 已提交
271 272 273 274 275 276 277 278
            for sample, start_prob_inst, end_prob_inst, inst_range in zip(
                    batch['raw_data'], start_prob_batch, end_prob_batch,
                    batch_lod):
                #one instance
                inst_lod = match_lod[1][inst_range[0]:inst_range[1] + 1]
                best_answer, best_span = find_best_answer_for_inst(
                    sample, start_prob_inst, end_prob_inst, inst_lod)
                pred = {
X
xuezhong 已提交
279 280
                    'question_id': sample['question_id'],
                    'question_type': sample['question_type'],
X
xuezhong 已提交
281
                    'answers': [best_answer],
X
xuezhong 已提交
282
                    'entity_answers': [[]],
X
xuezhong 已提交
283
                    'yesno_answers': []
X
xuezhong 已提交
284 285 286 287 288 289 290 291 292 293 294
                }
                pred_answers.append(pred)
                if 'answers' in sample:
                    ref = {
                        'question_id': sample['question_id'],
                        'question_type': sample['question_type'],
                        'answers': sample['answers'],
                        'entity_answers': [[]],
                        'yesno_answers': []
                    }
                    ref_answers.append(ref)
X
xuezhong 已提交
295
            batch_offset = batch_offset + batch_size
X
xuezhong 已提交
296 297 298 299

    result_dir = args.result_dir
    result_prefix = args.result_name
    if result_dir is not None and result_prefix is not None:
X
xuezhong 已提交
300 301
        if not os.path.exists(args.result_dir):
            os.makedirs(args.result_dir)
X
xuezhong 已提交
302
        result_file = os.path.join(result_dir, result_prefix + '.json')
Q
qiuxuezhong 已提交
303 304 305
        with open(result_file, 'w') as fout:
            for pred_answer in pred_answers:
                fout.write(json.dumps(pred_answer, ensure_ascii=False) + '\n')
X
xuezhong 已提交
306
        logger.info('Saving {} results to {}'.format(result_prefix,
Q
qiuxuezhong 已提交
307
                                                     result_file))
X
xuezhong 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

    ave_loss = 1.0 * total_loss / count
    # compute the bleu and rouge scores if reference answers is provided
    if len(ref_answers) > 0:
        pred_dict, ref_dict = {}, {}
        for pred, ref in zip(pred_answers, ref_answers):
            question_id = ref['question_id']
            if len(ref['answers']) > 0:
                pred_dict[question_id] = normalize(pred['answers'])
                ref_dict[question_id] = normalize(ref['answers'])
        bleu_rouge = compute_bleu_rouge(pred_dict, ref_dict)
    else:
        bleu_rouge = None
    return ave_loss, bleu_rouge

Q
qiuxuezhong 已提交
323

X
xuezhong 已提交
324 325 326 327 328 329 330 331 332
def l2_loss(train_prog):
    param_list = train_prog.block(0).all_parameters()
    para_sum = []
    for para in param_list:
        para_mul = fluid.layers.elementwise_mul(x=para, y=para, axis=0)
        para_sum.append(fluid.layers.reduce_sum(input=para_mul, dim=None))
    return fluid.layers.sums(para_sum) * 0.5


X
xuezhong 已提交
333
def train(logger, args):
X
xuezhong 已提交
334
    """train a model"""
X
xuezhong 已提交
335 336
    logger.info('Load data_set and vocab...')
    with open(os.path.join(args.vocab_dir, 'vocab.data'), 'rb') as fin:
X
xuezhong 已提交
337 338 339 340
        if six.PY2:
            vocab = pickle.load(fin)
        else:
            vocab = pickle.load(fin, encoding='bytes')
X
xuezhong 已提交
341 342 343 344 345 346 347 348
        logger.info('vocab size is {} and embed dim is {}'.format(vocab.size(
        ), vocab.embed_dim))
    brc_data = BRCDataset(args.max_p_num, args.max_p_len, args.max_q_len,
                          args.trainset, args.devset)
    logger.info('Converting text into ids...')
    brc_data.convert_to_ids(vocab)
    logger.info('Initialize the model...')

X
xuezhong 已提交
349 350 351 352 353 354 355
    if not args.use_gpu:
        place = fluid.CPUPlace()
        dev_count = int(os.environ.get('CPU_NUM', multiprocessing.cpu_count()))
    else:
        place = fluid.CUDAPlace(0)
        dev_count = fluid.core.get_cuda_device_count()

X
xuezhong 已提交
356 357 358
    # build model
    main_program = fluid.Program()
    startup_prog = fluid.Program()
X
xuezhong 已提交
359 360 361
    if args.enable_ce:
        main_program.random_seed = args.random_seed
        startup_prog.random_seed = args.random_seed
X
xuezhong 已提交
362 363
    with fluid.program_guard(main_program, startup_prog):
        with fluid.unique_name.guard():
X
xuezhong 已提交
364
            avg_cost, s_probs, e_probs, match, feed_order = rc_model.rc_model(
Q
qiuxuezhong 已提交
365
                args.hidden_size, vocab, args)
X
xuezhong 已提交
366 367 368
            # clone from default main program and use it as the validation program
            inference_program = main_program.clone(for_test=True)

Q
qiuxuezhong 已提交
369 370 371
            # build optimizer
            if args.optim == 'sgd':
                optimizer = fluid.optimizer.SGD(
X
xuezhong 已提交
372
                    learning_rate=args.learning_rate)
Q
qiuxuezhong 已提交
373 374
            elif args.optim == 'adam':
                optimizer = fluid.optimizer.Adam(
X
xuezhong 已提交
375
                    learning_rate=args.learning_rate)
Q
qiuxuezhong 已提交
376 377
            elif args.optim == 'rprop':
                optimizer = fluid.optimizer.RMSPropOptimizer(
X
xuezhong 已提交
378
                    learning_rate=args.learning_rate)
Q
qiuxuezhong 已提交
379 380 381
            else:
                logger.error('Unsupported optimizer: {}'.format(args.optim))
                exit(-1)
X
xuezhong 已提交
382
            if args.weight_decay > 0.0:
X
fix bug  
xuezhong 已提交
383 384 385 386 387
                obj_func = avg_cost + args.weight_decay * l2_loss(main_program)
                optimizer.minimize(obj_func)
            else:
                obj_func = avg_cost
                optimizer.minimize(obj_func)
Q
qiuxuezhong 已提交
388 389

            # initialize parameters
Y
Yibing Liu 已提交
390
            place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()
Q
qiuxuezhong 已提交
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
            exe = Executor(place)
            if args.load_dir:
                logger.info('load from {}'.format(args.load_dir))
                fluid.io.load_persistables(
                    exe, args.load_dir, main_program=main_program)
            else:
                exe.run(startup_prog)
                embedding_para = fluid.global_scope().find_var(
                    'embedding_para').get_tensor()
                embedding_para.set(vocab.embeddings.astype(np.float32), place)

            # prepare data
            feed_list = [
                main_program.global_block().var(var_name)
                for var_name in feed_order
            ]
            feeder = fluid.DataFeeder(feed_list, place)

            logger.info('Training the model...')
            parallel_executor = fluid.ParallelExecutor(
                main_program=main_program,
                use_cuda=bool(args.use_gpu),
                loss_name=avg_cost.name)
            print_para(main_program, parallel_executor, logger, args)

            for pass_id in range(1, args.pass_num + 1):
                pass_start_time = time.time()
                pad_id = vocab.get_id(vocab.pad_token)
X
xuezhong 已提交
419 420 421 422
                if args.enable_ce:
                    train_reader = lambda:brc_data.gen_mini_batches('train', args.batch_size, pad_id, shuffle=False)
                else:
                    train_reader = lambda:brc_data.gen_mini_batches('train', args.batch_size, pad_id, shuffle=True)
X
xuezhong 已提交
423
                train_reader = read_multiple(train_reader, dev_count)
Q
qiuxuezhong 已提交
424 425
                log_every_n_batch, n_batch_loss = args.log_interval, 0
                total_num, total_loss = 0, 0
X
xuezhong 已提交
426 427
                for batch_id, batch_list in enumerate(train_reader(), 1):
                    feed_data = batch_reader(batch_list, args)
Q
qiuxuezhong 已提交
428
                    fetch_outs = parallel_executor.run(
X
xuezhong 已提交
429
                        feed=list(feeder.feed_parallel(feed_data, dev_count)),
X
fix bug  
xuezhong 已提交
430
                        fetch_list=[obj_func.name],
Q
qiuxuezhong 已提交
431
                        return_numpy=False)
X
xuezhong 已提交
432 433
                    cost_train = np.array(fetch_outs[0]).mean()
                    total_num += args.batch_size * dev_count
Q
qiuxuezhong 已提交
434
                    n_batch_loss += cost_train
X
xuezhong 已提交
435 436
                    total_loss += cost_train * args.batch_size * dev_count

X
add ce  
xuezhong 已提交
437 438
                    if args.enable_ce and batch_id >= 100:
                        break
Q
qiuxuezhong 已提交
439 440 441 442 443 444 445 446 447
                    if log_every_n_batch > 0 and batch_id % log_every_n_batch == 0:
                        print_para(main_program, parallel_executor, logger,
                                   args)
                        logger.info(
                            'Average loss from batch {} to {} is {}'.format(
                                batch_id - log_every_n_batch + 1, batch_id,
                                "%.10f" % (n_batch_loss / log_every_n_batch)))
                        n_batch_loss = 0
                    if args.dev_interval > 0 and batch_id % args.dev_interval == 0:
X
xuezhong 已提交
448 449 450 451 452 453 454
                        if brc_data.dev_set is not None:
                            eval_loss, bleu_rouge = validation(
                                inference_program, avg_cost, s_probs, e_probs,
                                match, feed_order, place, dev_count, vocab,
                                brc_data, logger, args)
                            logger.info('Dev eval result: {}'.format(
                                bleu_rouge))
Q
qiuxuezhong 已提交
455
                pass_end_time = time.time()
456 457 458
                time_consumed = pass_end_time - pass_start_time
                logger.info('epoch: {0}, epoch_time_cost: {1:.2f}'.format(
                    pass_id, time_consumed))
Q
qiuxuezhong 已提交
459 460 461 462
                logger.info('Evaluating the model after epoch {}'.format(
                    pass_id))
                if brc_data.dev_set is not None:
                    eval_loss, bleu_rouge = validation(
X
xuezhong 已提交
463 464 465
                        inference_program, avg_cost, s_probs, e_probs, match,
                        feed_order, place, dev_count, vocab, brc_data, logger,
                        args)
Q
qiuxuezhong 已提交
466 467 468 469
                    logger.info('Dev eval result: {}'.format(bleu_rouge))
                else:
                    logger.warning(
                        'No dev set is loaded for evaluation in the dataset!')
470

Q
qiuxuezhong 已提交
471 472 473 474 475 476 477 478 479 480 481 482
                logger.info('Average train loss for epoch {} is {}'.format(
                    pass_id, "%.10f" % (1.0 * total_loss / total_num)))

                if pass_id % args.save_interval == 0:
                    model_path = os.path.join(args.save_dir, str(pass_id))
                    if not os.path.isdir(model_path):
                        os.makedirs(model_path)

                    fluid.io.save_persistables(
                        executor=exe,
                        dirname=model_path,
                        main_program=main_program)
X
add ce  
xuezhong 已提交
483 484 485 486 487 488 489 490
                if args.enable_ce:  # For CE
                    print("kpis\ttrain_cost_card%d\t%f" %
                          (dev_count, total_loss / total_num))
                    if brc_data.dev_set is not None:
                        print("kpis\ttest_cost_card%d\t%f" %
                              (dev_count, eval_loss))
                    print("kpis\ttrain_duration_card%d\t%f" %
                          (dev_count, time_consumed))
Q
qiuxuezhong 已提交
491

X
xuezhong 已提交
492 493

def evaluate(logger, args):
X
xuezhong 已提交
494
    """evaluate a specific model using devset"""
X
xuezhong 已提交
495 496 497 498 499
    logger.info('Load data_set and vocab...')
    with open(os.path.join(args.vocab_dir, 'vocab.data'), 'rb') as fin:
        vocab = pickle.load(fin)
        logger.info('vocab size is {} and embed dim is {}'.format(vocab.size(
        ), vocab.embed_dim))
Q
qiuxuezhong 已提交
500 501
    brc_data = BRCDataset(
        args.max_p_num, args.max_p_len, args.max_q_len, dev_files=args.devset)
X
xuezhong 已提交
502 503 504 505 506 507 508 509 510
    logger.info('Converting text into ids...')
    brc_data.convert_to_ids(vocab)
    logger.info('Initialize the model...')

    # build model
    main_program = fluid.Program()
    startup_prog = fluid.Program()
    with fluid.program_guard(main_program, startup_prog):
        with fluid.unique_name.guard():
X
xuezhong 已提交
511
            avg_cost, s_probs, e_probs, match, feed_order = rc_model.rc_model(
Q
qiuxuezhong 已提交
512 513
                args.hidden_size, vocab, args)
            # initialize parameters
X
xuezhong 已提交
514 515 516 517 518 519 520 521
            if not args.use_gpu:
                place = fluid.CPUPlace()
                dev_count = int(
                    os.environ.get('CPU_NUM', multiprocessing.cpu_count()))
            else:
                place = fluid.CUDAPlace(0)
                dev_count = fluid.core.get_cuda_device_count()

Q
qiuxuezhong 已提交
522 523 524 525 526 527 528 529 530
            exe = Executor(place)
            if args.load_dir:
                logger.info('load from {}'.format(args.load_dir))
                fluid.io.load_persistables(
                    exe, args.load_dir, main_program=main_program)
            else:
                logger.error('No model file to load ...')
                return

X
xuezhong 已提交
531
            inference_program = main_program.clone(for_test=True)
Q
qiuxuezhong 已提交
532
            eval_loss, bleu_rouge = validation(
X
xuezhong 已提交
533 534
                inference_program, avg_cost, s_probs, e_probs, match, feed_order,
                place, dev_count, vocab, brc_data, logger, args)
Q
qiuxuezhong 已提交
535 536 537 538 539
            logger.info('Dev eval result: {}'.format(bleu_rouge))
            logger.info('Predicted answers are saved to {}'.format(
                os.path.join(args.result_dir)))


X
xuezhong 已提交
540
def predict(logger, args):
X
xuezhong 已提交
541
    """do inference on the test dataset """
X
xuezhong 已提交
542 543 544 545 546
    logger.info('Load data_set and vocab...')
    with open(os.path.join(args.vocab_dir, 'vocab.data'), 'rb') as fin:
        vocab = pickle.load(fin)
        logger.info('vocab size is {} and embed dim is {}'.format(vocab.size(
        ), vocab.embed_dim))
Q
qiuxuezhong 已提交
547 548
    brc_data = BRCDataset(
        args.max_p_num, args.max_p_len, args.max_q_len, dev_files=args.testset)
X
xuezhong 已提交
549 550 551 552 553 554 555 556 557
    logger.info('Converting text into ids...')
    brc_data.convert_to_ids(vocab)
    logger.info('Initialize the model...')

    # build model
    main_program = fluid.Program()
    startup_prog = fluid.Program()
    with fluid.program_guard(main_program, startup_prog):
        with fluid.unique_name.guard():
X
xuezhong 已提交
558
            avg_cost, s_probs, e_probs, match, feed_order = rc_model.rc_model(
Q
qiuxuezhong 已提交
559 560
                args.hidden_size, vocab, args)
            # initialize parameters
X
xuezhong 已提交
561 562 563 564 565 566 567 568
            if not args.use_gpu:
                place = fluid.CPUPlace()
                dev_count = int(
                    os.environ.get('CPU_NUM', multiprocessing.cpu_count()))
            else:
                place = fluid.CUDAPlace(0)
                dev_count = fluid.core.get_cuda_device_count()

Q
qiuxuezhong 已提交
569 570 571 572 573 574 575 576 577
            exe = Executor(place)
            if args.load_dir:
                logger.info('load from {}'.format(args.load_dir))
                fluid.io.load_persistables(
                    exe, args.load_dir, main_program=main_program)
            else:
                logger.error('No model file to load ...')
                return

X
xuezhong 已提交
578
            inference_program = main_program.clone(for_test=True)
Q
qiuxuezhong 已提交
579
            eval_loss, bleu_rouge = validation(
X
xuezhong 已提交
580 581
                inference_program, avg_cost, s_probs, e_probs, match,
                feed_order, place, dev_count, vocab, brc_data, logger, args)
Q
qiuxuezhong 已提交
582

X
xuezhong 已提交
583

X
xuezhong 已提交
584 585 586 587 588 589
def prepare(logger, args):
    """
    checks data, creates the directories, prepare the vocabulary and embeddings
    """
    logger.info('Checking the data files...')
    for data_path in args.trainset + args.devset + args.testset:
Q
qiuxuezhong 已提交
590 591
        assert os.path.exists(data_path), '{} file does not exist.'.format(
            data_path)
X
xuezhong 已提交
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
    logger.info('Preparing the directories...')
    for dir_path in [args.vocab_dir, args.save_dir, args.result_dir]:
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

    logger.info('Building vocabulary...')
    brc_data = BRCDataset(args.max_p_num, args.max_p_len, args.max_q_len,
                          args.trainset, args.devset, args.testset)
    vocab = Vocab(lower=True)
    for word in brc_data.word_iter('train'):
        vocab.add(word)

    unfiltered_vocab_size = vocab.size()
    vocab.filter_tokens_by_cnt(min_cnt=2)
    filtered_num = unfiltered_vocab_size - vocab.size()
Q
qiuxuezhong 已提交
607 608
    logger.info('After filter {} tokens, the final vocab size is {}'.format(
        filtered_num, vocab.size()))
X
xuezhong 已提交
609 610 611 612 613 614 615 616 617

    logger.info('Assigning embeddings...')
    vocab.randomly_init_embeddings(args.embed_size)

    logger.info('Saving vocab...')
    with open(os.path.join(args.vocab_dir, 'vocab.data'), 'wb') as fout:
        pickle.dump(vocab, fout)

    logger.info('Done with preparing!')
X
xuezhong 已提交
618

Q
qiuxuezhong 已提交
619

X
xuezhong 已提交
620 621 622
if __name__ == '__main__':
    args = parse_args()

X
xuezhong 已提交
623 624 625
    if args.enable_ce:
        random.seed(args.random_seed)
        np.random.seed(args.random_seed)
X
xuezhong 已提交
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642

    logger = logging.getLogger("brc")
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    if args.log_path:
        file_handler = logging.FileHandler(args.log_path)
        file_handler.setLevel(logging.INFO)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
    else:
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)
    args = parse_args()
    logger.info('Running with args : {}'.format(args))
643 644 645 646 647 648
    try:
        if fluid.is_compiled_with_cuda() != True and args.use_cuda == True:
            print("\nYou can not set use_cuda = True in the model because you are using paddlepaddle-cpu.\nPlease: 1. Install paddlepaddle-gpu to run your models on GPU or 2. Set use_cuda = False to run models on CPU.\n")
            sys.exit(1)
    except Exception as e:
        pass
X
xuezhong 已提交
649 650
    if args.prepare:
        prepare(logger, args)
X
xuezhong 已提交
651 652 653 654 655 656
    if args.train:
        train(logger, args)
    if args.evaluate:
        evaluate(logger, args)
    if args.predict:
        predict(logger, args)