layers.py 64.7 KB
Newer Older
C
Chang Xu 已提交
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
C
ceci3 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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
import os
C
ceci3 已提交
16 17
import numpy as np
import logging
C
ceci3 已提交
18
import paddle
C
ceci3 已提交
19 20 21

from ...common import get_logger
from .utils.utils import compute_start_end, get_same_padding, convert_to_list
22
from .layers_base import *
C
ceci3 已提交
23 24 25

__all__ = [
    'SuperConv2D', 'SuperConv2DTranspose', 'SuperSeparableConv2D',
26
    'SuperBatchNorm2D', 'SuperLinear', 'SuperInstanceNorm2D',
C
ceci3 已提交
27
    'SuperGroupConv2D', 'SuperDepthwiseConv2D', 'SuperGroupConv2DTranspose',
C
Chang Xu 已提交
28 29
    'SuperDepthwiseConv2DTranspose', 'SuperLayerNorm', 'SuperEmbedding',
    'SuperSyncBatchNorm'
C
ceci3 已提交
30 31 32 33 34 35 36
]

_logger = get_logger(__name__, level=logging.INFO)

### TODO: if task is elastic width, need to add re_organize_middle_weight in 1x1 conv in MBBlock


W
whs 已提交
37
class SuperConv2D(paddle.nn.Conv2D):
W
whs 已提交
38
    """This interface is used to construct a callable object of the ``SuperConv2D``  class.
C
ceci3 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    Note: the channel in config need to less than first defined.
    The super convolution2D layer calculates the output based on the input, filter
    and strides, paddings, dilations, groups parameters. Input and
    Output are in NCHW format, where N is batch size, C is the number of
    the feature map, H is the height of the feature map, and W is the width of the feature map.
    Filter's shape is [MCHW] , where M is the number of output feature map,
    C is the number of input feature map, H is the height of the filter,
    and W is the width of the filter. If the groups is greater than 1,
    C will equal the number of input feature map divided by the groups.
    Please refer to UFLDL's `convolution
    <http://ufldl.stanford.edu/tutorial/supervised/FeatureExtractionUsingConvolution/>`_
    for more details.
    If bias attribution and activation type are provided, bias is added to the
    output of the convolution, and the corresponding activation function is
    applied to the final result.
    For each input :math:`X`, the equation is:
    .. math::
C
ceci3 已提交
56
        Out = sigma (W \\ast X + b)
C
ceci3 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    Where:
    * :math:`X`: Input value, a ``Tensor`` with NCHW format.
    * :math:`W`: Filter value, a ``Tensor`` with shape [MCHW] .
    * :math:`\\ast`: Convolution operation.
    * :math:`b`: Bias value, a 2-D ``Tensor`` with shape [M, 1].
    * :math:`\\sigma`: Activation function.
    * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
    Example:
        - Input:
          Input shape: :math:`(N, C_{in}, H_{in}, W_{in})`
          Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)`
        - Output:
          Output shape: :math:`(N, C_{out}, H_{out}, W_{out})`
        Where
        .. math::
C
ceci3 已提交
72
            H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1   
C
ceci3 已提交
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
            W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1
    Parameters:
        num_channels(int): The number of channels in the input image.
        num_filters(int): The number of filter. It is as same as the output
            feature map.
        filter_size (int or tuple): The filter size. If filter_size is a tuple,
            it must contain two integers, (filter_size_H, filter_size_W).
            Otherwise, the filter will be a square.
        candidate_config(dict, optional): Dictionary descripts candidate config of this layer,
            such as {'kernel_size': (3, 5, 7), 'channel': (4, 6, 8)}, means the kernel size of 
            this layer can be choose from (3, 5, 7), the key of candidate_config
            only can be 'kernel_size', 'channel' and 'expand_ratio', 'channel' and 'expand_ratio'
            CANNOT be set at the same time. Default: None.
        transform_kernel(bool, optional): Whether to use transform matrix to transform a large filter
            to a small filter. Default: False.
        stride (int or tuple, optional): The stride size. If stride is a tuple, it must
            contain two integers, (stride_H, stride_W). Otherwise, the
            stride_H = stride_W = stride. Default: 1.
        padding (int or tuple, optional): The padding size. If padding is a tuple, it must
            contain two integers, (padding_H, padding_W). Otherwise, the
            padding_H = padding_W = padding. Default: 0.
        dilation (int or tuple, optional): The dilation size. If dilation is a tuple, it must
            contain two integers, (dilation_H, dilation_W). Otherwise, the
            dilation_H = dilation_W = dilation. Default: 1.
        groups (int, optional): The groups number of the Conv2d Layer. According to grouped
            convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
            the first half of the filters is only connected to the first half
            of the input channels, while the second half of the filters is only
            connected to the second half of the input channels. Default: 1.
        param_attr (ParamAttr, optional): The parameter attribute for learnable weights(Parameter)
W
whs 已提交
103 104
            of conv2d. If it is set to None or one attribute of paddle.ParamAttr, conv2d
            will create paddle.ParamAttr as param_attr. If the Initializer of the param_attr
C
ceci3 已提交
105
            is not set, the parameter is initialized with :math:`Normal(0.0, std)`,
W
whs 已提交
106
            and the :math:`std` is :math:`(\\frac{2.0 }{filter\\_elem\\_num})^{0.5}`. Default: None.
C
ceci3 已提交
107 108
        bias_attr (ParamAttr or bool, optional): The attribute for the bias of conv2d.
            If it is set to False, no bias will be added to the output units.
W
whs 已提交
109 110
            If it is set to None or one attribute of paddle.ParamAttr, conv2d
            will create paddle.ParamAttr as bias_attr. If the Initializer of the bias_attr
C
ceci3 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
            is not set, the bias is initialized zero. Default: None.
        use_cudnn (bool, optional): Use cudnn kernel or not, it is valid only when the cudnn
            library is installed. Default: True.
        act (str, optional): Activation type, if it is set to None, activation is not appended.
            Default: None.
        dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32".
    Attribute:
        **weight** (Parameter): the learnable weights of filter of this layer.
        **bias** (Parameter or None): the learnable bias of this layer.
    Returns:
        None
    
    Raises:
        ValueError: if ``use_cudnn`` is not a bool value.
    Examples:
        .. code-block:: python
C
ceci3 已提交
127 128
          import paddle 
          from paddleslim.nas.ofa.layers import SuperConv2D
C
ceci3 已提交
129 130
          import numpy as np
          data = np.random.uniform(-1, 1, [10, 3, 32, 32]).astype('float32')
C
ceci3 已提交
131 132
          super_conv2d = SuperConv2D(3, 10, 3)
          config = {'channel': 5}
C
ceci3 已提交
133
          data = paddle.to_tensor(data)
C
ceci3 已提交
134
          conv = super_conv2d(data, config)
C
ceci3 已提交
135 136 137 138
    """

    ### NOTE: filter_size, num_channels and num_filters must be the max of candidate to define a largest network.
    def __init__(self,
C
ceci3 已提交
139 140 141
                 in_channels,
                 out_channels,
                 kernel_size,
C
ceci3 已提交
142 143 144 145
                 candidate_config={},
                 transform_kernel=False,
                 stride=1,
                 padding=0,
C
ceci3 已提交
146 147 148 149
                 dilation=1,
                 groups=1,
                 padding_mode='zeros',
                 weight_attr=None,
C
ceci3 已提交
150
                 bias_attr=None,
C
ceci3 已提交
151
                 data_format='NCHW'):
C
ceci3 已提交
152
        super(SuperConv2D, self).__init__(
C
ceci3 已提交
153 154 155 156 157 158 159 160 161 162 163
            in_channels,
            out_channels,
            kernel_size,
            stride=stride,
            padding=padding,
            padding_mode=padding_mode,
            dilation=dilation,
            groups=groups,
            weight_attr=weight_attr,
            bias_attr=bias_attr,
            data_format=data_format)
C
ceci3 已提交
164 165

        self.candidate_config = candidate_config
C
Chang Xu 已提交
166
        self.cur_config = None
C
ceci3 已提交
167 168 169 170 171 172 173 174 175 176 177
        if len(candidate_config.items()) != 0:
            for k, v in candidate_config.items():
                candidate_config[k] = list(set(v))

        self.ks_set = candidate_config[
            'kernel_size'] if 'kernel_size' in candidate_config else None

        self.expand_ratio = candidate_config[
            'expand_ratio'] if 'expand_ratio' in candidate_config else None
        self.channel = candidate_config[
            'channel'] if 'channel' in candidate_config else None
C
ceci3 已提交
178
        self.base_channel = self._out_channels
C
ceci3 已提交
179
        if self.expand_ratio != None:
C
ceci3 已提交
180
            self.base_channel = int(self._out_channels / max(self.expand_ratio))
C
ceci3 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193

        self.transform_kernel = transform_kernel
        if self.ks_set != None:
            self.ks_set.sort()
        if self.transform_kernel != False:
            scale_param = dict()
            ### create parameter to transform kernel
            for i in range(len(self.ks_set) - 1):
                ks_small = self.ks_set[i]
                ks_large = self.ks_set[i + 1]
                param_name = '%dto%d_matrix' % (ks_large, ks_small)
                ks_t = ks_small**2
                scale_param[param_name] = self.create_parameter(
C
ceci3 已提交
194
                    attr=paddle.ParamAttr(
C
ceci3 已提交
195
                        name=self._full_name + param_name,
W
whs 已提交
196
                        initializer=paddle.nn.initializer.Assign(np.eye(ks_t))),
C
ceci3 已提交
197 198 199 200 201 202 203
                    shape=(ks_t, ks_t),
                    dtype=self._dtype)

            for name, param in scale_param.items():
                setattr(self, name, param)

    def get_active_filter(self, in_nc, out_nc, kernel_size):
C
ceci3 已提交
204
        start, end = compute_start_end(self._kernel_size[0], kernel_size)
C
ceci3 已提交
205
        ### if NOT transform kernel, intercept a center filter with kernel_size from largest filter
206 207 208 209
        if self.weight.shape[0] <= out_nc and self.weight.shape[1] <= in_nc:
            filters = self.weight
        else:
            filters = self.weight[:out_nc, :in_nc, start:end, start:end]
210
        if self.transform_kernel != False and kernel_size < self._kernel_size[0]:
C
ceci3 已提交
211 212 213 214 215 216 217 218 219
            ### if transform kernel, then use matrix to transform
            start_filter = self.weight[:out_nc, :in_nc, :, :]
            for i in range(len(self.ks_set) - 1, 0, -1):
                src_ks = self.ks_set[i]
                if src_ks <= kernel_size:
                    break
                target_ks = self.ks_set[i - 1]
                start, end = compute_start_end(src_ks, target_ks)
                _input_filter = start_filter[:, :, start:end, start:end]
C
ceci3 已提交
220
                _input_filter = paddle.reshape(
C
ceci3 已提交
221 222 223
                    _input_filter,
                    shape=[(_input_filter.shape[0] * _input_filter.shape[1]),
                           -1])
224 225 226 227 228
                _input_filter = paddle.matmul(_input_filter,
                                              self.__getattr__(
                                                  '%dto%d_matrix' %
                                                  (src_ks, target_ks)), False,
                                              False)
C
ceci3 已提交
229
                _input_filter = paddle.reshape(
C
ceci3 已提交
230 231 232 233 234 235 236 237 238
                    _input_filter,
                    shape=[
                        filters.shape[0], filters.shape[1], target_ks, target_ks
                    ])
                start_filter = _input_filter
            filters = start_filter
        return filters

    def get_groups_in_out_nc(self, in_nc, out_nc):
C
ceci3 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
        if self._groups == 1:
            ### standard conv
            return self._groups, in_nc, out_nc
        elif self._groups == self._in_channels:
            ### depthwise convolution
            if in_nc != out_nc:
                _logger.debug(
                    "input channel and output channel in depthwise conv is different, change output channel to input channel! origin channel:(in_nc {}, out_nc {}): ".
                    format(in_nc, out_nc))
            groups = in_nc
            out_nc = in_nc
            return groups, in_nc, out_nc
        else:
            ### groups convolution
            ### conv: weight: (Cout, Cin/G, Kh, Kw)
            groups = self._groups
            in_nc = int(in_nc // groups)
            return groups, in_nc, out_nc
C
ceci3 已提交
257 258

    def forward(self, input, kernel_size=None, expand_ratio=None, channel=None):
C
ceci3 已提交
259 260 261 262 263 264 265
        """
        Parameters:
            input(Tensor): Input tensor.
            kernel_size(int, optional): the kernel size of the filter in actual calculation. Default: None.
            expand_ratio(int|float, optional): the expansion ratio of filter's channel number in actual calculation. Default: None.
            channel(int, optional): the expansion ratio of filter's channel number in actual calculation. Default: None.
        """
C
ceci3 已提交
266 267 268 269 270
        self.cur_config = {
            'kernel_size': kernel_size,
            'expand_ratio': expand_ratio,
            'channel': channel
        }
C
ceci3 已提交
271 272 273 274 275 276 277 278 279
        in_nc = int(input.shape[1])
        assert (
            expand_ratio == None or channel == None
        ), "expand_ratio and channel CANNOT be NOT None at the same time."
        if expand_ratio != None:
            out_nc = int(expand_ratio * self.base_channel)
        elif channel != None:
            out_nc = int(channel)
        else:
C
ceci3 已提交
280
            out_nc = self._out_channels
281 282
        ks = int(
            self._kernel_size[0]) if kernel_size == None else int(kernel_size)
C
ceci3 已提交
283

284 285
        groups, weight_in_nc, weight_out_nc = self.get_groups_in_out_nc(
            in_nc, out_nc)
C
ceci3 已提交
286 287

        weight = self.get_active_filter(weight_in_nc, weight_out_nc, ks)
C
ceci3 已提交
288 289 290 291 292

        if kernel_size != None or 'kernel_size' in self.candidate_config.keys():
            padding = convert_to_list(get_same_padding(ks), 2)
        else:
            padding = self._padding
C
ceci3 已提交
293 294

        if self.bias is not None:
295
            ### if conv is depthwise conv, expand_ratio=0, but conv' expand
C
ceci3 已提交
296 297 298 299 300 301 302 303
            ### ratio before depthwise conv is not equal to 1.0, the shape of the weight
            ### about this depthwise conv is changed, but out_nc is not change,
            ### so need to change bias shape according to the weight_out_nc.
            ### if in_nc > groups > 1, the actual output of conv is weight_out_nc * groups,
            ### so slice the shape of bias by weight_out_nc and groups.
            ### if in_nc = groups, slice the shape of bias by weight_out_nc.
            if groups != in_nc:
                weight_out_nc = weight_out_nc * groups
304 305 306 307
            if weight_out_nc >= self.bias.shape[0]:
                bias = self.bias
            else:
                bias = self.bias[:weight_out_nc]
C
ceci3 已提交
308
        else:
C
ceci3 已提交
309
            bias = self.bias
C
Chang Xu 已提交
310
        self.cur_config['prune_dim'] = list(weight.shape)
C
Chang Xu 已提交
311
        self.cur_config['prune_group'] = groups
W
whs 已提交
312
        out = paddle.nn.functional.conv2d(
C
ceci3 已提交
313 314 315 316 317 318
            input,
            weight,
            bias=bias,
            stride=self._stride,
            padding=padding,
            dilation=self._dilation,
C
ceci3 已提交
319
            groups=groups,
C
ceci3 已提交
320 321
            data_format=self._data_format)
        return out
C
ceci3 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344


class SuperGroupConv2D(SuperConv2D):
    def get_groups_in_out_nc(self, in_nc, out_nc):
        ### groups convolution
        ### conv: weight: (Cout, Cin/G, Kh, Kw)
        groups = self._groups
        in_nc = int(in_nc // groups)
        return groups, in_nc, out_nc


class SuperDepthwiseConv2D(SuperConv2D):
    ### depthwise convolution
    def get_groups_in_out_nc(self, in_nc, out_nc):
        if in_nc != out_nc:
            _logger.debug(
                "input channel and output channel in depthwise conv is different, change output channel to input channel! origin channel:(in_nc {}, out_nc {}): ".
                format(in_nc, out_nc))
        groups = in_nc
        out_nc = in_nc
        return groups, in_nc, out_nc


W
whs 已提交
345
class SuperConv2DTranspose(paddle.nn.Conv2DTranspose):
C
ceci3 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    """
    This interface is used to construct a callable object of the ``SuperConv2DTranspose`` 
    class.
    Note: the channel in config need to less than first defined.
    The super convolution2D transpose layer calculates the output based on the input,
    filter, and dilations, strides, paddings. Input and output
    are in NCHW format. Where N is batch size, C is the number of feature map,
    H is the height of the feature map, and W is the width of the feature map.
    Filter's shape is [MCHW] , where M is the number of input feature map,
    C is the number of output feature map, H is the height of the filter,
    and W is the width of the filter. If the groups is greater than 1,
    C will equal the number of input feature map divided by the groups.
    If bias attribution and activation type are provided, bias is added to
    the output of the convolution, and the corresponding activation function
    is applied to the final result.
    The details of convolution transpose layer, please refer to the following explanation and references
    `conv2dtranspose <http://www.matthewzeiler.com/wp-content/uploads/2017/07/cvpr2010.pdf>`_ .
    For each input :math:`X`, the equation is:
    .. math::
W
whs 已提交
365
        Out = \\sigma (W \\ast X + b)
C
ceci3 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    Where:
    * :math:`X`: Input value, a ``Tensor`` with NCHW format.
    * :math:`W`: Filter value, a ``Tensor`` with shape [MCHW] .
    * :math:`\\ast`: Convolution operation.
    * :math:`b`: Bias value, a 2-D ``Tensor`` with shape [M, 1].
    * :math:`\\sigma`: Activation function.
    * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
    Example:
        - Input:
          Input shape: :math:`(N, C_{in}, H_{in}, W_{in})`
          Filter shape: :math:`(C_{in}, C_{out}, H_f, W_f)`
        - Output:
          Output shape: :math:`(N, C_{out}, H_{out}, W_{out})`
        Where
        .. math::
W
whs 已提交
381 382 383 384
           H^\\prime_{out} &= (H_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (H_f - 1) + 1 \\\\
           W^\\prime_{out} &= (W_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (W_f - 1) + 1 \\\\
           H_{out} &\\in [ H^\\prime_{out}, H^\\prime_{out} + strides[0] ) \\\\
           W_{out} &\\in [ W^\\prime_{out}, W^\\prime_{out} + strides[1] )
C
ceci3 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    Parameters:
        num_channels(int): The number of channels in the input image.
        num_filters(int): The number of the filter. It is as same as the output
            feature map.
        filter_size(int or tuple): The filter size. If filter_size is a tuple,
            it must contain two integers, (filter_size_H, filter_size_W).
            Otherwise, the filter will be a square.
        candidate_config(dict, optional): Dictionary descripts candidate config of this layer,
            such as {'kernel_size': (3, 5, 7), 'channel': (4, 6, 8)}, means the kernel size of 
            this layer can be choose from (3, 5, 7), the key of candidate_config
            only can be 'kernel_size', 'channel' and 'expand_ratio', 'channel' and 'expand_ratio'
            CANNOT be set at the same time. Default: None.
        transform_kernel(bool, optional): Whether to use transform matrix to transform a large filter
            to a small filter. Default: False.
        output_size(int or tuple, optional): The output image size. If output size is a
            tuple, it must contain two integers, (image_H, image_W). None if use
            filter_size, padding, and stride to calculate output_size.
            if output_size and filter_size are specified at the same time, They
            should follow the formula above. Default: None.
        padding(int or tuple, optional): The padding size. If padding is a tuple, it must
            contain two integers, (padding_H, padding_W). Otherwise, the
            padding_H = padding_W = padding. Default: 0.
        stride(int or tuple, optional): The stride size. If stride is a tuple, it must
            contain two integers, (stride_H, stride_W). Otherwise, the
            stride_H = stride_W = stride. Default: 1.
        dilation(int or tuple, optional): The dilation size. If dilation is a tuple, it must
            contain two integers, (dilation_H, dilation_W). Otherwise, the
            dilation_H = dilation_W = dilation. Default: 1.
        groups(int, optional): The groups number of the Conv2d transpose layer. Inspired by
            grouped convolution in Alex Krizhevsky's Deep CNN paper, in which
            when group=2, the first half of the filters is only connected to the
            first half of the input channels, while the second half of the
            filters is only connected to the second half of the input channels.
            Default: 1.
        param_attr (ParamAttr, optional): The parameter attribute for learnable weights(Parameter)
W
whs 已提交
420 421
            of conv2d_transpose. If it is set to None or one attribute of paddle.ParamAttr, conv2d_transpose
            will create paddle.ParamAttr as param_attr. If the Initializer of the param_attr
C
ceci3 已提交
422 423 424
            is not set, the parameter is initialized with Xavier. Default: None.
        bias_attr (ParamAttr or bool, optional): The attribute for the bias of conv2d_transpose.
            If it is set to False, no bias will be added to the output units.
W
whs 已提交
425 426
            If it is set to None or one attribute of paddle.ParamAttr, conv2d_transpose
            will create paddle.ParamAttr as bias_attr. If the Initializer of the bias_attr
C
ceci3 已提交
427 428 429 430 431 432 433 434 435 436 437 438 439
            is not set, the bias is initialized zero. Default: None.
        use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn
            library is installed. Default: True.
        act (str, optional): Activation type, if it is set to None, activation is not appended.
            Default: None.
        dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32".
    Attribute:
        **weight** (Parameter): the learnable weights of filters of this layer.
        **bias** (Parameter or None): the learnable bias of this layer.
    Returns:
        None
    Examples:
       .. code-block:: python
C
ceci3 已提交
440
          import paddle
C
ceci3 已提交
441
          import numpy as np
C
ceci3 已提交
442 443 444
          from paddleslim.nas.ofa.layers import SuperConv2DTranspose
          data = np.random.random((3, 32, 32, 5)).astype('float32')
          config = {'channel': 5}
C
ceci3 已提交
445 446
          super_convtranspose = SuperConv2DTranspose(32, 10, 3)
          ret = super_convtranspose(paddle.to_tensor(data), config)
C
ceci3 已提交
447 448 449
    """

    def __init__(self,
C
ceci3 已提交
450 451 452
                 in_channels,
                 out_channels,
                 kernel_size,
C
ceci3 已提交
453 454 455 456
                 candidate_config={},
                 transform_kernel=False,
                 stride=1,
                 padding=0,
C
ceci3 已提交
457 458 459 460
                 output_padding=0,
                 dilation=1,
                 groups=1,
                 weight_attr=None,
C
ceci3 已提交
461
                 bias_attr=None,
C
ceci3 已提交
462
                 data_format="NCHW"):
C
ceci3 已提交
463
        super(SuperConv2DTranspose, self).__init__(
C
ceci3 已提交
464 465 466 467 468 469 470 471 472 473 474 475
            in_channels,
            out_channels,
            kernel_size,
            stride=stride,
            padding=padding,
            dilation=dilation,
            output_padding=output_padding,
            groups=groups,
            weight_attr=weight_attr,
            bias_attr=bias_attr,
            data_format=data_format)

C
ceci3 已提交
476
        self.candidate_config = candidate_config
C
Chang Xu 已提交
477
        self.cur_config = None
C
ceci3 已提交
478 479 480 481 482 483 484 485 486
        if len(self.candidate_config.items()) != 0:
            for k, v in candidate_config.items():
                candidate_config[k] = list(set(v))
        self.ks_set = candidate_config[
            'kernel_size'] if 'kernel_size' in candidate_config else None
        self.expand_ratio = candidate_config[
            'expand_ratio'] if 'expand_ratio' in candidate_config else None
        self.channel = candidate_config[
            'channel'] if 'channel' in candidate_config else None
C
ceci3 已提交
487
        self.base_channel = self._out_channels
C
ceci3 已提交
488
        if self.expand_ratio:
C
ceci3 已提交
489
            self.base_channel = int(self._out_channels / max(self.expand_ratio))
C
ceci3 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502

        self.transform_kernel = transform_kernel
        if self.ks_set != None:
            self.ks_set.sort()
        if self.transform_kernel != False:
            scale_param = dict()
            ### create parameter to transform kernel
            for i in range(len(self.ks_set) - 1):
                ks_small = self.ks_set[i]
                ks_large = self.ks_set[i + 1]
                param_name = '%dto%d_matrix' % (ks_large, ks_small)
                ks_t = ks_small**2
                scale_param[param_name] = self.create_parameter(
C
ceci3 已提交
503
                    attr=paddle.ParamAttr(
C
ceci3 已提交
504
                        name=self._full_name + param_name,
W
whs 已提交
505
                        initializer=paddle.nn.initializer.Assign(np.eye(ks_t))),
C
ceci3 已提交
506 507 508 509 510 511 512
                    shape=(ks_t, ks_t),
                    dtype=self._dtype)

            for name, param in scale_param.items():
                setattr(self, name, param)

    def get_active_filter(self, in_nc, out_nc, kernel_size):
C
ceci3 已提交
513
        start, end = compute_start_end(self._kernel_size[0], kernel_size)
C
ceci3 已提交
514
        filters = self.weight[:in_nc, :out_nc, start:end, start:end]
515
        if self.transform_kernel != False and kernel_size < self._kernel_size[0]:
C
ceci3 已提交
516 517 518 519 520 521 522 523
            start_filter = self.weight[:in_nc, :out_nc, :, :]
            for i in range(len(self.ks_set) - 1, 0, -1):
                src_ks = self.ks_set[i]
                if src_ks <= kernel_size:
                    break
                target_ks = self.ks_set[i - 1]
                start, end = compute_start_end(src_ks, target_ks)
                _input_filter = start_filter[:, :, start:end, start:end]
C
ceci3 已提交
524
                _input_filter = paddle.reshape(
C
ceci3 已提交
525 526 527
                    _input_filter,
                    shape=[(_input_filter.shape[0] * _input_filter.shape[1]),
                           -1])
528 529 530 531 532
                _input_filter = paddle.matmul(_input_filter,
                                              self.__getattr__(
                                                  '%dto%d_matrix' %
                                                  (src_ks, target_ks)), False,
                                              False)
C
ceci3 已提交
533
                _input_filter = paddle.reshape(
C
ceci3 已提交
534 535 536 537 538 539 540 541 542
                    _input_filter,
                    shape=[
                        filters.shape[0], filters.shape[1], target_ks, target_ks
                    ])
                start_filter = _input_filter
            filters = start_filter
        return filters

    def get_groups_in_out_nc(self, in_nc, out_nc):
C
ceci3 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
        if self._groups == 1:
            ### standard conv
            return self._groups, in_nc, out_nc
        elif self._groups == self._in_channels:
            ### depthwise convolution
            if in_nc != out_nc:
                _logger.debug(
                    "input channel and output channel in depthwise conv is different, change output channel to input channel! origin channel:(in_nc {}, out_nc {}): ".
                    format(in_nc, out_nc))
            groups = in_nc
            out_nc = in_nc
            return groups, in_nc, out_nc
        else:
            ### groups convolution
            ### groups conv transpose: weight: (Cin, Cout/G, Kh, Kw)
            groups = self._groups
            out_nc = int(out_nc // groups)
            return groups, in_nc, out_nc

    def forward(self,
                input,
                output_size=None,
                kernel_size=None,
                expand_ratio=None,
                channel=None):
        """
        Parameters:
            input(Tensor): input tensor.
            output_size(int, optional): the size of the feature map after transpose convolution. Default: None.
            kernel_size(int, optional): the kernel size of the filter in actual calculation. Default: None.
            expand_ratio(int|float, optional): the expansion ratio of filter's channel number in actual calculation. Default: None.
            channel(int, optional): the expansion ratio of filter's channel number in actual calculation. Default: None.
        """
C
ceci3 已提交
576 577 578 579 580
        self.cur_config = {
            'kernel_size': kernel_size,
            'expand_ratio': expand_ratio,
            'channel': channel
        }
C
ceci3 已提交
581 582 583 584 585 586 587 588 589
        in_nc = int(input.shape[1])
        assert (
            expand_ratio == None or channel == None
        ), "expand_ratio and channel CANNOT be NOT None at the same time."
        if expand_ratio != None:
            out_nc = int(expand_ratio * self.base_channel)
        elif channel != None:
            out_nc = int(channel)
        else:
C
ceci3 已提交
590
            out_nc = self._out_channels
C
ceci3 已提交
591

592 593
        ks = int(
            self._kernel_size[0]) if kernel_size == None else int(kernel_size)
C
ceci3 已提交
594

595 596
        groups, weight_in_nc, weight_out_nc = self.get_groups_in_out_nc(
            in_nc, out_nc)
C
ceci3 已提交
597 598

        weight = self.get_active_filter(weight_in_nc, weight_out_nc, ks)
C
ceci3 已提交
599

C
ceci3 已提交
600 601 602 603
        if kernel_size != None or 'kernel_size' in self.candidate_config.keys():
            padding = convert_to_list(get_same_padding(ks), 2)
        else:
            padding = self._padding
C
ceci3 已提交
604

C
ceci3 已提交
605 606 607 608 609
        if output_size is None:
            output_padding = self.output_padding
        else:
            output_padding = 0

C
ceci3 已提交
610
        if self.bias is not None:
C
ceci3 已提交
611 612 613
            if groups != in_nc:
                weight_out_nc = weight_out_nc * groups
            bias = self.bias[:weight_out_nc]
C
ceci3 已提交
614
        else:
C
ceci3 已提交
615
            bias = self.bias
C
Chang Xu 已提交
616
        self.cur_config['prune_dim'] = list(weight.shape)
C
Chang Xu 已提交
617
        self.cur_config['prune_group'] = groups
W
whs 已提交
618
        out = paddle.nn.functional.conv2d_transpose(
C
ceci3 已提交
619 620 621 622 623 624 625
            input,
            weight,
            bias=bias,
            padding=padding,
            output_padding=output_padding,
            stride=self._stride,
            dilation=self._dilation,
C
ceci3 已提交
626
            groups=groups,
C
ceci3 已提交
627 628 629
            output_size=output_size,
            data_format=self._data_format)
        return out
C
ceci3 已提交
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652


class SuperGroupConv2DTranspose(SuperConv2DTranspose):
    def get_groups_in_out_nc(self, in_nc, out_nc):
        ### groups convolution
        ### groups conv transpose: weight: (Cin, Cout/G, Kh, Kw)
        groups = self._groups
        out_nc = int(out_nc // groups)
        return groups, in_nc, out_nc


class SuperDepthwiseConv2DTranspose(SuperConv2DTranspose):
    def get_groups_in_out_nc(self, in_nc, out_nc):
        if in_nc != out_nc:
            _logger.debug(
                "input channel and output channel in depthwise conv transpose is different, change output channel to input channel! origin channel:(in_nc {}, out_nc {}): ".
                format(in_nc, out_nc))
        groups = in_nc
        out_nc = in_nc
        return groups, in_nc, out_nc


### NOTE: only search channel, write for GAN-compression, maybe change to SuperDepthwiseConv and SuperConv after.
W
whs 已提交
653
class SuperSeparableConv2D(paddle.nn.Layer):
C
ceci3 已提交
654 655 656 657 658 659 660 661
    """
    This interface is used to construct a callable object of the ``SuperSeparableConv2D``
    class.
    The difference between ```SuperSeparableConv2D``` and ```SeparableConv2D``` is: 
    ```SuperSeparableConv2D``` need to feed a config dictionary with the format of 
    {'channel', num_of_channel} represents the channels of the first conv's outputs and
    the second conv's inputs, used to change the first dimension of weight and bias, 
    only train the first channels of the weight and bias.
C
ceci3 已提交
662 663
    The architecture of super separable convolution2D op is [Conv2D, norm layer(may be BatchNorm2D
    or InstanceNorm2D), Conv2D]. The first conv is depthwise conv, the filter number is input channel
C
ceci3 已提交
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
    multiply scale_factor, the group is equal to the number of input channel. The second conv
    is standard conv, which filter size and stride size are 1. 
    Parameters:
        num_channels(int): The number of channels in the input image.
        num_filters(int): The number of the second conv's filter. It is as same as the output
            feature map.
        filter_size(int or tuple): The first conv's filter size. If filter_size is a tuple,
            it must contain two integers, (filter_size_H, filter_size_W).
            Otherwise, the filter will be a square.
        padding(int or tuple, optional): The first conv's padding size. If padding is a tuple, 
            it must contain two integers, (padding_H, padding_W). Otherwise, the
            padding_H = padding_W = padding. Default: 0.
        stride(int or tuple, optional): The first conv's stride size. If stride is a tuple,
            it must contain two integers, (stride_H, stride_W). Otherwise, the
            stride_H = stride_W = stride. Default: 1.
        dilation(int or tuple, optional): The first conv's dilation size. If dilation is a tuple, 
            it must contain two integers, (dilation_H, dilation_W). Otherwise, the
            dilation_H = dilation_W = dilation. Default: 1.
C
ceci3 已提交
682
        norm_layer(class): The normalization layer between two convolution. Default: InstanceNorm2D.
C
ceci3 已提交
683 684
        bias_attr (ParamAttr or bool, optional): The attribute for the bias of convolution.
            If it is set to False, no bias will be added to the output units.
W
whs 已提交
685 686
            If it is set to None or one attribute of paddle.ParamAttr, convolution
            will create paddle.ParamAttr as bias_attr. If the Initializer of the bias_attr
C
ceci3 已提交
687 688 689 690 691 692 693
            is not set, the bias is initialized zero. Default: None.
        scale_factor(float): The scale factor of the first conv's output channel. Default: 1.
    Returns:
        None
    """

    def __init__(self,
C
ceci3 已提交
694 695 696
                 in_channels,
                 out_channels,
                 kernel_size,
C
ceci3 已提交
697 698 699 700
                 candidate_config={},
                 stride=1,
                 padding=0,
                 dilation=1,
W
whs 已提交
701
                 norm_layer=paddle.nn.InstanceNorm2D,
C
ceci3 已提交
702
                 bias_attr=None,
C
ceci3 已提交
703
                 scale_factor=1):
C
ceci3 已提交
704
        super(SuperSeparableConv2D, self).__init__()
W
whs 已提交
705 706
        self.conv = paddle.nn.LayerList([
            paddle.nn.Conv2D(
C
ceci3 已提交
707 708 709
                in_channels=in_channels,
                out_channels=in_channels * scale_factor,
                kernel_size=kernel_size,
C
ceci3 已提交
710 711
                stride=stride,
                padding=padding,
C
ceci3 已提交
712
                groups=in_channels,
C
ceci3 已提交
713 714 715
                bias_attr=bias_attr)
        ])

C
ceci3 已提交
716
        self.conv.extend([norm_layer(in_channels * scale_factor)])
C
ceci3 已提交
717 718

        self.conv.extend([
W
whs 已提交
719
            paddle.nn.Conv2D(
C
ceci3 已提交
720 721 722
                in_channels=in_channels * scale_factor,
                out_channels=out_channels,
                kernel_size=1,
C
ceci3 已提交
723 724 725 726 727
                stride=1,
                bias_attr=bias_attr)
        ])

        self.candidate_config = candidate_config
C
Chang Xu 已提交
728
        self.cur_config = None
C
ceci3 已提交
729 730
        self.expand_ratio = candidate_config[
            'expand_ratio'] if 'expand_ratio' in candidate_config else None
C
ceci3 已提交
731
        self.base_output_dim = self.conv[0]._out_channels
C
ceci3 已提交
732
        if self.expand_ratio != None:
733 734
            self.base_output_dim = int(
                self.conv[0]._out_channels / max(self.expand_ratio))
C
ceci3 已提交
735 736

    def forward(self, input, expand_ratio=None, channel=None):
C
ceci3 已提交
737 738 739 740 741 742
        """
        Parameters:
            input(Tensor): input tensor.
            expand_ratio(int|float, optional): the expansion ratio of filter's channel number in actual calculation. Default: None.
            channel(int, optional): the expansion ratio of filter's channel number in actual calculation. Default: None.
        """
C
ceci3 已提交
743
        self.cur_config = {'expand_ratio': expand_ratio, 'channel': channel}
C
ceci3 已提交
744 745 746 747 748 749 750 751 752
        in_nc = int(input.shape[1])
        assert (
            expand_ratio == None or channel == None
        ), "expand_ratio and channel CANNOT be NOT None at the same time."
        if expand_ratio != None:
            out_nc = int(expand_ratio * self.base_output_dim)
        elif channel != None:
            out_nc = int(channel)
        else:
C
ceci3 已提交
753
            out_nc = self.conv[0]._out_channels
C
ceci3 已提交
754 755 756 757 758 759

        weight = self.conv[0].weight[:in_nc]
        ###  conv1
        if self.conv[0].bias is not None:
            bias = self.conv[0].bias[:in_nc]
        else:
C
ceci3 已提交
760 761
            bias = self.conv[0].bias

W
whs 已提交
762
        conv0_out = paddle.nn.functional.conv2d(
C
ceci3 已提交
763 764 765 766 767 768 769 770
            input,
            weight,
            bias,
            stride=self.conv[0]._stride,
            padding=self.conv[0]._padding,
            dilation=self.conv[0]._dilation,
            groups=in_nc,
            data_format=self.conv[0]._data_format)
C
ceci3 已提交
771 772 773 774 775 776 777 778

        norm_out = self.conv[1](conv0_out)

        weight = self.conv[2].weight[:out_nc, :in_nc, :, :]

        if self.conv[2].bias is not None:
            bias = self.conv[2].bias[:out_nc]
        else:
C
ceci3 已提交
779
            bias = self.conv[2].bias
C
Chang Xu 已提交
780
        self.cur_config['prune_dim'] = list(weight.shape)
W
whs 已提交
781
        conv1_out = paddle.nn.functional.conv2d(
C
ceci3 已提交
782 783 784 785 786 787 788 789
            norm_out,
            weight,
            bias,
            stride=self.conv[2]._stride,
            padding=self.conv[2]._padding,
            dilation=self.conv[2]._dilation,
            groups=self.conv[2]._groups,
            data_format=self.conv[2]._data_format)
C
ceci3 已提交
790 791 792
        return conv1_out


W
whs 已提交
793
class SuperLinear(paddle.nn.Linear):
C
ceci3 已提交
794
    """
C
ceci3 已提交
795 796 797 798 799 800 801
    Super Fully-connected linear transformation layer. 
    
    For each input :math:`X` , the equation is:
    .. math::
        Out = XW + b
    where :math:`W` is the weight and :math:`b` is the bias.
    Linear layer takes only one multi-dimensional tensor as input with the
W
whs 已提交
802
    shape :math:`[batch\\_size, *, in\\_features]` , where :math:`*` means any
C
ceci3 已提交
803
    number of additional dimensions. It multiplies input tensor with the weight
W
whs 已提交
804 805 806 807
    (a 2-D tensor of shape :math:`[in\\_features, out\\_features]` ) and produces
    an output tensor of shape :math:`[batch\\_size, *, out\\_features]` .
    If :math:`bias\\_attr` is not False, the bias (a 1-D tensor of
    shape :math:`[out\\_features]` ) will be created and added to the output.
C
ceci3 已提交
808 809 810 811 812 813 814 815 816 817 818 819 820
    Parameters:
        in_features (int): The number of input units.
        out_features (int): The number of output units.
        candidate_config(dict, optional): Dictionary descripts candidate config of this layer,
            such as {'channel': (4, 6, 8)}, the key of candidate_config
            only can be 'channel' and 'expand_ratio', 'channel' and 'expand_ratio'
            CANNOT be set at the same time. Default: None.
        weight_attr (ParamAttr, optional): The attribute for the learnable
            weight of this layer. The default value is None and the weight will be
            initialized to zero. For detailed information, please refer to
            paddle.ParamAttr.
        bias_attr (ParamAttr|bool, optional): The attribute for the learnable bias
            of this layer. If it is set to False, no bias will be added to the output.
W
whs 已提交
821 822
            If it is set to None or one kind of paddle.ParamAttr, a bias parameter will
            be created according to paddle.ParamAttr. For detailed information, please refer
C
ceci3 已提交
823 824 825 826 827 828 829 830
            to paddle.ParamAttr. The default value is None and the bias will be
            initialized to zero.
        name (str, optional): Normally there is no need for user to set this parameter.
            For detailed information, please refer to :ref:`api_guide_Name` .
    Attribute:
        **weight** (Parameter): the learnable weight of this layer.
        **bias** (Parameter): the learnable bias of this layer.
    Shape:
W
whs 已提交
831 832
        - input: Multi-dimentional tensor with shape :math:`[batch\\_size, *, in\\_features]` .
        - output: Multi-dimentional tensor with shape :math:`[batch\\_size, *, out\\_features]` .
C
ceci3 已提交
833 834 835 836 837 838
    Examples:
        .. code-block:: python
          import numpy as np
          import paddle
          from paddleslim.nas.ofa.layers import SuperLinear
          
C
ceci3 已提交
839
          data = np.random.uniform(-1, 1, [32, 64]).astype('float32')
C
ceci3 已提交
840
          config = {'channel': 16}
C
ceci3 已提交
841 842
          linear = SuperLinear(64, 64)
          data = paddle.to_tensor(data)
C
ceci3 已提交
843
          res = linear(data, **config)
C
ceci3 已提交
844 845 846
    """

    def __init__(self,
C
ceci3 已提交
847 848
                 in_features,
                 out_features,
C
ceci3 已提交
849
                 candidate_config={},
C
ceci3 已提交
850
                 weight_attr=None,
C
ceci3 已提交
851
                 bias_attr=None,
C
ceci3 已提交
852 853 854 855
                 name=None):
        super(SuperLinear, self).__init__(in_features, out_features,
                                          weight_attr, bias_attr, name)
        self._weight_attr = weight_attr
C
ceci3 已提交
856
        self._bias_attr = bias_attr
C
ceci3 已提交
857 858
        self._in_features = in_features
        self._out_features = out_features
C
ceci3 已提交
859
        self.candidate_config = candidate_config
C
Chang Xu 已提交
860
        self.cur_config = None
C
ceci3 已提交
861 862
        self.expand_ratio = candidate_config[
            'expand_ratio'] if 'expand_ratio' in candidate_config else None
C
ceci3 已提交
863
        self.base_output_dim = self._out_features
C
ceci3 已提交
864
        if self.expand_ratio != None:
865 866
            self.base_output_dim = int(
                self._out_features / max(self.expand_ratio))
C
ceci3 已提交
867 868

    def forward(self, input, expand_ratio=None, channel=None):
C
ceci3 已提交
869 870 871 872 873 874
        """
        Parameters:
            input(Tensor): input tensor.
            expand_ratio(int|float, optional): the expansion ratio of filter's channel number in actual calculation. Default: None.
            channel(int, optional): the expansion ratio of filter's channel number in actual calculation. Default: None.
        """
C
ceci3 已提交
875
        self.cur_config = {'expand_ratio': expand_ratio, 'channel': channel}
C
ceci3 已提交
876
        ### weight: (Cin, Cout)
C
ceci3 已提交
877
        in_nc = int(input.shape[-1])
C
ceci3 已提交
878 879 880 881 882 883 884 885
        assert (
            expand_ratio == None or channel == None
        ), "expand_ratio and channel CANNOT be NOT None at the same time."
        if expand_ratio != None:
            out_nc = int(expand_ratio * self.base_output_dim)
        elif channel != None:
            out_nc = int(channel)
        else:
C
ceci3 已提交
886
            out_nc = self._out_features
887 888 889 890
        if self.weight.shape[0] <= in_nc and self.weight.shape[1] <= out_nc:
            weight = self.weight
        else:
            weight = self.weight[:in_nc, :out_nc]
C
ceci3 已提交
891
        if self._bias_attr != False:
892 893 894 895
            if self.bias.shape[0] <= out_nc:
                bias = self.bias
            else:
                bias = self.bias[:out_nc]
C
ceci3 已提交
896
        else:
C
ceci3 已提交
897
            bias = self.bias
C
Chang Xu 已提交
898
        self.cur_config['prune_dim'] = list(weight.shape)
W
whs 已提交
899 900
        out = paddle.nn.functional.linear(
            x=input, weight=weight, bias=bias, name=self.name)
C
ceci3 已提交
901
        return out
C
ceci3 已提交
902 903


W
whs 已提交
904
class SuperBatchNorm2D(paddle.nn.BatchNorm2D):
C
ceci3 已提交
905
    """
C
ceci3 已提交
906 907 908 909 910 911
    This interface is used to construct a callable object of the ``SuperBatchNorm2D`` class. 
    Parameters:
        num_features(int): Indicate the number of channels of the input ``Tensor``.
        epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5.
        momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale`
W
whs 已提交
912 913
            of batch_norm. If it is set to None or one attribute of paddle.ParamAttr, batch_norm
            will create paddle.ParamAttr as weight_attr. If it is set to Fasle, the weight is not learnable.
C
ceci3 已提交
914 915
            If the Initializer of the weight_attr is not set, the parameter is initialized with Xavier. Default: None.
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of batch_norm.
W
whs 已提交
916 917
            If it is set to None or one attribute of paddle.ParamAttr, batch_norm
            will create paddle.ParamAttr as bias_attr. If it is set to Fasle, the weight is not learnable.
C
ceci3 已提交
918 919 920 921 922 923 924 925 926 927 928 929 930 931
            If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None.
        data_format(str, optional): Specify the input data format, the data format can be "NCHW" or "NHWC". Default: NCHW.
        name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..
    Examples:
       .. code-block:: python
         import paddle
         import numpy as np
         from paddleslim.nas.ofa.layers import SuperBatchNorm2D
         
         np.random.seed(123)
         x_data = np.random.random(size=(2, 5, 2, 3)).astype('float32')
         x = paddle.to_tensor(x_data)
         batch_norm = SuperBatchNorm2D(5)
         batch_norm_out = batch_norm(x)
C
ceci3 已提交
932 933 934
    """

    def __init__(self,
C
ceci3 已提交
935
                 num_features,
C
ceci3 已提交
936 937
                 momentum=0.9,
                 epsilon=1e-05,
C
ceci3 已提交
938
                 weight_attr=None,
C
ceci3 已提交
939
                 bias_attr=None,
C
ceci3 已提交
940
                 data_format='NCHW',
C
ceci3 已提交
941
                 use_global_stats=None,
C
ceci3 已提交
942
                 name=None):
943 944 945
        super(SuperBatchNorm2D,
              self).__init__(num_features, momentum, epsilon, weight_attr,
                             bias_attr, data_format, use_global_stats, name)
C
Chang Xu 已提交
946
        self.cur_config = None
C
ceci3 已提交
947 948

    def forward(self, input):
C
ceci3 已提交
949 950
        self._check_data_format(self._data_format)
        self._check_input_dim(input)
C
ceci3 已提交
951 952
        feature_dim = int(input.shape[1])

953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
        if self.weight.shape[0] <= feature_dim:
            weight = self.weight
        else:
            weight = self.weight[:feature_dim]
        if self.bias.shape[0] <= feature_dim:
            bias = self.bias
        else:
            bias = self.bias[:feature_dim]
        if self._mean.shape[0] <= feature_dim:
            mean = self._mean
        else:
            mean = self._mean[:feature_dim]
        if self._variance.shape[0] <= feature_dim:
            variance = self._variance
        else:
            variance = self._variance[:feature_dim]
C
ceci3 已提交
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985

        mean_out = self._mean
        variance_out = self._variance
        mean_out_tmp = mean
        variance_out_tmp = variance

        if self._use_global_stats == None:
            self._use_global_stats = not self.training
            trainable_statistics = False
        else:
            trainable_statistics = not self._use_global_stats

        attrs = ("momentum", self._momentum, "epsilon", self._epsilon,
                 "is_test", not self.training, "data_layout", self._data_format,
                 "use_mkldnn", False, "fuse_with_relu", False,
                 "use_global_stats", self._use_global_stats,
                 "trainable_statistics", trainable_statistics)
986

987
        if paddle.in_dynamic_mode():
988
            paddle_compile = os.environ.get("paddle_compile")
C
Chang Xu 已提交
989
            if feature_dim != self._mean.shape[0]:
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
                if not paddle_compile or "Develop" in paddle_compile:
                    # fit paddle develop
                    batch_norm_out, t1, t2, t3, t4, _ = paddle._C_ops.batch_norm(
                        input, mean, variance, weight, bias, not self.training,
                        self._momentum, self._epsilon, self._data_format,
                        self._use_global_stats, trainable_statistics)
                else:
                    # fit paddle release
                    batch_norm_out, t1, t2, t3, t4, _ = paddle._C_ops.batch_norm(
                        input, weight, bias, mean, variance, self._momentum,
                        self._epsilon, self._data_format, not self.training,
                        self._use_global_stats, trainable_statistics, False,
                        False)

C
Chang Xu 已提交
1004 1005 1006 1007
                self._mean[:feature_dim].set_value(mean)
                self._variance[:feature_dim].set_value(variance)
                mean_out[:feature_dim].set_value(mean_out_tmp)
                variance_out[:feature_dim].set_value(variance_out_tmp)
1008
                return batch_norm_out
C
Chang Xu 已提交
1009
            else:
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
                if not paddle_compile or "Develop" in paddle_compile:
                    # fit paddle develop
                    batch_norm_out, t1, t2, t3, t4, _ = paddle._C_ops.batch_norm(
                        input, mean, variance, weight, bias, not self.training,
                        self._momentum, self._epsilon, self._data_format,
                        self._use_global_stats, trainable_statistics)

                else:
                    # fit paddle release
                    batch_norm_out, t1, t2, t3, t4, _ = paddle._C_ops.batch_norm(
                        input, weight, bias, mean, variance, self._momentum,
                        self._epsilon, self._data_format, not self.training,
                        self._use_global_stats, trainable_statistics, False)

1024 1025
                return batch_norm_out

W
whs 已提交
1026
        paddle.common_ops_import.check_variable_and_dtype(
W
whs 已提交
1027
            input, 'input', ['float16', 'float32', 'float64'], 'BatchNorm')
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

        # for static need dict
        attrs = {
            "momentum": self._momentum,
            "epsilon": self._epsilon,
            "is_test": not self.training,
            "data_layout": self._data_format,
            "use_mkldnn": False,
            "fuse_with_relu": False,
            "use_global_stats": self._use_global_stats,
            "trainable_statistics": trainable_statistics,
        }

        inputs = {
            "X": [input],
            "Scale": [weight],
            "Bias": [bias],
            "Mean": [mean],
            "Variance": [variance]
        }
C
ceci3 已提交
1048

C
ceci3 已提交
1049 1050 1051 1052 1053 1054
        saved_mean = self._helper.create_variable_for_type_inference(
            dtype=self._dtype, stop_gradient=True)
        saved_variance = self._helper.create_variable_for_type_inference(
            dtype=self._dtype, stop_gradient=True)
        reserve_space = self._helper.create_variable_for_type_inference(
            dtype=self._helper.input_dtype(input), stop_gradient=True)
1055

C
ceci3 已提交
1056 1057 1058
        batch_norm_out = (
            input if self._in_place else
            self._helper.create_variable_for_type_inference(self._dtype))
1059 1060 1061 1062 1063 1064 1065 1066 1067

        outputs = {
            "Y": [batch_norm_out],
            "MeanOut": [mean],
            "VarianceOut": [variance],
            "SavedMean": [saved_mean],
            "SavedVariance": [saved_variance]
        }

C
ceci3 已提交
1068
        if reserve_space is not None:
1069 1070
            outputs["ReserveSpace"] = [reserve_space]

C
ceci3 已提交
1071
        self._helper.append_op(
1072
            type="batch_norm", inputs=inputs, outputs=outputs, attrs=attrs)
C
Chang Xu 已提交
1073
        self.cur_config = {'prune_dim': feature_dim}
1074
        return batch_norm_out
C
ceci3 已提交
1075 1076


W
whs 已提交
1077
class SuperSyncBatchNorm(paddle.nn.SyncBatchNorm):
C
Chang Xu 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    def __init__(self,
                 num_features,
                 momentum=0.9,
                 epsilon=1e-05,
                 weight_attr=None,
                 bias_attr=None,
                 data_format='NCHW',
                 name=None):
        super(SuperSyncBatchNorm,
              self).__init__(num_features, momentum, epsilon, weight_attr,
                             bias_attr, data_format, name)
C
Chang Xu 已提交
1089
        self.cur_config = None
C
Chang Xu 已提交
1090 1091

    def forward(self, input):
C
ceci3 已提交
1092
        self._check_data_format()
C
Chang Xu 已提交
1093 1094 1095 1096 1097 1098 1099
        feature_dim = int(input.shape[1])

        weight = self.weight[:feature_dim]
        bias = self.bias[:feature_dim]
        mean = self._mean[:feature_dim]
        variance = self._variance[:feature_dim]

C
ceci3 已提交
1100 1101 1102 1103
        mean_out = self._mean
        variance_out = self._variance
        mean_out_tmp = mean
        variance_out_tmp = variance
C
Chang Xu 已提交
1104
        self.cur_config = {'prune_dim': feature_dim}
C
Chang Xu 已提交
1105 1106 1107 1108 1109 1110

        attrs = ("momentum", self._momentum, "epsilon", self._epsilon,
                 "is_test", not self.training, "data_layout", self._data_format,
                 "use_mkldnn", False, "fuse_with_relu", False,
                 "use_global_stats", False, 'trainable_statistics', False)

W
whs 已提交
1111
        if paddle.in_dynamic_mode():
1112
            if feature_dim != self._mean.shape[0]:
W
whs 已提交
1113
                sync_batch_norm_out, _, _, _, _, _ = paddle._legacy_C_ops.sync_batch_norm(
1114 1115 1116 1117 1118 1119 1120 1121
                    input, weight, bias, self._mean, self._variance, mean_out,
                    variance_out, *attrs)

                self._mean[:feature_dim].set_value(mean)
                self._variance[:feature_dim].set_value(variance)
                mean_out[:feature_dim].set_value(mean_out_tmp)
                variance_out[:feature_dim].set_value(variance_out_tmp)
            else:
W
whs 已提交
1122
                sync_batch_norm_out, _, _, _, _, _ = paddle._legacy_C_ops.sync_batch_norm(
1123 1124 1125 1126 1127
                    input, weight, bias, self._mean, self._variance, mean_out,
                    variance_out, *attrs)

            return sync_batch_norm_out

W
whs 已提交
1128
        paddle.common_ops_import.check_variable_and_dtype(
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
            input, 'input', ['float16', 'float32', 'float64'], 'SyncBatchNorm')

        attrs = {
            "momentum": self._momentum,
            "epsilon": self._epsilon,
            "is_test": not self.training,
            "data_layout": self._data_format,
            "use_mkldnn": False,
            "fuse_with_relu": False,
            "use_global_stats": False,
            "trainable_statistics": False,
        }

        inputs = {
            "X": [input],
            "Scale": [weight],
            "Bias": [bias],
            "Mean": [self._mean],
            "Variance": [self._variance]
        }

1150
        helper = paddle.fluid.layer_helper.LayerHelper('sync_batch_norm')
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168

        saved_mean = helper.create_variable_for_type_inference(
            dtype=self._dtype, stop_gradient=True)
        saved_variance = helper.create_variable_for_type_inference(
            dtype=self._dtype, stop_gradient=True)
        sync_batch_norm_out = helper.create_variable_for_type_inference(
            self._dtype)

        outputs = {
            "Y": [sync_batch_norm_out],
            "MeanOut": [mean_out],
            "VarianceOut": [variance_out],
            "SavedMean": [saved_mean],
            "SavedVariance": [saved_variance]
        }

        helper.append_op(
            type="sync_batch_norm", inputs=inputs, outputs=outputs, attrs=attrs)
C
Chang Xu 已提交
1169 1170 1171
        return sync_batch_norm_out


W
whs 已提交
1172
class SuperInstanceNorm2D(paddle.nn.InstanceNorm2D):
C
ceci3 已提交
1173
    """
C
ceci3 已提交
1174
    This interface is used to construct a callable object of the ``SuperInstanceNorm2D`` class. 
C
ceci3 已提交
1175 1176 1177 1178 1179
    Parameters:
        num_features(int): Indicate the number of channels of the input ``Tensor``.
        epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5.
        momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale`
W
whs 已提交
1180 1181
            of batch_norm. If it is set to None or one attribute of paddle.ParamAttr, batch_norm
            will create paddle.ParamAttr as weight_attr. If it is set to Fasle, the weight is not learnable.
C
ceci3 已提交
1182 1183
            If the Initializer of the weight_attr is not set, the parameter is initialized with Xavier. Default: None.
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of batch_norm.
W
whs 已提交
1184 1185
            If it is set to None or one attribute of paddle.ParamAttr, batch_norm
            will create paddle.ParamAttr as bias_attr. If it is set to Fasle, the weight is not learnable.
C
ceci3 已提交
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
            If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None.
        data_format(str, optional): Specify the input data format, the data format can be "NCHW" or "NHWC". Default: NCHW.
        name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..
    Examples:
       .. code-block:: python
         import paddle
         import numpy as np
         from paddleslim.nas.ofa.layers import SuperInstanceNorm2D
         
         np.random.seed(123)
         x_data = np.random.random(size=(2, 5, 2, 3)).astype('float32')
         x = paddle.to_tensor(x_data)
         instance_norm = SuperInstanceNorm2D(5)
         out = instance_norm(x)
C
ceci3 已提交
1200 1201 1202
    """

    def __init__(self,
C
ceci3 已提交
1203
                 num_features,
C
ceci3 已提交
1204
                 epsilon=1e-05,
C
ceci3 已提交
1205 1206
                 momentum=0.9,
                 weight_attr=None,
C
ceci3 已提交
1207
                 bias_attr=None,
C
ceci3 已提交
1208 1209
                 data_format='NCHW',
                 name=None):
1210 1211 1212
        super(SuperInstanceNorm2D,
              self).__init__(num_features, epsilon, momentum, weight_attr,
                             bias_attr, data_format, name)
C
Chang Xu 已提交
1213
        self.cur_config = None
C
ceci3 已提交
1214 1215

    def forward(self, input):
C
ceci3 已提交
1216
        self._check_input_dim(input)
C
ceci3 已提交
1217 1218

        feature_dim = int(input.shape[1])
C
ceci3 已提交
1219
        if self._weight_attr == False and self._bias_attr == False:
C
ceci3 已提交
1220 1221 1222 1223 1224
            scale = None
            bias = None
        else:
            scale = self.scale[:feature_dim]
            bias = self.bias[:feature_dim]
C
Chang Xu 已提交
1225
        self.cur_config = {'prune_dim': feature_dim}
W
whs 已提交
1226 1227
        return paddle.nn.functional.instance_norm(
            input, scale, bias, eps=self._epsilon)
C
ceci3 已提交
1228 1229


W
whs 已提交
1230
class SuperLayerNorm(paddle.nn.LayerNorm):
C
ceci3 已提交
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    """
    This interface is used to construct a callable object of the ``SuperLayerNorm`` class.
    The difference between ```SuperLayerNorm``` and ```LayerNorm``` is: 
    the trained weight and bias in ```SuperLayerNorm``` can be changed according to the shape of input,
    only train the first channels of the weight and bias.
    Parameters:
        normalized_shape(int|list|tuple): Input shape from an expected input of
            size :math:`[*, normalized_shape[0], normalized_shape[1], ..., normalized_shape[-1]]`.
            If it is a single integer, this module will normalize over the last dimension
            which is expected to be of that specific size.
        epsilon(float, optional): The small value added to the variance to prevent
            division by zero. Default: 1e-05.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for the learnable
            gain :math:`g`. If False, weight is None. If is None, a default :code:`ParamAttr` would be added as scale. The
            :attr:`param_attr` is initialized as 1 if it is added. Default: None.
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the learnable
            bias :math:`b`. If is False, bias is None. If is None, a default :code:`ParamAttr` would be added as bias. The
            :attr:`bias_attr` is initialized as 0 if it is added. Default: None.
        name(str, optional): Name for the LayerNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..
    Shape:
        - x: 2-D, 3-D, 4-D or 5-D tensor.
        - output: same shape as input x.
    Returns:
        None
    Examples:
        .. code-block:: python
          import paddle
          import numpy as np
          from paddleslim.nas.ofa.layers import SuperLayerNorm
          
          np.random.seed(123)
C
ceci3 已提交
1262
          x_data = np.random.random(size=(2, 3)).astype('float32')
C
ceci3 已提交
1263
          x = paddle.to_tensor(x_data)
C
ceci3 已提交
1264
          layer_norm = SuperLayerNorm(x_data.shape[1])
C
ceci3 已提交
1265 1266
          layer_norm_out = layer_norm(x)
    """
C
ceci3 已提交
1267 1268 1269 1270

    def __init__(self,
                 normalized_shape,
                 epsilon=1e-05,
C
ceci3 已提交
1271
                 weight_attr=None,
C
ceci3 已提交
1272
                 bias_attr=None,
C
ceci3 已提交
1273 1274 1275
                 name=None):
        super(SuperLayerNorm, self).__init__(normalized_shape, epsilon,
                                             weight_attr, bias_attr, name)
C
Chang Xu 已提交
1276
        self.cur_config = None
C
ceci3 已提交
1277 1278 1279

    def forward(self, input):
        ### TODO(ceci3): fix if normalized_shape is not a single number
C
ceci3 已提交
1280 1281 1282
        input_ndim = len(list(input.shape))
        normalized_ndim = len(self._normalized_shape)
        begin_norm_axis = input_ndim - normalized_ndim
C
ceci3 已提交
1283
        feature_dim = int(input.shape[-1])
C
ceci3 已提交
1284
        if self._weight_attr != False:
1285 1286 1287 1288
            if self.weight.shape[0] <= feature_dim:
                weight = self.weight
            else:
                weight = self.weight[:feature_dim]
C
ceci3 已提交
1289 1290 1291
        else:
            weight = None
        if self._bias_attr != False:
1292 1293 1294 1295
            if self.bias.shape[0] <= feature_dim:
                bias = self.bias
            else:
                bias = self.bias[:feature_dim]
C
ceci3 已提交
1296 1297
        else:
            bias = None
C
Chang Xu 已提交
1298 1299
        self.cur_config = {'prune_dim': feature_dim}

W
whs 已提交
1300 1301 1302
        if paddle.in_dynamic_mode():
            out, _, _ = paddle._C_ops.layer_norm(
                input, weight, bias, self._epsilon, begin_norm_axis, False)
1303
        else:
W
whs 已提交
1304
            paddle.common_ops_import.check_variable_and_dtype(
W
whs 已提交
1305
                input, 'input', ['float32', 'float64'], 'LayerNorm')
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317

            inputs = dict()
            inputs['X'] = [input]
            if weight:
                inputs['Scale'] = [weight]
            if bias:
                inputs['Bias'] = [bias]
            attrs = {
                "epsilon": self._epsilon,
                "begin_norm_axis": begin_norm_axis
            }

1318
            helper = paddle.fluid.layer_helper.LayerHelper('layer_norm')
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340

            dtype = input.dtype
            mean_out = helper.create_variable_for_type_inference(
                dtype=dtype, stop_gradient=True)
            variance_out = helper.create_variable_for_type_inference(
                dtype=dtype, stop_gradient=True)
            layer_norm_out = helper.create_variable_for_type_inference(dtype)

            helper.append_op(
                type="layer_norm",
                inputs=inputs,
                outputs={
                    "Y": layer_norm_out,
                    "Mean": mean_out,
                    "Variance": variance_out,
                },
                attrs={
                    "epsilon": self._epsilon,
                    "begin_norm_axis": begin_norm_axis
                })
            return layer_norm_out

C
ceci3 已提交
1341
        return out
C
ceci3 已提交
1342 1343


W
whs 已提交
1344
class SuperEmbedding(paddle.nn.Embedding):
C
ceci3 已提交
1345 1346 1347 1348 1349 1350 1351
    """
    This interface is used to construct a callable object of the ``SuperEmbedding`` class.
    Parameters:
        num_embeddings (int): Just one element which indicate the size
            of the dictionary of embeddings.
        embedding_dim:  Just one element which indicate the size of each embedding vector respectively.
        padding_idx(int|long|None): padding_idx needs to be in the interval [-num_embeddings, num_embeddings).
W
whs 已提交
1352 1353 1354
            If :math:`padding\\_idx < 0`, the :math:`padding\\_idx` will automatically be converted
            to :math:`vocab\\_size + padding\\_idx` . It will output all-zero padding data whenever lookup
            encounters :math:`padding\\_idx` in id. And the padding data will not be updated while training.
C
ceci3 已提交
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
            If set None, it makes no effect to output. Default: None.
        sparse(bool): The flag indicating whether to use sparse update. This parameter only
            affects the performance of the backwards gradient update. It is recommended to set
            True because sparse update is faster. But some optimizer does not support sparse update,
            such as :ref:`api_optimizer_AdadeltaOptimizer` , :ref:`api_optimizer_AdamaxOptimizer` ,
            :ref:`api_optimizer_DecayedAdagradOptimizer` , :ref:`api_optimizer_FtrlOptimizer` ,
            :ref:`api_optimizer_LambOptimizer` and :ref:`api_optimizer_LarsMomentumOptimizer` .
            In these case, sparse must be False. Default: False.
        weight_attr(ParamAttr): To specify the weight parameter property. Default: None, which means the
            default weight parameter property is used. See usage for details in :ref:`api_ParamAttr` . In addition,
            user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter.
            The local word vector needs to be transformed into numpy format, and the shape of local word
W
whs 已提交
1367
            vector should be consistent with :attr:`num_embeddings` . Then :ref:`api_initializer_Assign`
C
ceci3 已提交
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
            is used to load custom or pre-trained word vectors. See code example for details.
        name(str|None): For detailed information, please refer
               to :ref:`api_guide_Name`. Usually name is no need to set and
               None by default.
    Attribute:
        **weight** (Parameter): the learnable weights of this layer.
    Returns:
        None
    Examples:
        .. code-block:: python
          import numpy as np
          import paddle
          from paddleslim.nas.ofa.layers import SuperEmbedding
          
C
ceci3 已提交
1382
          data = np.random.uniform(-1, 1, [32, 64]).astype('int64')
C
ceci3 已提交
1383
          config = {'channel': 16}
C
ceci3 已提交
1384 1385
          emb = SuperEmbedding(64, 64)
          data = paddle.to_tensor(data)
C
ceci3 已提交
1386 1387 1388
          res = emb(data, **config)
    """

C
ceci3 已提交
1389
    def __init__(self,
C
ceci3 已提交
1390 1391
                 num_embeddings,
                 embedding_dim,
C
ceci3 已提交
1392 1393
                 candidate_config={},
                 padding_idx=None,
C
ceci3 已提交
1394 1395 1396
                 sparse=False,
                 weight_attr=None,
                 name=None):
1397 1398 1399
        super(SuperEmbedding,
              self).__init__(num_embeddings, embedding_dim, padding_idx, sparse,
                             weight_attr, name)
C
ceci3 已提交
1400
        self.candidate_config = candidate_config
C
Chang Xu 已提交
1401
        self.cur_config = None
C
ceci3 已提交
1402 1403
        self.expand_ratio = candidate_config[
            'expand_ratio'] if 'expand_ratio' in candidate_config else None
C
ceci3 已提交
1404
        self.base_output_dim = self._embedding_dim
C
ceci3 已提交
1405
        if self.expand_ratio != None:
1406 1407
            self.base_output_dim = int(
                self._embedding_dim / max(self.expand_ratio))
C
ceci3 已提交
1408 1409

    def forward(self, input, expand_ratio=None, channel=None):
C
ceci3 已提交
1410 1411 1412 1413 1414 1415
        """
        Parameters:
            input(Tensor): input tensor.
            expand_ratio(int|float, optional): the expansion ratio of filter's channel number in actual calculation. Default: None.
            channel(int, optional): the expansion ratio of filter's channel number in actual calculation. Default: None.
        """
C
ceci3 已提交
1416 1417 1418 1419 1420 1421 1422 1423
        assert (
            expand_ratio == None or channel == None
        ), "expand_ratio and channel CANNOT be NOT None at the same time."
        if expand_ratio != None:
            out_nc = int(expand_ratio * self.base_output_dim)
        elif channel != None:
            out_nc = int(channel)
        else:
C
ceci3 已提交
1424
            out_nc = self._embedding_dim
C
ceci3 已提交
1425

1426 1427 1428 1429
        if self.weight.shape[1] <= out_nc:
            weight = self.weight
        else:
            weight = self.weight[:, :out_nc]
C
Chang Xu 已提交
1430
        self.cur_config = {'prune_dim': list(weight.shape)}
W
whs 已提交
1431
        return paddle.nn.functional.embedding(
C
ceci3 已提交
1432 1433 1434 1435
            input,
            weight=weight,
            padding_idx=self._padding_idx,
            sparse=self._sparse,
C
Chang Xu 已提交
1436
            name=self._name)