train.py 14.5 KB
Newer Older
1 2 3
import os
import math
import time
4
import argparse
5 6 7 8 9 10 11 12 13

import numpy as np
import paddle
import paddle.fluid as fluid
from paddle.fluid.initializer import NormalInitializer

import reader


14
def parse_args():
Y
Yibing Liu 已提交
15
    parser = argparse.ArgumentParser("Run training.")
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    parser.add_argument(
        '--batch_size',
        type=int,
        default=256,
        help='The size of a batch. (default: %(default)d)')
    parser.add_argument(
        '--word_dict_len',
        type=int,
        default=1942563,
        help='The lenght of the word dictionary. (default: %(default)d)')
    parser.add_argument(
        '--label_dict_len',
        type=int,
        default=49,
        help='The lenght of the label dictionary. (default: %(default)d)')
    parser.add_argument(
        '--device',
        type=str,
        default='GPU',
        choices=['CPU', 'GPU'],
        help='The device type. (default: %(default)s)')
    parser.add_argument(
        '--train_data_dir',
        type=str,
        default='data/train_files',
        help='A directory with train data files. (default: %(default)s)')
    parser.add_argument(
        '--parallel',
        type=bool,
        default=False,
        help="Whether to use parallel training. (default: %(default)s)")
    parser.add_argument(
        '--test_data_dir',
        type=str,
        default='data/test_files',
        help='A directory with test data files. (default: %(default)s)')
    parser.add_argument(
        '--model_save_dir',
        type=str,
        default='./output',
        help='A directory for saving models. (default: %(default)s)')
    parser.add_argument(
        '--num_passes',
        type=int,
        default=1000,
        help='The number of epochs. (default: %(default)d)')
Z
zhengya01 已提交
62 63 64 65
    parser.add_argument(
        '--enable_ce',
        action='store_true',
        help='If set, run the task with continuous evaluation logs.')
66 67 68 69 70 71
    args = parser.parse_args()
    return args


def print_arguments(args):
    print('-----------  Configuration Arguments -----------')
72
    for arg, value in sorted(vars(args).items()):
73 74 75 76
        print('%s: %s' % (arg, value))
    print('------------------------------------------------')


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 103 104 105 106 107 108 109 110 111 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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
def load_reverse_dict(dict_path):
    return dict((idx, line.strip().split("\t")[0])
                for idx, line in enumerate(open(dict_path, "r").readlines()))


def to_lodtensor(data, place):
    seq_lens = [len(seq) for seq in data]
    cur_len = 0
    lod = [cur_len]
    for l in seq_lens:
        cur_len += l
        lod.append(cur_len)
    flattened_data = np.concatenate(data, axis=0).astype("int64")
    flattened_data = flattened_data.reshape([len(flattened_data), 1])
    res = fluid.LoDTensor()
    res.set(flattened_data, place)
    res.set_lod([lod])
    return res


def ner_net(word_dict_len, label_dict_len):
    IS_SPARSE = False
    word_dim = 32
    mention_dict_len = 57
    mention_dim = 20
    grnn_hidden = 36
    emb_lr = 5
    init_bound = 0.1

    def _net_conf(word, mark, target):
        word_embedding = fluid.layers.embedding(
            input=word,
            size=[word_dict_len, word_dim],
            dtype='float32',
            is_sparse=IS_SPARSE,
            param_attr=fluid.ParamAttr(
                learning_rate=emb_lr,
                name="word_emb",
                initializer=fluid.initializer.Uniform(
                    low=-init_bound, high=init_bound)))

        mention_embedding = fluid.layers.embedding(
            input=mention,
            size=[mention_dict_len, mention_dim],
            dtype='float32',
            is_sparse=IS_SPARSE,
            param_attr=fluid.ParamAttr(
                learning_rate=emb_lr,
                name="mention_emb",
                initializer=fluid.initializer.Uniform(
                    low=-init_bound, high=init_bound)))

        word_embedding_r = fluid.layers.embedding(
            input=word,
            size=[word_dict_len, word_dim],
            dtype='float32',
            is_sparse=IS_SPARSE,
            param_attr=fluid.ParamAttr(
                learning_rate=emb_lr,
                name="word_emb_r",
                initializer=fluid.initializer.Uniform(
                    low=-init_bound, high=init_bound)))

        mention_embedding_r = fluid.layers.embedding(
            input=mention,
            size=[mention_dict_len, mention_dim],
            dtype='float32',
            is_sparse=IS_SPARSE,
            param_attr=fluid.ParamAttr(
                learning_rate=emb_lr,
                name="mention_emb_r",
                initializer=fluid.initializer.Uniform(
                    low=-init_bound, high=init_bound)))

        word_mention_vector = fluid.layers.concat(
            input=[word_embedding, mention_embedding], axis=1)

        word_mention_vector_r = fluid.layers.concat(
            input=[word_embedding_r, mention_embedding_r], axis=1)

        pre_gru = fluid.layers.fc(
            input=word_mention_vector,
            size=grnn_hidden * 3,
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Uniform(
                    low=-init_bound, high=init_bound),
                regularizer=fluid.regularizer.L2DecayRegularizer(
                    regularization_coeff=1e-4)))
        gru = fluid.layers.dynamic_gru(
            input=pre_gru,
            size=grnn_hidden,
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Uniform(
                    low=-init_bound, high=init_bound),
                regularizer=fluid.regularizer.L2DecayRegularizer(
                    regularization_coeff=1e-4)))

        pre_gru_r = fluid.layers.fc(
            input=word_mention_vector_r,
            size=grnn_hidden * 3,
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Uniform(
                    low=-init_bound, high=init_bound),
                regularizer=fluid.regularizer.L2DecayRegularizer(
                    regularization_coeff=1e-4)))
        gru_r = fluid.layers.dynamic_gru(
            input=pre_gru_r,
            size=grnn_hidden,
            is_reverse=True,
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Uniform(
                    low=-init_bound, high=init_bound),
                regularizer=fluid.regularizer.L2DecayRegularizer(
                    regularization_coeff=1e-4)))

        gru_merged = fluid.layers.concat(input=[gru, gru_r], axis=1)

        emission = fluid.layers.fc(
            size=label_dict_len,
            input=gru_merged,
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Uniform(
                    low=-init_bound, high=init_bound),
                regularizer=fluid.regularizer.L2DecayRegularizer(
                    regularization_coeff=1e-4)))

        crf_cost = fluid.layers.linear_chain_crf(
            input=emission,
            label=target,
            param_attr=fluid.ParamAttr(
                name='crfw',
J
jshower 已提交
208
                learning_rate=0.2, ))
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        avg_cost = fluid.layers.mean(x=crf_cost)
        return avg_cost, emission

    word = fluid.layers.data(name='word', shape=[1], dtype='int64', lod_level=1)
    mention = fluid.layers.data(
        name='mention', shape=[1], dtype='int64', lod_level=1)
    target = fluid.layers.data(
        name="target", shape=[1], dtype='int64', lod_level=1)

    avg_cost, emission = _net_conf(word, mention, target)

    return avg_cost, emission, word, mention, target


def test2(exe, chunk_evaluator, inference_program, test_data, place,
          cur_fetch_list):
    chunk_evaluator.reset()
    for data in test_data():
227 228 229
        word = to_lodtensor(list(map(lambda x: x[0], data)), place)
        mention = to_lodtensor(list(map(lambda x: x[1], data)), place)
        target = to_lodtensor(list(map(lambda x: x[2], data)), place)
230 231
        result_list = exe.run(
            inference_program,
J
jshower 已提交
232 233 234
            feed={"word": word,
                  "mention": mention,
                  "target": target},
235 236 237 238
            fetch_list=cur_fetch_list)
        number_infer = np.array(result_list[0])
        number_label = np.array(result_list[1])
        number_correct = np.array(result_list[2])
239 240 241
        chunk_evaluator.update(number_infer[0].astype('int64'),
                               number_label[0].astype('int64'),
                               number_correct[0].astype('int64'))
242 243 244 245 246 247 248
    return chunk_evaluator.eval()


def test(test_exe, chunk_evaluator, inference_program, test_data, place,
         cur_fetch_list):
    chunk_evaluator.reset()
    for data in test_data():
249 250 251
        word = to_lodtensor(list(map(lambda x: x[0], data)), place)
        mention = to_lodtensor(list(map(lambda x: x[1], data)), place)
        target = to_lodtensor(list(map(lambda x: x[2], data)), place)
252 253
        result_list = test_exe.run(
            fetch_list=cur_fetch_list,
J
jshower 已提交
254 255 256
            feed={"word": word,
                  "mention": mention,
                  "target": target})
257 258 259
        number_infer = np.array(result_list[0])
        number_label = np.array(result_list[1])
        number_correct = np.array(result_list[2])
260 261 262
        chunk_evaluator.update(number_infer.sum().astype('int64'),
                               number_label.sum().astype('int64'),
                               number_correct.sum().astype('int64'))
263 264 265
    return chunk_evaluator.eval()


266 267 268
def main(args):
    if not os.path.exists(args.model_save_dir):
        os.makedirs(args.model_save_dir)
269 270 271

    main = fluid.Program()
    startup = fluid.Program()
Z
zhengya01 已提交
272 273 274 275
    if args.enable_ce:
        SEED = 102
        main.random_seed = SEED
        startup.random_seed = SEED
276
    with fluid.program_guard(main, startup):
277 278
        avg_cost, feature_out, word, mention, target = ner_net(
            args.word_dict_len, args.label_dict_len)
279 280

        crf_decode = fluid.layers.crf_decoding(
J
jshower 已提交
281
            input=feature_out, param_attr=fluid.ParamAttr(name='crfw'))
J
jshower 已提交
282

283 284 285 286 287
        (precision, recall, f1_score, num_infer_chunks, num_label_chunks,
         num_correct_chunks) = fluid.layers.chunk_eval(
             input=crf_decode,
             label=target,
             chunk_scheme="IOB",
288
             num_chunk_types=int(math.ceil((args.label_dict_len - 1) / 2.0)))
289

290 291 292 293 294
        inference_program = fluid.default_main_program().clone(for_test=True)

        sgd_optimizer = fluid.optimizer.SGD(learning_rate=1e-3)
        sgd_optimizer.minimize(avg_cost)

295 296 297 298
        chunk_evaluator = fluid.metrics.ChunkEvaluator()

        train_reader = paddle.batch(
            paddle.reader.shuffle(
299 300
                reader.file_reader(args.train_data_dir), buf_size=2000000),
            batch_size=args.batch_size)
301 302
        test_reader = paddle.batch(
            paddle.reader.shuffle(
303 304
                reader.file_reader(args.test_data_dir), buf_size=2000000),
            batch_size=args.batch_size)
305

306
        place = fluid.CUDAPlace(0) if args.device == 'GPU' else fluid.CPUPlace()
307 308 309 310 311 312
        feeder = fluid.DataFeeder(
            feed_list=[word, mention, target], place=place)

        exe = fluid.Executor(place)

        exe.run(startup)
313 314 315 316 317 318 319 320 321 322 323
        if args.parallel:
            train_exe = fluid.ParallelExecutor(
                loss_name=avg_cost.name, use_cuda=(args.device == 'GPU'))
            test_exe = fluid.ParallelExecutor(
                use_cuda=(args.device == 'GPU'),
                main_program=inference_program,
                share_vars_from=train_exe)
        else:
            train_exe = exe
            test_exe = exe

Z
zhengya01 已提交
324 325
        total_time = 0
        ce_info = []
326
        batch_id = 0
327
        for pass_id in range(args.num_passes):
328 329 330 331 332 333 334 335 336 337 338 339 340
            chunk_evaluator.reset()
            train_reader_iter = train_reader()
            start_time = time.time()
            while True:
                try:
                    cur_batch = next(train_reader_iter)
                    cost, nums_infer, nums_label, nums_correct = train_exe.run(
                        fetch_list=[
                            avg_cost.name, num_infer_chunks.name,
                            num_label_chunks.name, num_correct_chunks.name
                        ],
                        feed=feeder.feed(cur_batch))
                    chunk_evaluator.update(
341 342 343
                        np.array(nums_infer).sum().astype("int64"),
                        np.array(nums_label).sum().astype("int64"),
                        np.array(nums_correct).sum().astype("int64"))
344 345 346 347 348
                    cost_list = np.array(cost)
                    batch_id += 1
                except StopIteration:
                    break
            end_time = time.time()
Z
zhengya01 已提交
349
            total_time += end_time - start_time
J
jshower 已提交
350 351
            print("pass_id:" + str(pass_id) + ", time_cost:" + str(
                end_time - start_time) + "s")
352
            precision, recall, f1_score = chunk_evaluator.eval()
J
jshower 已提交
353 354
            print("[Train] precision:" + str(precision) + ", recall:" + str(
                recall) + ", f1:" + str(f1_score))
Z
zhengya01 已提交
355
            ce_info.append(recall)
356 357 358
            p, r, f1 = test2(
                exe, chunk_evaluator, inference_program, test_reader, place,
                [num_infer_chunks, num_label_chunks, num_correct_chunks])
J
jshower 已提交
359 360
            print("[Test] precision:" + str(p) + ", recall:" + str(r) + ", f1:"
                  + str(f1))
361
            save_dirname = os.path.join(args.model_save_dir,
362
                                        "params_pass_%d" % pass_id)
363 364
            fluid.io.save_inference_model(save_dirname, ['word', 'mention'],
                                          [crf_decode], exe)
Z
zhengya01 已提交
365 366 367 368 369 370 371 372 373 374 375 376
        # only for ce
        if args.enable_ce:
            ce_recall = 0
            try:
                ce_recall = ce_info[-2]
            except:
                print("ce info error")
            epoch_idx = args.num_passes
            device = get_device(args)
            if args.device == "GPU":
                gpu_num = device[1]
                print("kpis\teach_pass_duration_gpu%s\t%s" %
Y
Yibing Liu 已提交
377 378
                      (gpu_num, total_time / epoch_idx))
                print("kpis\ttrain_recall_gpu%s\t%s" % (gpu_num, ce_recall))
Z
zhengya01 已提交
379 380 381 382
            else:
                cpu_num = device[1]
                threads_num = device[2]
                print("kpis\teach_pass_duration_cpu%s_thread%s\t%s" %
Y
Yibing Liu 已提交
383
                      (cpu_num, threads_num, total_time / epoch_idx))
Z
zhengya01 已提交
384
                print("kpis\ttrain_recall_cpu%s_thread%s\t%s" %
Y
Yibing Liu 已提交
385 386
                      (cpu_num, threads_num, ce_recall))

Z
zhengya01 已提交
387 388 389 390 391 392 393 394 395 396

def get_device(args):
    if args.device == "GPU":
        gpus = os.environ.get("CUDA_VISIBLE_DEVICES", "")
        gpu_num = len(gpus.split(','))
        return "gpu", gpu_num
    else:
        threads_num = os.environ.get('NUM_THREADS', 1)
        cpu_num = os.environ.get('CPU_NUM', 1)
        return "cpu", int(cpu_num), int(threads_num)
Y
Yibing Liu 已提交
397

398 399

if __name__ == "__main__":
400 401 402
    args = parse_args()
    print_arguments(args)
    main(args)