test_export_n_load_module.py 6.5 KB
Newer Older
Z
Zeyu Chen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#   Copyright (c) 2019  PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

from __future__ import print_function
from __future__ import division
from __future__ import print_function

import numpy as np
import paddle.fluid as fluid
import paddle
W
wuzewu 已提交
22
import paddlehub as hub
Z
Zeyu Chen 已提交
23 24 25
import unittest
import os

Z
Zeyu Chen 已提交
26 27
from collections import defaultdict

Z
Zeyu Chen 已提交
28 29 30 31
EMBED_SIZE = 16
HIDDEN_SIZE = 256
N = 5
BATCH_SIZE = 64
32
PASS_NUM = 1000
Z
Zeyu Chen 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45

word_dict = paddle.dataset.imikolov.build_dict()
dict_size = len(word_dict)
data = paddle.dataset.imikolov.train(word_dict, N)

_MOCK_DATA = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]


def mock_data():
    for d in _MOCK_DATA:
        yield d


Z
Zeyu Chen 已提交
46 47
batch_reader = paddle.batch(mock_data, BATCH_SIZE)
#batch_reader = paddle.batch(data, BATCH_SIZE)
Z
Zeyu Chen 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
batch_size = 0
for d in batch_reader():
    batch_size += 1


def word2vec(words, is_sparse, trainable=True):
    emb_param_attr = fluid.ParamAttr(name="embedding", trainable=trainable)
    embed_first = fluid.layers.embedding(
        input=words[0],
        size=[dict_size, EMBED_SIZE],
        dtype='float32',
        is_sparse=is_sparse,
        param_attr=emb_param_attr)
    embed_second = fluid.layers.embedding(
        input=words[1],
        size=[dict_size, EMBED_SIZE],
        dtype='float32',
        is_sparse=is_sparse,
        param_attr=emb_param_attr)
    embed_third = fluid.layers.embedding(
        input=words[2],
        size=[dict_size, EMBED_SIZE],
        dtype='float32',
        is_sparse=is_sparse,
        param_attr=emb_param_attr)
    embed_fourth = fluid.layers.embedding(
        input=words[3],
        size=[dict_size, EMBED_SIZE],
        dtype='float32',
        is_sparse=is_sparse,
        param_attr=emb_param_attr)

    concat_emb = fluid.layers.concat(
        input=[embed_first, embed_second, embed_third, embed_fourth], axis=1)
    hidden1 = fluid.layers.fc(input=concat_emb, size=HIDDEN_SIZE, act='sigmoid')
83
    pred_prob = fluid.layers.fc(input=hidden1, size=dict_size, act='softmax')
Z
Zeyu Chen 已提交
84 85 86 87

    # declare later than predict word
    next_word = fluid.layers.data(name='nextw', shape=[1], dtype='int64')

88
    cost = fluid.layers.cross_entropy(input=pred_prob, label=next_word)
Z
Zeyu Chen 已提交
89 90
    avg_cost = fluid.layers.mean(cost)

91 92 93 94 95 96 97 98 99 100 101 102 103
    return pred_prob, avg_cost


def get_dictionary(word_dict):
    dictionary = defaultdict(int)
    w_id = 0
    for w in word_dict:
        if isinstance(w, bytes):
            w = w.decode("ascii")
        dictionary[w] = w_id
        w_id += 1

    return dictionary
Z
Zeyu Chen 已提交
104 105


106 107
def test_create_w2v_module(use_gpu=False):
    place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
Z
Zeyu Chen 已提交
108 109 110 111 112 113 114 115

    first_word = fluid.layers.data(name='firstw', shape=[1], dtype='int64')
    second_word = fluid.layers.data(name='secondw', shape=[1], dtype='int64')
    third_word = fluid.layers.data(name='thirdw', shape=[1], dtype='int64')
    forth_word = fluid.layers.data(name='fourthw', shape=[1], dtype='int64')
    next_word = fluid.layers.data(name='nextw', shape=[1], dtype='int64')

    word_list = [first_word, second_word, third_word, forth_word, next_word]
116
    pred_prob, avg_cost = word2vec(word_list, is_sparse=True)
Z
Zeyu Chen 已提交
117 118 119 120

    main_program = fluid.default_main_program()
    startup_program = fluid.default_startup_program()

121
    sgd_optimizer = fluid.optimizer.SGDOptimizer(learning_rate=1e-2)
Z
Zeyu Chen 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

    sgd_optimizer.minimize(avg_cost)
    exe = fluid.Executor(place)
    exe.run(startup_program)  # initialization

    step = 0
    for epoch in range(0, PASS_NUM):
        for mini_batch in batch_reader():
            feed_var_list = [
                main_program.global_block().var("firstw"),
                main_program.global_block().var("secondw"),
                main_program.global_block().var("thirdw"),
                main_program.global_block().var("fourthw"),
                main_program.global_block().var("nextw")
            ]
            feeder = fluid.DataFeeder(feed_list=feed_var_list, place=place)
            cost = exe.run(
                main_program,
                feed=feeder.feed(mini_batch),
                fetch_list=[avg_cost])
            step += 1
            if step % 100 == 0:
                print("Epoch={} Step={} Cost={}".format(epoch, step, cost[0]))

146
    saved_module_dir = "./tmp/word2vec_test_module"
Z
Zeyu Chen 已提交
147
    # save inference model including feed and fetch variable info
148 149 150 151 152 153 154 155 156
    dictionary = get_dictionary(word_dict)

    module_inputs = [
        main_program.global_block().var("firstw"),
        main_program.global_block().var("secondw"),
        main_program.global_block().var("thirdw"),
        main_program.global_block().var("fourthw"),
    ]
    signature = hub.create_signature(
157 158 159 160 161
        "default",
        inputs=module_inputs,
        outputs=[pred_prob],
        feed_names=["firstw", "secondw", "thirdw", "fourthw"],
        fetch_names=["pred_prob"])
162
    hub.create_module(
163
        sign_arr=signature, module_dir=saved_module_dir, word_dict=dictionary)
164 165 166


def test_load_w2v_module(use_gpu=False):
Z
Zeyu Chen 已提交
167 168
    saved_module_dir = "./tmp/word2vec_test_module"
    w2v_module = hub.Module(module_dir=saved_module_dir)
169
    feed_dict, fetch_dict, program = w2v_module(
170 171
        sign_name="default", trainable=False)
    with fluid.program_guard(main_program=program):
172 173 174 175 176 177 178 179 180
        pred_prob = fetch_dict["pred_prob"]
        pred_word = fluid.layers.argmax(x=pred_prob, axis=1)
        # set place, executor, datafeeder
        place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
        exe = fluid.Executor(place)
        feed_vars = [
            feed_dict["firstw"], feed_dict["secondw"], feed_dict["thirdw"],
            feed_dict["fourthw"]
        ]
Z
Zeyu Chen 已提交
181
        feeder = fluid.DataFeeder(place=place, feed_list=feed_vars)
182 183 184 185 186 187 188 189 190

        word_ids = [[1, 2, 3, 4]]
        result = exe.run(
            fluid.default_main_program(),
            feed=feeder.feed(word_ids),
            fetch_list=[pred_word],
            return_numpy=True)

        print(result)
Z
Zeyu Chen 已提交
191 192 193


if __name__ == "__main__":
194 195 196 197 198
    use_gpu = False
    print("test create word2vec module")
    test_create_w2v_module(use_gpu)
    print("test load word2vec module")
    test_load_w2v_module(use_gpu=False)