module.py 13.5 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
# coding=utf-8

Z
Zeyu Chen 已提交
17 18 19 20 21
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import paddle.fluid as fluid
Z
Zeyu Chen 已提交
22
import numpy as np
Z
Zeyu Chen 已提交
23 24
import tempfile
import os
W
wuzewu 已提交
25
import pickle
Z
Zeyu Chen 已提交
26

Z
Zeyu Chen 已提交
27
from collections import defaultdict
Z
Zeyu Chen 已提交
28
from paddle_hub.downloader import download_and_uncompress
Z
Zeyu Chen 已提交
29
from paddle_hub import module_desc_pb2
Z
Zeyu Chen 已提交
30 31
from paddle_hub.signature import Signature
from paddle_hub.utils import to_list
32
from paddle_hub.version import __version__
Z
Zeyu Chen 已提交
33

Z
Zeyu Chen 已提交
34
__all__ = ["Module", "ModuleConfig", "ModuleUtils"]
Z
Zeyu Chen 已提交
35 36 37 38 39 40 41 42 43 44

# paddle hub module dir name
ASSETS_DIRNAME = "assets"
META_DIRNAME = "meta"
MODEL_DIRNAME = "model"
# paddle hub module serialze file name
DICT_FILENAME = "vocab.txt"
PARAM_FILENAME = "param.pkl"
MODULE_DESC_PBNAME = "module_desc.pb"
GENERATOR_FILENAME = "unique_name_generator.pkl"
Z
Zeyu Chen 已提交
45 46 47 48 49 50 51


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

Z
Zeyu Chen 已提交
53

Z
Zeyu Chen 已提交
54
class Module(object):
Z
Zeyu Chen 已提交
55
    """
56
    Core object of PaddleHub
Z
Zeyu Chen 已提交
57 58
    """

Z
Zeyu Chen 已提交
59 60 61
    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 已提交
62 63 64

        self.module_dir = ""
        self.module_name = ""
Z
Zeyu Chen 已提交
65
        # donwload module
Z
Zeyu Chen 已提交
66
        if module_url is not None and module_url.startswith("http"):
Z
Zeyu Chen 已提交
67
            # if it's remote url link, then download and uncompress it
Z
Zeyu Chen 已提交
68 69
            self.module_name, self.module_dir = download_and_uncompress(
                module_url)
Z
Zeyu Chen 已提交
70
            #TODO(ZeyuChen): check url link is valid url
Z
Zeyu Chen 已提交
71
        elif module_dir is not None:
Z
Zeyu Chen 已提交
72
            # otherwise it's local path, no need to deal with it
Z
Zeyu Chen 已提交
73
            self.module_dir = module_dir
Z
Zeyu Chen 已提交
74
            # use the path name as module name by default
Z
Zeyu Chen 已提交
75
            self.module_name = module_dir.split("/")[-1]
Z
Zeyu Chen 已提交
76
            #TODO(ZeyuChen) add more check about loading module from local path
Z
Zeyu Chen 已提交
77

W
wuzewu 已提交
78 79
    def _process_parameter(self):
        global_block = self.inference_program.global_block()
Z
Zeyu Chen 已提交
80 81
        param_path = ModuleConfig.meta_param_path(self.module_dir)
        with open(param_path, "rb") as file:
W
wuzewu 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95
            param_arr = pickle.load(file)
        for param in param_arr:
            if (param['name'] not in global_block.vars):
                continue
            var = global_block.var(param['name'])
            global_block.create_parameter(
                **param,
                shape=var.shape,
                dtype=var.dtype,
                type=var.type,
                lod_level=var.lod_level,
                error_clip=var.error_clip,
                stop_gradient=var.stop_gradient,
                is_data=var.is_data)
Z
Zeyu Chen 已提交
96

Z
Zeyu Chen 已提交
97
    def __call__(self, sign_name="default", trainable=False):
Z
Zeyu Chen 已提交
98 99
        """ Call default signature and return results
        """
100 101 102 103 104

        def _set_param_trainable(program, trainable=False):
            for param in program.global_block().iter_parameters():
                param.trainable = trainable

W
wuzewu 已提交
105 106 107 108 109
        def _process_op_attr(program, is_test=False):
            for op in program.global_block().ops:
                if op.has_attr("is_test"):
                    op._set_attr("is_test", is_test)

W
wuzewu 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        def _process_input_output_key(module_desc, signature):
            signature = module_desc.sign2var[signature]

            feed_dict = {}
            fetch_dict = {}

            for index, feed in enumerate(signature.feed_desc):
                if feed.alias != "":
                    feed_dict[feed.alias] = feed.var_name
                feed_dict[index] = feed.var_name

            for index, fetch in enumerate(signature.fetch_desc):
                if fetch.alias != "":
                    fetch_dict[fetch.alias] = fetch.var_name
                fetch_dict[index] = fetch.var_name

            return feed_dict, fetch_dict

        self.config = ModuleConfig(self.module_dir)
        self.config.load()
W
wuzewu 已提交
130 131 132 133 134
        # load paddle inference model
        place = fluid.CPUPlace()
        model_dir = os.path.join(self.module_dir, MODEL_DIRNAME)
        self.exe = fluid.Executor(fluid.CPUPlace())
        self.inference_program, self.feed_target_names, self.fetch_targets = fluid.io.load_inference_model(
W
wuzewu 已提交
135
            dirname=os.path.join(model_dir, sign_name), executor=self.exe)
W
wuzewu 已提交
136

W
wuzewu 已提交
137 138 139
        feed_dict, fetch_dict = _process_input_output_key(
            self.config.desc, sign_name)

W
wuzewu 已提交
140 141 142 143 144 145 146 147 148 149 150
        # remove feed fetch operator and variable
        ModuleUtils.remove_feed_fetch_op(self.inference_program)
        # print("inference_program")
        # print(self.inference_program)
        print("**feed_target_names**\n{}".format(self.feed_target_names))
        print("**fetch_targets**\n{}".format(self.fetch_targets))
        self._process_parameter()
        name_generator_path = ModuleConfig.name_generator_path(self.module_dir)
        with open(name_generator_path, "rb") as data:
            generator = pickle.load(data)

151 152
        program = self.get_inference_program().clone()

W
wuzewu 已提交
153
        _process_op_attr(program=program, is_test=False)
Z
Zeyu Chen 已提交
154
        _set_param_trainable(program=program, trainable=trainable)
155

W
wuzewu 已提交
156 157 158 159 160 161 162 163 164
        for key, value in feed_dict.items():
            var = program.global_block().var(value)
            feed_dict[key] = var

        for key, value in fetch_dict.items():
            var = program.global_block().var(value)
            fetch_dict[key] = var

        return feed_dict, fetch_dict, program, generator
Z
Zeyu Chen 已提交
165 166 167 168 169

    def get_inference_program(self):
        return self.inference_program

    # for text sequence input, transform to lod tensor as paddle graph's input
Z
Zeyu Chen 已提交
170
    def _preprocess_input(self, inputs):
Z
Zeyu Chen 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
        # 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 已提交
197 198 199
        word_dict = self.config.get_dict()
        return list(map(lambda x: word_dict[x], inputs))

Z
Zeyu Chen 已提交
200

Z
Zeyu Chen 已提交
201
class ModuleConfig(object):
Z
Zeyu Chen 已提交
202
    def __init__(self, module_dir, module_name=None):
Z
Zeyu Chen 已提交
203 204
        # generate model desc protobuf
        self.module_dir = module_dir
Z
Zeyu Chen 已提交
205 206 207
        self.desc = module_desc_pb2.ModuleDesc()
        if module_name == None:
            module_name = module_dir.split("/")[-1]
Z
Zeyu Chen 已提交
208
        # initialize module config default value
Z
Zeyu Chen 已提交
209 210
        self.desc.name = module_name
        self.desc.contain_assets = True
Z
Zeyu Chen 已提交
211
        self.desc.return_numpy = False
Z
Zeyu Chen 已提交
212

Z
Zeyu Chen 已提交
213 214 215 216
        # init dict
        self.dict = defaultdict(int)
        self.dict.setdefault(0)

Z
Zeyu Chen 已提交
217 218 219 220
    def get_dict(self):
        """ Return dictionary in Module"""
        return self.dict

221
    def load(self):
Z
Zeyu Chen 已提交
222 223
        """
        Load module config from module directory.
Z
Zeyu Chen 已提交
224
        """
Z
Zeyu Chen 已提交
225
        #TODO(ZeyuChen): check module_desc.pb exsitance
Z
Zeyu Chen 已提交
226
        with open(ModuleConfig.module_desc_path(self.module_dir), "rb") as fi:
Z
Zeyu Chen 已提交
227 228 229 230 231
            self.desc.ParseFromString(fi.read())

        if self.desc.contain_assets:
            # load assets
            word_id = 0
Z
Zeyu Chen 已提交
232
            with open(ModuleConfig.assets_dict_path(self.module_dir)) as fi:
Z
Zeyu Chen 已提交
233 234 235 236 237 238
                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 已提交
239 240 241 242 243
    def return_numpy(self):
        """Return numpy or not according to the proto config.
        """
        return self.desc.return_numpy

Z
Zeyu Chen 已提交
244
    def save_dict(self, word_dict, dict_name=DICT_FILENAME):
Z
Zeyu Chen 已提交
245 246
        """ Save dictionary for NLP module
        """
Z
Zeyu Chen 已提交
247 248
        for w in word_dict:
            self.dict[w] = word_dict[w]
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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    @staticmethod
    def module_desc_path(module_dir):
        return os.path.join(module_dir, MODULE_DESC_PBNAME)

    @staticmethod
    def name_generator_path(module_dir):
        meta_path = os.path.join(module_dir, META_DIRNAME)
        mkdir(meta_path)
        return os.path.join(meta_path, GENERATOR_FILENAME)

    @staticmethod
    def assets_dict_path(module_dir):
        assets_path = os.path.join(module_dir, ASSETS_DIRNAME)
        mkdir(assets_path)
        return os.path.join(assets_path, DICT_FILENAME)

    @staticmethod
    def meta_param_path(module_dir):
        meta_path = os.path.join(module_dir, META_DIRNAME)
        mkdir(meta_path)
        return os.path.join(meta_path, PARAM_FILENAME)

    @staticmethod
    def meta_name_generator_path(module_dir):
        meta_path = os.path.join(module_dir, META_DIRNAME)
        mkdir(meta_path)
        return os.path.join(meta_path, GENERATOR_FILENAME)


def create_module(sign_arr, program, module_dir=None, word_dict=None):
    """ Create a module from main program
    """
    assert isinstance(
        program, fluid.Program), "program should be instance of fluid.Program"
    assert sign_arr, "signature array should not be None"

    if module_dir is None:
        module_dir = os.path.join(".", "hub_module")
    # create module path for saving
    mkdir(module_dir)

291 292
    module_desc = module_desc_pb2.ModuleDesc()
    module_desc.version = __version__
Z
Zeyu Chen 已提交
293 294 295
    program = program.clone()

    if word_dict is None:
296
        module_desc.contain_assets = False
Z
Zeyu Chen 已提交
297
    else:
298
        module_desc.contain_assets = True
Z
Zeyu Chen 已提交
299 300 301 302 303 304
        with open(ModuleConfig.assets_dict_path(module_dir), "w") as fo:
            for w in word_dict:
                w_id = word_dict[w]
                fo.write("{}\t{}\n".format(w, w_id))

    # save the unique name generator object
305 306 307 308 309 310 311 312 313
    var_name_arr = [
        '_'.join(var.split('@')[0].split('.')[0].split('_')[0:-1])
        for block in program.blocks for var in block.vars
    ]
    with fluid.unique_name.guard():
        for var_name in var_name_arr:
            fluid.unique_name.generate(var_name)
        generator = fluid.unique_name.generator

Z
Zeyu Chen 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    with open(ModuleConfig.name_generator_path(module_dir), "wb") as fo:
        pickle.dump(generator, fo)

    # save fluid Parameter
    param_arr = []
    for param in program.global_block().iter_parameters():
        param_info = {
            'name': param.name,
            'regularizer': param.regularizer,
            'gradient_clip_attr': param.gradient_clip_attr,
            'trainable': param.trainable,
            'optimize_attr': param.optimize_attr,
            'do_model_average': param.do_model_average
        }
        param_arr.append(param_info)

    with open(ModuleConfig.meta_param_path(module_dir), "wb") as fo:
        pickle.dump(param_arr, fo)

    # save signarture info
334
    sign_map = module_desc.sign2var
Z
Zeyu Chen 已提交
335 336 337 338 339 340 341 342 343 344 345
    sign_arr = to_list(sign_arr)
    for sign in sign_arr:
        assert isinstance(sign,
                          Signature), "sign_arr should be list of Signature"

        if sign.get_name() in sign_map:
            raise "Error! sign_arr contains repeat signatrue %s" % sign

        var = sign_map[sign.get_name()]
        feed_desc = var.feed_desc
        fetch_desc = var.fetch_desc
W
wuzewu 已提交
346 347 348
        feed_names = sign.get_feed_names()
        fetch_names = sign.get_fetch_names()
        for index, input in enumerate(sign.get_inputs()):
Z
Zeyu Chen 已提交
349 350
            feed_var = feed_desc.add()
            feed_var.var_name = input.name
W
wuzewu 已提交
351
            feed_var.alias = feed_names[index]
Z
Zeyu Chen 已提交
352

W
wuzewu 已提交
353
        for index, output in enumerate(sign.get_outputs()):
Z
Zeyu Chen 已提交
354 355
            fetch_var = fetch_desc.add()
            fetch_var.var_name = output.name
W
wuzewu 已提交
356
            fetch_var.alias = fetch_names[index]
Z
Zeyu Chen 已提交
357 358 359 360 361

    # save inference program
    exe = fluid.Executor(place=fluid.CPUPlace())
    model_dir = os.path.join(module_dir, "model")
    mkdir(model_dir)
W
wuzewu 已提交
362 363 364 365 366 367 368 369 370
    # TODO(wuzewu): save paddle model with a more effective way
    for sign in sign_arr:
        save_model_dir = os.path.join(model_dir, sign.get_name())
        fluid.io.save_inference_model(
            save_model_dir,
            feeded_var_names=[var.name for var in sign.get_inputs()],
            target_vars=sign.get_outputs(),
            main_program=program,
            executor=exe)
Z
Zeyu Chen 已提交
371

372 373
    # Serialize module_desc pb
    module_pb = module_desc.SerializeToString()
Z
Zeyu Chen 已提交
374
    with open(ModuleConfig.module_desc_path(module_dir), "wb") as f:
375
        f.write(module_pb)
Z
Zeyu Chen 已提交
376

Z
Zeyu Chen 已提交
377 378 379

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

Z
Zeyu Chen 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    @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()