paddle_helper.py 10.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 24
import paddle
import paddle.fluid as fluid

W
wuzewu 已提交
25 26 27 28
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 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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()))

48 49

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

53 54
    var_info = {
        'name': var.name,
W
wuzewu 已提交
55
        'dtype': convert_dtype_to_string(var.dtype),
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
        '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 已提交
74
def from_param_to_module_attr(param, module_attr):
W
wuzewu 已提交
75 76 77 78 79 80
    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 已提交
81 82 83 84 85 86 87 88
    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 已提交
89
        param.regularizer,
W
wuzewu 已提交
90
        module_attr.map.data['regularizer'],
W
wuzewu 已提交
91
        obj_filter=paddle_obj_filter)
W
wuzewu 已提交
92
    from_pyobj_to_module_attr(
W
wuzewu 已提交
93
        param.gradient_clip_attr,
W
wuzewu 已提交
94
        module_attr.map.data['gradient_clip_attr'],
W
wuzewu 已提交
95
        obj_filter=paddle_obj_filter)
96 97


W
wuzewu 已提交
98
def from_module_attr_to_param(module_attr):
99
    param = {'gradient_clip_attr': None, 'regularizer': None}
W
wuzewu 已提交
100 101 102 103
    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 已提交
104
    # do not recover learning rate
W
wuzewu 已提交
105 106 107 108 109 110
    #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.
111
            data['_regularization_coeff'])
112 113 114 115
        param['regularizer'] = eval(
            "fluid.regularizer.%s(regularization_coeff = %f)" %
            (regularizer_type, regularization_coeff))

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

    return param
W
wuzewu 已提交
143 144


W
wuzewu 已提交
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
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 已提交
170 171 172 173 174
def connect_program(pre_program,
                    next_program,
                    input_dict=None,
                    inplace=True,
                    need_log=True):
W
wuzewu 已提交
175

W
wuzewu 已提交
176 177 178 179 180 181
    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")

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

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

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

    block_map = {0: 0}
W
wuzewu 已提交
207 208
    if need_log:
        logger.info("Connect program's input tensor")
W
wuzewu 已提交
209 210
    for index, block in enumerate(next_program.blocks):
        if block.idx == 0:
211
            _copy_vars_and_ops_in_blocks(block, output_program.global_block())
W
wuzewu 已提交
212
        else:
213
            block_map[index] = len(output_program.blocks)
W
wuzewu 已提交
214 215 216
            logger.info(
                "block_%d in next_program merge into block_%d in pre_program" %
                (index, block_map[index]))
217
            new_block = output_program._create_block(
W
wuzewu 已提交
218 219
                parent_idx=block_map[block.parent_idx])
            _copy_vars_and_ops_in_blocks(block, new_block)
W
wuzewu 已提交
220 221
    if need_log:
        logger.info("Connect program's input tensor done")
222
    return output_program
W
wuzewu 已提交
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 254


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 已提交
255 256 257 258 259 260 261 262
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 已提交
263 264 265 266 267 268 269


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 已提交
270 271 272


def clone_program(origin_program, for_test=False):
W
wuzewu 已提交
273 274 275 276
    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 已提交
277 278 279 280 281 282
    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