paddle_helper.py 11.6 KB
Newer Older
S
Steffy-zxf 已提交
1
#coding:utf-8
W
wuzewu 已提交
2
# Copyright (c) 2019  PaddlePaddle Authors. All Rights Reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#
# 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 absolute_import
from __future__ import division
from __future__ import print_function
W
wuzewu 已提交
19

20 21
import copy

22 23
import paddle.fluid as fluid

W
wuzewu 已提交
24 25 26 27
from paddlehub.module import module_desc_pb2
from paddlehub.common.utils import from_pyobj_to_module_attr, from_module_attr_to_pyobj
from paddlehub.common.logger import logger

W
wuzewu 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
dtype_map = {
    fluid.core.VarDesc.VarType.FP32: "float32",
    fluid.core.VarDesc.VarType.FP64: "float64",
    fluid.core.VarDesc.VarType.FP16: "float16",
    fluid.core.VarDesc.VarType.INT32: "int32",
    fluid.core.VarDesc.VarType.INT16: "int16",
    fluid.core.VarDesc.VarType.INT64: "int64",
    fluid.core.VarDesc.VarType.BOOL: "bool",
    fluid.core.VarDesc.VarType.INT16: "int16",
    fluid.core.VarDesc.VarType.UINT8: "uint8",
    fluid.core.VarDesc.VarType.INT8: "int8",
}


def convert_dtype_to_string(dtype):
    if dtype in dtype_map:
        return dtype_map[dtype]
    raise TypeError("dtype shoule in %s" % list(dtype_map.keys()))

47 48

def get_variable_info(var):
W
wuzewu 已提交
49 50 51
    if not isinstance(var, fluid.framework.Variable):
        raise TypeError("var shoule be an instance of fluid.framework.Variable")

52 53
    var_info = {
        'name': var.name,
W
wuzewu 已提交
54
        'dtype': convert_dtype_to_string(var.dtype),
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
        'lod_level': var.lod_level,
        'shape': var.shape,
        'stop_gradient': var.stop_gradient,
        'is_data': var.is_data,
        'error_clip': var.error_clip
    }
    if isinstance(var, fluid.framework.Parameter):
        var_info['trainable'] = var.trainable
        var_info['optimize_attr'] = var.optimize_attr
        var_info['regularizer'] = var.regularizer
        var_info['gradient_clip_attr'] = var.gradient_clip_attr
        var_info['do_model_average'] = var.do_model_average
    else:
        var_info['persistable'] = var.persistable

    return var_info


W
wuzewu 已提交
73
def from_param_to_module_attr(param, module_attr):
W
wuzewu 已提交
74 75 76 77 78 79
    def paddle_obj_filter(pyobj):
        return isinstance(pyobj, fluid.framework.Variable) or isinstance(
            pyobj, fluid.framework.Block) or isinstance(
                pyobj, fluid.framework.Program) or isinstance(
                    pyobj, fluid.framework.Operator)

W
wuzewu 已提交
80 81 82 83 84 85 86 87
    module_attr.type = module_desc_pb2.MAP
    from_pyobj_to_module_attr(param.trainable,
                              module_attr.map.data['trainable'])
    from_pyobj_to_module_attr(param.do_model_average,
                              module_attr.map.data['do_model_average'])
    from_pyobj_to_module_attr(param.optimize_attr,
                              module_attr.map.data['optimize_attr'])
    from_pyobj_to_module_attr(
W
wuzewu 已提交
88
        param.regularizer,
W
wuzewu 已提交
89
        module_attr.map.data['regularizer'],
W
wuzewu 已提交
90
        obj_filter=paddle_obj_filter)
W
wuzewu 已提交
91
    from_pyobj_to_module_attr(
W
wuzewu 已提交
92
        param.gradient_clip_attr,
W
wuzewu 已提交
93
        module_attr.map.data['gradient_clip_attr'],
W
wuzewu 已提交
94
        obj_filter=paddle_obj_filter)
95 96


W
wuzewu 已提交
97
def from_module_attr_to_param(module_attr):
98
    param = {'gradient_clip_attr': None, 'regularizer': None}
W
wuzewu 已提交
99 100 101 102
    param['trainable'] = from_module_attr_to_pyobj(
        module_attr.map.data['trainable'])
    param['do_model_average'] = from_module_attr_to_pyobj(
        module_attr.map.data['do_model_average'])
W
wuzewu 已提交
103
    # do not recover learning rate
W
wuzewu 已提交
104 105 106 107 108 109
    #param['optimize_attr'] = from_module_attr_to_pyobj(
    #    module_attr.map.data['optimize_attr'])
    if module_attr.map.data['regularizer'].type != module_desc_pb2.NONE:
        regularizer_type = module_attr.map.data['regularizer'].name
        regularization_coeff = from_module_attr_to_pyobj(
            module_attr.map.data['regularizer'].object.
110
            data['_regularization_coeff'])
111 112 113 114
        param['regularizer'] = eval(
            "fluid.regularizer.%s(regularization_coeff = %f)" %
            (regularizer_type, regularization_coeff))

W
wuzewu 已提交
115 116
    if module_attr.map.data['gradient_clip_attr'].type != module_desc_pb2.NONE:
        clip_type = module_attr.map.data['gradient_clip_attr'].name
117
        if clip_type == "ErrorClipByValue" or clip_type == "GradientClipByValue":
W
wuzewu 已提交
118 119 120 121
            max = from_module_attr_to_pyobj(
                module_attr.map.data['gradient_clip_attr'].object.data['max'])
            min = from_module_attr_to_pyobj(
                module_attr.map.data['gradient_clip_attr'].object.data['min'])
122 123 124
            param['gradient_clip_attr'] = eval(
                "fluid.clip.%s(max = %f, min = %f)" % (clip_type, max, min))
        if clip_type == "GradientClipByNorm":
W
wuzewu 已提交
125 126
            clip_norm = from_module_attr_to_pyobj(
                module_attr.map.data['gradient_clip_attr'].object.
127
                data['clip_norm'])
128 129 130
            param['gradient_clip_attr'] = eval(
                "fluid.clip.%s(clip_norm = %f)" % (clip_type, clip_norm))
        if clip_type == "GradientClipByGlobalNorm":
W
wuzewu 已提交
131 132
            clip_norm = from_module_attr_to_pyobj(
                module_attr.map.data['gradient_clip_attr'].object.
133
                data['clip_norm'])
W
wuzewu 已提交
134 135
            group_name = from_module_attr_to_pyobj(
                module_attr.map.data['gradient_clip_attr'].object.
136
                data['group_name'])
137
            param['gradient_clip_attr'] = eval(
138
                "fluid.clip.%s(clip_norm = %f, group_name = \"%s\")" %
139 140 141
                (clip_type, clip_norm, group_name))

    return param
W
wuzewu 已提交
142 143


W
wuzewu 已提交
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
def _copy_vars_and_ops_in_blocks(from_block, to_block):
    for var in from_block.vars:
        var = from_block.var(var)
        var_info = copy.deepcopy(get_variable_info(var))
        if isinstance(var, fluid.framework.Parameter):
            to_block.create_parameter(**var_info)
        else:
            to_block.create_var(**var_info)

    for op in from_block.ops:
        op_info = {
            'type': op.type,
            'inputs': {
                input: [to_block.var(var) for var in op.input(input)]
                for input in op.input_names
            },
            'outputs': {
                output: [to_block.var(var) for var in op.output(output)]
                for output in op.output_names
            },
            'attrs': copy.deepcopy(op.all_attrs())
        }
        to_block.append_op(**op_info)


W
wuzewu 已提交
169 170 171 172 173
def connect_program(pre_program,
                    next_program,
                    input_dict=None,
                    inplace=True,
                    need_log=True):
W
wuzewu 已提交
174

W
wuzewu 已提交
175 176 177 178 179 180
    if not isinstance(pre_program, fluid.Program):
        raise TypeError("pre_program shoule be an instance of fluid.Program")

    if not isinstance(next_program, fluid.Program):
        raise TypeError("next_program shoule be an instance of fluid.Program")

181 182
    output_program = pre_program if inplace else pre_program.clone(
        for_test=False)
W
wuzewu 已提交
183
    if input_dict:
W
wuzewu 已提交
184 185 186 187 188
        if not isinstance(input_dict, dict):
            raise TypeError(
                "input_dict shoule be a python dict like {str:fluid.framework.Variable}"
            )

W
wuzewu 已提交
189
        for key, var in input_dict.items():
W
wuzewu 已提交
190 191 192 193 194
            if not isinstance(var, fluid.framework.Variable):
                raise TypeError(
                    "input_dict shoule be a python dict like {str:fluid.framework.Variable}"
                )

W
wuzewu 已提交
195
            var_info = copy.deepcopy(get_variable_info(var))
196
            input_var = output_program.global_block().create_var(**var_info)
W
wuzewu 已提交
197 198
            output_var = next_program.global_block().var(key)
            var_info = copy.deepcopy(get_variable_info(output_var))
199 200
            output_var = output_program.global_block().create_var(**var_info)
            output_program.global_block().append_op(
W
wuzewu 已提交
201 202 203 204 205
                type="assign",
                inputs={'X': input_var},
                outputs={'Out': output_var})

    block_map = {0: 0}
W
wuzewu 已提交
206 207
    if need_log:
        logger.info("Connect program's input tensor")
W
wuzewu 已提交
208 209
    for index, block in enumerate(next_program.blocks):
        if block.idx == 0:
210
            _copy_vars_and_ops_in_blocks(block, output_program.global_block())
W
wuzewu 已提交
211
        else:
212
            block_map[index] = len(output_program.blocks)
W
wuzewu 已提交
213 214 215
            logger.info(
                "block_%d in next_program merge into block_%d in pre_program" %
                (index, block_map[index]))
216
            new_block = output_program._create_block(
W
wuzewu 已提交
217 218
                parent_idx=block_map[block.parent_idx])
            _copy_vars_and_ops_in_blocks(block, new_block)
W
wuzewu 已提交
219 220
    if need_log:
        logger.info("Connect program's input tensor done")
221
    return output_program
W
wuzewu 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253


def remove_feed_fetch_op(program):
    """ remove feed and fetch operator and variable for fine-tuning
    """
    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)

    need_to_remove_var = []
    for var in block.vars:
        if var.endswith("feed"):
            need_to_remove_var.append(var)
        if var.endswith("fetch"):
            need_to_remove_var.append(var)

    for var in need_to_remove_var:
        block._remove_var(var)

    program.desc.flush()


def set_parameter_trainable(program, trainable=True):
    for param in program.global_block().iter_parameters():
        param.trainable = trainable


W
wuzewu 已提交
254 255 256 257 258 259 260 261
def set_parameter_regularizer(program, regularizer):
    for param in program.global_block().iter_parameters():
        param.regularizer = regularizer


def set_parameter_learning_rate(program, learning_rate):
    for param in program.global_block().iter_parameters():
        param.optimize_attr['learning_rate'] = learning_rate
W
wuzewu 已提交
262 263 264 265 266 267 268


def set_op_attr(program, is_test=False):
    for block in program.blocks:
        for op in block.ops:
            if op.has_attr("is_test"):
                op._set_attr("is_test", is_test)
S
Steffy-zxf 已提交
269 270 271


def clone_program(origin_program, for_test=False):
W
wuzewu 已提交
272 273 274 275
    dest_program = fluid.Program()
    _copy_vars_and_ops_in_blocks(origin_program.global_block(),
                                 dest_program.global_block())
    dest_program = dest_program.clone(for_test=for_test)
S
Steffy-zxf 已提交
276 277 278 279 280 281
    if not for_test:
        for name, var in origin_program.global_block().vars.items():
            dest_program.global_block(
            ).vars[name].stop_gradient = var.stop_gradient

    return dest_program
W
wuzewu 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296


def rename_var(block, old_name, new_name):
    for op in block.ops:
        for input_name in op.input_arg_names:
            if input_name == old_name:
                op._rename_input(old_name, new_name)

        for output_name in op.output_arg_names:
            if output_name == old_name:
                op._rename_output(old_name, new_name)

    block._rename_var(old_name, new_name)


W
wuzewu 已提交
297
def add_vars_prefix(program, prefix, vars=None, excludes=None):
W
wuzewu 已提交
298 299
    block = program.global_block()
    vars = list(vars) if vars else list(block.vars.keys())
W
wuzewu 已提交
300
    vars = [var for var in vars if var not in excludes] if excludes else vars
W
wuzewu 已提交
301 302 303 304
    for var in vars:
        rename_var(block, var, prefix + var)


W
wuzewu 已提交
305
def remove_vars_prefix(program, prefix, vars=None, excludes=None):
W
wuzewu 已提交
306 307 308 309
    block = program.global_block()
    vars = [var for var in vars if var.startswith(prefix)] if vars else [
        var for var in block.vars.keys() if var.startswith(prefix)
    ]
W
wuzewu 已提交
310
    vars = [var for var in vars if var not in excludes] if excludes else vars
W
wuzewu 已提交
311 312
    for var in vars:
        rename_var(block, var, var.replace(prefix, "", 1))