notest_understand_sentiment.py 13.2 KB
Newer Older
1
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13
# 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.
14

15
import unittest
16
import paddle.fluid as fluid
17
import paddle
18
import contextlib
19
import math
20
import numpy as np
21
import sys
武毅 已提交
22
import os
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
def convolution_net(
    data, label, input_dim, class_dim=2, emb_dim=32, hid_dim=32
):
    emb = fluid.layers.embedding(
        input=data, size=[input_dim, emb_dim], is_sparse=True
    )
    conv_3 = fluid.nets.sequence_conv_pool(
        input=emb,
        num_filters=hid_dim,
        filter_size=3,
        act="tanh",
        pool_type="sqrt",
    )
    conv_4 = fluid.nets.sequence_conv_pool(
        input=emb,
        num_filters=hid_dim,
        filter_size=4,
        act="tanh",
        pool_type="sqrt",
    )
    prediction = fluid.layers.fc(
        input=[conv_3, conv_4], size=class_dim, act="softmax"
    )
48
    cost = fluid.layers.cross_entropy(input=prediction, label=label)
49
    avg_cost = paddle.mean(cost)
50
    accuracy = fluid.layers.accuracy(input=prediction, label=label)
51
    return avg_cost, accuracy, prediction
Q
QI JUN 已提交
52 53


54 55 56 57 58 59
def dyn_rnn_lstm(
    data, label, input_dim, class_dim=2, emb_dim=32, lstm_size=128
):
    emb = fluid.layers.embedding(
        input=data, size=[input_dim, emb_dim], is_sparse=True
    )
Y
Yu Yang 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72
    sentence = fluid.layers.fc(input=emb, size=lstm_size, act='tanh')

    rnn = fluid.layers.DynamicRNN()
    with rnn.block():
        word = rnn.step_input(sentence)
        prev_hidden = rnn.memory(value=0.0, shape=[lstm_size])
        prev_cell = rnn.memory(value=0.0, shape=[lstm_size])

        def gate_common(ipt, hidden, size):
            gate0 = fluid.layers.fc(input=ipt, size=size, bias_attr=True)
            gate1 = fluid.layers.fc(input=hidden, size=size, bias_attr=False)
            return gate0 + gate1

73
        forget_gate = paddle.nn.functional.sigmoid(
74 75
            x=gate_common(word, prev_hidden, lstm_size)
        )
76
        input_gate = paddle.nn.functional.sigmoid(
77 78
            x=gate_common(word, prev_hidden, lstm_size)
        )
79
        output_gate = paddle.nn.functional.sigmoid(
80 81
            x=gate_common(word, prev_hidden, lstm_size)
        )
82
        cell_gate = paddle.nn.functional.sigmoid(
83 84
            x=gate_common(word, prev_hidden, lstm_size)
        )
Y
Yu Yang 已提交
85 86

        cell = forget_gate * prev_cell + input_gate * cell_gate
87
        hidden = output_gate * paddle.tanh(x=cell)
Y
Yu Yang 已提交
88 89 90 91 92 93 94
        rnn.update_memory(prev_cell, cell)
        rnn.update_memory(prev_hidden, hidden)
        rnn.output(hidden)

    last = fluid.layers.sequence_last_step(rnn())
    prediction = fluid.layers.fc(input=last, size=class_dim, act="softmax")
    cost = fluid.layers.cross_entropy(input=prediction, label=label)
95
    avg_cost = paddle.mean(cost)
Y
Yu Yang 已提交
96 97 98 99
    accuracy = fluid.layers.accuracy(input=prediction, label=label)
    return avg_cost, accuracy, prediction


100 101 102
def stacked_lstm_net(
    data, label, input_dim, class_dim=2, emb_dim=128, hid_dim=512, stacked_num=3
):
Q
QI JUN 已提交
103 104
    assert stacked_num % 2 == 1

105 106 107
    emb = fluid.layers.embedding(
        input=data, size=[input_dim, emb_dim], is_sparse=True
    )
Q
QI JUN 已提交
108 109 110
    # add bias attr

    # TODO(qijun) linear act
111 112
    fc1 = fluid.layers.fc(input=emb, size=hid_dim)
    lstm1, cell1 = fluid.layers.dynamic_lstm(input=fc1, size=hid_dim)
Q
QI JUN 已提交
113 114 115 116

    inputs = [fc1, lstm1]

    for i in range(2, stacked_num + 1):
117
        fc = fluid.layers.fc(input=inputs, size=hid_dim)
118 119 120
        lstm, cell = fluid.layers.dynamic_lstm(
            input=fc, size=hid_dim, is_reverse=(i % 2) == 0
        )
Q
QI JUN 已提交
121 122
        inputs = [fc, lstm]

123 124
    fc_last = fluid.layers.sequence_pool(input=inputs[0], pool_type='max')
    lstm_last = fluid.layers.sequence_pool(input=inputs[1], pool_type='max')
Q
QI JUN 已提交
125

126 127 128
    prediction = fluid.layers.fc(
        input=[fc_last, lstm_last], size=class_dim, act='softmax'
    )
129
    cost = fluid.layers.cross_entropy(input=prediction, label=label)
130
    avg_cost = paddle.mean(cost)
131
    accuracy = fluid.layers.accuracy(input=prediction, label=label)
132
    return avg_cost, accuracy, prediction
Q
QI JUN 已提交
133

134

135 136 137 138 139 140 141 142
def train(
    word_dict,
    net_method,
    use_cuda,
    parallel=False,
    save_dirname=None,
    is_local=True,
):
143 144
    BATCH_SIZE = 128
    PASS_NUM = 5
Q
QI JUN 已提交
145 146 147
    dict_dim = len(word_dict)
    class_dim = 2

148 149 150
    data = fluid.layers.data(
        name="words", shape=[1], dtype="int64", lod_level=1
    )
Y
Yu Yang 已提交
151
    label = fluid.layers.data(name="label", shape=[1], dtype="int64")
152 153

    if not parallel:
154 155 156
        cost, acc_out, prediction = net_method(
            data, label, input_dim=dict_dim, class_dim=class_dim
        )
157
    else:
X
Xin Pan 已提交
158
        raise NotImplementedError()
159 160

    adagrad = fluid.optimizer.Adagrad(learning_rate=0.002)
W
Wu Yi 已提交
161
    adagrad.minimize(cost)
Q
QI JUN 已提交
162

163 164 165 166 167 168
    train_data = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.imdb.train(word_dict), buf_size=1000
        ),
        batch_size=BATCH_SIZE,
    )
169
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
170
    exe = fluid.Executor(place)
Y
Yu Yang 已提交
171
    feeder = fluid.DataFeeder(feed_list=[data, label], place=place)
Q
QI JUN 已提交
172

武毅 已提交
173 174 175
    def train_loop(main_program):
        exe.run(fluid.default_startup_program())

176
        for pass_id in range(PASS_NUM):
武毅 已提交
177
            for data in train_data():
178 179 180 181 182
                cost_val, acc_val = exe.run(
                    main_program,
                    feed=feeder.feed(data),
                    fetch_list=[cost, acc_out],
                )
183
                print("cost=" + str(cost_val) + " acc=" + str(acc_val))
武毅 已提交
184 185
                if cost_val < 0.4 and acc_val > 0.8:
                    if save_dirname is not None:
186 187 188
                        fluid.io.save_inference_model(
                            save_dirname, ["words"], prediction, exe
                        )
武毅 已提交
189 190 191
                    return
                if math.isnan(float(cost_val)):
                    sys.exit("got NaN loss, training failed.")
192 193 194
        raise AssertionError(
            "Cost is too large for {0}".format(net_method.__name__)
        )
武毅 已提交
195 196 197 198

    if is_local:
        train_loop(fluid.default_main_program())
    else:
G
gongweibao 已提交
199 200
        port = os.getenv("PADDLE_PSERVER_PORT", "6174")
        pserver_ips = os.getenv("PADDLE_PSERVER_IPS")  # ip,ip...
武毅 已提交
201 202 203 204
        eplist = []
        for ip in pserver_ips.split(","):
            eplist.append(':'.join([ip, port]))
        pserver_endpoints = ",".join(eplist)  # ip:port,ip:port...
G
gongweibao 已提交
205
        trainers = int(os.getenv("PADDLE_TRAINERS"))
武毅 已提交
206
        current_endpoint = os.getenv("POD_IP") + ":" + port
G
gongweibao 已提交
207 208
        trainer_id = int(os.getenv("PADDLE_TRAINER_ID"))
        training_role = os.getenv("PADDLE_TRAINING_ROLE", "TRAINER")
武毅 已提交
209
        t = fluid.DistributeTranspiler()
Y
Yancey1989 已提交
210
        t.transpile(trainer_id, pservers=pserver_endpoints, trainers=trainers)
武毅 已提交
211 212
        if training_role == "PSERVER":
            pserver_prog = t.get_pserver_program(current_endpoint)
213 214 215
            pserver_startup = t.get_startup_program(
                current_endpoint, pserver_prog
            )
武毅 已提交
216 217 218 219
            exe.run(pserver_startup)
            exe.run(pserver_prog)
        elif training_role == "TRAINER":
            train_loop(t.get_trainer_program())
220 221


L
Liu Yiqun 已提交
222
def infer(word_dict, use_cuda, save_dirname=None):
223 224 225 226 227 228
    if save_dirname is None:
        return

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

229 230 231
    inference_scope = fluid.core.Scope()
    with fluid.scope_guard(inference_scope):
        # Use fluid.io.load_inference_model to obtain the inference program desc,
T
tianshuo78520a 已提交
232
        # the feed_target_names (the names of variables that will be fed
233 234
        # data using feed operators), and the fetch_targets (variables that
        # we want to obtain data from using fetch operators).
235 236 237 238 239
        [
            inference_program,
            feed_target_names,
            fetch_targets,
        ] = fluid.io.load_inference_model(save_dirname, exe)
240 241 242

        word_dict_len = len(word_dict)

K
Kexin Zhao 已提交
243
        # Setup input by creating LoDTensor to represent sequence of words.
244 245
        # Here each word is the basic element of the LoDTensor and the shape of
        # each word (base_shape) should be [1] since it is simply an index to
K
Kexin Zhao 已提交
246
        # look up for the corresponding word vector.
247
        # Suppose the recursive_sequence_lengths info is set to [[3, 4, 2]],
248 249 250 251
        # which has only one level of detail. Then the created LoDTensor 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.
252 253
        # Note that recursive_sequence_lengths should be a list of lists.
        recursive_seq_lens = [[3, 4, 2]]
K
Kexin Zhao 已提交
254 255
        base_shape = [1]
        # The range of random integers is [low, high]
256 257 258
        tensor_words = fluid.create_random_int_lodtensor(
            recursive_seq_lens, base_shape, place, low=0, high=word_dict_len - 1
        )
259 260 261 262

        # 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] == "words"
263 264 265 266 267 268
        results = exe.run(
            inference_program,
            feed={feed_target_names[0]: tensor_words},
            fetch_list=fetch_targets,
            return_numpy=False,
        )
269
        print(results[0].recursive_sequence_lengths())
270
        np_data = np.array(results[0])
271 272
        print("Inference Shape: ", np_data.shape)
        print("Inference results: ", np_data)
273 274


275
def main(word_dict, net_method, use_cuda, parallel=False, save_dirname=None):
276 277 278
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return

279 280 281 282 283 284 285
    train(
        word_dict,
        net_method,
        use_cuda,
        parallel=parallel,
        save_dirname=save_dirname,
    )
286
    infer(word_dict, use_cuda, save_dirname)
287 288


289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
class TestUnderstandSentiment(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.word_dict = paddle.dataset.imdb.word_dict()

    @contextlib.contextmanager
    def new_program_scope(self):
        prog = fluid.Program()
        startup_prog = fluid.Program()
        scope = fluid.core.Scope()
        with fluid.scope_guard(scope):
            with fluid.program_guard(prog, startup_prog):
                yield

    def test_conv_cpu(self):
        with self.new_program_scope():
305 306 307 308 309 310
            main(
                self.word_dict,
                net_method=convolution_net,
                use_cuda=False,
                save_dirname="understand_sentiment_conv.inference.model",
            )
311

312 313
    def test_conv_cpu_parallel(self):
        with self.new_program_scope():
314 315 316 317 318 319
            main(
                self.word_dict,
                net_method=convolution_net,
                use_cuda=False,
                parallel=True,
            )
320 321

    @unittest.skip(reason="make CI faster")
322 323
    def test_stacked_lstm_cpu(self):
        with self.new_program_scope():
324 325 326 327
            main(
                self.word_dict,
                net_method=stacked_lstm_net,
                use_cuda=False,
328
                save_dirname="understand_sentiment_stacked_lstm.inference.model",
329
            )
330

331 332
    def test_stacked_lstm_cpu_parallel(self):
        with self.new_program_scope():
333 334 335 336 337 338
            main(
                self.word_dict,
                net_method=stacked_lstm_net,
                use_cuda=False,
                parallel=True,
            )
339

340 341
    def test_conv_gpu(self):
        with self.new_program_scope():
342 343 344 345 346 347
            main(
                self.word_dict,
                net_method=convolution_net,
                use_cuda=True,
                save_dirname="understand_sentiment_conv.inference.model",
            )
348 349 350

    def test_conv_gpu_parallel(self):
        with self.new_program_scope():
351 352 353 354 355 356
            main(
                self.word_dict,
                net_method=convolution_net,
                use_cuda=True,
                parallel=True,
            )
357

358
    @unittest.skip(reason="make CI faster")
359 360
    def test_stacked_lstm_gpu(self):
        with self.new_program_scope():
361 362 363 364
            main(
                self.word_dict,
                net_method=stacked_lstm_net,
                use_cuda=True,
365
                save_dirname="understand_sentiment_stacked_lstm.inference.model",
366
            )
Q
QI JUN 已提交
367

368 369
    def test_stacked_lstm_gpu_parallel(self):
        with self.new_program_scope():
370 371 372 373 374 375
            main(
                self.word_dict,
                net_method=stacked_lstm_net,
                use_cuda=True,
                parallel=True,
            )
376

Y
Yu Yang 已提交
377 378 379
    @unittest.skip(reason='make CI faster')
    def test_dynrnn_lstm_gpu(self):
        with self.new_program_scope():
380 381 382 383 384 385
            main(
                self.word_dict,
                net_method=dyn_rnn_lstm,
                use_cuda=True,
                parallel=False,
            )
Y
Yu Yang 已提交
386 387 388

    def test_dynrnn_lstm_gpu_parallel(self):
        with self.new_program_scope():
389 390 391 392 393 394
            main(
                self.word_dict,
                net_method=dyn_rnn_lstm,
                use_cuda=True,
                parallel=True,
            )
Y
Yu Yang 已提交
395

Q
QI JUN 已提交
396 397

if __name__ == '__main__':
398
    unittest.main()