dirac.py 12.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   Copyright (c) 2021 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.

from ...fluid.initializer import Initializer
from ...fluid.data_feeder import check_variable_and_dtype
from ...fluid.core import VarDesc
Z
zhiboniu 已提交
18 19 20
from ...fluid import framework
from paddle import in_dynamic_mode
from paddle.utils import unique_name
J
Jiabin Yang 已提交
21 22
from paddle import _C_ops
from ... import fluid
23

24 25 26 27
__all__ = []


class Dirac(Initializer):
28
    r"""Initialize the 3D/4D/5D Tensor with Dirac delta function.
29 30 31 32 33
    
    It can reserve the feature of convolution layer input, which means that
    as many channels are reserved as possible.

    In this initialize method, elements in the middle of convolution kernels will
34
    be set to 1 . The formula can be described as follow.
35

36
    .. math::
37

38
        X[d, d, shape[2]//2, shape[3]//2, ...]=1,  \   d=0,1...N
39 40
    
    where, ``N`` is the minimum value of ``in_channels`` and ``out_channels``
41 42

    Args:
43 44
        groups(int, optional): 0-dimension of the Tensor will be divided by groups, 
            each group has the same value. Default: 1.
45 46 47 48 49 50 51 52 53 54 55
        name(str, optional): The default value is None. Normally there is no need for user to set this
            property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Dirac initializer instance objects.

    Examples:
        .. code-block:: python

            import paddle
            
56
            #1. For kernel_size is uneven number:
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 103 104 105 106 107 108 109
            
            attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Dirac())
            conv = paddle.nn.Conv1D(3, 2, 3, weight_attr=attr)
            conv.weight
            # Tensor(shape=[2, 3, 3], dtype=float32, place=CPUPlace, stop_gradient=False,
            #       [[[0., 1., 0.],
            #         [0., 0., 0.],
            #         [0., 0., 0.]],
            # 
            #        [[0., 0., 0.],
            #         [0., 1., 0.],
            #         [0., 0., 0.]]])

            input = paddle.rand([8, 3, 10])
            output = conv(input)
            output == input[:, 0:2, 1:9]  
            # output.shape is [8, 2, 8], It means output is almost the same with input, 2 channels are reserved


            #2. For kernel_size is even number:
            attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Dirac())
            conv = paddle.nn.Conv1D(3, 2, 4, weight_attr=attr)
            conv.weight
            # Tensor(shape=[2, 3, 4], dtype=float32, place=CPUPlace, stop_gradient=False,
            #       [[[0., 0., 1., 0.],
            #         [0., 0., 0., 0.],
            #         [0., 0., 0., 0.]],
            # 
            #        [[0., 0., 0., 0.],
            #         [0., 0., 1., 0.],
            #         [0., 0., 0., 0.]]])
    """

    def __init__(self, groups=1, name=None):
        assert groups > 0 and isinstance(
            groups, int), " 'groups' must be a positive integer. "
        super(Dirac, self).__init__()
        self._groups = groups

    def __call__(self, var, block=None):
        """Initialize the input tensor with dirac initializer.

        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 most critical OP(scatter) in this initializer, which contains 7~8 ops in total.
        """
        block = self._check_block(block)
        assert isinstance(var, framework.Parameter)
        assert isinstance(block, framework.Block)
110 111 112
        check_variable_and_dtype(var, "Out",
                                 ['float16', 'bfloat16', 'float32', 'float64'],
                                 'Dirac')
113 114 115 116

        assert len(var.shape) in [
            3, 4, 5
        ], "Only Tensor with 3/4/5 dimensions can be initialized by Dirac"
117 118 119
        assert (
            var.shape[0] %
            self._groups) == 0, "Tensor 0-dimension must be divisible by groups"
120 121

        if var.dtype != VarDesc.VarType.FP32:
122 123 124 125 126 127
            out_var = block.create_var(name=unique_name.generate(".".join(
                ['dirac', var.name, 'tmp'])),
                                       shape=var.shape,
                                       dtype=VarDesc.VarType.FP32,
                                       type=VarDesc.VarType.LOD_TENSOR,
                                       persistable=False)
128 129
        else:
            out_var = var
J
Jiabin Yang 已提交
130 131 132
        op = None
        if framework.in_dygraph_mode():
            with fluid.dygraph.no_grad():
133 134
                _C_ops.fill_constant(out_var, 'value', float(0), 'force_cpu',
                                     False, 'dtype', out_var.dtype, 'str_value',
J
Jiabin Yang 已提交
135 136
                                     str(float(0)), 'shape', out_var.shape)
        else:
137 138 139 140 141 142 143 144 145
            block.append_op(type='fill_constant',
                            inputs={},
                            outputs={'Out': out_var},
                            attrs={
                                'value': float(0),
                                'dtype': out_var.dtype,
                                'shape': out_var.shape,
                            },
                            stop_gradient=True)
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

        origin_shape = var.shape
        num_per_group = origin_shape[0] // self._groups
        min_shape = min(num_per_group, origin_shape[1])

        idx_list = []
        value_list = []
        strides = []
        prod = 1
        for dim in reversed(origin_shape):
            strides.insert(0, prod)
            prod *= dim
        for i in range(self._groups):
            for j in range(min_shape):
                value_list.append(1.0)
                offset = 0
                for (k, stride) in enumerate(strides):
                    if (k == 0):
                        offset += (j + i * num_per_group) * stride
                    elif (k == 1):
                        offset += j * stride
                    else:
                        offset += origin_shape[k] // 2 * stride
                idx_list.append(offset)
J
Jiabin Yang 已提交
170 171
        if framework.in_dygraph_mode():
            with fluid.dygraph.no_grad():
172
                tmp_out, _ = _C_ops.reshape2(out_var, None, 'shape', [-1])
J
Jiabin Yang 已提交
173 174
                tmp_out._share_underline_tensor_to(out_var)
        else:
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
            x_shape = block.create_var(name=unique_name.generate(".".join(
                [out_var.name, "XShape"])),
                                       dtype=out_var.dtype,
                                       shape=out_var.shape,
                                       type=VarDesc.VarType.LOD_TENSOR,
                                       persistable=False,
                                       stop_gradient=True)
            block.append_op(type="reshape2",
                            inputs={"X": out_var},
                            attrs={'shape': [-1]},
                            outputs={
                                "Out": out_var,
                                "XShape": x_shape
                            },
                            stop_gradient=True)
190 191 192 193 194 195

        index_tensor = block.create_var(
            name=unique_name.generate('scatter_index'),
            persistable=False,
            stop_gradient=True)

J
Jiabin Yang 已提交
196 197
        if framework.in_dygraph_mode():
            with fluid.dygraph.no_grad():
W
wanghuancoder 已提交
198 199 200 201
                tmp_tensor = framework._varbase_creator()
                _C_ops.assign_value(tmp_tensor, 'shape', [len(idx_list)],
                                    'dtype', VarDesc.VarType.INT64,
                                    'int64_values', idx_list)
J
Jiabin Yang 已提交
202 203
                tmp_tensor._share_underline_tensor_to(index_tensor)
        else:
204 205 206 207 208 209 210 211
            block.append_op(type='assign_value',
                            outputs={'Out': index_tensor},
                            attrs={
                                'dtype': VarDesc.VarType.INT64,
                                'shape': [len(idx_list)],
                                'int64_values': idx_list
                            },
                            stop_gradient=True)
212 213 214 215 216 217

        value_tensor = block.create_var(
            name=unique_name.generate('scatter_value'),
            persistable=False,
            stop_gradient=True)

J
Jiabin Yang 已提交
218 219
        if framework.in_dygraph_mode():
            with fluid.dygraph.no_grad():
W
wanghuancoder 已提交
220 221 222 223
                tmp_tensor = framework._varbase_creator()
                _C_ops.assign_value(tmp_tensor, 'shape', [len(value_list)],
                                    'dtype', VarDesc.VarType.FP32,
                                    'fp32_values', value_list)
J
Jiabin Yang 已提交
224 225
                tmp_tensor._share_underline_tensor_to(value_tensor)
        else:
226 227 228 229 230 231 232 233
            block.append_op(type='assign_value',
                            outputs={'Out': value_tensor},
                            attrs={
                                'dtype': VarDesc.VarType.FP32,
                                'shape': [len(value_list)],
                                'fp32_values': value_list
                            },
                            stop_gradient=True)
234

J
Jiabin Yang 已提交
235 236 237 238 239
        if framework.in_dygraph_mode():
            with fluid.dygraph.no_grad():
                tmp_out = _C_ops.final_state_scatter(out_var, index_tensor,
                                                     value_tensor, True)
                tmp_out._share_underline_tensor_to(out_var)
240 241
                tmp_reshape_out, _ = _C_ops.reshape2(out_var, None, 'shape',
                                                     origin_shape)
J
Jiabin Yang 已提交
242 243 244 245 246 247
                tmp_reshape_out._share_underline_tensor_to(out_var)
                if var.dtype != VarDesc.VarType.FP32:
                    tmp_cast_out = _C_ops.cast(out_var, 'in_dtype',
                                               out_var.dtype, 'out_dtype',
                                               var.dtype)
                    tmp_cast_out._share_underline_tensor_to(var)
248

J
Jiabin Yang 已提交
249
        else:
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
            op = block.append_op(type="scatter",
                                 inputs={
                                     "X": out_var,
                                     "Ids": index_tensor,
                                     "Updates": value_tensor
                                 },
                                 attrs={'overwrite': True},
                                 outputs={"Out": out_var},
                                 stop_gradient=True)
            x_shape = block.create_var(name=unique_name.generate(".".join(
                [out_var.name, "XShape"])),
                                       dtype=out_var.dtype,
                                       shape=out_var.shape,
                                       type=VarDesc.VarType.LOD_TENSOR,
                                       persistable=False,
                                       stop_gradient=True)
            block.append_op(type="reshape2",
                            inputs={"X": out_var},
                            attrs={'shape': origin_shape},
                            outputs={
                                "Out": out_var,
                                "XShape": x_shape
                            },
                            stop_gradient=True)
J
Jiabin Yang 已提交
274
            if var.dtype != VarDesc.VarType.FP32:
275 276 277 278 279 280 281 282
                block.append_op(type="cast",
                                inputs={"X": out_var},
                                outputs={"Out": var},
                                attrs={
                                    "in_dtype": out_var.dtype,
                                    "out_dtype": var.dtype
                                },
                                stop_gradient=True)
Z
zhiboniu 已提交
283
        if not in_dynamic_mode():
284 285
            var.op = op
        return op