module_v1.py 7.4 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
W
wuzewu 已提交
21
from easydict import EasyDict
W
wuzewu 已提交
22 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

W
wuzewu 已提交
32 33 34 35 36 37
    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 已提交
38 39
        self.helper = self
        self.signatures = self.desc.signatures
W
wuzewu 已提交
40
        self.default_signature = self.desc.default_signature
W
wuzewu 已提交
41 42

        self.directory = directory
W
wuzewu 已提交
43 44 45 46 47
        self._load_model()
        self._load_parameters()
        self._load_processor()
        self._load_assets()
        self._load_extra_info()
W
wuzewu 已提交
48
        self._generate_func()
W
wuzewu 已提交
49 50

    def _load_processor(self):
W
wuzewu 已提交
51 52 53 54
        # Some module does not have a processor(e.g. ernie)
        if not 'processor_info' in self.desc:
            return

W
wuzewu 已提交
55 56 57
        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 已提交
58
        self.processor = self.processor.Processor(module=self)
W
wuzewu 已提交
59 60 61

    def _load_assets(self):
        self.assets = []
W
wuzewu 已提交
62 63
        for file in os.listdir(self.assets_path()):
            filepath = os.path.join(self.assets_path(), file)
W
wuzewu 已提交
64 65 66 67
            self.assets.append(filepath)

    def _load_parameters(self):
        global_block = self.program.global_block()
W
wuzewu 已提交
68 69 70 71

        # record num parameters loaded by PaddleHub
        num_param_loaded = 0

W
wuzewu 已提交
72 73 74 75 76
        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 已提交
77
            num_param_loaded += 1
W
wuzewu 已提交
78
            var = global_block.vars[name]
W
wuzewu 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91

            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 已提交
92 93 94 95 96

    def _load_extra_info(self):
        for key, value in self.desc.extra_info.items():
            self.__dict__['get_{}'.format(key)] = value

W
wuzewu 已提交
97
    def _generate_func(self):
W
wuzewu 已提交
98
        for signature in self.desc.signatures:
W
wuzewu 已提交
99
            self.__dict__[signature] = functools.partial(self.__call__, sign_name=signature)
W
wuzewu 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112

    def _load_model(self):
        model_path = os.path.join(self.directory, 'model')
        exe = paddle.static.Executor(paddle.CPUPlace())
        self.program, _, _ = paddle.io.load_inference_model(model_path, executor=exe)

        # 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', [''])

W
wuzewu 已提交
113 114
    def context(self, signature: str = None, for_test: bool = False,
                trainable: bool = True) -> Tuple[dict, dict, paddle.static.Program]:
W
wuzewu 已提交
115 116 117 118 119 120 121 122
        '''
        '''
        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 已提交
123 124 125 126
        varinfos = [self.desc.signatures[signature]] if signature else self.desc.signatures.values()

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

W
wuzewu 已提交
130
            for fetch_var in info.outputs:
W
wuzewu 已提交
131 132 133 134 135 136 137 138
                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

        return feed_dict, fetch_dict, program

W
wuzewu 已提交
139
    def __call__(self, sign_name: str, data: dict, use_gpu: bool = False, batch_size: int = 1, **kwargs):
W
wuzewu 已提交
140 141
        '''
        '''
W
wuzewu 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

        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 已提交
175 176 177 178 179 180

    @classmethod
    def get_py_requirements(cls) -> List[str]:
        return []

    @classmethod
W
wuzewu 已提交
181 182 183 184 185 186 187 188
    def load(cls, directory: str) -> EasyDict:
        module_info = cls.load_module_info(directory)
        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 已提交
189
        cls.directory = directory
W
wuzewu 已提交
190
        return cls
W
wuzewu 已提交
191

W
wuzewu 已提交
192 193 194 195 196 197
    @classmethod
    def load_module_info(cls, directory: str) -> EasyDict:
        desc_file = os.path.join(directory, 'module_desc.pb')
        desc = module_v1_utils.convert_module_desc(desc_file)
        return desc.module_info

W
wuzewu 已提交
198 199
    def assets_path(self):
        return os.path.join(self.directory, 'assets')
W
wuzewu 已提交
200 201 202 203

    @property
    def is_runnable(self):
        return self.default_signature != None