train.py 11.1 KB
Newer Older
1 2
from __future__ import print_function

D
dzhwinter 已提交
3
import math, os
4
import numpy as np
D
daminglu 已提交
5
import paddle
6
import paddle.dataset.conll05 as conll05
D
daminglu 已提交
7
import paddle.fluid as fluid
8
import six
D
daminglu 已提交
9
import time
u010070587's avatar
u010070587 已提交
10
import argparse
11

D
dzhwinter 已提交
12 13
with_gpu = os.getenv('WITH_GPU', '0') != '0'

14 15 16
word_dict, verb_dict, label_dict = conll05.get_dict()
word_dict_len = len(word_dict)
label_dict_len = len(label_dict)
D
daminglu 已提交
17
pred_dict_len = len(verb_dict)
18

19 20 21 22 23 24
mark_dict_len = 2
word_dim = 32
mark_dim = 5
hidden_dim = 512
depth = 8
mix_hidden_lr = 1e-3
25

D
daminglu 已提交
26 27 28
IS_SPARSE = True
PASS_NUM = 10
BATCH_SIZE = 10
29

D
daminglu 已提交
30
embedding_name = 'emb'
31

32

u010070587's avatar
u010070587 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46
def parse_args():
    parser = argparse.ArgumentParser("label_semantic_roles")
    parser.add_argument(
        '--enable_ce',
        action='store_true',
        help="If set, run the task with continuous evaluation logs.")
    parser.add_argument(
        '--use_gpu', type=int, default=0, help="Whether to use GPU or not.")
    parser.add_argument(
        '--num_epochs', type=int, default=100, help="number of epochs.")
    args = parser.parse_args()
    return args


D
daminglu 已提交
47 48 49 50
def load_parameter(file_name, h, w):
    with open(file_name, 'rb') as f:
        f.read(16)  # skip header.
        return np.fromfile(f, dtype=np.float32).reshape(h, w)
51 52


D
daminglu 已提交
53 54 55
def db_lstm(word, predicate, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2, mark,
            **ignored):
    # 8 features
Y
Yibing Liu 已提交
56
    predicate_embedding = fluid.embedding(
57
        input=predicate,
D
daminglu 已提交
58 59 60 61 62
        size=[pred_dict_len, word_dim],
        dtype='float32',
        is_sparse=IS_SPARSE,
        param_attr='vemb')

Y
Yibing Liu 已提交
63
    mark_embedding = fluid.embedding(
D
daminglu 已提交
64 65 66 67
        input=mark,
        size=[mark_dict_len, mark_dim],
        dtype='float32',
        is_sparse=IS_SPARSE)
68 69 70

    word_input = [word, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2]
    emb_layers = [
Y
Yibing Liu 已提交
71
        fluid.embedding(
D
daminglu 已提交
72 73
            size=[word_dict_len, word_dim],
            input=x,
74 75
            param_attr=fluid.ParamAttr(name=embedding_name, trainable=False))
        for x in word_input
76 77 78 79
    ]
    emb_layers.append(predicate_embedding)
    emb_layers.append(mark_embedding)

D
daminglu 已提交
80 81 82 83
    hidden_0_layers = [
        fluid.layers.fc(input=emb, size=hidden_dim, act='tanh')
        for emb in emb_layers
    ]
84

D
daminglu 已提交
85
    hidden_0 = fluid.layers.sums(input=hidden_0_layers)
86

D
daminglu 已提交
87
    lstm_0 = fluid.layers.dynamic_lstm(
88
        input=hidden_0,
D
daminglu 已提交
89 90 91 92
        size=hidden_dim,
        candidate_activation='relu',
        gate_activation='sigmoid',
        cell_activation='sigmoid')
93

D
daminglu 已提交
94
    # stack L-LSTM and R-LSTM with direct edges
95 96 97
    input_tmp = [hidden_0, lstm_0]

    for i in range(1, depth):
D
daminglu 已提交
98 99 100 101 102 103
        mix_hidden = fluid.layers.sums(input=[
            fluid.layers.fc(input=input_tmp[0], size=hidden_dim, act='tanh'),
            fluid.layers.fc(input=input_tmp[1], size=hidden_dim, act='tanh')
        ])

        lstm = fluid.layers.dynamic_lstm(
104
            input=mix_hidden,
D
daminglu 已提交
105 106 107 108 109
            size=hidden_dim,
            candidate_activation='relu',
            gate_activation='sigmoid',
            cell_activation='sigmoid',
            is_reverse=((i % 2) == 1))
110 111 112

        input_tmp = [mix_hidden, lstm]

D
daminglu 已提交
113 114 115 116
    feature_out = fluid.layers.sums(input=[
        fluid.layers.fc(input=input_tmp[0], size=label_dict_len, act='tanh'),
        fluid.layers.fc(input=input_tmp[1], size=label_dict_len, act='tanh')
    ])
117

118
    return feature_out
119 120


D
daminglu 已提交
121
def train(use_cuda, save_dirname=None, is_local=True):
Y
Yibing Liu 已提交
122
    # define data layers
Y
Yibing Liu 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    word = fluid.data(
        name='word_data', shape=[None, 1], dtype='int64', lod_level=1)
    predicate = fluid.data(
        name='verb_data', shape=[None, 1], dtype='int64', lod_level=1)
    ctx_n2 = fluid.data(
        name='ctx_n2_data', shape=[None, 1], dtype='int64', lod_level=1)
    ctx_n1 = fluid.data(
        name='ctx_n1_data', shape=[None, 1], dtype='int64', lod_level=1)
    ctx_0 = fluid.data(
        name='ctx_0_data', shape=[None, 1], dtype='int64', lod_level=1)
    ctx_p1 = fluid.data(
        name='ctx_p1_data', shape=[None, 1], dtype='int64', lod_level=1)
    ctx_p2 = fluid.data(
        name='ctx_p2_data', shape=[None, 1], dtype='int64', lod_level=1)
    mark = fluid.data(
        name='mark_data', shape=[None, 1], dtype='int64', lod_level=1)
139

u010070587's avatar
u010070587 已提交
140 141 142 143
    if args.enable_ce:
        fluid.default_startup_program().random_seed = 90
        fluid.default_main_program().random_seed = 90

144
    # define network topology
D
daminglu 已提交
145 146 147 148
    feature_out = db_lstm(**locals())
    target = fluid.layers.data(
        name='target', shape=[1], dtype='int64', lod_level=1)
    crf_cost = fluid.layers.linear_chain_crf(
149 150
        input=feature_out,
        label=target,
151
        param_attr=fluid.ParamAttr(name='crfw', learning_rate=mix_hidden_lr))
D
daminglu 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

    avg_cost = fluid.layers.mean(crf_cost)

    sgd_optimizer = fluid.optimizer.SGD(
        learning_rate=fluid.layers.exponential_decay(
            learning_rate=0.01,
            decay_steps=100000,
            decay_rate=0.5,
            staircase=True))

    sgd_optimizer.minimize(avg_cost)

    crf_decode = fluid.layers.crf_decoding(
        input=feature_out, param_attr=fluid.ParamAttr(name='crfw'))

u010070587's avatar
u010070587 已提交
167 168 169 170 171 172 173
    if args.enable_ce:
        train_data = paddle.batch(
            paddle.dataset.conll05.test(), batch_size=BATCH_SIZE)
    else:
        train_data = paddle.batch(
            paddle.reader.shuffle(paddle.dataset.conll05.test(), buf_size=8192),
            batch_size=BATCH_SIZE)
D
daminglu 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()

    feeder = fluid.DataFeeder(
        feed_list=[
            word, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2, predicate, mark, target
        ],
        place=place)
    exe = fluid.Executor(place)

    def train_loop(main_program):
        exe.run(fluid.default_startup_program())
        embedding_param = fluid.global_scope().find_var(
            embedding_name).get_tensor()
        embedding_param.set(
            load_parameter(conll05.get_embedding(), word_dict_len, word_dim),
            place)

        start_time = time.time()
        batch_id = 0
194
        for pass_id in six.moves.xrange(PASS_NUM):
D
daminglu 已提交
195
            for data in train_data():
196 197
                cost = exe.run(
                    main_program, feed=feeder.feed(data), fetch_list=[avg_cost])
D
daminglu 已提交
198 199 200 201 202
                cost = cost[0]

                if batch_id % 10 == 0:
                    print("avg_cost:" + str(cost))
                    if batch_id != 0:
203 204
                        print("second per batch: " + str((
                            time.time() - start_time) / batch_id))
D
daminglu 已提交
205 206
                    # Set the threshold low to speed up the CI test
                    if float(cost) < 60.0:
u010070587's avatar
u010070587 已提交
207 208 209
                        if args.enable_ce:
                            print("kpis\ttrain_cost\t%f" % cost)

D
daminglu 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                        if save_dirname is not None:
                            # TODO(liuyiqun): Change the target to crf_decode
                            fluid.io.save_inference_model(save_dirname, [
                                'word_data', 'verb_data', 'ctx_n2_data',
                                'ctx_n1_data', 'ctx_0_data', 'ctx_p1_data',
                                'ctx_p2_data', 'mark_data'
                            ], [feature_out], exe)
                        return

                batch_id = batch_id + 1

    train_loop(fluid.default_main_program())


def infer(use_cuda, save_dirname=None):
    if save_dirname is None:
        return

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)

    inference_scope = fluid.core.Scope()
    with fluid.scope_guard(inference_scope):
        # Use fluid.io.load_inference_model to obtain the inference program desc,
        # the feed_target_names (the names of variables that will be fed
        # data using feed operators), and the fetch_targets (variables that
        # we want to obtain data from using fetch operators).
        [inference_program, feed_target_names,
         fetch_targets] = fluid.io.load_inference_model(save_dirname, exe)

        # Setup inputs by creating LoDTensors to represent sequences of words.
        # Here each word is the basic element of these LoDTensors and the shape of
        # each word (base_shape) should be [1] since it is simply an index to
        # look up for the corresponding word vector.
        # Suppose the length_based level of detail (lod) info is set to [[3, 4, 2]],
        # which has only one lod level. Then the created LoDTensors will have only
        # one higher level structure (sequence of words, or sentence) than the basic
        # element (word). Hence the LoDTensor will hold data for three sentences of
        # length 3, 4 and 2, respectively.
        # Note that lod info should be a list of lists.
        lod = [[3, 4, 2]]
        base_shape = [1]
        # The range of random integers is [low, high]
        word = fluid.create_random_int_lodtensor(
            lod, base_shape, place, low=0, high=word_dict_len - 1)
        pred = fluid.create_random_int_lodtensor(
            lod, base_shape, place, low=0, high=pred_dict_len - 1)
        ctx_n2 = fluid.create_random_int_lodtensor(
            lod, base_shape, place, low=0, high=word_dict_len - 1)
        ctx_n1 = fluid.create_random_int_lodtensor(
            lod, base_shape, place, low=0, high=word_dict_len - 1)
        ctx_0 = fluid.create_random_int_lodtensor(
            lod, base_shape, place, low=0, high=word_dict_len - 1)
        ctx_p1 = fluid.create_random_int_lodtensor(
            lod, base_shape, place, low=0, high=word_dict_len - 1)
        ctx_p2 = fluid.create_random_int_lodtensor(
            lod, base_shape, place, low=0, high=word_dict_len - 1)
        mark = fluid.create_random_int_lodtensor(
            lod, base_shape, place, low=0, high=mark_dict_len - 1)

        # Construct feed as a dictionary of {feed_target_name: feed_target_data}
        # and results will contain a list of data corresponding to fetch_targets.
        assert feed_target_names[0] == 'word_data'
        assert feed_target_names[1] == 'verb_data'
        assert feed_target_names[2] == 'ctx_n2_data'
        assert feed_target_names[3] == 'ctx_n1_data'
        assert feed_target_names[4] == 'ctx_0_data'
        assert feed_target_names[5] == 'ctx_p1_data'
        assert feed_target_names[6] == 'ctx_p2_data'
        assert feed_target_names[7] == 'mark_data'

281 282 283 284 285 286 287 288 289 290 291 292 293 294
        results = exe.run(
            inference_program,
            feed={
                feed_target_names[0]: word,
                feed_target_names[1]: pred,
                feed_target_names[2]: ctx_n2,
                feed_target_names[3]: ctx_n1,
                feed_target_names[4]: ctx_0,
                feed_target_names[5]: ctx_p1,
                feed_target_names[6]: ctx_p2,
                feed_target_names[7]: mark
            },
            fetch_list=fetch_targets,
            return_numpy=False)
D
daminglu 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
        print(results[0].lod())
        np_data = np.array(results[0])
        print("Inference Shape: ", np_data.shape)


def main(use_cuda, is_local=True):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return

    # Directory for saving the trained model
    save_dirname = "label_semantic_roles.inference.model"

    train(use_cuda, save_dirname, is_local)
    infer(use_cuda, save_dirname)


u010070587's avatar
u010070587 已提交
311 312 313 314 315
if __name__ == '__main__':
    args = parse_args()
    use_cuda = args.use_gpu
    PASS_NUM = args.num_epochs
    main(use_cuda)