test_machine_translation.py 10.2 KB
Newer Older
D
dzhwinter 已提交
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
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.
Y
Yang Yu 已提交
14
import contextlib
D
dzhwinter 已提交
15

Y
Yan Chunwei 已提交
16 17
import numpy as np
import paddle.v2 as paddle
Q
Qiao Longfei 已提交
18
import paddle.v2.fluid as fluid
Y
Yan Chunwei 已提交
19
import paddle.v2.fluid.framework as framework
Q
Qiao Longfei 已提交
20
import paddle.v2.fluid.layers as pd
Q
Qiao Longfei 已提交
21
from paddle.v2.fluid.executor import Executor
Y
Yang Yu 已提交
22
import unittest
Y
Yan Chunwei 已提交
23 24 25

dict_size = 30000
source_dict_dim = target_dict_dim = dict_size
Q
Qiao Longfei 已提交
26 27
hidden_dim = 32
word_dim = 16
Q
Qiao Longfei 已提交
28 29
batch_size = 2
max_length = 8
Y
Yan Chunwei 已提交
30 31
topk_size = 50
trg_dic_size = 10000
Q
Qiao Longfei 已提交
32
beam_size = 2
Y
Yan Chunwei 已提交
33

Q
Qiao Longfei 已提交
34 35 36
decoder_size = hidden_dim


Y
Yang Yu 已提交
37
def encoder(is_sparse):
Q
Qiao Longfei 已提交
38
    # encoder
Q
Qiao Longfei 已提交
39
    src_word_id = pd.data(
Q
Qiao Longfei 已提交
40
        name="src_word_id", shape=[1], dtype='int64', lod_level=1)
Q
Qiao Longfei 已提交
41
    src_embedding = pd.embedding(
Q
Qiao Longfei 已提交
42 43 44
        input=src_word_id,
        size=[dict_size, word_dim],
        dtype='float32',
Y
Yang Yu 已提交
45
        is_sparse=is_sparse,
Q
Qiao Longfei 已提交
46 47
        param_attr=fluid.ParamAttr(name='vemb'))

Q
Qiao Longfei 已提交
48 49 50 51 52
    fc1 = pd.fc(input=src_embedding, size=hidden_dim * 4, act='tanh')
    lstm_hidden0, lstm_0 = pd.dynamic_lstm(input=fc1, size=hidden_dim * 4)
    encoder_out = pd.sequence_last_step(input=lstm_hidden0)
    return encoder_out

Q
Qiao Longfei 已提交
53

Y
Yang Yu 已提交
54
def decoder_train(context, is_sparse):
Q
Qiao Longfei 已提交
55
    # decoder
Q
Qiao Longfei 已提交
56
    trg_language_word = pd.data(
Q
Qiao Longfei 已提交
57
        name="target_language_word", shape=[1], dtype='int64', lod_level=1)
Q
Qiao Longfei 已提交
58
    trg_embedding = pd.embedding(
Q
Qiao Longfei 已提交
59 60 61
        input=trg_language_word,
        size=[dict_size, word_dim],
        dtype='float32',
Y
Yang Yu 已提交
62
        is_sparse=is_sparse,
Q
Qiao Longfei 已提交
63 64
        param_attr=fluid.ParamAttr(name='vemb'))

Q
Qiao Longfei 已提交
65
    rnn = pd.DynamicRNN()
Q
Qiao Longfei 已提交
66 67
    with rnn.block():
        current_word = rnn.step_input(trg_embedding)
Q
Qiao Longfei 已提交
68 69
        pre_state = rnn.memory(init=context)
        current_state = pd.fc(input=[current_word, pre_state],
Q
Qiao Longfei 已提交
70 71
                              size=decoder_size,
                              act='tanh')
Q
Qiao Longfei 已提交
72 73 74 75 76 77

        current_score = pd.fc(input=current_state,
                              size=target_dict_dim,
                              act='softmax')
        rnn.update_memory(pre_state, current_state)
        rnn.output(current_score)
Q
Qiao Longfei 已提交
78 79

    return rnn()
Y
Yan Chunwei 已提交
80 81


Y
Yang Yu 已提交
82
def decoder_decode(context, is_sparse):
Q
Qiao Longfei 已提交
83 84
    init_state = context
    array_len = pd.fill_constant(shape=[1], dtype='int64', value=max_length)
Y
Yang Yu 已提交
85
    counter = pd.zeros(shape=[1], dtype='int64', force_cpu=True)
Q
Qiao Longfei 已提交
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

    # fill the first element with init_state
    state_array = pd.create_array('float32')
    pd.array_write(init_state, array=state_array, i=counter)

    # ids, scores as memory
    ids_array = pd.create_array('int64')
    scores_array = pd.create_array('float32')

    init_ids = pd.data(name="init_ids", shape=[1], dtype="int64", lod_level=2)
    init_scores = pd.data(
        name="init_scores", shape=[1], dtype="float32", lod_level=2)

    pd.array_write(init_ids, array=ids_array, i=counter)
    pd.array_write(init_scores, array=scores_array, i=counter)

    cond = pd.less_than(x=counter, y=array_len)

    while_op = pd.While(cond=cond)
    with while_op.block():
        pre_ids = pd.array_read(array=ids_array, i=counter)
        pre_state = pd.array_read(array=state_array, i=counter)
        pre_score = pd.array_read(array=scores_array, i=counter)

        # expand the lod of pre_state to be the same with pre_score
        pre_state_expanded = pd.sequence_expand(pre_state, pre_score)

        pre_ids_emb = pd.embedding(
            input=pre_ids,
            size=[dict_size, word_dim],
            dtype='float32',
Y
Yang Yu 已提交
117
            is_sparse=is_sparse)
Q
Qiao Longfei 已提交
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

        # use rnn unit to update rnn
        current_state = pd.fc(input=[pre_ids_emb, pre_state_expanded],
                              size=decoder_size,
                              act='tanh')

        # use score to do beam search
        current_score = pd.fc(input=current_state,
                              size=target_dict_dim,
                              act='softmax')
        topk_scores, topk_indices = pd.topk(current_score, k=50)
        selected_ids, selected_scores = pd.beam_search(
            pre_ids, topk_indices, topk_scores, beam_size, end_id=10, level=0)

        pd.increment(x=counter, value=1, in_place=True)

        # update the memories
        pd.array_write(current_state, array=state_array, i=counter)
        pd.array_write(selected_ids, array=ids_array, i=counter)
        pd.array_write(selected_scores, array=scores_array, i=counter)

        pd.less_than(x=counter, y=array_len, cond=cond)

    translation_ids, translation_scores = pd.beam_search_decode(
        ids=ids_array, scores=scores_array)

    # return init_ids, init_scores

    return translation_ids, translation_scores


def set_init_lod(data, lod, place):
Y
Yang Yu 已提交
150
    res = fluid.LoDTensor()
Q
Qiao Longfei 已提交
151 152 153 154 155
    res.set(data, place)
    res.set_lod(lod)
    return res


Y
Yan Chunwei 已提交
156 157 158 159 160 161 162 163 164
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])
Y
Yang Yu 已提交
165
    res = fluid.LoDTensor()
Y
Yan Chunwei 已提交
166 167 168 169 170
    res.set(flattened_data, place)
    res.set_lod([lod])
    return res


Y
Yang Yu 已提交
171 172 173 174 175 176 177
def train_main(use_cuda, is_sparse):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()

    context = encoder(is_sparse)
    rnn_out = decoder_train(context, is_sparse)
Q
Qiao Longfei 已提交
178
    label = pd.data(
Q
Qiao Longfei 已提交
179
        name="target_language_next_word", shape=[1], dtype='int64', lod_level=1)
Q
Qiao Longfei 已提交
180 181
    cost = pd.cross_entropy(input=rnn_out, label=label)
    avg_cost = pd.mean(x=cost)
Q
Qiao Longfei 已提交
182 183 184

    optimizer = fluid.optimizer.Adagrad(learning_rate=1e-4)
    optimizer.minimize(avg_cost)
Y
Yan Chunwei 已提交
185 186 187

    train_data = paddle.batch(
        paddle.reader.shuffle(
Q
Qiao Longfei 已提交
188
            paddle.dataset.wmt14.train(dict_size), buf_size=1000),
Y
Yan Chunwei 已提交
189 190 191 192 193 194 195
        batch_size=batch_size)

    exe = Executor(place)

    exe.run(framework.default_startup_program())

    batch_id = 0
Q
Qiao Longfei 已提交
196
    for pass_id in xrange(1):
Y
Yan Chunwei 已提交
197 198
        for data in train_data():
            word_data = to_lodtensor(map(lambda x: x[0], data), place)
Q
Qiao Longfei 已提交
199 200
            trg_word = to_lodtensor(map(lambda x: x[1], data), place)
            trg_word_next = to_lodtensor(map(lambda x: x[2], data), place)
Y
Yan Chunwei 已提交
201
            outs = exe.run(framework.default_main_program(),
Q
Qiao Longfei 已提交
202 203 204 205 206 207 208 209 210 211
                           feed={
                               'src_word_id': word_data,
                               'target_language_word': trg_word,
                               'target_language_next_word': trg_word_next
                           },
                           fetch_list=[avg_cost])
            avg_cost_val = np.array(outs[0])
            print('pass_id=' + str(pass_id) + ' batch=' + str(batch_id) +
                  " avg_cost=" + str(avg_cost_val))
            if batch_id > 3:
Q
Qiao Longfei 已提交
212
                break
Q
Qiao Longfei 已提交
213
            batch_id += 1
Y
Yan Chunwei 已提交
214 215


Y
Yang Yu 已提交
216 217 218 219 220 221 222
def decode_main(use_cuda, is_sparse):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()

    context = encoder(is_sparse)
    translation_ids, translation_scores = decoder_decode(context, is_sparse)
Q
Qiao Longfei 已提交
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

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

    init_ids_data = np.array([1 for _ in range(batch_size)], dtype='int64')
    init_scores_data = np.array(
        [1. for _ in range(batch_size)], dtype='float32')
    init_ids_data = init_ids_data.reshape((batch_size, 1))
    init_scores_data = init_scores_data.reshape((batch_size, 1))
    init_lod = [i for i in range(batch_size)] + [batch_size]
    init_lod = [init_lod, init_lod]

    train_data = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.wmt14.train(dict_size), buf_size=1000),
        batch_size=batch_size)
    for _, data in enumerate(train_data()):
        init_ids = set_init_lod(init_ids_data, init_lod, place)
        init_scores = set_init_lod(init_scores_data, init_lod, place)

        src_word_data = to_lodtensor(map(lambda x: x[0], data), place)

        result_ids, result_scores = exe.run(
            framework.default_main_program(),
            feed={
                'src_word_id': src_word_data,
                'init_ids': init_ids,
                'init_scores': init_scores
            },
            fetch_list=[translation_ids, translation_scores],
            return_numpy=False)
        print result_ids.lod()
        break


Y
Yang Yu 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
class TestMachineTranslation(unittest.TestCase):
    pass


@contextlib.contextmanager
def scope_prog_guard():
    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 inject_test_train(use_cuda, is_sparse):
    f_name = 'test_{0}_{1}_train'.format('cuda' if use_cuda else 'cpu', 'sparse'
                                         if is_sparse else 'dense')

    def f(*args):
        with scope_prog_guard():
            train_main(use_cuda, is_sparse)

    setattr(TestMachineTranslation, f_name, f)


def inject_test_decode(use_cuda, is_sparse, decorator=None):
    f_name = 'test_{0}_{1}_decode'.format('cuda'
                                          if use_cuda else 'cpu', 'sparse'
                                          if is_sparse else 'dense')

    def f(*args):
        with scope_prog_guard():
            decode_main(use_cuda, is_sparse)

    if decorator is not None:
        f = decorator(f)

    setattr(TestMachineTranslation, f_name, f)


for _use_cuda_ in (False, True):
    for _is_sparse_ in (False, True):
        inject_test_train(_use_cuda_, _is_sparse_)

for _use_cuda_ in (False, True):
    for _is_sparse_ in (False, True):

        _decorator_ = None
        if _use_cuda_:
            _decorator_ = unittest.skip(
                reason='Beam Search does not support CUDA!')

        inject_test_decode(
            is_sparse=_is_sparse_, use_cuda=_use_cuda_, decorator=_decorator_)

Y
Yan Chunwei 已提交
313
if __name__ == '__main__':
Y
Yang Yu 已提交
314
    unittest.main()