mpc_layer_helper.py 9.0 KB
Newer Older
J
jingqinghe 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
# Copyright (c) 2020 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.
"""
This module provide MpcLayerHelper, which are similar to
LayerHelper in PaddlePaddle.
"""

# system module
import copy
import six

# paddle module
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid import core
from paddle.fluid import unique_name
from paddle.fluid.param_attr import ParamAttr, WeightNormParamAttr
from paddle.fluid.initializer import ConstantInitializer

# mpc_paddle module
from .framework import MpcVariable, MpcParameter, create_mpc_parameter, create_mpc_var
J
jhjiangcs 已提交
32
from .initializer import XavierInitializer
J
jingqinghe 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

class MpcLayerHelper(LayerHelper):
    """
    Refer to paddle.fluid.LayerHelper.
    Add new methods for MpcVariable and MpcOps.
    """

    def create_global_mpc_variable(self, persistable=False, *args, **kwargs):
        """
        Refer to paddle.fluid.layer_helper_base.create_global_variable().
        Create global mpc variable.
        :param persistable:
        :param args:
        :param kwargs:
        :return:
        """
        mpc_block = self.main_program.global_block()
        mpc_var = MpcVariable(
            block=mpc_block, *args, persistable=persistable, **kwargs)
        if 'initializer' in kwargs:
            kwargs['initializer'](mpc_var, self)
        return mpc_var

    # TODO(Paddle1.7): hide the func after we move the layers to Layers
    def create_mpc_parameter(self,
                             attr,
                             shape,
                             dtype,
                             is_bias=False,
                             default_initializer=None,
                             stop_gradient=False,
                             type=core.VarDesc.VarType.LOD_TENSOR):
        """
        Create mpc parameters for this layers.
        Refer to LayerHelper.create_parameter in Paddle 1.7.
        :param attr:
        :param shape:
        :param dtype:
        :param is_bias:
        :param default_initializer:
        :param stop_gradient:
        :param type:
        :return:
        """
        # Deepcopy the attr so that parameters can be shared in program
        attr = copy.deepcopy(attr)
        attr = ParamAttr._to_attr(attr)
        if not attr:
            return None
        assert isinstance(attr, ParamAttr)
        suffix = 'b' if is_bias else 'w'
        if attr.name is None:
            attr.name = unique_name.generate(".".join([self.name, suffix]))

        if default_initializer is None and attr.initializer is None:
            if isinstance(dtype, core.VarDesc.VarType):
                if dtype != core.VarDesc.VarType.INT64:
                    raise TypeError(
                        "Can not create mpc parameter with default initializer "
                        "when dtype is not int64 type. Set default_initializer "
                        "to fit the parameter dtype!")
            else:
                if not dtype == "int64":
                    raise TypeError(
                        "Can not create mpc parameter with default initializer when "
                        "dtype is not int64 type. Set default_initializer to "
                        "fit the parameter dtype!")
            if is_bias:
                attr._set_default_bias_initializer()
            else:
J
jhjiangcs 已提交
103
                attr._set_default_initializer(XavierInitializer(seed=65536))
J
jingqinghe 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 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 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 205 206 207 208 209 210 211 212 213 214 215 216 217
        else:
            attr._set_default_initializer(default_initializer)

        # TODO(xukun07): not support WeightNormParamAttr in this first version
        # Paddle1.7: If weight normalization is set, insert extra parameters and ops.
        # Refer to https://arxiv.org/pdf/1602.07868.pdf
        if isinstance(attr, WeightNormParamAttr):
            # param = self._create_weight_normalize(attr, shape, dtype)
            # WeightNormParamAttr.params_with_weight_norm.append(param)
            # return param
            raise NotImplementedError(
                "The WeightNormParamAttr for attr is not "
                "supported in this version")

        startup_program_global_block = self.startup_program.global_block()
        create_mpc_parameter(
            block=startup_program_global_block,
            dtype=dtype,
            shape=shape,
            type=type,
            **attr._to_kwargs(with_initializer=True))
        main_program_global_block = self.main_program.global_block()
        return create_mpc_parameter(
            block=main_program_global_block,
            dtype=dtype,
            shape=shape,
            type=type,
            **attr._to_kwargs())

    # Note : not sure if this rewrite is needed
    def get_mpc_parameter(self, name):
        """
        Refer to LayerHelper.get_parameter in Paddle.
        :param name:
        :return:
        """
        param = self.main_program.global_block().var(name)
        if not isinstance(param, MpcParameter):
            raise ValueError("no MpcParameter name %s found" % name)
        return param

    def create_mpc_variable_for_type_inference(self,
                                               dtype,
                                               stop_gradient=False):
        """
        Create a temporary mpc variable that should be type inferred layer.
        Refer to LayerHelperBase.create_variable_for_type_inference in Paddle 1.7.
        :param dtype:
        :param stop_gradient:
        :return:
        """
        main_program_current_block = self.main_program.current_block()
        return create_mpc_var(
            block=main_program_current_block,
            name=unique_name.generate_with_ignorable_key(".".join(
                [self.name, 'tmp'])),
            dtype=dtype,
            type=core.VarDesc.VarType.LOD_TENSOR,
            persistable=False,
            stop_gradient=stop_gradient)

    def append_mpc_bias_op(self, input_var, dim_start=1, dim_end=None):
        """
        Append bias operator and return its mpc output. If the user does not set
        bias_attr, append_bias_op will return mpc input_var
        Refer to LayerHelper.append_bias_op in Paddle 1.7. Return mpc var.
        :param input_var:
        :param dim_start:
        :param dim_end:
        :return:
        """
        size = list(input_var.shape[
            dim_start + 1:dim_end])  # dims[0]: share_num; dims[1]: batch_size
        bias_attr = self.bias_attr
        if not bias_attr:
            return input_var

        b = self.create_mpc_parameter(
            attr=bias_attr, shape=size, dtype=input_var.dtype, is_bias=True)
        tmp = self.create_mpc_variable_for_type_inference(
            dtype=input_var.dtype)
        # Note: the type of mpc op = "mpc_" + paddle op
        self.append_op(
            type='mpc_elementwise_add',
            inputs={'X': [input_var],
                    'Y': [b]},
            outputs={'Out': [tmp]},
            attrs={'axis': dim_start})
        return tmp

    def append_mpc_activation(self, input_var):
        """
        Append mpc activation for this layer.
        Refer to LayerHelper.append_activation in Paddle 1.7.
        Return mpc ver.
        :param input_var:
        :return:
        """
        act = self.kwargs.get('act', None)
        if act is None:
            return input_var
        if isinstance(act, six.string_types):
            act = {'type': act}
        else:
            raise TypeError(str(act) + " should be unicode or str")

        if 'use_cudnn' in self.kwargs and self.kwargs.get('use_cudnn'):
            act['use_cudnn'] = self.kwargs.get('use_cudnn')
        if 'use_mkldnn' in self.kwargs:
            act['use_mkldnn'] = self.kwargs.get('use_mkldnn')
        act_type = act.pop('type')

        tmp = self.create_mpc_variable_for_type_inference(
            dtype=input_var.dtype)
J
jhjiangcs 已提交
218 219
        derivative = self.create_mpc_variable_for_type_inference(
            dtype=input_var.dtype)
J
jingqinghe 已提交
220 221 222 223
        # add "mpc_" as prefix of mpc activation
        self.append_op(
            type="mpc_" + act_type,
            inputs={"X": [input_var]},
J
jhjiangcs 已提交
224 225 226 227 228 229
<<<<<<< HEAD
            outputs={"Out": [tmp],
=======
            outputs={"Y": [tmp],
>>>>>>> 5a09665c36ffb7eae2288b3f837d3be18091c259
                     "Derivative": [derivative]},
J
jingqinghe 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
            attrs=act)
        return tmp

    def create_mpc_variable(self, *args, **kwargs):
        """
        Create MpcVariable for this layers.
        Refer to LayerHelperBase.create_variable in Paddle 1.7.
        Return created MpcVariable.
        :param args:
        :param kwargs:
        :return:
        """
        main_program_current_block = self.main_program.current_block()
        return create_mpc_var(
            block=main_program_current_block, *args, **kwargs)