normal.py 9.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15 16 17 18 19 20
from paddle import _C_ops

from ...fluid import core, framework, unique_name
from ...fluid.data_feeder import check_variable_and_dtype
from ...fluid.framework import _current_expected_place, in_dygraph_mode
from .initializer import Initializer
21

22 23
__all__ = []

24

25 26 27 28 29 30 31 32 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
class NormalInitializer(Initializer):
    """Implements the Random Normal(Gaussian) distribution initializer

    Args:
        loc (float, optional): mean of the normal distribution. Default is 0.0.
        scale (float, optional): standard deviation of the normal distribution. Default is 1.0.
        seed (int, optional): random seed. Default is 0.

    """

    def __init__(self, loc=0.0, scale=1.0, seed=0):
        assert loc is not None
        assert scale is not None
        assert seed is not None
        super().__init__()
        self._mean = loc
        self._std_dev = scale
        self._seed = seed

    def forward(self, var, block=None):
        """Initialize the input tensor with Normal distribution.

        Args:
            var(Tensor): Tensor that needs to be initialized.
            block(Block, optional): The block in which initialization ops
                   should be added. Used in static graph only, default None.

        Returns:
            The initialization op
        """
        block = self._check_block(block)

        assert isinstance(block, framework.Block)

        check_variable_and_dtype(
            var,
            "Out",
            ["uint16", "float16", "float32", "float64"],
            "guassian_random",
        )

        if self._seed == 0:
            self._seed = block.program.random_seed

        if in_dygraph_mode():
            place = _current_expected_place()
            out_var = _C_ops.gaussian(
                var.shape,
                self._mean,
                self._std_dev,
                self._seed,
                var.dtype,
                place,
            )
            out_var._share_underline_tensor_to(var)
            return None

        else:
            op = block.append_op(
                type="gaussian_random",
                outputs={"Out": var},
                attrs={
                    "shape": var.shape,
                    "dtype": var.dtype,
                    "mean": self._mean,
                    "std": self._std_dev,
                    "seed": self._seed,
                    "use_mkldnn": False,
                },
                stop_gradient=True,
            )
            var.op = op
            return op


100 101 102 103
class Normal(NormalInitializer):
    """The Random Normal (Gaussian) distribution initializer.

    Args:
104 105
        mean (float, optional): mean of the normal distribution. Default is 0.0.
        std (float, optional): standard deviation of the normal distribution. Default is 1.0.
106
        name(str, optional): The default value is None. Normally there is no need for user to set this
107
            property. For more information, please refer to :ref:`api_guide_Name`. Default: None.
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

    Returns:
        A parameter initialized by Random Normal (Gaussian) distribution.

    Examples:
        .. code-block:: python

            import paddle

            data = paddle.ones(shape=[3, 1, 2], dtype='float32')
            weight_attr = paddle.framework.ParamAttr(
                name="linear_weight",
                initializer=paddle.nn.initializer.Normal(mean=0.0, std=2.0))
            bias_attr = paddle.framework.ParamAttr(
                name="linear_bias",
                initializer=paddle.nn.initializer.Normal(mean=0.0, std=2.0))
            linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr)
            # linear.weight:  [[ 2.1973135 -2.2697184]
            #                  [-1.9104223 -1.0541488]]
            # linear.bias:  [ 0.7885926  -0.74719954]
128

129 130 131 132 133 134 135 136 137
            res = linear(data)
            # res:  [[[ 1.0754838 -4.071067 ]]
            #        [[ 1.0754838 -4.071067 ]]
            #        [[ 1.0754838 -4.071067 ]]]
    """

    def __init__(self, mean=0.0, std=1.0, name=None):
        assert mean is not None, 'mean should not be None'
        assert std is not None, 'std should not be None'
138
        super().__init__(loc=mean, scale=std, seed=0)
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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
class TruncatedNormalInitializer(Initializer):
    """Implements the Random TruncatedNormal(Gaussian) distribution initializer

    Args:
        loc (float, optional): Mean of the normal distribution. Default is :math:`0.0`.
        scale (float, optional): Standard deviation of the normal distribution. Default is :math:`1.0`.
        seed (int, optional): random seed. Default is 0.

    """

    def __init__(self, loc=0.0, scale=1.0, seed=0):
        assert loc is not None
        assert scale is not None
        assert seed is not None
        super().__init__()
        self._mean = loc
        self._std_dev = scale
        self._seed = seed

    def forward(self, var, block=None):
        """Initialize the input tensor with TruncatedNormal distribution.

        Args:
            var(Tensor): Tensor that needs to be initialized.
            block(Block, optional): The block in which initialization ops
                   should be added. Used in static graph only, default None.

        Returns:
            The initialization op
        """
        block = self._check_block(block)

        assert isinstance(var, framework.Variable)
        assert isinstance(block, framework.Block)

        if self._seed == 0:
            self._seed = block.program.random_seed

        # to be compatible of fp16 initalizers
        if var.dtype in [core.VarDesc.VarType.FP16, core.VarDesc.VarType.BF16]:
            out_dtype = core.VarDesc.VarType.FP32
            out_var = block.create_var(
                name=unique_name.generate(
                    ".".join(['truncated_gaussian_random', var.name, 'tmp'])
                ),
                shape=var.shape,
                dtype=out_dtype,
                type=core.VarDesc.VarType.LOD_TENSOR,
                persistable=False,
            )
        else:
            out_dtype = var.dtype
            out_var = var

        if in_dygraph_mode():
            out_var = _C_ops.truncated_gaussian_random(
                var.shape,
                self._mean,
                self._std_dev,
                self._seed,
                out_dtype,
                _current_expected_place(),
            )
            if var.dtype in [
                core.VarDesc.VarType.FP16,
                core.VarDesc.VarType.BF16,
            ]:
                var_tmp = _C_ops.cast(out_var, var.dtype)
                var_tmp._share_underline_tensor_to(var)
            else:
                out_var._share_underline_tensor_to(var)
            return None

        else:
            op = block.append_op(
                type="truncated_gaussian_random",
                outputs={"Out": out_var},
                attrs={
                    "shape": var.shape,
                    "dtype": out_dtype,
                    "mean": self._mean,
                    "std": self._std_dev,
                    "seed": self._seed,
                },
                stop_gradient=True,
            )

            if var.dtype in [
                core.VarDesc.VarType.FP16,
                core.VarDesc.VarType.BF16,
            ]:
                block.append_op(
                    type="cast",
                    inputs={"X": out_var},
                    outputs={"Out": var},
                    attrs={"in_dtype": out_var.dtype, "out_dtype": var.dtype},
                )
            var.op = op
            return op


242
class TruncatedNormal(TruncatedNormalInitializer):
B
BrilliantYuKaimin 已提交
243
    """The truncated normal distribution (Gaussian distribution) initializer.
244 245

    Args:
246 247
        mean (float, optional): Mean of the normal distribution. Default is :math:`0.0`.
        std (float, optional): Standard deviation of the normal distribution. Default is :math:`1.0`.
B
BrilliantYuKaimin 已提交
248
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
249 250

    Returns:
B
BrilliantYuKaimin 已提交
251
        A parameter initialized by truncated normal distribution (Gaussian distribution).
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

    Examples:
        .. code-block:: python

            import paddle

            data = paddle.ones(shape=[3, 1, 2], dtype='float32')
            weight_attr = paddle.framework.ParamAttr(
                name="linear_weight",
                initializer=paddle.nn.initializer.TruncatedNormal(mean=0.0, std=2.0))
            bias_attr = paddle.framework.ParamAttr(
                name="linear_bias",
                initializer=paddle.nn.initializer.TruncatedNormal(mean=0.0, std=2.0))
            linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr)
            # linear.weight:  [[-1.0981836  1.4140984]
            #                  [ 3.1390522 -2.8266568]]
            # linear.bias:  [-2.1546738 -1.6570673]

            res = linear(data)
            # res:  [[[-0.11380529 -3.0696259 ]]
            #        [[-0.11380529 -3.0696259 ]]
            #        [[-0.11380529 -3.0696259 ]]
    """

    def __init__(self, mean=0.0, std=1.0, name=None):
        assert mean is not None, 'mean should not be None'
        assert std is not None, 'std should not be None'
279
        super().__init__(loc=mean, scale=std, seed=0)