test_machine_translation.py 11.8 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

from __future__ import print_function
Y
Yang Yu 已提交
16
import contextlib
D
dzhwinter 已提交
17

Y
Yan Chunwei 已提交
18
import numpy as np
19
import paddle
20 21 22 23
import paddle.fluid as fluid
import paddle.fluid.framework as framework
import paddle.fluid.layers as pd
from paddle.fluid.executor import Executor
Y
Yang Yu 已提交
24
import unittest
武毅 已提交
25
import os
Y
Yan Chunwei 已提交
26 27 28

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

Q
Qiao Longfei 已提交
37 38 39
decoder_size = hidden_dim


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

Q
Qiao Longfei 已提交
51 52 53 54 55
    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 已提交
56

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

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

        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 已提交
81 82

    return rnn()
Y
Yan Chunwei 已提交
83 84


Y
Yang Yu 已提交
85
def decoder_decode(context, is_sparse):
Q
Qiao Longfei 已提交
86 87
    init_state = context
    array_len = pd.fill_constant(shape=[1], dtype='int64', value=max_length)
Y
Yang Yu 已提交
88
    counter = pd.zeros(shape=[1], dtype='int64', force_cpu=True)
Q
Qiao Longfei 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

    # 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)

113
        # expand the recursive_sequence_lengths of pre_state to be the same with pre_score
Q
Qiao Longfei 已提交
114 115 116 117 118 119
        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 已提交
120
            is_sparse=is_sparse)
Q
Qiao Longfei 已提交
121 122

        # use rnn unit to update rnn
123
        current_state = pd.fc(input=[pre_state_expanded, pre_ids_emb],
Q
Qiao Longfei 已提交
124 125
                              size=decoder_size,
                              act='tanh')
126
        current_state_with_lod = pd.lod_reset(x=current_state, y=pre_score)
Q
Qiao Longfei 已提交
127
        # use score to do beam search
128
        current_score = pd.fc(input=current_state_with_lod,
Q
Qiao Longfei 已提交
129 130
                              size=target_dict_dim,
                              act='softmax')
131 132 133 134 135
        topk_scores, topk_indices = pd.topk(current_score, k=beam_size)
        # calculate accumulated scores after topk to reduce computation cost
        accu_scores = pd.elementwise_add(
            x=pd.log(topk_scores), y=pd.reshape(
                pre_score, shape=[-1]), axis=0)
Q
Qiao Longfei 已提交
136
        selected_ids, selected_scores = pd.beam_search(
137 138 139 140 141 142 143
            pre_ids,
            pre_score,
            topk_indices,
            accu_scores,
            beam_size,
            end_id=10,
            level=0)
Q
Qiao Longfei 已提交
144 145 146 147 148 149 150 151

        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)

152 153 154 155 156
        # update the break condition: up to the max length or all candidates of
        # source sentences have ended.
        length_cond = pd.less_than(x=counter, y=array_len)
        finish_cond = pd.logical_not(pd.is_empty(x=selected_ids))
        pd.logical_and(x=length_cond, y=finish_cond, out=cond)
Q
Qiao Longfei 已提交
157 158

    translation_ids, translation_scores = pd.beam_search_decode(
159
        ids=ids_array, scores=scores_array, beam_size=beam_size, end_id=10)
Q
Qiao Longfei 已提交
160 161 162 163 164 165

    # return init_ids, init_scores

    return translation_ids, translation_scores


武毅 已提交
166
def train_main(use_cuda, is_sparse, is_local=True):
Y
Yang Yu 已提交
167 168 169 170 171 172
    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 已提交
173
    label = pd.data(
Q
Qiao Longfei 已提交
174
        name="target_language_next_word", shape=[1], dtype='int64', lod_level=1)
Q
Qiao Longfei 已提交
175
    cost = pd.cross_entropy(input=rnn_out, label=label)
Y
Yu Yang 已提交
176
    avg_cost = pd.mean(cost)
Q
Qiao Longfei 已提交
177

178 179 180 181
    optimizer = fluid.optimizer.Adagrad(
        learning_rate=1e-4,
        regularization=fluid.regularizer.L2DecayRegularizer(
            regularization_coeff=0.1))
W
Wu Yi 已提交
182
    optimizer.minimize(avg_cost)
Y
Yan Chunwei 已提交
183 184 185

    train_data = paddle.batch(
        paddle.reader.shuffle(
Q
Qiao Longfei 已提交
186
            paddle.dataset.wmt14.train(dict_size), buf_size=1000),
Y
Yan Chunwei 已提交
187 188
        batch_size=batch_size)

189 190 191 192
    feed_order = [
        'src_word_id', 'target_language_word', 'target_language_next_word'
    ]

Y
Yan Chunwei 已提交
193 194
    exe = Executor(place)

武毅 已提交
195 196 197
    def train_loop(main_program):
        exe.run(framework.default_startup_program())

198 199 200 201 202
        feed_list = [
            main_program.global_block().var(var_name) for var_name in feed_order
        ]
        feeder = fluid.DataFeeder(feed_list, place)

武毅 已提交
203
        batch_id = 0
204
        for pass_id in range(1):
武毅 已提交
205 206
            for data in train_data():
                outs = exe.run(main_program,
207
                               feed=feeder.feed(data),
武毅 已提交
208 209
                               fetch_list=[avg_cost])
                avg_cost_val = np.array(outs[0])
210 211
                print('pass_id=' + str(pass_id) + ' batch=' + str(batch_id) +
                      " avg_cost=" + str(avg_cost_val))
武毅 已提交
212 213 214 215 216 217 218
                if batch_id > 3:
                    break
                batch_id += 1

    if is_local:
        train_loop(framework.default_main_program())
    else:
G
gongweibao 已提交
219 220
        port = os.getenv("PADDLE_PSERVER_PORT", "6174")
        pserver_ips = os.getenv("PADDLE_PSERVER_IPS")  # ip,ip...
武毅 已提交
221 222 223 224
        eplist = []
        for ip in pserver_ips.split(","):
            eplist.append(':'.join([ip, port]))
        pserver_endpoints = ",".join(eplist)  # ip:port,ip:port...
G
gongweibao 已提交
225
        trainers = int(os.getenv("PADDLE_TRAINERS"))
武毅 已提交
226
        current_endpoint = os.getenv("POD_IP") + ":" + port
G
gongweibao 已提交
227 228
        trainer_id = int(os.getenv("PADDLE_TRAINER_ID"))
        training_role = os.getenv("PADDLE_TRAINING_ROLE", "TRAINER")
武毅 已提交
229
        t = fluid.DistributeTranspiler()
Y
Yancey1989 已提交
230
        t.transpile(trainer_id, pservers=pserver_endpoints, trainers=trainers)
武毅 已提交
231 232 233 234 235 236 237 238
        if training_role == "PSERVER":
            pserver_prog = t.get_pserver_program(current_endpoint)
            pserver_startup = t.get_startup_program(current_endpoint,
                                                    pserver_prog)
            exe.run(pserver_startup)
            exe.run(pserver_prog)
        elif training_role == "TRAINER":
            train_loop(t.get_trainer_program())
Y
Yan Chunwei 已提交
239 240


Y
Yang Yu 已提交
241 242 243 244 245 246 247
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 已提交
248 249 250 251 252 253 254 255 256

    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))
257 258
    init_recursive_seq_lens = [1] * batch_size
    init_recursive_seq_lens = [init_recursive_seq_lens, init_recursive_seq_lens]
Q
Qiao Longfei 已提交
259

260 261 262 263
    init_ids = fluid.create_lod_tensor(init_ids_data, init_recursive_seq_lens,
                                       place)
    init_scores = fluid.create_lod_tensor(init_scores_data,
                                          init_recursive_seq_lens, place)
264

Q
Qiao Longfei 已提交
265 266 267 268 269
    train_data = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.wmt14.train(dict_size), buf_size=1000),
        batch_size=batch_size)

270 271 272 273 274 275 276 277
    feed_order = ['src_word_id']
    feed_list = [
        framework.default_main_program().global_block().var(var_name)
        for var_name in feed_order
    ]
    feeder = fluid.DataFeeder(feed_list, place)

    for data in train_data():
278
        feed_dict = feeder.feed([[x[0]] for x in data])
279 280
        feed_dict['init_ids'] = init_ids
        feed_dict['init_scores'] = init_scores
Q
Qiao Longfei 已提交
281 282 283

        result_ids, result_scores = exe.run(
            framework.default_main_program(),
284
            feed=feed_dict,
Q
Qiao Longfei 已提交
285 286
            fetch_list=[translation_ids, translation_scores],
            return_numpy=False)
287
        print(result_ids.recursive_sequence_lengths())
Q
Qiao Longfei 已提交
288 289 290
        break


Y
Yang Yu 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
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 已提交
346
if __name__ == '__main__':
Y
Yang Yu 已提交
347
    unittest.main()