layers_old.py 45.8 KB
Newer Older
C
ceci3 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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.

C
ceci3 已提交
15 16
### NOTE: the API of this file is based on Paddle1.8, the API in layers.py is based on Paddle2.0

C
ceci3 已提交
17 18
import numpy as np
import logging
C
ceci3 已提交
19
import paddle.fluid as fluid
C
ceci3 已提交
20
import paddle.fluid.core as core
C
ceci3 已提交
21 22 23 24
import paddle.fluid.dygraph_utils as dygraph_utils
from paddle.fluid.data_feeder import check_variable_and_dtype
from paddle.fluid.framework import _varbase_creator
from paddle.fluid.dygraph.nn import InstanceNorm, Conv2D, Conv2DTranspose, BatchNorm
C
ceci3 已提交
25 26 27 28 29 30

from ...common import get_logger
from .utils.utils import compute_start_end, get_same_padding, convert_to_list

__all__ = [
    'SuperConv2D', 'SuperConv2DTranspose', 'SuperSeparableConv2D',
C
ceci3 已提交
31
    'SuperBatchNorm', 'SuperLinear', 'SuperInstanceNorm', 'Block',
C
ceci3 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    'SuperGroupConv2D', 'SuperDepthwiseConv2D', 'SuperGroupConv2DTranspose',
    'SuperDepthwiseConv2DTranspose', 'SuperLayerNorm', 'SuperEmbedding'
]

_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

_cnt = 0


def counter():
    global _cnt
    _cnt += 1
    return _cnt


C
ceci3 已提交
49
class BaseBlock(fluid.dygraph.Layer):
C
ceci3 已提交
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
    def __init__(self, key=None):
        super(BaseBlock, self).__init__()
        if key is not None:
            self._key = str(key)
        else:
            self._key = self.__class__.__name__ + str(counter())

    # set SuperNet class
    def set_supernet(self, supernet):
        self.__dict__['supernet'] = supernet

    @property
    def key(self):
        return self._key


class Block(BaseBlock):
    """
    Model is composed of nest blocks.

    Parameters:
        fn(Layer): instance of super layers, such as: SuperConv2D(3, 5, 3).
        key(str, optional): key of this layer, one-to-one correspondence between key and candidate config. Default: None.
    """

    def __init__(self, fn, fixed=False, key=None):
        super(Block, self).__init__(key)
        self.fn = fn
        self.fixed = fixed
        self.candidate_config = self.fn.candidate_config

    def forward(self, *inputs, **kwargs):
        out = self.supernet.layers_forward(self, *inputs, **kwargs)
        return out


C
ceci3 已提交
86
class SuperConv2D(fluid.dygraph.Conv2D):
C
ceci3 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    """
    This interface is used to construct a callable object of the ``SuperConv2D``  class.
    The difference between ```SuperConv2D``` and ```Conv2D``` is: ```SuperConv2D``` need 
    to feed a config dictionary with the format of {'channel', num_of_channel} represents 
    the channels of the outputs, used to change the first dimension of weight and bias, 
    only train the first channels of the weight and bias.

    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::
        Out = \\sigma (W \\ast X + b)
    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::
            H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\
            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)
            of conv2d. If it is set to None or one attribute of ParamAttr, conv2d
            will create ParamAttr as param_attr. If the Initializer of the param_attr
            is not set, the parameter is initialized with :math:`Normal(0.0, std)`,
            and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None.
        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.
            If it is set to None or one attribute of ParamAttr, conv2d
            will create ParamAttr as bias_attr. If the Initializer of the bias_attr
            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 已提交
184 185 186
          from paddle.fluid.dygraph.base import to_variable
          import paddle.fluid as fluid
          from paddleslim.core.layers import SuperConv2D
C
ceci3 已提交
187 188
          import numpy as np
          data = np.random.uniform(-1, 1, [10, 3, 32, 32]).astype('float32')
C
ceci3 已提交
189 190 191 192 193
          with fluid.dygraph.guard():
              super_conv2d = SuperConv2D(3, 10, 3)
              config = {'channel': 5}
              data = to_variable(data)
              conv = super_conv2d(data, config)
C
ceci3 已提交
194 195 196 197 198

    """

    ### NOTE: filter_size, num_channels and num_filters must be the max of candidate to define a largest network.
    def __init__(self,
C
ceci3 已提交
199 200 201
                 num_channels,
                 num_filters,
                 filter_size,
C
ceci3 已提交
202 203 204 205
                 candidate_config={},
                 transform_kernel=False,
                 stride=1,
                 dilation=1,
C
ceci3 已提交
206 207 208
                 padding=0,
                 groups=None,
                 param_attr=None,
C
ceci3 已提交
209
                 bias_attr=None,
C
ceci3 已提交
210 211 212 213
                 use_cudnn=True,
                 act=None,
                 dtype='float32'):
        ### NOTE: padding always is 0, add padding in forward because of kernel size is uncertain
C
ceci3 已提交
214
        super(SuperConv2D, self).__init__(
C
ceci3 已提交
215 216 217 218 219
            num_channels, num_filters, filter_size, stride, padding, dilation,
            groups, param_attr, bias_attr, use_cudnn, act, dtype)

        if isinstance(self._filter_size, int):
            self._filter_size = convert_to_list(self._filter_size, 2)
C
ceci3 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232

        self.candidate_config = candidate_config
        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 已提交
233
        self.base_channel = self._num_filters
C
ceci3 已提交
234
        if self.expand_ratio != None:
C
ceci3 已提交
235
            self.base_channel = int(self._num_filters / max(self.expand_ratio))
C
ceci3 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248

        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 已提交
249
                    attr=fluid.ParamAttr(
C
ceci3 已提交
250
                        name=self._full_name + param_name,
C
ceci3 已提交
251 252
                        initializer=fluid.initializer.NumpyArrayInitializer(
                            np.eye(ks_t))),
C
ceci3 已提交
253 254 255 256 257 258 259
                    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 已提交
260
        start, end = compute_start_end(self._filter_size[0], kernel_size)
C
ceci3 已提交
261 262
        ### if NOT transform kernel, intercept a center filter with kernel_size from largest filter
        filters = self.weight[:out_nc, :in_nc, start:end, start:end]
C
ceci3 已提交
263
        if self.transform_kernel != False and kernel_size < self._filter_size[
C
ceci3 已提交
264 265 266 267 268 269 270 271 272 273
                0]:
            ### 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 已提交
274
                _input_filter = fluid.layers.reshape(
C
ceci3 已提交
275 276 277
                    _input_filter,
                    shape=[(_input_filter.shape[0] * _input_filter.shape[1]),
                           -1])
C
ceci3 已提交
278 279 280 281 282 283
                core.ops.matmul(_input_filter,
                                self.__getattr__('%dto%d_matrix' %
                                                 (src_ks, target_ks)),
                                _input_filter, 'transpose_X', False,
                                'transpose_Y', False, "alpha", 1)
                _input_filter = fluid.layers.reshape(
C
ceci3 已提交
284 285 286 287 288 289 290 291 292
                    _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 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
        if self._groups == 1 or self._groups == None:
            ### standard conv
            return self._groups, in_nc, out_nc
        elif self._groups == self._num_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 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326

    def forward(self, input, kernel_size=None, expand_ratio=None, channel=None):
        self.cur_config = {
            'kernel_size': kernel_size,
            'expand_ratio': expand_ratio,
            'channel': channel
        }
        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 已提交
327 328
            out_nc = self._num_filters
        ks = int(self._filter_size[0]) if kernel_size == None else int(
C
ceci3 已提交
329 330 331 332 333 334 335 336 337 338 339 340
            kernel_size)

        groups, weight_in_nc, weight_out_nc = self.get_groups_in_out_nc(in_nc,
                                                                        out_nc)

        weight = self.get_active_filter(weight_in_nc, weight_out_nc, ks)

        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 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        if self._l_type == 'conv2d':
            attrs = ('strides', self._stride, 'paddings', padding, 'dilations',
                     self._dilation, 'groups', groups
                     if groups else 1, 'use_cudnn', self._use_cudnn)
            out = core.ops.conv2d(input, weight, *attrs)
        elif self._l_type == 'depthwise_conv2d':
            attrs = ('strides', self._stride, 'paddings', padding, 'dilations',
                     self._dilation, 'groups', groups
                     if groups else self._groups, 'use_cudnn', self._use_cudnn)
            out = core.ops.depthwise_conv2d(input, weight, *attrs)
        else:
            raise ValueError("conv type error")

        pre_bias = out
        out_nc = int(pre_bias.shape[1])
C
ceci3 已提交
356 357
        if self.bias is not None:
            bias = self.bias[:out_nc]
C
ceci3 已提交
358
            pre_act = dygraph_utils._append_bias_in_dygraph(pre_bias, bias, 1)
C
ceci3 已提交
359
        else:
C
ceci3 已提交
360 361 362
            pre_act = pre_bias

        return dygraph_utils._append_activation_in_dygraph(pre_act, self._act)
C
ceci3 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385


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


C
ceci3 已提交
386
class SuperConv2DTranspose(fluid.dygraph.Conv2DTranspose):
C
ceci3 已提交
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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    """
    This interface is used to construct a callable object of the ``SuperConv2DTranspose`` 
    class.
    The difference between ```SuperConv2DTranspose``` and ```Conv2DTranspose``` is: 
    ```SuperConv2DTranspose``` need to feed a config dictionary with the format of 
    {'channel', num_of_channel} represents the channels of the outputs, used to change 
    the first dimension of weight and bias, only train the first channels of the weight 
    and bias.

    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::
        Out = \sigma (W \\ast X + b)
    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::
           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] )
    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)
            of conv2d_transpose. If it is set to None or one attribute of ParamAttr, conv2d_transpose
            will create ParamAttr as param_attr. If the Initializer of the param_attr
            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.
            If it is set to None or one attribute of ParamAttr, conv2d_transpose
            will create ParamAttr as bias_attr. If the Initializer of the bias_attr
            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 已提交
488 489
          import paddle.fluid as fluid
          from paddleslim.core.layers import SuperConv2DTranspose
C
ceci3 已提交
490
          import numpy as np
C
ceci3 已提交
491 492 493 494 495
          with fluid.dygraph.guard():
              data = np.random.random((3, 32, 32, 5)).astype('float32')
              config = {'channel': 5
              super_convtranspose = SuperConv2DTranspose(num_channels=32, num_filters=10, filter_size=3)
              ret = super_convtranspose(fluid.dygraph.base.to_variable(data), config)
C
ceci3 已提交
496 497 498
    """

    def __init__(self,
C
ceci3 已提交
499 500 501 502
                 num_channels,
                 num_filters,
                 filter_size,
                 output_size=None,
C
ceci3 已提交
503 504 505 506
                 candidate_config={},
                 transform_kernel=False,
                 stride=1,
                 dilation=1,
C
ceci3 已提交
507 508 509
                 padding=0,
                 groups=None,
                 param_attr=None,
C
ceci3 已提交
510
                 bias_attr=None,
C
ceci3 已提交
511 512 513
                 use_cudnn=True,
                 act=None,
                 dtype='float32'):
C
ceci3 已提交
514
        super(SuperConv2DTranspose, self).__init__(
C
ceci3 已提交
515 516 517
            num_channels, num_filters, filter_size, output_size, padding,
            stride, dilation, groups, param_attr, bias_attr, use_cudnn, act,
            dtype)
C
ceci3 已提交
518 519 520 521 522 523
        self.candidate_config = candidate_config
        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
C
ceci3 已提交
524 525 526 527

        if isinstance(self._filter_size, int):
            self._filter_size = convert_to_list(self._filter_size, 2)

C
ceci3 已提交
528 529 530 531
        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 已提交
532
        self.base_channel = self._num_filters
C
ceci3 已提交
533
        if self.expand_ratio:
C
ceci3 已提交
534
            self.base_channel = int(self._num_filters / max(self.expand_ratio))
C
ceci3 已提交
535 536 537 538 539 540 541 542 543 544 545 546 547

        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 已提交
548
                    attr=fluid.ParamAttr(
C
ceci3 已提交
549
                        name=self._full_name + param_name,
C
ceci3 已提交
550 551
                        initializer=fluid.initializer.NumpyArrayInitializer(
                            np.eye(ks_t))),
C
ceci3 已提交
552 553 554 555 556 557 558
                    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 已提交
559
        start, end = compute_start_end(self._filter_size[0], kernel_size)
C
ceci3 已提交
560
        filters = self.weight[:in_nc, :out_nc, start:end, start:end]
C
ceci3 已提交
561
        if self.transform_kernel != False and kernel_size < self._filter_size[
C
ceci3 已提交
562 563 564 565 566 567 568 569 570
                0]:
            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 已提交
571
                _input_filter = fluid.layers.reshape(
C
ceci3 已提交
572 573 574
                    _input_filter,
                    shape=[(_input_filter.shape[0] * _input_filter.shape[1]),
                           -1])
C
ceci3 已提交
575 576 577 578 579 580
                core.ops.matmul(_input_filter,
                                self.__getattr__('%dto%d_matrix' %
                                                 (src_ks, target_ks)),
                                _input_filter, 'transpose_X', False,
                                'transpose_Y', False, "alpha", 1)
                _input_filter = fluid.layers.reshape(
C
ceci3 已提交
581 582 583 584 585 586 587 588 589
                    _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 已提交
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
        if self._groups == 1 or self._groups == None:
            ### standard conv
            return self._groups, in_nc, out_nc
        elif self._groups == self._num_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, kernel_size=None, expand_ratio=None, channel=None):
C
ceci3 已提交
610 611 612 613 614 615 616 617 618 619 620 621 622 623
        self.cur_config = {
            'kernel_size': kernel_size,
            'expand_ratio': expand_ratio,
            'channel': channel
        }
        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 已提交
624
            out_nc = self._num_filters
C
ceci3 已提交
625

C
ceci3 已提交
626
        ks = int(self._filter_size[0]) if kernel_size == None else int(
C
ceci3 已提交
627 628 629 630 631 632 633 634 635 636 637
            kernel_size)

        groups, weight_in_nc, weight_out_nc = self.get_groups_in_out_nc(in_nc,
                                                                        out_nc)

        weight = self.get_active_filter(weight_in_nc, weight_out_nc, ks)
        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 已提交
638 639 640 641 642 643
        op = getattr(core.ops, self._op_type)
        out = op(input, weight, 'output_size', self._output_size, 'strides',
                 self._stride, 'paddings', padding, 'dilations', self._dilation,
                 'groups', groups, 'use_cudnn', self._use_cudnn)
        pre_bias = out
        out_nc = int(pre_bias.shape[1])
C
ceci3 已提交
644 645
        if self.bias is not None:
            bias = self.bias[:out_nc]
C
ceci3 已提交
646
            pre_act = dygraph_utils._append_bias_in_dygraph(pre_bias, bias, 1)
C
ceci3 已提交
647
        else:
C
ceci3 已提交
648 649 650 651
            pre_act = pre_bias

        return dygraph_utils._append_activation_in_dygraph(
            pre_act, act=self._act)
C
ceci3 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674


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.
C
ceci3 已提交
675
class SuperSeparableConv2D(fluid.dygraph.Layer):
C
ceci3 已提交
676 677 678 679 680 681 682 683 684
    """
    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 已提交
685 686
    The architecture of super separable convolution2D op is [Conv2D, norm layer(may be BatchNorm
    or InstanceNorm), Conv2D]. The first conv is depthwise conv, the filter number is input channel
C
ceci3 已提交
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    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 已提交
706
        norm_layer(class): The normalization layer between two convolution. Default: InstanceNorm.
C
ceci3 已提交
707 708 709 710 711 712
        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.
            If it is set to None or one attribute of ParamAttr, convolution
            will create ParamAttr as bias_attr. If the Initializer of the bias_attr
            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.
C
ceci3 已提交
713 714
        use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn
            library is installed. Default: True.
C
ceci3 已提交
715 716 717 718 719
    Returns:
        None
    """

    def __init__(self,
C
ceci3 已提交
720 721 722
                 num_channels,
                 num_filters,
                 filter_size,
C
ceci3 已提交
723 724 725 726
                 candidate_config={},
                 stride=1,
                 padding=0,
                 dilation=1,
C
ceci3 已提交
727
                 norm_layer=InstanceNorm,
C
ceci3 已提交
728
                 bias_attr=None,
C
ceci3 已提交
729 730
                 scale_factor=1,
                 use_cudnn=False):
C
ceci3 已提交
731
        super(SuperSeparableConv2D, self).__init__()
C
ceci3 已提交
732 733 734 735 736
        self.conv = fluid.dygraph.LayerList([
            fluid.dygraph.nn.Conv2D(
                num_channels=num_channels,
                num_filters=num_channels * scale_factor,
                filter_size=filter_size,
C
ceci3 已提交
737 738
                stride=stride,
                padding=padding,
C
ceci3 已提交
739 740
                use_cudnn=False,
                groups=num_channels,
C
ceci3 已提交
741 742 743
                bias_attr=bias_attr)
        ])

C
ceci3 已提交
744
        self.conv.extend([norm_layer(num_channels * scale_factor)])
C
ceci3 已提交
745 746

        self.conv.extend([
C
ceci3 已提交
747 748 749 750
            fluid.dygraph.nn.Conv2D(
                num_channels=num_channels * scale_factor,
                num_filters=num_filters,
                filter_size=1,
C
ceci3 已提交
751
                stride=1,
C
ceci3 已提交
752
                use_cudnn=use_cudnn,
C
ceci3 已提交
753 754 755 756 757 758
                bias_attr=bias_attr)
        ])

        self.candidate_config = candidate_config
        self.expand_ratio = candidate_config[
            'expand_ratio'] if 'expand_ratio' in candidate_config else None
C
ceci3 已提交
759
        self.base_output_dim = self.conv[0]._num_filters
C
ceci3 已提交
760
        if self.expand_ratio != None:
C
ceci3 已提交
761
            self.base_output_dim = int(self.conv[0]._num_filters /
C
ceci3 已提交
762 763 764 765 766 767 768 769 770 771 772 773 774
                                       max(self.expand_ratio))

    def forward(self, input, expand_ratio=None, channel=None):
        self.cur_config = {'expand_ratio': expand_ratio, 'channel': channel}
        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 已提交
775
            out_nc = self.conv[0]._num_filters
C
ceci3 已提交
776 777 778

        weight = self.conv[0].weight[:in_nc]
        ###  conv1
C
ceci3 已提交
779 780 781 782 783 784 785 786 787 788 789 790 791 792
        if self.conv[0]._l_type == 'conv2d':
            attrs = ('strides', self.conv[0]._stride, 'paddings',
                     self.conv[0]._padding, 'dilations', self.conv[0]._dilation,
                     'groups', in_nc, 'use_cudnn', self.conv[0]._use_cudnn)
            out = core.ops.conv2d(input, weight, *attrs)
        elif self.conv[0]._l_type == 'depthwise_conv2d':
            attrs = ('strides', self.conv[0]._stride, 'paddings',
                     self.conv[0]._padding, 'dilations', self.conv[0]._dilation,
                     'groups', in_nc, 'use_cudnn', self.conv[0]._use_cudnn)
            out = core.ops.depthwise_conv2d(input, weight, *attrs)
        else:
            raise ValueError("conv type error")

        pre_bias = out
C
ceci3 已提交
793 794
        if self.conv[0].bias is not None:
            bias = self.conv[0].bias[:in_nc]
C
ceci3 已提交
795
            pre_act = dygraph_utils._append_bias_in_dygraph(pre_bias, bias, 1)
C
ceci3 已提交
796
        else:
C
ceci3 已提交
797 798 799 800
            pre_act = pre_bias

        conv0_out = dygraph_utils._append_activation_in_dygraph(
            pre_act, self.conv[0]._act)
C
ceci3 已提交
801 802 803 804 805

        norm_out = self.conv[1](conv0_out)

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

C
ceci3 已提交
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
        if self.conv[2]._l_type == 'conv2d':
            attrs = ('strides', self.conv[2]._stride, 'paddings',
                     self.conv[2]._padding, 'dilations', self.conv[2]._dilation,
                     'groups', self.conv[2]._groups if self.conv[2]._groups else
                     1, 'use_cudnn', self.conv[2]._use_cudnn)
            out = core.ops.conv2d(norm_out, weight, *attrs)
        elif self.conv[2]._l_type == 'depthwise_conv2d':
            attrs = ('strides', self.conv[2]._stride, 'paddings',
                     self.conv[2]._padding, 'dilations', self.conv[2]._dilation,
                     'groups', self.conv[2]._groups, 'use_cudnn',
                     self.conv[2]._use_cudnn)
            out = core.ops.depthwise_conv2d(norm_out, weight, *attrs)
        else:
            raise ValueError("conv type error")

        pre_bias = out
C
ceci3 已提交
822 823
        if self.conv[2].bias is not None:
            bias = self.conv[2].bias[:out_nc]
C
ceci3 已提交
824
            pre_act = dygraph_utils._append_bias_in_dygraph(pre_bias, bias, 1)
C
ceci3 已提交
825
        else:
C
ceci3 已提交
826 827 828 829 830
            pre_act = pre_bias

        conv1_out = dygraph_utils._append_activation_in_dygraph(
            pre_act, self.conv[2]._act)

C
ceci3 已提交
831 832 833
        return conv1_out


C
ceci3 已提交
834
class SuperLinear(fluid.dygraph.Linear):
C
ceci3 已提交
835 836 837 838
    """
    """

    def __init__(self,
C
ceci3 已提交
839 840
                 input_dim,
                 output_dim,
C
ceci3 已提交
841
                 candidate_config={},
C
ceci3 已提交
842
                 param_attr=None,
C
ceci3 已提交
843
                 bias_attr=None,
C
ceci3 已提交
844 845 846 847 848
                 act=None,
                 dtype="float32"):
        super(SuperLinear, self).__init__(input_dim, output_dim, param_attr,
                                          bias_attr, act, dtype)
        self._param_attr = param_attr
C
ceci3 已提交
849
        self._bias_attr = bias_attr
C
ceci3 已提交
850
        self.output_dim = output_dim
C
ceci3 已提交
851 852 853
        self.candidate_config = candidate_config
        self.expand_ratio = candidate_config[
            'expand_ratio'] if 'expand_ratio' in candidate_config else None
C
ceci3 已提交
854
        self.base_output_dim = self.output_dim
C
ceci3 已提交
855
        if self.expand_ratio != None:
C
ceci3 已提交
856
            self.base_output_dim = int(self.output_dim / max(self.expand_ratio))
C
ceci3 已提交
857 858 859 860 861 862 863 864 865 866 867 868 869

    def forward(self, input, expand_ratio=None, channel=None):
        self.cur_config = {'expand_ratio': expand_ratio, 'channel': channel}
        ### weight: (Cin, Cout)
        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 已提交
870
            out_nc = self.output_dim
C
ceci3 已提交
871 872 873 874

        weight = self.weight[:in_nc, :out_nc]
        if self._bias_attr != False:
            bias = self.bias[:out_nc]
C
ceci3 已提交
875 876 877 878 879 880 881 882
            use_bias = True

        pre_bias = _varbase_creator(dtype=input.dtype)
        core.ops.matmul(input, weight, pre_bias, 'transpose_X', False,
                        'transpose_Y', False, "alpha", 1)
        if self._bias_attr != False:
            pre_act = dygraph_utils._append_bias_in_dygraph(
                pre_bias, bias, axis=len(input.shape) - 1)
C
ceci3 已提交
883
        else:
C
ceci3 已提交
884
            pre_act = pre_bias
C
ceci3 已提交
885

C
ceci3 已提交
886
        return dygraph_utils._append_activation_in_dygraph(pre_act, self._act)
C
ceci3 已提交
887 888


C
ceci3 已提交
889
class SuperBatchNorm(fluid.dygraph.BatchNorm):
C
ceci3 已提交
890 891 892 893 894
    """
    add comment
    """

    def __init__(self,
C
ceci3 已提交
895 896 897
                 num_channels,
                 act=None,
                 is_test=False,
C
ceci3 已提交
898 899
                 momentum=0.9,
                 epsilon=1e-05,
C
ceci3 已提交
900
                 param_attr=None,
C
ceci3 已提交
901
                 bias_attr=None,
C
ceci3 已提交
902 903 904 905 906 907 908 909 910 911 912 913 914
                 dtype='float32',
                 data_layout='NCHW',
                 in_place=False,
                 moving_mean_name=None,
                 moving_variance_name=None,
                 do_model_average_for_mean_and_var=True,
                 use_global_stats=False,
                 trainable_statistics=False):
        super(SuperBatchNorm, self).__init__(
            num_channels, act, is_test, momentum, epsilon, param_attr,
            bias_attr, dtype, data_layout, in_place, moving_mean_name,
            moving_variance_name, do_model_average_for_mean_and_var,
            use_global_stats, trainable_statistics)
C
ceci3 已提交
915 916 917 918 919 920 921 922 923

    def forward(self, input):
        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 已提交
924 925 926 927 928 929 930 931 932 933 934 935
        mean_out = mean
        variance_out = variance

        attrs = ("momentum", self._momentum, "epsilon", self._epsilon,
                 "is_test", not self.training, "data_layout", self._data_layout,
                 "use_mkldnn", False, "fuse_with_relu", self._fuse_with_relu,
                 "use_global_stats", self._use_global_stats,
                 'trainable_statistics', self._trainable_statistics)
        batch_norm_out, _, _, _, _, _ = core.ops.batch_norm(
            input, weight, bias, mean, variance, mean_out, variance_out, *attrs)
        return dygraph_utils._append_activation_in_dygraph(
            batch_norm_out, act=self._act)
C
ceci3 已提交
936 937


C
ceci3 已提交
938
class SuperInstanceNorm(fluid.dygraph.InstanceNorm):
C
ceci3 已提交
939 940 941 942
    """
    """

    def __init__(self,
C
ceci3 已提交
943
                 num_channels,
C
ceci3 已提交
944
                 epsilon=1e-05,
C
ceci3 已提交
945
                 param_attr=None,
C
ceci3 已提交
946
                 bias_attr=None,
C
ceci3 已提交
947 948 949
                 dtype='float32'):
        super(SuperInstanceNorm, self).__init__(num_channels, epsilon,
                                                param_attr, bias_attr, dtype)
C
ceci3 已提交
950 951 952

    def forward(self, input):
        feature_dim = int(input.shape[1])
C
ceci3 已提交
953 954

        if self._param_attr == False and self._bias_attr == False:
C
ceci3 已提交
955 956 957 958 959 960
            scale = None
            bias = None
        else:
            scale = self.scale[:feature_dim]
            bias = self.bias[:feature_dim]

C
ceci3 已提交
961 962 963
        out, _, _ = core.ops.instance_norm(input, scale, bias, 'epsilon',
                                           self._epsilon)
        return out
C
ceci3 已提交
964 965


C
ceci3 已提交
966
class SuperLayerNorm(fluid.dygraph.LayerNorm):
C
ceci3 已提交
967 968
    def __init__(self,
                 normalized_shape,
C
ceci3 已提交
969 970
                 scale=True,
                 shift=True,
C
ceci3 已提交
971
                 epsilon=1e-05,
C
ceci3 已提交
972
                 param_attr=None,
C
ceci3 已提交
973
                 bias_attr=None,
C
ceci3 已提交
974 975 976 977 978
                 act=None,
                 dtype='float32'):
        super(SuperLayerNorm,
              self).__init__(normalized_shape, scale, shift, epsilon,
                             param_attr, bias_attr, act, dtype)
C
ceci3 已提交
979 980

    def forward(self, input):
C
ceci3 已提交
981 982
        input_shape = list(input.shape)
        input_ndim = len(input_shape)
C
ceci3 已提交
983
        normalized_ndim = len(self._normalized_shape)
C
ceci3 已提交
984 985 986
        self._begin_norm_axis = input_ndim - normalized_ndim

        ### TODO(ceci3): fix if normalized_shape is not a single number
C
ceci3 已提交
987
        feature_dim = int(input.shape[-1])
C
ceci3 已提交
988 989 990 991 992 993 994
        weight = self.weight[:feature_dim]
        bias = self.bias[:feature_dim]
        pre_act, _, _ = core.ops.layer_norm(input, weight, bias, 'epsilon',
                                            self._epsilon, 'begin_norm_axis',
                                            self._begin_norm_axis)
        return dygraph_utils._append_activation_in_dygraph(
            pre_act, act=self._act)
C
ceci3 已提交
995 996


C
ceci3 已提交
997
class SuperEmbedding(fluid.dygraph.Embedding):
C
ceci3 已提交
998
    def __init__(self,
C
ceci3 已提交
999
                 size,
C
ceci3 已提交
1000
                 candidate_config={},
C
ceci3 已提交
1001 1002
                 is_sparse=False,
                 is_distributed=False,
C
ceci3 已提交
1003
                 padding_idx=None,
C
ceci3 已提交
1004 1005 1006 1007
                 param_attr=None,
                 dtype='float32'):
        super(SuperEmbedding, self).__init__(size, is_sparse, is_distributed,
                                             padding_idx, param_attr, dtype)
C
ceci3 已提交
1008 1009 1010
        self.candidate_config = candidate_config
        self.expand_ratio = candidate_config[
            'expand_ratio'] if 'expand_ratio' in candidate_config else None
C
ceci3 已提交
1011
        self.base_output_dim = self._size[-1]
C
ceci3 已提交
1012
        if self.expand_ratio != None:
C
ceci3 已提交
1013
            self.base_output_dim = int(self._size[-1] / max(self.expand_ratio))
C
ceci3 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

    def forward(self, input, expand_ratio=None, channel=None):
        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 已提交
1024
            out_nc = self._size[-1]
C
ceci3 已提交
1025 1026

        weight = self.weight[:, :out_nc]
C
ceci3 已提交
1027 1028 1029 1030
        return core.ops.lookup_table_v2(
            weight, input, 'is_sparse', self._is_sparse, 'is_distributed',
            self._is_distributed, 'remote_prefetch', self._remote_prefetch,
            'padding_idx', self._padding_idx)