module.py 9.3 KB
Newer Older
Z
Zeyu Chen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

Z
Zeyu Chen 已提交
15 16 17 18 19
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import paddle.fluid as fluid
Z
Zeyu Chen 已提交
20
import numpy as np
Z
Zeyu Chen 已提交
21 22
import tempfile
import os
Z
Zeyu Chen 已提交
23
import module_desc_pb2
Z
Zeyu Chen 已提交
24

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

Z
Zeyu Chen 已提交
28
__all__ = ["Module", "ModuleConfig", "ModuleUtils"]
Z
Zeyu Chen 已提交
29
DICT_NAME = "dict.txt"
Z
Zeyu Chen 已提交
30
ASSETS_NAME = "assets"
Z
Zeyu Chen 已提交
31 32 33 34 35 36 37


def mkdir(path):
    """ the same as the shell command mkdir -p "
    """
    if not os.path.exists(path):
        os.makedirs(path)
Z
Zeyu Chen 已提交
38

Z
Zeyu Chen 已提交
39

Z
Zeyu Chen 已提交
40
class Module(object):
Z
Zeyu Chen 已提交
41 42 43
    def __init__(self, module_url=None, module_dir=None):
        if module_url == None and module_dir == None:
            raise Exception("Module:module_url and module_dir are None!")
Z
Zeyu Chen 已提交
44 45 46

        self.module_dir = ""
        self.module_name = ""
Z
Zeyu Chen 已提交
47
        # donwload module
Z
Zeyu Chen 已提交
48
        if module_url is not None and module_url.startswith("http"):
Z
Zeyu Chen 已提交
49
            # if it's remote url link, then download and uncompress it
Z
Zeyu Chen 已提交
50 51
            self.module_name, self.module_dir = download_and_uncompress(
                module_url)
Z
Zeyu Chen 已提交
52
            #TODO(ZeyuChen): check url link is valid url
Z
Zeyu Chen 已提交
53
        elif module_dir is not None:
Z
Zeyu Chen 已提交
54
            # otherwise it's local path, no need to deal with it
Z
Zeyu Chen 已提交
55
            self.module_dir = module_dir
Z
Zeyu Chen 已提交
56
            # use the path name as module name by default
Z
Zeyu Chen 已提交
57
            self.module_name = module_dir.split("/")[-1]
Z
Zeyu Chen 已提交
58
            #TODO(ZeyuChen) add more check about loading module from local path
Z
Zeyu Chen 已提交
59 60 61 62 63 64

        # load paddle inference model
        place = fluid.CPUPlace()
        self.exe = fluid.Executor(fluid.CPUPlace())
        [self.inference_program, self.feed_target_names,
         self.fetch_targets] = fluid.io.load_inference_model(
65
             dirname=self.module_dir, executor=self.exe)
Z
Zeyu Chen 已提交
66 67 68 69 70 71 72 73

        print("inference_program")
        print(self.inference_program)
        print("feed_target_names")
        print(self.feed_target_names)
        print("fetch_targets")
        print(self.fetch_targets)

Z
Zeyu Chen 已提交
74 75
        self.config = ModuleConfig(self.module_dir)
        self.config.load()
Z
Zeyu Chen 已提交
76
        # load assets
Z
Zeyu Chen 已提交
77 78 79
        # self.dict = defaultdict(int)
        # self.dict.setdefault(0)
        # self._load_assets(module_dir)
Z
Zeyu Chen 已提交
80

Z
Zeyu Chen 已提交
81 82
    #TODO(ZeyuChen): Need add register more signature to execute different
    # implmentation
Z
Zeyu Chen 已提交
83
    def __call__(self, inputs=None, signature=None):
Z
Zeyu Chen 已提交
84 85 86 87 88 89
        """ Call default signature and return results
        """
        # TODO(ZeyuChen): add proto spec to check which task we need to run
        # if it's NLP word embedding task, then do words preprocessing
        # if it's image classification or image feature task do the other works

Z
Zeyu Chen 已提交
90
        # if it's
Z
Zeyu Chen 已提交
91 92 93 94 95 96 97 98 99 100
        word_ids_lod_tensor = self._process_input(inputs)
        np_words_id = np.array(word_ids_lod_tensor)
        print("word_ids_lod_tensor\n", np_words_id)

        results = self.exe.run(
            self.inference_program,
            feed={self.feed_target_names[0]: word_ids_lod_tensor},
            fetch_list=self.fetch_targets,
            return_numpy=False)  # return_numpy=Flase is important

Z
Zeyu Chen 已提交
101 102 103
        print("module fetch_target_names", self.feed_target_names)
        print("module fetch_targets", self.fetch_targets)
        np_result = np.array(results[0])
Z
Zeyu Chen 已提交
104 105 106

        return np_result

Z
Zeyu Chen 已提交
107 108 109
    def add_input_desc(var_name):
        pass

Z
Zeyu Chen 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122
    def get_vars(self):
        return self.inference_program.list_vars()

    def get_input_vars(self):
        for var in self.inference_program.list_vars():
            print(var)
            if var.name == "words":
                return var
        # return self.fetch_targets

    def get_module_output(self):
        for var in self.inference_program.list_vars():
            print(var)
Z
Zeyu Chen 已提交
123
            # NOTE: just hack for load Senta's
Z
Zeyu Chen 已提交
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 150 151 152 153 154 155 156 157
            if var.name == "embedding_0.tmp_0":
                return var

    def get_inference_program(self):
        return self.inference_program

    # for text sequence input, transform to lod tensor as paddle graph's input
    def _process_input(self, inputs):
        # words id mapping and dealing with oov
        # transform to lod tensor
        seq = []
        for s in inputs:
            seq.append(self._word_id_mapping(s))

        lod_tensor = self.seq2lod_tensor(seq)

        return lod_tensor

    def seq2lod_tensor(self, seq_inputs, place=fluid.CPUPlace()):
        """ sequence to lod tensor, need to determine which space"""
        lod = []
        lod.append([])
        for s in seq_inputs:
            # generate lod
            lod[0].append(len(s))

        # print("seq", seq_inputs)
        # print("lod", lod)

        lod_tensor = fluid.create_lod_tensor(seq_inputs, lod, place)

        return lod_tensor

    def _word_id_mapping(self, inputs):
Z
Zeyu Chen 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        word_dict = self.config.get_dict()
        return list(map(lambda x: word_dict[x], inputs))

    # # load assets folder
    # def _load_assets(self, module_dir):
    #     assets_dir = os.path.join(module_dir, ASSETS_NAME)
    #     dict_path = os.path.join(assets_dir, DICT_NAME)
    #     word_id = 0

    #     with open(dict_path) as fi:
    #         words = fi.readlines()
    #         #TODO(ZeyuChen) check whether word id is duplicated and valid
    #         for line in fi:
    #             w, w_id = line.split()
    #             self.dict[w] = int(w_id)
Z
Zeyu Chen 已提交
173

Z
Zeyu Chen 已提交
174 175 176 177 178 179 180
    def add_module_feed_list(self, feed_list):
        self.feed_list = feed_list

    def add_module_output_list(self, output_list):
        self.output_list = output_list


Z
Zeyu Chen 已提交
181
class ModuleConfig(object):
Z
Zeyu Chen 已提交
182
    def __init__(self, module_dir, module_name=None):
Z
Zeyu Chen 已提交
183 184
        # generate model desc protobuf
        self.module_dir = module_dir
Z
Zeyu Chen 已提交
185 186 187
        self.desc = module_desc_pb2.ModuleDesc()
        if module_name == None:
            module_name = module_dir.split("/")[-1]
Z
Zeyu Chen 已提交
188 189 190 191 192 193 194
        self.desc.name = module_name
        print("desc.name=", self.desc.name)
        self.desc.signature = "default"
        print("desc.signature=", self.desc.signature)
        self.desc.contain_assets = True
        print("desc.signature=", self.desc.contain_assets)

Z
Zeyu Chen 已提交
195 196 197 198
        # init dict
        self.dict = defaultdict(int)
        self.dict.setdefault(0)

199
    def load(self):
Z
Zeyu Chen 已提交
200
        """load module config from module dir
Z
Zeyu Chen 已提交
201
        """
Z
Zeyu Chen 已提交
202
        #TODO(ZeyuChen): check module_desc.pb exsitance
203 204
        pb_path = os.path.join(self.module_dir, "module_desc.pb")
        with open(pb_path, "rb") as fi:
Z
Zeyu Chen 已提交
205 206 207 208
            self.desc.ParseFromString(fi.read())

        if self.desc.contain_assets:
            # load assets
Z
Zeyu Chen 已提交
209
            assets_dir = os.path.join(self.module_dir, ASSETS_NAME)
Z
Zeyu Chen 已提交
210 211 212 213 214 215 216 217 218 219
            dict_path = os.path.join(assets_dir, DICT_NAME)
            word_id = 0

            with open(dict_path) as fi:
                words = fi.readlines()
                #TODO(ZeyuChen) check whether word id is duplicated and valid
                for line in fi:
                    w, w_id = line.split()
                    self.dict[w] = int(w_id)

Z
Zeyu Chen 已提交
220
    def dump(self):
Z
Zeyu Chen 已提交
221
        # save module_desc.proto first
Z
Zeyu Chen 已提交
222
        pb_path = os.path.join(self.module_dir, "module_desc.pb")
Z
Zeyu Chen 已提交
223 224 225 226
        with open(pb_path, "wb") as fo:
            fo.write(self.desc.SerializeToString())

        # save assets/dictionary
Z
Zeyu Chen 已提交
227
        assets_dir = os.path.join(self.module_dir, ASSETS_NAME)
Z
Zeyu Chen 已提交
228 229
        mkdir(assets_dir)
        with open(os.path.join(assets_dir, DICT_NAME), "w") as fo:
Z
Zeyu Chen 已提交
230 231
            for w in self.dict:
                w_id = self.dict[w]
Z
Zeyu Chen 已提交
232
                fo.write("{}\t{}\n".format(w, w_id))
Z
Zeyu Chen 已提交
233

Z
Zeyu Chen 已提交
234
    def save_dict(self, word_dict, dict_name=DICT_NAME):
Z
Zeyu Chen 已提交
235 236
        """ Save dictionary for NLP module
        """
Z
Zeyu Chen 已提交
237
        mkdir(self.module_dir)
Z
Zeyu Chen 已提交
238 239 240 241
        with open(os.path.join(self.module_dir, DICT_NAME), "w") as fo:
            for w in word_dict:
                self.dict[w] = word_dict[w]

Z
Zeyu Chen 已提交
242 243 244
    def get_dict(self):
        return self.dict

Z
Zeyu Chen 已提交
245 246 247

class ModuleUtils(object):
    def __init__(self):
Z
Zeyu Chen 已提交
248
        pass
Z
Zeyu Chen 已提交
249

Z
Zeyu Chen 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    @staticmethod
    def remove_feed_fetch_op(program):
        """ remove feed and fetch operator and variable for fine-tuning
        """
        print("remove feed fetch op")
        block = program.global_block()
        need_to_remove_op_index = []
        for i, op in enumerate(block.ops):
            if op.type == "feed" or op.type == "fetch":
                need_to_remove_op_index.append(i)

        for index in need_to_remove_op_index[::-1]:
            block._remove_op(index)

        block._remove_var("feed")
        block._remove_var("fetch")

        program.desc.flush()
        print("********************************")
        print(program)
        print("********************************")

Z
Zeyu Chen 已提交
272 273

if __name__ == "__main__":
Z
Zeyu Chen 已提交
274 275
    url = "http://paddlehub.cdn.bcebos.com/word2vec/word2vec-dim16-simple-example-2.tar.gz"
    m = Module(module_url=url)
Z
Zeyu Chen 已提交
276 277 278 279 280
    inputs = [["it", "is", "new"], ["hello", "world"]]
    #tensor = m._process_input(inputs)
    #print(tensor)
    result = m(inputs)
    print(result)