module_v1.py 13.2 KB
Newer Older
W
wuzewu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# coding:utf-8
# 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.

import functools
import os
from typing import Tuple, List

import paddle
21
import paddle2onnx
W
wuzewu 已提交
22
from easydict import EasyDict
W
wuzewu 已提交
23 24 25 26 27 28 29 30

from paddlehub.compat import paddle_utils
from paddlehub.compat.module import module_v1_utils
from paddlehub.utils import utils, log


class ModuleV1(object):
    '''
W
wuzewu 已提交
31 32 33
    ModuleV1 is an old version of the PaddleHub Module format, which is no longer in use. In order to maintain
    compatibility, users can still load the corresponding Module for prediction. User should call `hub.Module`
    to initialize the corresponding object, rather than `ModuleV1`.
W
wuzewu 已提交
34
    '''
W
wuzewu 已提交
35

W
wuzewu 已提交
36
    # All ModuleV1 in PaddleHub is static graph model
37
    @paddle_utils.run_in_static_mode
W
wuzewu 已提交
38 39 40 41 42 43
    def __init__(self, name: str = None, directory: str = None, version: str = None):
        if not directory:
            return

        desc_file = os.path.join(directory, 'module_desc.pb')
        self.desc = module_v1_utils.convert_module_desc(desc_file)
W
wuzewu 已提交
44 45
        self.helper = self
        self.signatures = self.desc.signatures
W
wuzewu 已提交
46
        self.default_signature = self.desc.default_signature
W
wuzewu 已提交
47 48

        self.directory = directory
W
wuzewu 已提交
49 50 51 52 53
        self._load_model()
        self._load_parameters()
        self._load_processor()
        self._load_assets()
        self._load_extra_info()
W
wuzewu 已提交
54
        self._generate_func()
W
wuzewu 已提交
55 56

    def _load_processor(self):
W
wuzewu 已提交
57 58 59 60
        # Some module does not have a processor(e.g. ernie)
        if not 'processor_info' in self.desc:
            return

W
wuzewu 已提交
61 62 63
        python_path = os.path.join(self.directory, 'python')
        processor_name = self.desc.processor_info
        self.processor = utils.load_py_module(python_path, processor_name)
W
wuzewu 已提交
64
        self.processor = self.processor.Processor(module=self)
W
wuzewu 已提交
65 66 67

    def _load_assets(self):
        self.assets = []
W
wuzewu 已提交
68 69
        for file in os.listdir(self.assets_path()):
            filepath = os.path.join(self.assets_path(), file)
W
wuzewu 已提交
70 71 72 73
            self.assets.append(filepath)

    def _load_parameters(self):
        global_block = self.program.global_block()
W
wuzewu 已提交
74 75 76 77

        # record num parameters loaded by PaddleHub
        num_param_loaded = 0

W
wuzewu 已提交
78 79 80 81 82
        for param, attrs in self.desc.param_attrs.items():
            name = self.desc.name_prefix + param
            if not name in global_block.vars:
                continue

W
wuzewu 已提交
83
            num_param_loaded += 1
W
wuzewu 已提交
84
            var = global_block.vars[name]
W
wuzewu 已提交
85

W
wuzewu 已提交
86 87
            # Since the pre-trained model saved by the old version of Paddle cannot restore the corresponding
            # parameters, we need to restore them manually.
W
wuzewu 已提交
88 89 90 91 92 93 94 95 96 97 98 99
            global_block.create_parameter(
                name=name,
                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,
                **attrs)

        log.logger.info('{} pretrained paramaters loaded by PaddleHub'.format(num_param_loaded))
W
wuzewu 已提交
100 101

    def _load_extra_info(self):
W
wuzewu 已提交
102 103 104
        if not 'extra_info' in self.desc:
            return

W
wuzewu 已提交
105 106 107
        for key, value in self.desc.extra_info.items():
            self.__dict__['get_{}'.format(key)] = value

W
wuzewu 已提交
108
    def _generate_func(self):
W
wuzewu 已提交
109
        for signature in self.desc.signatures:
W
wuzewu 已提交
110
            self.__dict__[signature] = functools.partial(self.__call__, sign_name=signature)
W
wuzewu 已提交
111 112 113 114

    def _load_model(self):
        model_path = os.path.join(self.directory, 'model')
        exe = paddle.static.Executor(paddle.CPUPlace())
W
wuzewu 已提交
115
        self.program, _, _ = paddle.fluid.io.load_inference_model(model_path, executor=exe)
W
wuzewu 已提交
116 117 118 119 120 121 122 123

        # Clear the callstack since it may leak the privacy of the creator.
        for block in self.program.blocks:
            for op in block.ops:
                if not 'op_callstack' in op.all_attrs():
                    continue
                op._set_attr('op_callstack', [''])

124
    @paddle_utils.run_in_static_mode
W
wuzewu 已提交
125 126
    def context(self, signature: str = None, for_test: bool = False, trainable: bool = True,
                max_seq_len: int = 128) -> Tuple[dict, dict, paddle.static.Program]:
W
wuzewu 已提交
127
        '''Get module context information, including graph structure and graph input and output variables.'''
W
wuzewu 已提交
128 129 130 131 132 133
        program = self.program.clone(for_test=for_test)
        paddle_utils.remove_feed_fetch_op(program)

        # generate feed vars and fetch vars from signatures
        feed_dict = {}
        fetch_dict = {}
W
wuzewu 已提交
134 135 136 137
        varinfos = [self.desc.signatures[signature]] if signature else self.desc.signatures.values()

        for info in varinfos:
            for feed_var in info.inputs:
W
wuzewu 已提交
138 139 140
                paddle_var = program.global_block().vars[feed_var.name]
                feed_dict[feed_var.alias] = paddle_var

W
wuzewu 已提交
141
            for fetch_var in info.outputs:
W
wuzewu 已提交
142 143 144 145 146 147
                paddle_var = program.global_block().vars[fetch_var.name]
                fetch_dict[fetch_var.alias] = paddle_var

        for param in program.all_parameters():
            param.trainable = trainable

W
wuzewu 已提交
148 149 150 151 152
        # The bert series model saved by ModuleV1 sets max_seq_len to 512 by default. We need to adjust max_seq_len
        # according to the parameters in actual use.
        if 'bert' in self.name or self.name.startswith('ernie'):
            self._update_bert_max_seq_len(program, feed_dict, max_seq_len)

W
wuzewu 已提交
153 154
        return feed_dict, fetch_dict, program

W
wuzewu 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168
    def _update_bert_max_seq_len(self, program: paddle.static.Program, feed_dict: dict, max_seq_len: int = 128):
        MAX_SEQ_LENGTH = 512
        if max_seq_len > MAX_SEQ_LENGTH or max_seq_len <= 0:
            raise ValueError("max_seq_len({}) should be in the range of [1, {}]".format(max_seq_len, MAX_SEQ_LENGTH))
        log.logger.info("Set maximum sequence length of input tensor to {}".format(max_seq_len))
        if self.name.startswith("ernie_v2"):
            feed_list = ["input_ids", "position_ids", "segment_ids", "input_mask", "task_ids"]
        else:
            feed_list = ["input_ids", "position_ids", "segment_ids", "input_mask"]
        for tensor_name in feed_list:
            seq_tensor_shape = [-1, max_seq_len, 1]
            log.logger.info("The shape of input tensor[{}] set to {}".format(tensor_name, seq_tensor_shape))
            program.global_block().var(feed_dict[tensor_name].name).desc.set_shape(seq_tensor_shape)

169
    @paddle_utils.run_in_static_mode
W
wuzewu 已提交
170
    def __call__(self, sign_name: str, data: dict, use_gpu: bool = False, batch_size: int = 1, **kwargs):
W
wuzewu 已提交
171
        '''Call the specified signature function for prediction.'''
W
wuzewu 已提交
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 197 198 199 200 201 202 203 204

        def _get_reader_and_feeder(data_format, data, place):
            def _reader(process_data):
                for item in zip(*process_data):
                    yield item

            process_data = []
            feed_name_list = []
            for key in data_format:
                process_data.append([value['processed'] for value in data[key]])
                feed_name_list.append(data_format[key]['feed_key'])
            feeder = paddle.fluid.DataFeeder(feed_list=feed_name_list, place=place)
            return functools.partial(_reader, process_data=process_data), feeder

        _, fetch_dict, program = self.context(signature=sign_name, for_test=True)
        fetch_list = list([value for key, value in fetch_dict.items()])
        with paddle.static.program_guard(program):
            result = []
            index = 0
            place = paddle.CUDAPlace(0) if use_gpu else paddle.CPUPlace()

            exe = paddle.static.Executor(place=place)
            data = self.processor.preprocess(sign_name=sign_name, data_dict=data)
            data_format = self.processor.data_format(sign_name=sign_name)
            reader, feeder = _get_reader_and_feeder(data_format, data, place)
            reader = paddle.batch(reader, batch_size=batch_size)
            for batch in reader():
                data_out = exe.run(feed=feeder.feed(batch), fetch_list=fetch_list, return_numpy=False)
                sub_data = {key: value[index:index + len(batch)] for key, value in data.items()}
                result += self.processor.postprocess(sign_name, data_out, sub_data, **kwargs)
                index += len(batch)

        return result
W
wuzewu 已提交
205 206 207

    @classmethod
    def get_py_requirements(cls) -> List[str]:
W
wuzewu 已提交
208
        '''Get Module's python package dependency list.'''
W
wuzewu 已提交
209 210 211
        return []

    @classmethod
W
wuzewu 已提交
212
    def load(cls, directory: str) -> EasyDict:
W
wuzewu 已提交
213
        '''Load the Module object defined in the specified directory.'''
W
wuzewu 已提交
214
        module_info = cls.load_module_info(directory)
W
wuzewu 已提交
215 216 217 218 219 220

        # Generate a uuid based on the class information, and dynamically create a new type.
        # If we do not do this, the information generated later will overwrite the information
        # previously generated.
        cls_uuid = utils.md5(module_info.name + module_info.author + module_info.author_email + module_info.type +
                             module_info.summary + module_info.version + directory)
221
        cls = type('ModuleV1_{}'.format(cls_uuid), (cls, ), {})
W
wuzewu 已提交
222

W
wuzewu 已提交
223 224 225 226 227 228
        cls.name = module_info.name
        cls.author = module_info.author
        cls.author_email = module_info.author_email
        cls.type = module_info.type
        cls.summary = module_info.summary
        cls.version = utils.Version(module_info.version)
W
wuzewu 已提交
229
        cls.directory = directory
W
wuzewu 已提交
230
        return cls
W
wuzewu 已提交
231

W
wuzewu 已提交
232 233
    @classmethod
    def load_module_info(cls, directory: str) -> EasyDict:
W
wuzewu 已提交
234
        '''Load the infomation of Module object defined in the specified directory.'''
W
wuzewu 已提交
235 236
        desc_file = os.path.join(directory, 'module_desc.pb')
        desc = module_v1_utils.convert_module_desc(desc_file)
W
wuzewu 已提交
237 238 239 240 241 242

        # The naming of some old versions of Module is not standardized, which format of uppercase
        # letters. This will cause the path of these modules to be incorrect after installation.
        module_info = desc.module_info
        module_info.name = module_info.name.lower()
        return module_info
W
wuzewu 已提交
243

W
wuzewu 已提交
244 245
    def assets_path(self):
        return os.path.join(self.directory, 'assets')
W
wuzewu 已提交
246

W
wuzewu 已提交
247 248 249
    def get_name_prefix(self):
        return self.desc.name_prefix

W
wuzewu 已提交
250 251
    @property
    def is_runnable(self):
W
wuzewu 已提交
252 253 254 255
        '''
        Whether the Module is runnable, in other words, whether can we execute the Module through the
        `hub run` command.
        '''
W
wuzewu 已提交
256
        return self.default_signature != None
W
wuzewu 已提交
257

258
    @paddle_utils.run_in_static_mode
W
wuzewu 已提交
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
    def save_inference_model(self,
                             dirname: str,
                             model_filename: str = None,
                             params_filename: str = None,
                             combined: bool = False):
        if hasattr(self, 'processor'):
            if hasattr(self.processor, 'save_inference_model'):
                return self.processor.save_inference_model(dirname, model_filename, params_filename, combined)

        if combined:
            model_filename = '__model__' if not model_filename else model_filename
            params_filename = '__params__' if not params_filename else params_filename

        place = paddle.CPUPlace()
        exe = paddle.static.Executor(place)

        feed_dict, fetch_dict, program = self.context(for_test=True, trainable=False)
        paddle.fluid.io.save_inference_model(
            dirname=dirname,
            main_program=program,
            executor=exe,
            feeded_var_names=[var.name for var in list(feed_dict.values())],
            target_vars=list(fetch_dict.values()),
            model_filename=model_filename,
            params_filename=params_filename)
284

W
wuzewu 已提交
285
    @paddle_utils.run_in_static_mode
286 287 288 289 290 291 292
    def export_onnx_model(self, dirname: str, **kwargs):
        '''
        Export the model to ONNX format.

        Args:
            dirname(str): The directory to save the onnx model.
            **kwargs(dict|optional): Other export configuration options for compatibility, some may be removed
W
wuzewu 已提交
293 294
                in the future. Don't use them If not necessary. Refer to https://github.com/PaddlePaddle/paddle2onnx
                for more information.
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        '''
        feed_dict, fetch_dict, program = self.context(for_test=True, trainable=False)
        inputs = set([var.name for var in feed_dict.values()])
        if self.type == 'CV/classification':
            outputs = [fetch_dict['class_probs']]
        else:
            outputs = set([var.name for var in fetch_dict.values()])
            outputs = [program.global_block().vars[key] for key in outputs]

        save_file = os.path.join(dirname, '{}.onnx'.format(self.name))
        paddle2onnx.program2onnx(
            program=program,
            scope=paddle.static.global_scope(),
            feed_var_names=inputs,
            target_vars=outputs,
            save_file=save_file,
            **kwargs)
W
wuzewu 已提交
312 313 314 315 316 317 318 319 320

    def sub_modules(self, recursive: bool = True):
        '''
        Get all sub modules.

        Args:
            recursive(bool): Whether to get sub modules recursively. Default to True.
        '''
        return []