layers.py 128.0 KB
Newer Older
Z
zhangjinchao01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2016 Baidu, Inc. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import functools
16
import collections
Z
zhangjinchao01 已提交
17 18 19 20 21 22 23 24

from paddle.trainer.config_parser import *
from .activations import LinearActivation, SigmoidActivation, TanhActivation, \
    ReluActivation, IdentityActivation, SoftmaxActivation
from .evaluators import *
from .poolings import MaxPooling, AvgPooling, BasePoolingType
from .attrs import *
from .default_decorators import *
25

Z
zhangjinchao01 已提交
26 27 28 29 30 31 32
try:
    import cPickle as pickle
except ImportError:
    import pickle
import copy

__all__ = ["full_matrix_projection", "AggregateLevel", "ExpandLevel",
33
           "identity_projection", "dotmul_projection", "dotmul_operator",
Z
zhangjinchao01 已提交
34 35 36 37 38 39
           "table_projection", "mixed_layer", "data_layer",
           "embedding_layer", "fc_layer", "grumemory",
           "pooling_layer", "lstmemory", "last_seq", "first_seq",
           "cos_sim", "hsigmoid",
           "regression_cost", 'classification_cost', "LayerOutput",
           'img_conv_layer', 'img_pool_layer', 'batch_norm_layer',
40
           'img_cmrnorm_layer', 'addto_layer',
Z
zhangjinchao01 已提交
41 42 43 44 45 46 47 48 49 50
           'concat_layer', 'lstm_step_layer', 'recurrent_group',
           'memory', 'StaticInput', 'expand_layer', 'scaling_layer',
           'power_layer', 'interpolation_layer', 'trans_layer',
           'sum_to_one_norm_layer',
           'get_output_layer', 'LayerType', 'context_projection',
           'beam_search', 'maxid_layer', 'GeneratedInput', 'SubsequenceInput',
           'gru_step_layer', 'recurrent_layer',
           'BaseGeneratedInput', 'conv_operator', 'conv_shift_layer',
           'tensor_layer', 'selective_fc_layer', 'sampling_id_layer',
           'slope_intercept_layer', 'trans_full_matrix_projection',
51
           'linear_comb_layer',
Z
zhangjinchao01 已提交
52
           'convex_comb_layer', 'ctc_layer', 'crf_layer', 'crf_decoding_layer',
53
           'nce_layer',
Z
zhangjinchao01 已提交
54 55 56
           'cross_entropy_with_selfnorm', 'cross_entropy',
           'multi_binary_label_cross_entropy',
           'rank_cost', 'lambda_cost', 'huber_cost',
57 58
           # 'block_expand_layer',  # TODO(yuyang18): this layer is not correct
           'out_prod_layer', 'print_layer'
Z
zhangjinchao01 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
           ]


class LayerType(object):
    """
    Layer type enumerations.
    """

    DATA = "data"
    MIXED_LAYER = "mixed"
    LSTMEMORY = "lstmemory"
    GRUMEMORY = "gated_recurrent"
    SEQUENCE_LAST_INSTANCE = "seqlastins"
    SEQUENCE_FIRST_INSTANCE = "seqfirstins"
    POOLING_MAX = "max"
    POOLING_AVG = 'average'
    FC_LAYER = "fc"
    COST = 'cost'
77 78
    COSINE_SIM_VEC = 'cos_vm'
    COSINE_SIM = 'cos'
Z
zhangjinchao01 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    HSIGMOID = 'hsigmoid'
    CONV_LAYER = "conv"
    POOL_LAYER = "pool"
    BATCH_NORM_LAYER = 'batch_norm'
    NORM_LAYER = 'norm'
    SUM_TO_ONE_NORM_LAYER = 'sum_to_one_norm'
    ADDTO_LAYER = 'addto'

    CONCAT_LAYER = 'concat'
    CONCAT_PROJ_LAYER = 'concat2'

    LSTM_STEP_LAYER = 'lstm_step'
    GRU_STEP_LAYER = 'gru_step'
    GET_OUTPUT_LAYER = 'get_output'

    EXPAND_LAYER = 'expand'
    INTERPOLATION_LAYER = 'interpolation'
    POWER_LAYER = 'power'
    SCALING_LAYER = 'scaling'
    TRANS_LAYER = 'trans'
H
Haonan 已提交
99
    OUT_PROD_LAYER = 'out_prod'
Z
zhangjinchao01 已提交
100 101 102 103 104 105 106 107 108 109 110

    MEMORY = 'memory'
    MAXID_LAYER = 'maxid'
    EOSID_LAYER = 'eos_id'
    RECURRENT_LAYER = 'recurrent'

    CONV_SHIFT_LAYER = "conv_shift"
    TENSOR_LAYER = "tensor"
    SEL_FC_LAYER = "selective_fc"
    SAMPLING_ID_LAYER = "sampling_id"
    SLOPE_INTERCEPT_LAYER = "slope_intercept"
111
    LINEAR_COMBINATION_LAYER = "convex_comb"
Z
zhangjinchao01 已提交
112 113
    BLOCK_EXPAND = "blockexpand"

114 115
    PRINT_LAYER = "print"

Z
zhangjinchao01 已提交
116 117 118
    CTC_LAYER = "ctc"
    CRF_LAYER = "crf"
    CRF_DECODING_LAYER = "crf_decoding"
119
    NCE_LAYER = 'nce'
Z
zhangjinchao01 已提交
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

    RANK_COST = "rank-cost"
    LAMBDA_COST = "lambda_cost"
    HUBER = "huber"
    CROSS_ENTROPY = "multi-class-cross-entropy"
    CROSS_ENTROPY_WITH_SELFNORM = "multi_class_cross_entropy_with_selfnorm"
    SOFT_BIN_CLASS_CROSS_ENTROPY = "soft_binary_class_cross_entropy"
    MULTI_BIN_LABEL_CROSS_ENTROPY = "multi_binary_label_cross_entropy"

    @staticmethod
    def is_layer_type(type_name):
        """
        If type_name is a layer type.

        :param type_name: layer type name. Because layer type enumerations are
                          strings.
        :type type_name: basestring
        :return: True if is a layer_type
        :rtype: bool
        """
        for key in dir(LayerType):
            if key.isupper():
                att = getattr(LayerType, key)
                if isinstance(att, basestring) and type_name == att:
                    return True
        return False


class AggregateLevel(object):
    EACH_TIMESTEP = 'non-seq'
    EACH_SEQUENCE = 'seq'


class LayerOutput(object):
    """
    LayerOutput is output for layer function. It is used internally by several
    reasons.

    - Check layer connection make sense.

        - FC(Softmax) => Cost(MSE Error) is not good for example.

    - Tracking layer connection.

    - Pass to layer methods as input.

    :param name: Layer output name.
    :type name: basestring
    :param layer_type: Current Layer Type. One of LayerType enumeration.
    :type layer_type: basestring
    :param activation: Layer Activation.
    :type activation: BaseActivation.
    :param parents: Layer's parents.
173
    :type parents: list|tuple|collections.Sequence
Z
zhangjinchao01 已提交
174 175 176
    """

    def __init__(self, name, layer_type, parents=None, activation=None,
177 178
                 num_filters=None, img_norm_type=None, size=None, outputs=None,
                 reverse=None):
Z
zhangjinchao01 已提交
179 180 181 182 183
        assert isinstance(name, basestring)
        assert isinstance(layer_type, basestring)
        assert LayerType.is_layer_type(layer_type)
        self.name = name
        self.layer_type = layer_type
184 185
        if parents is not None and type(parents) != list:
            parents = [parents]
Z
zhangjinchao01 已提交
186 187 188 189 190 191 192 193
        self.parents = [] if parents is None else parents
        self.activation = activation
        self.num_filters = num_filters
        self.img_norm_type = img_norm_type
        self.size = size
        if outputs is None:
            outputs = ['default']
        self.outputs = outputs
194
        self.reverse = reverse
Z
zhangjinchao01 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

    def __repr__(self):
        """
        Disable __repr__ for debug reason. Will be implemented when release
        """
        assert False, "this method should not be invoked"

    def __str__(self):
        """
        Disable __str__ for debug reason. Will be implemented when release
        """
        assert False, "this method should not be invoked"


ERROR_CLIPPING = 'error_clipping_threshold'
DROPOUT = 'drop_rate'
211
DEVICE = 'device'
Z
zhangjinchao01 已提交
212 213 214


def layer_support(*attrs):
215
    attrs_list = list(attrs)
216
    attrs_list.append(DEVICE)
Z
zhangjinchao01 已提交
217 218 219
    def decorator(method):
        @functools.wraps(method)
        def wrapper(*args, **kwargs):
220
            for attr in attrs_list:
Z
zhangjinchao01 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
                for each in args:
                    if isinstance(each, ExtraLayerAttribute):
                        setattr(each, '_'.join(['can', attr]), True)
                for key in kwargs:
                    val = kwargs[key]
                    if isinstance(val, ExtraLayerAttribute):
                        setattr(val, '_'.join(['can', attr]), True)
            for each in args:
                if isinstance(each, ExtraLayerAttribute):
                    each.check(method.__name__)
            for key in kwargs:
                val = kwargs[key]
                if isinstance(val, ExtraLayerAttribute):
                    val.check(method.__name__)
            return method(*args, **kwargs)

        return wrapper

    return decorator


@wrap_param_attr_default()
def full_matrix_projection(input, size=0, param_attr=None):
    """
    Full Matrix Projection. It performs full matrix multiplication.

    ..  math::
        out.row[i] += in.row[i] * weight

    There are two styles of usage.

    1. When used in mixed_layer like this, you can only set the input:

    .. code-block:: python

       with mixed_layer(size=100) as m:
           m += full_matrix_projection(input=layer)

    2. When used as an independant object like this, you must set the size:

    .. code-block:: python

       proj = full_matrix_projection(input=layer,
                                     size=100,
                                     param_attr=ParamAttr(name='_proj'))

    :param input: input layer
    :type input: LayerOutput
    :param size: The parameter size. Means the width of parameter.
    :type size: int
    :param param_attr: Parameter config, None if use default.
    :type param_attr: ParameterAttribute
    :return: A FullMatrixProjection Object.
    :rtype: FullMatrixProjection
    """
    proj = FullMatrixProjection(input_layer_name=input.name,
                                size=size,
                                **param_attr.attr)
    proj.origin = input
    return proj


283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
@wrap_param_attr_default()
def trans_full_matrix_projection(input, size=0, param_attr=None):
    """
    Different from full_matrix_projection, this projection performs matrix
    multiplication, using transpose of weight.

    ..  math::
        out.row[i] += in.row[i] * w^\mathrm{T}

    :math:`w^\mathrm{T}` means transpose of weight.
    The simply usage is:

    .. code-block:: python

       proj = trans_full_matrix_projection(input=layer,
                                           size=100,
                                           param_attr=ParamAttr(
                                                name='_proj',
                                                initial_mean=0.0,
                                                initial_std=0.01))

    :param input: input layer
    :type input: LayerOutput
    :param size: The parameter size. Means the width of parameter.
    :type size: int
    :param param_attr: Parameter config, None if use default.
    :type param_attr: ParameterAttribute
    :return: A TransposedFullMatrixProjection Object.
    :rtype: TransposedFullMatrixProjection
    """
    proj = TransposedFullMatrixProjection(input_layer_name=input.name,
                                          size=size,
                                          **param_attr.attr)
    proj.origin = input
    return proj


Z
zhangjinchao01 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
@wrap_param_attr_default()
def table_projection(input, size=0, param_attr=None):
    """
    Table Projection. It selects rows from parameter where row\_id
    is in input\_ids.

    .. math::
       out.row[i] += table.row[ids[i]]

    where :math:`out` is output, :math:`table` is parameter, :math:`ids` is input\_ids,
    and :math:`i` is row\_id.

    There are two styles of usage.

    1. When used in mixed_layer like this, you can only set the input:

    .. code-block:: python

       with mixed_layer(size=100) as m:
           m += table_projection(input=layer)

    2. When used as an independant object like this, you must set the size:

    .. code-block:: python

       proj = table_projection(input=layer,
                               size=100,
                               param_attr=ParamAttr(name='_proj'))


    :param input: Input layer, which must contains id fields.
    :type input: LayerOutput
    :param size: The parameter size. Means the width of parameter.
    :type size: int
    :param param_attr: Parameter config, None if use default.
    :type param_attr: ParameterAttribute
    :return: A TableProjection Object.
    :rtype: TableProjection
    """
    proj = TableProjection(input_layer_name=input.name,
                           size=size,
                           **param_attr.attr)
    proj.origin = input
    return proj


def identity_projection(input, offset=None):
    """
    1. IdentityProjection if offset=None. It performs:

    .. math::
       out.row[i] += in.row[i]

    The example usage is:

    .. code-block:: python

       proj = identity_projection(input=layer)


    2. IdentityOffsetProjection if offset!=None. It likes IdentityProjection,
    but layer size may be smaller than input size.
    It select dimesions [offset, offset+layer_size) from input:

    .. math::
       out.row[i] += in.row[i + \\textrm{offset}]

    The example usage is:

    .. code-block:: python

       proj = identity_projection(input=layer,
                                  offset=10)

    Note that both of two projections should not have any parameter.

    :param input: Input Layer.
397
    :type input: LayerOutput
Z
zhangjinchao01 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
    :param offset: Offset, None if use default.
    :type offset: int
    :return: A IdentityProjection or IdentityOffsetProjection Object
    :rtype: IdentityProjection or IdentityOffsetProjection
    """
    if offset is None:
        proj = IdentityProjection(input_layer_name=input.name)
        proj.origin = input
    else:
        proj = IdentityOffsetProjection(input_layer_name=input.name,
                                        offset=offset)
        proj.origin = input
    return proj


@wrap_param_attr_default()
414
def dotmul_projection(input, param_attr=None):
Z
zhangjinchao01 已提交
415
    """
416
    DotMulProjection with a layer as input.
Z
zhangjinchao01 已提交
417 418 419 420 421 422 423 424 425 426 427 428 429
    It performs element-wise multiplication with weight.

    ..  math::
        out.row[i] += in.row[i] .* weight

    where :math:`.*` means element-wise multiplication.

    The example usage is:

    .. code-block:: python

       proj = dotmul_projection(input=layer)

430 431 432 433 434 435 436 437
    :param input: Input layer.
    :type input: LayerOutput
    :param param_attr: Parameter config, None if use default.
    :type param_attr: ParameterAttribute
    :return: A DotMulProjection Object.
    :rtype: DotMulProjection
    """
    proj = DotMulProjection(input_layer_name=input.name,
438 439
                            size=input.size,
                            **param_attr.attr)
440
    proj.origin = input
441
    return proj
Z
zhangjinchao01 已提交
442

443 444

def dotmul_operator(a=None, b=None, scale=1, **kwargs):
445 446
    """
    DotMulOperator takes two inputs and performs element-wise multiplication:
447

Z
zhangjinchao01 已提交
448
    .. math::
449 450
       out.row[i] += scale * (x.row[i] .* y.row[i])

Z
zhangjinchao01 已提交
451 452
    where :math:`.*` means element-wise multiplication, and
    scale is a config scalar, its default value is one.
453

Z
zhangjinchao01 已提交
454
    The example usage is:
455

Z
zhangjinchao01 已提交
456
    .. code-block:: python
457 458 459

       op = dotmul_operator(x=layer1, y=layer2, scale=0.5)

460 461 462 463
    :param a: Input layer1
    :type a: LayerOutput
    :param b: Input layer2
    :type b: LayerOutput
Z
zhangjinchao01 已提交
464 465
    :param scale: config scalar, default value is one.
    :type scale: float
466 467
    :return: A DotMulOperator Object.
    :rtype: DotMulOperator
Z
zhangjinchao01 已提交
468
    """
469 470 471 472 473 474 475 476 477 478 479
    if 'x' in kwargs or 'y' in kwargs:
        logger.warning('x and y arguments for dotmul_operator is deprecated. '
                       'Please use a and b as parameter.')
    a = kwargs.get('x', a)    # For Backward capacity.
    b = kwargs.get('y', b)
    assert isinstance(a, LayerOutput)
    assert isinstance(b, LayerOutput)
    if a.size is not None and b.size is not None:
        assert a.size == b.size

    op = DotMulOperator(input_layer_names=[a.name, b.name],
480
                        scale=scale)
481
    op.origin = [a, b]
482
    return op
Z
zhangjinchao01 已提交
483

484

Z
zhangjinchao01 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 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
@wrap_bias_attr_default(['padding_attr'])
def context_projection(input, context_len, context_start=None,
                       padding_attr=False):
    """
    Context Projection.

    It just simply reorganizes input sequence, combines "context_len" sequence
    to one context from context_start. "context_start" will be set to
    -(context_len - 1) / 2 by default. If context position out of sequence
    length, padding will be filled as zero if padding_attr = False, otherwise
    it is trainable.

    For example, origin sequence is [A B C D E F G], context len is 3, then
    after context projection and not set padding_attr, sequence will
    be [ 0AB ABC BCD CDE DEF EFG FG0 ].

    :param input: Input Sequence.
    :type input: LayerOutput
    :param context_len: context length.
    :type context_len: int
    :param context_start: context start position. Default is
                          -(context_len - 1)/2
    :type context_start: int
    :param padding_attr: Padding Parameter Attribute. If false, it means padding
                         always be zero. Otherwise Padding is learnable, and
                         parameter attribute is set by this parameter.
    :type padding_attr: bool|ParameterAttribute
    :return: Projection
    :rtype: Projection
    """
    context_start = -(
        context_len - 1) / 2 if context_start is None else context_start

    extra_dict = dict()
    trainable = isinstance(padding_attr, ParameterAttribute)
    if trainable:
        extra_dict = padding_attr.attr

    proj = ContextProjection(input_layer_name=input.name,
                             context_length=context_len,
                             context_start=context_start,
                             trainable_padding=trainable,
                             **extra_dict)
    proj.origin = input
    return proj


class MixedLayerType(LayerOutput):
    """
    The internal object for trainer_helpers.
    """

    class AddToSealedMixedLayerException(Exception):
        def __init__(self):
            Exception.__init__(self)

    def __init__(self, name, size, act, bias_attr, layer_attr,
                 parents=None):
        """
        Ctor.
        :param name: layer name.
        :type name: basestring
        :param size: layer size.
        :type size: int
        :param act: activation type.
        :type act: BaseActivation
        :param bias_attr: The Bias Attribute. If no bias, then pass False or
                          something not type of ParameterAttribute. None will
                          get a default Bias.
        :type bias_attr: ParameterAttribute or None means has bias. Any other
                         type means no bias.
        :param layer_attr: Extra Layer Attribute.
        :type layer_attr: ExtraLayerAttribute or None
        """
        LayerOutput.__init__(self, name, LayerType.MIXED_LAYER, parents,
                             size=size, activation=act)
        self.bias_attr = bias_attr
        self.layer_attr = layer_attr
        self.inputs = []
        self.finalized = False

    def __add__(self, other):
        """
        + += operator
        :param other: Other projection.
        :type other: Projection
        :return: self.
        :rtype: MixedLayerType
        """
        if not self.finalized:
575
            assert isinstance(other, Projection) or isinstance(other, Operator)
Z
zhangjinchao01 已提交
576
            self.inputs.append(other)
577 578 579 580
            if isinstance(other, Projection):
                self.parents.append(other.origin)
            else:
                self.parents.extend(other.origin)
Z
zhangjinchao01 已提交
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
            return self
        else:
            raise MixedLayerType.AddToSealedMixedLayerException()

    def __enter__(self):
        assert len(self.inputs) == 0
        return self

    def __exit__(self, *args, **kwargs):
        del args, kwargs  # unused parameter to suppress warning
        assert len(self.inputs) != 0
        MixedLayer(
            name=self.name,
            size=self.size,
            active_type=self.activation.name,
            bias=ParamAttr.to_bias(self.bias_attr),
            inputs=self.inputs,
            **ExtraLayerAttribute.to_kwargs(self.layer_attr)
        )


@wrap_name_default("mixed")
@wrap_act_default(act=LinearActivation())
@wrap_bias_attr_default(has_bias=False)
@layer_support(ERROR_CLIPPING, DROPOUT)
606
def mixed_layer(size=0, input=None, name=None, act=None, bias_attr=False,
Z
zhangjinchao01 已提交
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
                layer_attr=None):
    """
    Mixed Layer. A mixed layer will add all inputs together, then activate.
    Each inputs is a projection or operator.

    There are two styles of usages.

    1. When not set inputs parameter, use mixed_layer like this:

    .. code-block:: python

       with mixed_layer(size=256) as m:
           m += full_matrix_projection(input=layer1)
           m += identity_projection(input=layer2)

    2. You can also set all inputs when invoke mixed_layer as follows:

    .. code-block:: python

       m = mixed_layer(size=256,
                       input=[full_matrix_projection(input=layer1),
                              full_matrix_projection(input=layer2)])

    :param name: mixed layer name. Can be referenced by other layer.
    :type name: basestring
    :param size: layer size.
    :type size: int
    :param input: inputs layer. It is an optional parameter. If set,
                  then this function will just return layer's name.
    :param act: Activation Type.
    :type act: BaseActivation
    :param bias_attr: The Bias Attribute. If no bias, then pass False or
                      something not type of ParameterAttribute. None will get a
                      default Bias.
    :type bias_attr: ParameterAttribute or None or bool
    :param layer_attr: The extra layer config. Default is None.
    :type layer_attr: ExtraLayerAttribute
    :return: MixedLayerType object can add inputs or layer name.
    :rtype: MixedLayerType
    """

    if input is None:
        return MixedLayerType(name, size, act, bias_attr, layer_attr)
    else:
        with mixed_layer(name=name, size=size, act=act, bias_attr=bias_attr,
                         layer_attr=layer_attr) as m:
653
            if isinstance(input, collections.Sequence):
Z
zhangjinchao01 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
                for each in input:
                    m += each
            else:
                m += input
        return m


@layer_support()
def data_layer(name, size, layer_attr=None):
    """
    Define DataLayer For NeuralNetwork.

    The example usage is:

    ..  code-block:: python

        data = data_layer(name="input",
                          size=1000)

    :param name: Name of this data layer.
    :type name: basestring
    :param size: Size of this data layer.
    :type size: int
    :param layer_attr: Extra Layer Attribute.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
679
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    :rtype: LayerOutput
    """
    Layer(type=LayerType.DATA, name=name, size=size,
          **ExtraLayerAttribute.to_kwargs(layer_attr))

    return LayerOutput(name, LayerType.DATA, size=size)


@wrap_name_default("embedding")
@wrap_param_attr_default()
@layer_support(ERROR_CLIPPING)
def embedding_layer(input, size, name=None, param_attr=None, layer_attr=None):
    """
    Define a embedding Layer.

    :param name: Name of this embedding layer.
    :type name: basestring
    :param input: The input layer for this embedding. NOTE: must be Index Data.
    :type input: LayerOutput
    :param size: The embedding dimension.
    :type size: int
    :param param_attr: The embedding parameter attribute. See ParameterAttribute
                      for details.
    :type param_attr: ParameterAttribute|None
    :param layer_attr: Extra layer Config. Default is None.
    :type layer_attr: ExtraLayerAttribute|None
D
dangqingqing 已提交
706
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
    :rtype: LayerOutput
    """
    with mixed_layer(name=name, size=size, act=LinearActivation(),
                     bias_attr=False,
                     layer_attr=layer_attr) as mix:
        mix += table_projection(input=input, size=size, param_attr=param_attr)
    return mix


@wrap_name_default()
@wrap_param_attr_default()
@wrap_bias_attr_default()
@wrap_act_default()
@layer_support(ERROR_CLIPPING, DROPOUT)
def fc_layer(input, size, act=None, name=None,
             param_attr=None, bias_attr=None, layer_attr=None):
    """
    Helper for declare fully connected layer.

    The example usage is:

    .. code-block:: python

       fc = fc_layer(input=layer,
                     size=1024,
                     act=LinearActivation(),
                     bias_attr=False)

L
luotao02 已提交
735
    which is equal to:
Z
zhangjinchao01 已提交
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

    .. code-block:: python

       with mixed_layer(size=1024) as fc:
           fc += full_matrix_projection(input=layer)

    :param name: The Layer Name.
    :type name: basestring
    :param input: The input layer. Could be a list/tuple of input layer.
    :type input: LayerOutput|list|tuple
    :param size: The layer dimension.
    :type size: int
    :param act: Activation Type. Default is tanh.
    :type act: BaseActivation
    :param param_attr: The Parameter Attribute|list.
    :type param_attr: ParameterAttribute
    :param bias_attr: The Bias Attribute. If no bias, then pass False or
                      something not type of ParameterAttribute. None will get a
                      default Bias.
    :type bias_attr: ParameterAttribute|None|Any
    :param layer_attr: Extra Layer config.
    :type layer_attr: ExtraLayerAttribute|None
D
dangqingqing 已提交
758
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
759 760 761 762
    :rtype: LayerOutput
    """
    if isinstance(input, LayerOutput):
        input = [input]
763
        assert not isinstance(param_attr, collections.Sequence)
Z
zhangjinchao01 已提交
764 765
        param_attr = [param_attr]
    else:
766
        if isinstance(param_attr, collections.Sequence):
Z
zhangjinchao01 已提交
767 768 769 770
            assert len(input) == len(param_attr)
        else:
            param_attr = [copy.deepcopy(param_attr) for _ in range(len(input))]

771
    assert isinstance(input, collections.Sequence)
Z
zhangjinchao01 已提交
772 773

    Layer(
774 775
        inputs=[Input(ipt.name, **attr.attr) for ipt, attr in zip(
            input, param_attr)],
Z
zhangjinchao01 已提交
776 777 778 779 780 781 782 783 784 785
        name=name,
        type=LayerType.FC_LAYER,
        size=size,
        bias=ParamAttr.to_bias(bias_attr),
        active_type=act.name,
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.FC_LAYER, input, activation=act,
                       size=size)

786

787 788 789 790
@wrap_name_default("print")
def print_layer(input, name=None):
    """
    Print the output value of input layers. This layer is useful for debugging.
791 792 793 794 795

    :param name: The Layer Name.
    :type name: basestring
    :param input: The input layer. Could be a list/tuple of input layer.
    :type input: LayerOutput|list|tuple
796
    :return: LayerOutput
797
    """
798 799 800 801 802
    if isinstance(input, LayerOutput):
        input = [input]
    assert isinstance(input, collections.Sequence)  # list or tuple
    for each in input:
        assert isinstance(each, LayerOutput)
803 804 805 806 807 808

    Layer(
        name=name,
        type=LayerType.PRINT_LAYER,
        inputs=[l.name for l in input],
    )
809
    # this layer don't return anything, can not be input of other layer.
810

Z
zhangjinchao01 已提交
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829

@wrap_name_default("seq_pooling")
@wrap_bias_attr_default(has_bias=False)
@wrap_param_default(['pooling_type'], default_factory=lambda _: MaxPooling())
@layer_support()
def pooling_layer(input, pooling_type=None, name=None, bias_attr=None,
                  agg_level=AggregateLevel.EACH_TIMESTEP,
                  layer_attr=None):
    """
    Pooling layer for sequence inputs, not used for Image.

    The example usage is:

    .. code-block:: python

       seq_pool = pooling_layer(input=layer,
                                pooling_type=AvgPooling(),
                                agg_level=AggregateLevel.EACH_SEQUENCE)

C
caoying03 已提交
830 831
    :param agg_level: AggregateLevel.EACH_TIMESTEP or
                      AggregateLevel.EACH_SEQUENCE
Z
zhangjinchao01 已提交
832 833 834 835 836 837 838 839 840 841 842 843
    :type agg_level: AggregateLevel
    :param name: layer name.
    :type name: basestring
    :param input: input layer name.
    :type input: LayerOutput
    :param pooling_type: Type of pooling, MaxPooling(default), AvgPooling,
                         SumPooling, SquareRootNPooling.
    :type pooling_type: BasePoolingType|None
    :param bias_attr: Bias parameter attribute. False if no bias.
    :type bias_attr: ParameterAttribute|None|False
    :param layer_attr: The Extra Attributes for layer, such as dropout.
    :type layer_attr: ExtraLayerAttribute|None
D
dangqingqing 已提交
844
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
845 846 847
    :rtype: LayerType
    """
    extra_dict = dict()
848
    # noinspection PyUnresolvedReferences
Z
zhangjinchao01 已提交
849 850
    if isinstance(pooling_type, AvgPooling):
        extra_dict['average_strategy'] = pooling_type.strategy
851 852 853 854
    elif isinstance(pooling_type, MaxPooling) and \
                    pooling_type.output_max_index is not None:
        assert isinstance(pooling_type.output_max_index, bool)
        extra_dict['output_max_index'] = pooling_type.output_max_index
Z
zhangjinchao01 已提交
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
    extra_dict.update(ExtraLayerAttribute.to_kwargs(layer_attr))

    Layer(
        name=name,
        type=pooling_type.name,
        inputs=[Input(input.name)],
        bias=ParamAttr.to_bias(bias_attr),
        trans_type=agg_level,
        **extra_dict
    )

    return LayerOutput(name, pooling_type.name, parents=[input],
                       size=input.size)


@wrap_bias_attr_default()
@wrap_param_attr_default()
@wrap_act_default(param_names=['gate_act'],
                  act=SigmoidActivation())
@wrap_act_default(param_names=["act", 'state_act'], act=TanhActivation())
@wrap_name_default("lstmemory")
@layer_support(DROPOUT)
def lstmemory(input, name=None, reverse=False, act=None,
878
              gate_act=None, size=None,
Z
zhangjinchao01 已提交
879 880 881 882 883 884 885 886 887
              state_act=None, bias_attr=None, param_attr=None,
              layer_attr=None):
    """
    Long Short-term Memory Cell.

    The memory cell was implemented as follow equations.

    ..  math::

L
luotao02 已提交
888
        i_t & = \\sigma(W_{xi}x_{t} + W_{hi}h_{t-1} + W_{ci}c_{t-1} + b_i)
Z
zhangjinchao01 已提交
889

L
luotao02 已提交
890
        f_t & = \\sigma(W_{xf}x_{t} + W_{hf}h_{t-1} + W_{cf}c_{t-1} + b_f)
Z
zhangjinchao01 已提交
891

L
luotao02 已提交
892
        c_t & = f_tc_{t-1} + i_t tanh (W_{xc}x_t+W_{hc}h_{t-1} + b_c)
Z
zhangjinchao01 已提交
893

L
luotao02 已提交
894
        o_t & = \\sigma(W_{xo}x_{t} + W_{ho}h_{t-1} + W_{co}c_t + b_o)
Z
zhangjinchao01 已提交
895

L
luotao02 已提交
896
        h_t & = o_t tanh(c_t)
Z
zhangjinchao01 已提交
897 898


C
caoying03 已提交
899
    NOTE: In PaddlePaddle's implementation, the multiplications
Z
zhangjinchao01 已提交
900
    :math:`W_{xi}x_{t}` , :math:`W_{xf}x_{t}`,
C
caoying03 已提交
901 902 903 904
    :math:`W_{xc}x_t`, :math:`W_{xo}x_{t}` are not done in the lstmemory layer,
    so an additional mixed_layer with full_matrix_projection or a fc_layer must
    be included in the configuration file to complete the input-to-hidden
    mappings before lstmemory is called.
Z
zhangjinchao01 已提交
905

C
caoying03 已提交
906
    NOTE: This is a low level user interface. You can use network.simple_lstm
Z
zhangjinchao01 已提交
907 908
    to config a simple plain lstm layer.

C
caoying03 已提交
909 910 911 912
    Please refer to **Generating Sequences With Recurrent Neural Networks** for
    more details about LSTM.

    Link_ goes as below.
Z
zhangjinchao01 已提交
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935

    .. _Link: http://arxiv.org/abs/1308.0850

    :param name: The lstmemory layer name.
    :type name: basestring
    :param input: input layer name.
    :type input: LayerOutput
    :param reverse: is sequence process reversed or not.
    :type reverse: bool
    :param act: activation type, TanhActivation by default. :math:`h_t`
    :type act: BaseActivation
    :param gate_act: gate activation type, SigmoidActivation by default.
    :type gate_act: BaseActivation
    :param state_act: state activation type, TanhActivation by default.
    :type state_act: BaseActivation

    :param bias_attr: Bias attribute. None means default bias. False means no
                      bias.
    :type bias_attr: ParameterAttribute|None|False
    :param param_attr: Parameter Attribute.
    :type param_attr: ParameterAttribute|None|False
    :param layer_attr: Extra Layer attribute
    :type layer_attr: ExtraLayerAttribute|None
D
dangqingqing 已提交
936
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
937 938 939 940 941 942
    :rtype: LayerOutput
    """

    assert gate_act.support_hppl
    assert state_act.support_hppl
    assert act.support_hppl
943 944 945 946 947 948 949 950 951 952
    assert input.size is not None and input.size % 4 == 0
    if size is not None:
        if input.size / 4 == size:
            plog = logger.warning
        else:
            plog = logger.fatal

        plog("NOTE: The lstmemory layer[%s]'s size is set by previous input "
             "layer. The lstm size should be equal with input layer size/4. The"
             " size which is set explicitly will be ignored." % name)
Z
zhangjinchao01 已提交
953 954 955 956 957 958 959 960 961 962 963

    Layer(name=name,
          type=LayerType.LSTMEMORY,
          active_type=act.name,
          active_state_type=state_act.name,
          active_gate_type=gate_act.name,
          reversed=reverse,
          bias=ParamAttr.to_bias(bias_attr),
          inputs=[Input(input.name, **param_attr.attr)],
          **ExtraLayerAttribute.to_kwargs(layer_attr))

964 965 966
    return LayerOutput(name, LayerType.LSTMEMORY, [input], size=input.size / 4,
                       reverse=reverse)

Z
zhangjinchao01 已提交
967 968 969 970 971 972 973 974 975

@wrap_bias_attr_default()
@wrap_param_attr_default()
@wrap_act_default(param_names=['gate_act'],
                  act=SigmoidActivation())
@wrap_act_default(param_names=["act"], act=TanhActivation())
@wrap_name_default("gru")
@layer_support(DROPOUT)
def grumemory(input, name=None, reverse=False, act=None,
976
              gate_act=None, size=None,
Z
zhangjinchao01 已提交
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
              bias_attr=None, param_attr=None,
              layer_attr=None):
    """
    Gate Recurrent Unit Layer.

    The memory cell was implemented as follow equations.

    1. update gate :math:`z`: defines how much of the previous memory to
    keep around or the unit updates its activations. The update gate
    is computed by:

    ..  math::

        z_t = \\sigma(W_{z}x_{t} + U_{z}h_{t-1} + b_z)

    2. reset gate :math:`r`: determines how to combine the new input with the
    previous memory. The reset gate is computed similarly to the update gate:

    ..  math::

        r_t = \\sigma(W_{r}x_{t} + U_{r}h_{t-1} + b_r)

C
caoying03 已提交
999 1000
    3. The candidate activation :math:`\\tilde{h_t}` is computed similarly to
    that of the traditional recurrent unit:
Z
zhangjinchao01 已提交
1001 1002 1003 1004 1005

    ..  math::

        {\\tilde{h_t}} = tanh(W x_{t} + U (r_{t} \odot h_{t-1}) + b)

C
caoying03 已提交
1006 1007 1008
    4. The hidden activation :math:`h_t` of the GRU at time t is a linear
    interpolation between the previous activation :math:`h_{t-1}` and the
    candidate activation :math:`\\tilde{h_t}`:
Z
zhangjinchao01 已提交
1009 1010 1011 1012 1013

    ..  math::

        h_t = (1 - z_t) h_{t-1} + z_t {\\tilde{h_t}}

C
caoying03 已提交
1014
    NOTE: In PaddlePaddle's implementation, the multiplication operations
Z
zhangjinchao01 已提交
1015
    :math:`W_{r}x_{t}`, :math:`W_{z}x_{t}` and :math:`W x_t` are not computed in
C
caoying03 已提交
1016 1017 1018
    gate_recurrent layer. Consequently, an additional mixed_layer with
    full_matrix_projection or a fc_layer must be included before grumemory
    is called.
Z
zhangjinchao01 已提交
1019

C
caoying03 已提交
1020 1021 1022
    More details can be found by referring to `Empirical Evaluation of Gated
    Recurrent Neural Networks on Sequence Modeling.
    <https://arxiv.org/abs/1412.3555>`_
Z
zhangjinchao01 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033

    The simple usage is:

    .. code-block:: python

       gru = grumemory(input)

    :param name: The gru layer name.
    :type name: None|basestring
    :param input: input layer.
    :type input: LayerOutput.
1034
    :param reverse: Whether sequence process is reversed or not.
Z
zhangjinchao01 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    :type reverse: bool
    :param act: activation type, TanhActivation by default. This activation
                affects the :math:`{\\tilde{h_t}}`.
    :type act: BaseActivation
    :param gate_act: gate activation type, SigmoidActivation by default.
                     This activation affects the :math:`z_t` and :math:`r_t`. It is the
                     :math:`\\sigma` in the above formula.
    :type gate_act: BaseActivation
    :param bias_attr: Bias attribute. None means default bias. False means no
                      bias.
    :type bias_attr: ParameterAttribute|None|False
    :param param_attr: Parameter Attribute.
    :type param_attr: ParameterAttribute|None|False
    :param layer_attr: Extra Layer attribute
    :type layer_attr: ExtraLayerAttribute|None
1050 1051 1052
    :param size: Stub parameter of size, but actually not used. If set this size
                 will get a warning.
    :type size: None
D
dangqingqing 已提交
1053
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1054 1055 1056 1057
    :rtype: LayerOutput
    """
    assert act.support_hppl
    assert gate_act.support_hppl
1058 1059 1060 1061 1062 1063 1064 1065 1066
    assert input.size is not None and input.size % 3 == 0
    if size is not None:
        if input.size / 3 == size:
            plog = logger.warning
        else:
            plog = logger.fatal
        plog("NOTE: the gru memory layer's size is set by previous input layer,"
             " and should be input size / 3. Set size explicitly will be "
             "ignored.")
Z
zhangjinchao01 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077

    Layer(name=name,
          type=LayerType.GRUMEMORY,
          active_type=act.name,
          active_gate_type=gate_act.name,
          reversed=reverse,
          bias=ParamAttr.to_bias(bias_attr),
          inputs=[Input(input.name, **param_attr.attr)],
          **ExtraLayerAttribute.to_kwargs(layer_attr)
          )

1078 1079 1080
    return LayerOutput(name, LayerType.GRUMEMORY, [input], size=input.size / 3,
                       reverse=reverse)

Z
zhangjinchao01 已提交
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095

@wrap_name_default()
@layer_support()
def last_seq(input, name=None, agg_level=AggregateLevel.EACH_TIMESTEP,
             layer_attr=None):
    """
    Get Last Timestamp Activation of a sequence.

    :param agg_level: Aggregated level
    :param name: Layer name.
    :type name: basestring
    :param input: Input layer name.
    :type input: LayerOutput
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
1096
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1097 1098
    :rtype: LayerOutput
    """
1099 1100 1101 1102 1103 1104
    if input.reverse is not None and input.reverse:
        logger.warning("You are getting the last instance of a sequence that"
                       " is a output of a REVERSED layer. There is no time"
                       " series information at all. Maybe you want to use"
                       " first_seq instead.")

Z
zhangjinchao01 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
    Layer(
        name=name,
        type=LayerType.SEQUENCE_LAST_INSTANCE,
        inputs=[input.name],
        trans_type=agg_level,
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.SEQUENCE_LAST_INSTANCE, parents=[input],
                       size=input.size)


@wrap_name_default()
@layer_support()
def first_seq(input, name=None, agg_level=AggregateLevel.EACH_TIMESTEP,
              layer_attr=None):
    """
    Get First Timestamp Activation of a sequence.

    :param agg_level: aggregation level
    :param name: Layer name.
    :type name: basestring
    :param input: Input layer name.
    :type input: LayerOutput
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
1130
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1131 1132
    :rtype: LayerOutput
    """
1133 1134 1135 1136 1137 1138 1139

    if input.reverse is not None and not input.reverse:
        logger.warning('You are getting the first instance for a time series,'
                       ' and it is a normal recurrent layer output. There is no'
                       ' time series information at all. Maybe you want to use'
                       ' last_seq instead.')

Z
zhangjinchao01 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    Layer(
        name=name,
        type=LayerType.SEQUENCE_FIRST_INSTANCE,
        inputs=[input.name],
        trans_type=agg_level,
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.SEQUENCE_FIRST_INSTANCE,
                       parents=[input], size=input.size)


class ExpandLevel(object):
    FROM_TIMESTEP = AggregateLevel.EACH_TIMESTEP
    FROM_SEQUENCE = AggregateLevel.EACH_SEQUENCE

1155

Z
zhangjinchao01 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
@wrap_name_default()
@layer_support()
def expand_layer(input, expand_as,
                 name=None,
                 bias_attr=False,
                 expand_level=ExpandLevel.FROM_TIMESTEP,
                 layer_attr=None):
    """
    A layer for "Expand Dense data or (sequence data where the length of each
    sequence is one) to sequence data."

    The example usage is:

    .. code-block:: python

       expand = expand_layer(input=layer1,
                             expand_as=layer2,
                             expand_level=ExpandLevel.FROM_TIMESTEP)

    :param input: Input layer
    :type input: LayerOutput
    :param expand_as: Expand as this layer's sequence info.
    :type expand_as: LayerOutput
    :param name: Layer name.
    :type name: basestring
    :param bias_attr: Bias attribute. None means default bias. False means no
                      bias.
    :type bias_attr: ParameterAttribute|None|False
    :param expand_level: whether input layer is timestep(default) or sequence.
    :type expand_level: ExpandLevel
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
1188
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    :rtype: LayerOutput
    """

    Layer(
        inputs=[input.name, expand_as.name],
        name=name,
        bias=ParamAttr.to_bias(bias_attr=bias_attr),
        type=LayerType.EXPAND_LAYER,
        trans_type=expand_level,
        **ExtraAttr.to_kwargs(layer_attr)
    )
    return LayerOutput(name=name,
                       size=input.size,
                       layer_type=LayerType.EXPAND_LAYER,
                       parents=[input, expand_as])


@wrap_name_default()
@layer_support()
def interpolation_layer(input, weight, name=None, layer_attr=None):
    """
    This layer is for linear interpolation with two inputs,
    which is used in NEURAL TURING MACHINE.

    .. math::
       y.row[i] = w[i] * x_1.row[i] + (1 - w[i]) * x_2.row[i]

    where :math:`x_1` and :math:`x_2` are two (batchSize x dataDim) inputs,
    :math:`w` is (batchSize x 1) weight vector, and :math:`y` is
    (batchSize x dataDim) output.

    The example usage is:

    .. code-block:: python

       interpolation = interpolation_layer(input=[layer1, layer2], weight=layer3)

    :param input: Input layer.
    :type input: list|tuple
    :param weight: Weight layer.
    :type weight: LayerOutput
    :param name: Layer name.
    :type name: basestring
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
1234
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1235 1236
    :rtype: LayerOutput
    """
1237
    assert isinstance(input, collections.Sequence)
Z
zhangjinchao01 已提交
1238
    assert len(input) == 2
1239 1240 1241 1242 1243 1244 1245
    assert isinstance(input[0], LayerOutput) and isinstance(input[1],
                                                            LayerOutput)
    if input[0].size is not None and input[1].size is not None:
        assert input[0].size == input[1].size
    assert isinstance(weight, LayerOutput)
    if weight.size is not None:
        assert weight.size == 1
Z
zhangjinchao01 已提交
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
    Layer(
        name=name,
        type=LayerType.INTERPOLATION_LAYER,
        inputs=[weight.name, input[0].name, input[1].name],
        **ExtraAttr.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.INTERPOLATION_LAYER,
                       parents=[weight, input[0], input[1]],
                       size=input[0].size)


@wrap_name_default()
@layer_support()
def power_layer(input, weight, name=None, layer_attr=None):
    """
    This layer applies a power function to a vector element-wise,
    which is used in NEURAL TURING MACHINE.

    .. math::
       y = x^w

    where :math:`x` is a input vector, :math:`w` is scalar weight,
    and :math:`y` is a output vector.

    The example usage is:

    .. code-block:: python

       power = power_layer(input=layer1, weight=layer2)

    :param input: Input layer.
    :type input: LayerOutput
    :param weight: Weight layer.
    :type weight: LayerOutput
    :param name: Layer name.
    :type name: basestring
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
1284
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1285 1286
    :rtype: LayerOutput
    """
1287 1288 1289
    assert isinstance(input, LayerOutput) and isinstance(weight, LayerOutput)
    if weight.size is not None:
        assert weight.size == 1
Z
zhangjinchao01 已提交
1290 1291 1292
    Layer(
        name=name,
        type=LayerType.POWER_LAYER,
1293
        inputs=[weight.name, input.name],
Z
zhangjinchao01 已提交
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
        **ExtraAttr.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.POWER_LAYER,
                       parents=[input, weight], size=input.size)


@wrap_name_default()
@layer_support()
def scaling_layer(input, weight, name=None, layer_attr=None):
    """
1304
    A layer for multiplying input vector by weight scalar.
Z
zhangjinchao01 已提交
1305 1306

    .. math::
1307
       y  = w x
Z
zhangjinchao01 已提交
1308

1309 1310 1311 1312 1313
    where :math:`x` is size=dataDim input, :math:`w` is size=1 weight,
    and :math:`y` is size=dataDim output.

    Note that the above computation is for one sample. Multiple samples are
    processed in one batch.
Z
zhangjinchao01 已提交
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328

    The example usage is:

    .. code-block:: python

       scale = scaling_layer(input=layer1, weight=layer2)

    :param input: Input layer.
    :type input: LayerOutput
    :param weight: Weight layer.
    :type weight: LayerOutput
    :param name: Layer name.
    :type name: basestring
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
1329
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1330 1331
    :rtype: LayerOutput
    """
1332 1333 1334
    assert isinstance(weight, LayerOutput) and isinstance(input, LayerOutput)
    if weight.size is not None:
        assert weight.size == 1
Z
zhangjinchao01 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
    Layer(
        name=name,
        type=LayerType.SCALING_LAYER,
        inputs=[weight.name, input.name],
        **ExtraAttr.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.SCALING_LAYER, parents=[weight, input],
                       size=input.size)


@wrap_name_default()
@layer_support()
def trans_layer(input, name=None, layer_attr=None):
    """
    A layer for transposition.

    .. math::
       y = x^\mathrm{T}

    where :math:`x` is (M x N) input, and :math:`y` is (N x M) output.

    The example usage is:

    .. code-block:: python

       trans = trans_layer(input=layer)

    :param input: Input layer.
    :type input: LayerOutput
    :param name: Layer name.
    :type name: basestring
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
1368
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
    :rtype: LayerOutput
    """
    Layer(
        name=name,
        type=LayerType.TRANS_LAYER,
        inputs=[input.name],
        **ExtraAttr.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.TRANS_LAYER, parents=[input],
                       size=input.size)


@wrap_name_default()
@layer_support()
def cos_sim(a, b, scale=5, size=1, name=None, layer_attr=None):
    """
    Cosine Similarity Layer. The cosine similarity equation is here.

    ..  math::
D
dangqingqing 已提交
1388
        similarity = cos(\\theta) = {\\mathbf{a} \\cdot \\mathbf{b}
1389 1390 1391 1392 1393
        \\over \\|\\mathbf{a}\\| \\|\\mathbf{b}\\|}

    The size of a is M, size of b is M*N,
    Similarity will be calculated N times by step M. The output size is
    N. The scale will be multiplied to similarity.
Z
zhangjinchao01 已提交
1394

1395 1396
    Note that the above computation is for one sample. Multiple samples are
    processed in one batch.
Z
zhangjinchao01 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409

    :param name: layer name
    :type name: basestring
    :param a: input layer a
    :type a: LayerOutput
    :param b: input layer b
    :type b: LayerOutput
    :param scale: scale for cosine value. default is 5.
    :type scale: float
    :param size: layer size. NOTE size_a * size should equal size_b.
    :type size: int
    :param layer_attr: Extra Layer Attribute.
    :type layer_attr: ExtraLayerAttribute
D
dangqingqing 已提交
1410
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1411 1412
    :rtype: LayerOutput
    """
1413
    assert isinstance(a, LayerOutput) and isinstance(b, LayerOutput)
1414 1415 1416 1417 1418 1419 1420 1421 1422
    if size == 1:
        Layer(
            name=name,
            type=LayerType.COSINE_SIM,
            cos_scale=scale,
            inputs=[a.name, b.name],
            **ExtraLayerAttribute.to_kwargs(layer_attr)
        )
    else:
1423 1424
        if a.size is not None and b.size is not None:
            assert size == b.size / a.size
1425 1426 1427 1428 1429 1430 1431 1432
        Layer(
            name=name,
            type=LayerType.COSINE_SIM_VEC,
            size=size,
            cos_scale=scale,
            inputs=[a.name, b.name],
            **ExtraLayerAttribute.to_kwargs(layer_attr)
        )
Z
zhangjinchao01 已提交
1433 1434
    return LayerOutput(name, LayerType.COSINE_SIM, parents=[a, b])

1435

Z
zhangjinchao01 已提交
1436 1437
@wrap_name_default()
@wrap_bias_attr_default(has_bias=True)
1438
@wrap_param_attr_default()
Z
zhangjinchao01 已提交
1439
@layer_support()
C
caoying03 已提交
1440
def hsigmoid(input, label, num_classes, name=None, bias_attr=None,
1441
             param_attr=None, layer_attr=None):
Z
zhangjinchao01 已提交
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    """
    Organize the classes into a binary tree. At each node, a sigmoid function
    is used to calculate the probability of belonging to the right branch.
    This idea is from "F. Morin, Y. Bengio (AISTATS 05):
    Hierarchical Probabilistic Neural Network Language Model."

    The example usage is:

    ..  code-block:: python

        cost = hsigmoid(input=[layer1, layer2],
                        label=data_layer,
                        num_classes=3)

    :param input: Input layers. It could be a LayerOutput or list/tuple of
                 LayerOutput.
    :type input: LayerOutput|list|tuple
    :param label: Label layer.
    :type label: LayerOutput
    :param num_classes: number of classes.
    :type num_classes: int
L
luotao02 已提交
1463 1464
    :param name: layer name
    :type name: basestring
Z
zhangjinchao01 已提交
1465 1466 1467 1468 1469
    :param bias_attr: Bias attribute. None means default bias.
                      False means no bias.
    :type bias_attr: ParameterAttribute|False
    :param layer_attr: Extra Layer Attribute.
    :type layer_attr: ExtraLayerAttribute
D
dangqingqing 已提交
1470
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1471 1472 1473 1474
    :rtype: LayerOutput
    """
    if isinstance(input, LayerOutput):
        input = [input]
1475 1476 1477 1478 1479 1480 1481 1482 1483
        if not isinstance(param_attr, collections.Sequence):
            param_attr = [param_attr]
    else:
        if not isinstance(param_attr, collections.Sequence):
            param_attr = [param_attr] * len(input)
        else:
            assert len(param_attr) == len(input)

    assert isinstance(input, collections.Sequence)
Z
zhangjinchao01 已提交
1484 1485 1486 1487 1488
    assert isinstance(label, LayerOutput)
    assert label.layer_type == LayerType.DATA

    ipts_for_layer = []
    parents = []
1489
    for each_input, each_param_attr in zip(input, param_attr):
Z
zhangjinchao01 已提交
1490
        assert isinstance(each_input, LayerOutput)
1491
        ipts_for_layer.append(Input(each_input.name, **each_param_attr.attr))
Z
zhangjinchao01 已提交
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
        parents.append(each_input)
    ipts_for_layer.append(label.name)
    parents.append(label)

    Layer(
        name=name,
        type=LayerType.HSIGMOID,
        num_classes=num_classes,
        bias=ParamAttr.to_bias(bias_attr),
        inputs=ipts_for_layer,
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.HSIGMOID, parents=parents)

1506

Z
zhangjinchao01 已提交
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
@wrap_name_default("conv")
@wrap_param_attr_default()
@wrap_bias_attr_default()
@wrap_act_default(act=ReluActivation())
@layer_support(DROPOUT)
def img_conv_layer(input, filter_size, num_filters,
                   name=None, num_channels=None,
                   act=None, groups=1, stride=1, padding=0, bias_attr=None,
                   param_attr=None, shared_biases=True, layer_attr=None,
                   filter_size_y=None, stride_y=None, padding_y=None):
    """
    Convolution layer for image. Paddle only support square input currently and
    thus input image's width equals height.

    The details of convolution layer, please refer UFLDL's `convolution
    <http://ufldl.stanford.edu/tutorial/supervised/
    FeatureExtractionUsingConvolution/>`_ .

    The num_channel means input image's channel number. It may be 1 or 3 when
    input is raw pixels of image(mono or RGB), or it may be the previous layer's
    num_filters * num_group.

C
caoying03 已提交
1529 1530 1531
    There are several group of filter in PaddlePaddle implementation.
    Each group will process some channel of the inputs. For example, if an input
    num_channel = 256, group = 4, num_filter=32, the PaddlePaddle will create
Z
zhangjinchao01 已提交
1532
    32*4 = 128 filters to process inputs. The channels will be split into 4
C
caoying03 已提交
1533 1534
    pieces. First 256/4 = 64 channels will process by first 32 filters. The
    rest channels will be processed by rest group of filters.
Z
zhangjinchao01 已提交
1535 1536 1537 1538 1539

    :param name: Layer name.
    :type name: basestring
    :param input: Layer Input.
    :type input: LayerOutput
1540 1541 1542
    :param filter_size: The x dimension of a filter kernel. Or input a tuple for
                        two image dimension.
    :type filter_size: int|tuple|list
C
caoying03 已提交
1543 1544 1545
    :param filter_size_y: The y dimension of a filter kernel. Since PaddlePaddle
                        currently supports rectangular filters, the filter's
                        shape will be (filter_size, filter_size_y).
1546
    :type filter_size_y: int|None
Z
zhangjinchao01 已提交
1547 1548 1549 1550 1551
    :param num_filters: Each filter group's number of filter
    :param act: Activation type. Default is tanh
    :type act: BaseActivation
    :param groups: Group size of filters.
    :type groups: int
1552 1553 1554
    :param stride: The x dimension of the stride. Or input a tuple for two image
                   dimension.
    :type stride: int|tuple|list
Z
zhangjinchao01 已提交
1555 1556
    :param stride_y: The y dimension of the stride.
    :type stride_y: int
1557 1558 1559
    :param padding: The x dimension of the padding. Or input a tuple for two
                    image dimension
    :type padding: int|tuple|list
Z
zhangjinchao01 已提交
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
    :param padding_y: The y dimension of the padding.
    :type padding_y: int
    :param bias_attr: Convolution bias attribute. None means default bias.
                      False means no bias.
    :type bias_attr: ParameterAttribute|False
    :param num_channels: number of input channels. If None will be set
                        automatically from previous output.
    :type num_channels: int
    :param param_attr: Convolution param attribute. None means default attribute
    :type param_attr: ParameterAttribute
    :param shared_biases: Is biases will be shared between filters or not.
    :type shared_biases: bool
    :param layer_attr: Layer Extra Attribute.
    :type layer_attr: ExtraLayerAttribute
D
dangqingqing 已提交
1574
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1575 1576 1577 1578 1579
    :rtype: LayerOutput
    """
    if num_channels is None:
        assert input.num_filters is not None
        num_channels = input.num_filters
1580

Z
zhangjinchao01 已提交
1581
    if filter_size_y is None:
1582 1583 1584 1585 1586 1587
        if isinstance(filter_size, collections.Sequence):
            assert len(filter_size) == 2
            filter_size, filter_size_y = filter_size
        else:
            filter_size_y = filter_size

Z
zhangjinchao01 已提交
1588
    if stride_y is None:
1589 1590 1591 1592 1593 1594
        if isinstance(stride, collections.Sequence):
            assert len(stride) == 2
            stride, stride_y = stride
        else:
            stride_y = stride

Z
zhangjinchao01 已提交
1595
    if padding_y is None:
1596 1597 1598 1599 1600 1601 1602 1603
        if isinstance(padding, collections.Sequence):
            assert len(padding) == 2
            padding, padding_y = padding
        else:
            padding_y = padding

    if param_attr.attr.get('initial_smart'):
        # special initial for conv layers.
Z
zhangjinchao01 已提交
1604
        init_w = (2.0 / (filter_size ** 2 * num_channels)) ** 0.5
1605 1606 1607 1608
        param_attr.attr["initial_mean"] = 0.0
        param_attr.attr["initial_std"] = init_w
        param_attr.attr["initial_strategy"] = 0
        param_attr.attr["initial_smart"] = False
Z
zhangjinchao01 已提交
1609 1610 1611 1612 1613
    Layer(
        name=name,
        inputs=Input(input.name, conv=Conv(
            filter_size=filter_size, padding=padding, stride=stride,
            channels=num_channels, groups=groups,
1614 1615 1616
            filter_size_y=filter_size_y, padding_y=padding_y,
            stride_y=stride_y),
                     **param_attr.attr),
Z
zhangjinchao01 已提交
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
        active_type=act.name,
        num_filters=num_filters,
        bias=ParamAttr.to_bias(bias_attr),
        shared_biases=shared_biases,
        type=LayerType.CONV_LAYER,
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.CONV_LAYER, parents=[input],
                       activation=act, num_filters=num_filters)


@wrap_name_default("pool")
@layer_support()
def img_pool_layer(input, pool_size, name=None,
                   num_channels=None, pool_type=None,
1632 1633 1634
                   stride=1, start=None, padding=0, layer_attr=None,
                   pool_size_y=None, stride_y=None, padding_y=None,
                   img_width=None):
Z
zhangjinchao01 已提交
1635 1636 1637 1638 1639 1640 1641
    """
    Image pooling Layer.

    The details of pooling layer, please refer ufldl's pooling_ .

    .. _pooling: http://ufldl.stanford.edu/tutorial/supervised/Pooling/

1642
    :param padding: pooling padding width.
Z
zhangjinchao01 已提交
1643
    :type padding: int
1644 1645
    :param padding_y: pooling padding height. It's equal to padding by default.
    :type padding_y: int|None
Z
zhangjinchao01 已提交
1646 1647 1648 1649
    :param name: name of pooling layer
    :type name: basestring.
    :param input: layer's input
    :type input: LayerOutput
1650
    :param pool_size: pooling window width
Z
zhangjinchao01 已提交
1651
    :type pool_size: int
1652 1653
    :param pool_size_y: pooling window height. It's eaqual to pool_size by default.
    :type pool_size_y: int|None
Z
zhangjinchao01 已提交
1654 1655 1656 1657 1658
    :param num_channels: number of input channel.
    :type num_channels: int
    :param pool_type: pooling type. MaxPooling or AveragePooling. Default is
                      MaxPooling.
    :type pool_type: BasePoolingType
1659
    :param stride: stride width of pooling.
Z
zhangjinchao01 已提交
1660
    :type stride: int
1661 1662 1663 1664
    :param stride_y: stride height of pooling. It is equal to stride by default.
    :type stride_y: int|None
    :param start: start position of pooling operation. Note it is deprecated now.
    :type start: int|None
Z
zhangjinchao01 已提交
1665 1666
    :param layer_attr: Extra Layer attribute.
    :type layer_attr: ExtraLayerAttribute
1667 1668 1669
    :param img_width: the width of input feature map. If it is None, the input feature
                      map should be square.
    :type img_width: int|None
D
dangqingqing 已提交
1670 1671
    :return: LayerOutput object.
    :rtype: LayerOutput
Z
zhangjinchao01 已提交
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
    """
    if num_channels is None:
        assert input.num_filters is not None
        num_channels = input.num_filters

    if pool_type is None:
        pool_type = MaxPooling()
    elif isinstance(pool_type, AvgPooling):
        pool_type.name = 'avg'

1682 1683 1684 1685 1686 1687 1688 1689
    type_name = pool_type.name + '-projection' \
      if (isinstance(pool_type, AvgPooling) or isinstance(pool_type, MaxPooling)) \
      else pool_type.name

    pool_size_y = pool_size if pool_size_y is None else pool_size_y
    stride_y = stride if stride_y is None else stride_y
    padding_y = padding if padding_y is None else padding_y

Z
zhangjinchao01 已提交
1690 1691 1692 1693 1694
    Layer(
        name=name,
        type=LayerType.POOL_LAYER,
        inputs=[Input(input.name,
                      pool=Pool(
1695
                          pool_type=type_name,
Z
zhangjinchao01 已提交
1696 1697 1698 1699
                          channels=num_channels,
                          size_x=pool_size,
                          start=start,
                          stride=stride,
1700 1701 1702 1703 1704
                          padding=padding,
                          size_y=pool_size_y,
                          stride_y=stride_y,
                          padding_y=padding_y,
                          img_width=img_width
Z
zhangjinchao01 已提交
1705 1706 1707 1708 1709 1710 1711 1712
                      ))],
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.POOL_LAYER, parents=[input],
                       num_filters=num_channels)


def __img_norm_layer__(name, input, size, norm_type, scale, power,
1713
                       num_channels, blocked, layer_attr):
Z
zhangjinchao01 已提交
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
    if num_channels is None:
        assert input.num_filters is not None
        num_channels = input.num_filters

    Layer(
        name=name, type=LayerType.NORM_LAYER, inputs=Input(
            input.name, norm=Norm(norm_type=norm_type,
                                  channels=num_channels, size=size,
                                  scale=scale,
                                  pow=power, blocked=blocked)
        ),
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
    return LayerOutput(name, layer_type=LayerType.NORM_LAYER, parents=[input],
                       num_filters=num_channels, img_norm_type=norm_type)


@wrap_name_default("crmnorm")
@layer_support()
D
dangqingqing 已提交
1733 1734
def img_cmrnorm_layer(input, size, scale=0.0128, power=0.75,
                      name=None, num_channels=None,
1735
                      layer_attr=None):
Z
zhangjinchao01 已提交
1736
    """
1737
    Response normalization across feature maps.
D
dangqingqing 已提交
1738 1739
    The details please refer to
    `Alex's paper <http://www.cs.toronto.edu/~fritz/absps/imagenet.pdf>`_.
Z
zhangjinchao01 已提交
1740 1741

    :param name: layer name.
D
dangqingqing 已提交
1742
    :type name: None|basestring
Z
zhangjinchao01 已提交
1743 1744
    :param input: layer's input.
    :type input: LayerOutput
1745
    :param size: Normalize in number of :math:`size` feature maps.
Z
zhangjinchao01 已提交
1746
    :type size: int
D
dangqingqing 已提交
1747
    :param scale: The hyper-parameter.
Z
zhangjinchao01 已提交
1748
    :type scale: float
D
dangqingqing 已提交
1749
    :param power: The hyper-parameter.
Z
zhangjinchao01 已提交
1750 1751 1752 1753 1754
    :type power: float
    :param num_channels: input layer's filers number or channels. If
                         num_channels is None, it will be set automatically.
    :param layer_attr: Extra Layer Attribute.
    :type layer_attr: ExtraLayerAttribute
D
dangqingqing 已提交
1755
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1756 1757 1758
    :rtype: LayerOutput
    """
    return __img_norm_layer__(name, input, size, "cmrnorm-projection", scale,
1759
                              power, num_channels, 0, layer_attr)
Z
zhangjinchao01 已提交
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804


@wrap_bias_attr_default()
@wrap_param_attr_default(default_factory=lambda _: ParamAttr(initial_mean=1.0,
                                                             initial_std=0.))
@wrap_act_default(act=ReluActivation())
@wrap_name_default("batch_norm")
@layer_support(DROPOUT)
def batch_norm_layer(input, act=None, name=None, num_channels=None,
                     bias_attr=None, param_attr=None, layer_attr=None,
                     batch_norm_type=None,
                     moving_average_fraction=0.9,
                     use_global_stats=None):
    """
    Batch Normalization Layer. The notation of this layer as follow.

    :math:`x` is the input features over a mini-batch.

    ..  math::

        \\mu_{\\beta} &\\gets \\frac{1}{m} \\sum_{i=1}^{m} x_i \\qquad &//\\
        \ mini-batch\ mean \\\\
        \\sigma_{\\beta}^{2} &\\gets \\frac{1}{m} \\sum_{i=1}^{m}(x_i - \\
        \\mu_{\\beta})^2 \\qquad &//\ mini-batch\ variance \\\\
        \\hat{x_i} &\\gets \\frac{x_i - \\mu_\\beta} {\\sqrt{\\
        \\sigma_{\\beta}^{2} + \\epsilon}} \\qquad &//\ normalize \\\\
        y_i &\\gets \\gamma \\hat{x_i} + \\beta \\qquad &//\ scale\ and\ shift

    The details of batch normalization please refer to this
    `paper <http://arxiv.org/abs/1502.03167>`_.

    :param name: layer name.
    :type name: basestring
    :param input: batch normalization input. Better be linear activation.
                Because there is an activation inside batch_normalization.
    :type input: LayerOutput
    :param batch_norm_type: We have batch_norm and cudnn_batch_norm. batch_norm
                            supports both CPU and GPU. cudnn_batch_norm requires
                            cuDNN version greater or equal to v4 (>=v4). But
                            cudnn_batch_norm is faster and needs less memory
                            than batch_norm. By default (None), we will
                            automaticly select cudnn_batch_norm for GPU and
                            batch_norm for CPU. Otherwise, select batch norm
                            type based on the specified type. If you use cudnn_batch_norm,
                            we suggested you use latest version, such as v5.1.
1805
    :type batch_norm_type: None|string, None or "batch_norm" or "cudnn_batch_norm"
Z
zhangjinchao01 已提交
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
    :param act: Activation Type. Better be relu. Because batch
                     normalization will normalize input near zero.
    :type act: BaseActivation
    :param num_channels: num of image channels or previous layer's number of
                         filters. None will automatically get from layer's
                         input.
    :type num_channels: int
    :param bias_attr: :math:`\\beta`, better be zero when initialize. So the
                      initial_std=0, initial_mean=1 is best practice.
    :type bias_attr: ParameterAttribute
    :param param_attr: :math:`\\gamma`, better be one when initialize. So the
                       initial_std=0, initial_mean=1 is best practice.
    :type param_attr: ParameterAttribute
    :param layer_attr: Extra Layer Attribute.
    :type layer_attr: ExtraLayerAttribute
    :param use_global_stats: whether use moving mean/variance statistics
                             during testing peroid. If None or True,
                             it will use moving mean/variance statistics during
                             testing. If False, it will use the mean
                             and variance of current batch of test data for
                             testing.
    :type use_global_stats: bool|None.
    :param moving_average_fraction: Factor used in the moving average
                                   computation, referred to as facotr,
                                   :math:`runningMean = newMean*(1-factor)
                                   + runningMean*factor`
    :type moving_average_fraction: float.
D
dangqingqing 已提交
1833
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
    :rtype: LayerOutput
    """
    if not isinstance(act, ReluActivation):
        logger.log(logging.WARN,
                   "%s is not recommend for batch normalization's activation, "
                   "maybe the relu is better" % act.name)

    if not isinstance(input.activation, LinearActivation):
        logger.log(logging.WARN,
                   "The activation should be inside batch normalization, the "
                   "previous layer's activation may be Linear")

    if num_channels is None:
        if input.num_filters is not None:
            num_channels = input.num_filters
        else:
            num_channels = input.size
    assert (batch_norm_type is None) or (batch_norm_type == "batch_norm") or \
           (batch_norm_type == "cudnn_batch_norm")
    Layer(
        name=name,
        inputs=Input(input.name,
                     image=Image(channels=num_channels),
                     **param_attr.attr),
        active_type=act.name,
        type=LayerType.BATCH_NORM_LAYER,
        batch_norm_type=batch_norm_type,
        bias=ParamAttr.to_bias(bias_attr),
        moving_average_fraction=moving_average_fraction,
        use_global_stats=use_global_stats,
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )

    return LayerOutput(name=name, layer_type=LayerType.BATCH_NORM_LAYER,
                       parents=[input], activation=act,
                       num_filters=num_channels)


@wrap_name_default()
@layer_support()
def sum_to_one_norm_layer(input, name=None, layer_attr=None):
    """
    A layer for sum-to-one normalization,
    which is used in NEURAL TURING MACHINE.

    .. math::
       out[i] = \\frac {in[i]} {\sum_{k=1}^N in[k]}

    where :math:`in` is a (batchSize x dataDim) input vector,
    and :math:`out` is a (batchSize x dataDim) output vector.

    The example usage is:

    .. code-block:: python

       sum_to_one_norm = sum_to_one_norm_layer(input=layer)

    :param input: Input layer.
    :type input: LayerOutput
    :param name: Layer name.
    :type name: basestring
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
1897
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
    :rtype: LayerOutput
    """
    Layer(
        name=name,
        type=LayerType.SUM_TO_ONE_NORM_LAYER,
        inputs=[input.name],
        **ExtraAttr.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.SUM_TO_ONE_NORM_LAYER, parents=[input],
                       size=input.size)


@wrap_name_default("addto")
@wrap_act_default(act=LinearActivation())
@wrap_bias_attr_default(has_bias=False)
@layer_support(DROPOUT)
def addto_layer(input, act=None, name=None, bias_attr=None,
                layer_attr=None):
    """
    AddtoLayer.

    ..  math::

        y = f(\\sum_{i} x_i + b)

    where :math:`y` is output, :math:`x` is input, :math:`b` is bias,
    and :math:`f` is activation function.

    The example usage is:

    ..  code-block:: python

        addto = addto_layer(input=[layer1, layer2],
                            act=ReluActivation(),
                            bias_attr=False)

    This layer just simply add all input layers together, then activate the sum
    inputs. Each input of this layer should be the same size, which is also the
    output size of this layer.

C
caoying03 已提交
1938 1939 1940
    There is no weight matrix for each input, because it just a simple add
    operation. If you want a complicated operation before add, please use
    mixed_layer.
Z
zhangjinchao01 已提交
1941 1942

    It is a very good way to set dropout outside the layers. Since not all
C
caoying03 已提交
1943 1944
    PaddlePaddle layer support dropout, you can add an add_to layer, set
    dropout here.
Z
zhangjinchao01 已提交
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
    Please refer to dropout_layer for details.

    :param name: Layer name.
    :type name: basestring
    :param input: Input layers. It could be a LayerOutput or list/tuple of
                 LayerOutput.
    :type input: LayerOutput|list|tuple
    :param act: Activation Type, default is tanh.
    :type act: BaseActivation
    :param bias_attr: Bias attribute. If False, means no bias. None is default
                      bias.
    :type bias_attr: ParameterAttribute|bool
    :param layer_attr: Extra Layer attribute.
    :type layer_attr: ExtraLayerAttribute
D
dangqingqing 已提交
1959
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
1960 1961 1962 1963 1964 1965
    :rtype: LayerOutput
    """
    num_filters = None
    if isinstance(input, LayerOutput):
        input = [input]

1966
    assert isinstance(input, collections.Sequence)
Z
zhangjinchao01 已提交
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
    ipts_for_layer = []
    for each_input in input:
        assert isinstance(each_input, LayerOutput)
        ipts_for_layer.append(Input(each_input.name))
        if each_input.num_filters is not None:
            num_filters = each_input.num_filters

    Layer(
        name=name, type=LayerType.ADDTO_LAYER, inputs=ipts_for_layer,
        bias=ParamAttr.to_bias(bias_attr),
        active_type=act.name,
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
1980

Z
zhangjinchao01 已提交
1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
    return LayerOutput(name, LayerType.ADDTO_LAYER, parents=input,
                       activation=act, num_filters=num_filters)


@wrap_act_default(act=IdentityActivation())
@wrap_name_default("concat")
@layer_support()
def concat_layer(input, act=None, name=None, layer_attr=None):
    """
    Concat all input vector into one huge vector.
    Inputs can be list of LayerOutput or list of projection.

1993 1994 1995 1996 1997 1998
    The example usage is:

    ..  code-block:: python

        concat = concat_layer(input=[layer1, layer2])

Z
zhangjinchao01 已提交
1999 2000 2001
    :param name: Layer name.
    :type name: basestring
    :param input: input layers or projections
2002
    :type input: list|tuple|collections.Sequence
Z
zhangjinchao01 已提交
2003 2004 2005 2006
    :param act: Activation type.
    :type act: BaseActivation
    :param layer_attr: Extra Layer Attribute.
    :type layer_attr: ExtraLayerAttribute
D
dangqingqing 已提交
2007
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
2008 2009 2010 2011 2012 2013 2014 2015
    :rtype: LayerOutput
    """

    if isinstance(input, LayerOutput):
        input = [input]
    elif isinstance(input, Projection):
        input = [input]
    else:
2016
        assert isinstance(input, collections.Sequence)
Z
zhangjinchao01 已提交
2017 2018

    def __is_type__(o, tp):
2019
        if not isinstance(o, collections.Sequence):
Z
zhangjinchao01 已提交
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
            if o == tp:
                return True
            elif len(o.__bases__) == 0:
                return False
            else:
                for bs in o.__bases__:
                    if __is_type__(bs, tp):
                        return True
                return False
        else:
            tmp = map(lambda _x: __is_type__(_x, tp), o)
            a = tmp[0]
            for b in tmp[1:]:
                assert a == b
            return a

    def __reduce_concat_type__(a, b):
        assert __is_type__([a, b], Projection) or __is_type__([a, b],
                                                              LayerOutput)
        return a

    is_concat_layer = __is_type__(reduce(__reduce_concat_type__,
                                         map(type, input)), LayerOutput)

    layer_type = (LayerType.CONCAT_LAYER if is_concat_layer
                  else LayerType.CONCAT_PROJ_LAYER)

    Layer(
        name=name, type=layer_type,
        inputs=[x.name for x in input] if is_concat_layer else input,
        active_type=act.name,
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )

    sz = 0
    for each_input in input:
        if each_input.size is not None:
            sz += each_input.size
        else:
            sz = None
            break

    return LayerOutput(name, layer_type=layer_type,
                       parents=input if is_concat_layer else [
                           x.origin for x in input],
                       activation=act, size=sz)


def memory(name, size, is_seq=False, boot_layer=None,
           boot_bias=None, boot_bias_active_type=None,
           boot_with_const_id=None):
    """
    The memory layers is a layer cross each time step. Reference this output
    as previous time step layer :code:`name` 's output.

    The default memory is zero in first time step, previous time step's
    output in the rest time steps.

    If boot_bias, the first time step value is this bias and
    with activation.

    If boot_with_const_id, then the first time stop is a IndexSlot, the
    Arguments.ids()[0] is this :code:`cost_id`.

    If boot_layer is not null, the memory is just the boot_layer's output.
    Set :code:`is_seq` is true boot layer is sequence.


    The same name layer in recurrent group will set memory on each time
    step.

    :param name: memory's name.
    :type name: basestring
    :param size: size of memory.
    :type size: int
    :param is_seq: is sequence for boot_layer
    :type is_seq: bool
    :param boot_layer: boot layer of memory.
    :type boot_layer: LayerOutput|None
    :param boot_bias: boot layer's bias
    :type boot_bias: ParameterAttribute|None
    :param boot_bias_active_type: boot layer's active type.
    :type boot_bias_active_type: BaseActivation
    :param boot_with_const_id: boot layer's id.
    :type boot_with_const_id: int
D
dangqingqing 已提交
2105
    :return: LayerOutput object which is a memory.
Z
zhangjinchao01 已提交
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
    :rtype: LayerOutput
    """
    if boot_bias_active_type is None:
        boot_bias_active_type = LinearActivation()

    assert boot_bias is None or isinstance(boot_bias, ParameterAttribute)
    if isinstance(boot_bias, ParameterAttribute):
        boot_bias = ParamAttr.to_bias(boot_bias)

    assert boot_layer is None or isinstance(boot_layer, LayerOutput)

    agent_name = Memory(name, size,
                        is_seq,
                        boot_layer.name if boot_layer is not None else None,
                        boot_bias,
                        boot_bias_active_type.name,
                        boot_with_const_id)

    lout = LayerOutput(name=agent_name, size=size,
                       layer_type=LayerType.MEMORY,
                       parents=[boot_layer] if boot_layer is not None
                       else None)
    return lout


@wrap_bias_attr_default()
@wrap_act_default(param_names=['gate_act',
                               'state_act'],
                  act=SigmoidActivation())
@wrap_act_default(act=TanhActivation())
@wrap_name_default('lstm_step')
@layer_support()
def lstm_step_layer(input, state, size, act=None,
                    name=None, gate_act=None, state_act=None,
                    bias_attr=None, layer_attr=None):
    """
    LSTM Step Layer. It used in recurrent_group. The lstm equations are shown
    as follow.

    ..  math::

L
luotao02 已提交
2147
        i_t & = \\sigma(W_{xi}x_{t} + W_{hi}h_{t-1} + W_{ci}c_{t-1} + b_i)
Z
zhangjinchao01 已提交
2148

L
luotao02 已提交
2149
        f_t & = \\sigma(W_{xf}x_{t} + W_{hf}h_{t-1} + W_{cf}c_{t-1} + b_f)
Z
zhangjinchao01 已提交
2150

L
luotao02 已提交
2151
        c_t & = f_tc_{t-1} + i_t tanh (W_{xc}x_t+W_{hc}h_{t-1} + b_c)
Z
zhangjinchao01 已提交
2152

L
luotao02 已提交
2153
        o_t & = \\sigma(W_{xo}x_{t} + W_{ho}h_{t-1} + W_{co}c_t + b_o)
Z
zhangjinchao01 已提交
2154

L
luotao02 已提交
2155
        h_t & = o_t tanh(c_t)
Z
zhangjinchao01 已提交
2156 2157


L
luotao02 已提交
2158
    The input of lstm step is :math:`Wx_t + Wh_{t-1}`, and user should use
Z
zhangjinchao01 已提交
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
    :code:`mixed_layer` and :code:`full_matrix_projection` to calculate these
    input vector.

    The state of lstm step is :math:`c_{t-1}`. And lstm step layer will do

    ..  math::

        i_t = \\sigma(input + W_{ci}c_{t-1} + b_i)

        ...


    This layer contains two outputs. Default output is :math:`h_t`. The other
    output is :math:`o_t`, which name is 'state' and can use
    :code:`get_output_layer` to extract this output.

    :param name: Layer's name.
    :type name: basestring
    :param size: Layer's size. NOTE: lstm layer's size, should be equal as
                 :code:`input.size/4`, and should be equal as
                 :code:`state.size`.
    :type size: int
    :param input: input layer. :math:`Wx_t + Wh_{t-1}`
    :type input: LayerOutput
    :param state: State Layer. :math:`c_{t-1}`
    :type state: LayerOutput
    :param act: Activation type. Default is tanh
    :type act: BaseActivation
    :param gate_act: Gate Activation Type. Default is sigmoid, and should
                          be sigmoid only.
    :type gate_act: BaseActivation
    :param state_act: State Activation Type. Default is sigmoid, and should
                           be sigmoid only.
    :type state_act: BaseActivation
    :param bias_attr: Bias Attribute.
    :type bias_attr: ParameterAttribute
    :param layer_attr: layer's extra attribute.
    :type layer_attr: ExtraLayerAttribute
D
dangqingqing 已提交
2197
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
    :rtype: LayerOutput
    """
    Layer(
        name=name,
        type=LayerType.LSTM_STEP_LAYER,
        active_type=act.name,
        active_gate_type=gate_act.name,
        active_state_type=state_act.name,
        bias=ParamAttr.to_bias(bias_attr),
        size=size, inputs=[input.name, state.name],
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )

    return LayerOutput(name=name, layer_type=LayerType.LSTM_STEP_LAYER,
                       parents=[input, state], activation=act,
                       size=size, outputs=['default', 'state'])


@wrap_bias_attr_default()
@wrap_act_default(param_names=['gate_act'],
                  act=SigmoidActivation())
@wrap_act_default(act=TanhActivation())
@wrap_name_default('gru_step')
@layer_support()
def gru_step_layer(input, output_mem, size=None, act=None,
                   name=None, gate_act=None,
                   bias_attr=None, layer_attr=None):
    """

    :param input:
    :type input: LayerOutput
    :param output_mem:
    :param size:
    :param act:
    :param name:
    :param gate_act:
    :param bias_attr:
    :param layer_attr:
D
dangqingqing 已提交
2236
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
    :rtype: LayerOutput
    """
    assert input.size % 3 == 0
    if size is None:
        size = input.size / 3
    Layer(
        name=name,
        type=LayerType.GRU_STEP_LAYER,
        inputs=[
            input.name,
            output_mem.name
        ],
        bias=ParamAttr.to_bias(bias_attr),
        size=size,
        active_type=act.name,
        active_gate_type=gate_act.name,
        **ExtraAttr.to_kwargs(layer_attr)
    )
    return LayerOutput(
        name=name, layer_type=LayerType.GRU_STEP_LAYER,
        parents=[input, output_mem],
        size=size, activation=act)


@wrap_name_default()
@layer_support()
def get_output_layer(input, arg_name, name=None, layer_attr=None):
    """
C
caoying03 已提交
2265 2266 2267 2268
    Get layer's output by name. In PaddlePaddle, a layer might return multiple
    values, but returns one layer's output. If the user wants to use another
    output besides the default one, please use get_output_layer first to get
    the output from input.
Z
zhangjinchao01 已提交
2269 2270 2271 2272 2273 2274 2275 2276 2277

    :param name: Layer's name.
    :type name: basestring
    :param input: get output layer's input. And this layer should contains
                   multiple outputs.
    :type input: LayerOutput
    :param arg_name: Output name from input.
    :type arg_name: basestring
    :param layer_attr: Layer's extra attribute.
D
dangqingqing 已提交
2278
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
    :rtype: LayerOutput
    """
    # GetOutputLayer
    assert arg_name in input.outputs, 'Get Output From an not existed input.' \
                                      ' The get output name is %s, which not' \
                                      ' in %s' % (
                                          arg_name, ",".join(input.outputs))
    Layer(name=name, type=LayerType.GET_OUTPUT_LAYER,
          inputs=[Input(input.name, input_layer_argument=arg_name)],
          size=input.size,
          **ExtraLayerAttribute.to_kwargs(layer_attr))

    return LayerOutput(name=name, layer_type=LayerType.GET_OUTPUT_LAYER,
                       parents=[input], size=input.size)


@wrap_name_default()
@wrap_act_default()
@wrap_bias_attr_default()
@wrap_param_attr_default()
@layer_support()
def recurrent_layer(input, act=None, bias_attr=None,
2301
                    param_attr=None, name=None, reverse=False, layer_attr=None):
Z
zhangjinchao01 已提交
2302
    """
2303 2304
    Simple recurrent unit layer. It is just a fully connect layer through both
    time and neural network.
Z
zhangjinchao01 已提交
2305

2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
    For each sequence [start, end] it performs the following computation\:

    ..  math::

        out_{i} = act(in_{i})     \\      \\      \\text{for} \\ i = start \\\\
        out_{i} = act(in_{i} + out_{i-1} * W) \\ \\ \\text{for} \\ start < i <= end

    If reversed is true, the order is reversed\:

    ..  math::

        out_{i} = act(in_{i})           \\    \\   \\text{for} \\ i = end  \\\\
        out_{i} = act(in_{i} + out_{i+1} * W) \\ \\ \\text{for} \\ start <= i < end


    :param input: Input Layer
    :type input: LayerOutput
    :param act: activation.
    :type act: BaseActivation
    :param bias_attr: bias attribute.
    :type bias_attr: ParameterAttribute
    :param param_attr: parameter attribute.
    :type param_attr: ParameterAttribute
    :param name: name of the layer
    :type name: basestring
    :param layer_attr: Layer Attribute.
    :type layer_attr: ExtraLayerAttribute
D
dangqingqing 已提交
2333
    :return: LayerOutput object.
2334
    :rtype: LayerOutput
Z
zhangjinchao01 已提交
2335 2336 2337 2338 2339 2340
    """
    Layer(name=name,
          type=LayerType.RECURRENT_LAYER,
          inputs=Input(input.name, **param_attr.attr),
          active_type=act.name,
          bias=ParamAttr.to_bias(bias_attr),
2341
          reversed=reverse,
Z
zhangjinchao01 已提交
2342 2343
          **ExtraAttr.to_kwargs(layer_attr))
    return LayerOutput(name=name, layer_type=LayerType.RECURRENT_LAYER,
2344 2345
                       parents=[input], size=input.size, activation=act,
                       reverse=reverse)
Z
zhangjinchao01 已提交
2346 2347 2348 2349 2350 2351 2352


class StaticInput(object):
    """
    StaticInput is only used in recurrent_group which defines a read-only memory
    that can be a sequence or non-sequence.
    """
2353

Z
zhangjinchao01 已提交
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
    def __init__(self, input, is_seq=False, size=None):
        assert isinstance(input, LayerOutput)
        self.input = input
        self.is_seq = is_seq
        assert input.size is not None or size is not None
        if size is not None:
            input.size = size


class SubsequenceInput(object):
    """
    Input sequence has sub-sequence, used in recurrent_group.

    The example usage is:

    .. code-block:: python

       input = SubsequenceInput(layer)
    """
2373

Z
zhangjinchao01 已提交
2374 2375 2376 2377 2378 2379 2380
    def __init__(self, input):
        assert isinstance(input, LayerOutput)
        assert input.size is not None
        self.input = input


@wrap_name_default("recurrent_group")
2381
def recurrent_group(step, input, reverse=False, name=None, targetInlink=None):
Z
zhangjinchao01 已提交
2382
    """
C
caoying03 已提交
2383 2384 2385 2386 2387
    Recurrent layer group is an extremely flexible recurrent unit in
    PaddlePaddle. As long as the user defines the calculation done within a
    time step, PaddlePaddle will iterate such a recurrent calculation over
    sequence input. This is extremely usefull for attention based model, or
    Neural Turning Machine like models.
Z
zhangjinchao01 已提交
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431

    The basic usage (time steps) is:

    .. code-block:: python

       def step(input):
           output = fc_layer(input=layer,
                             size=1024,
                             act=LinearActivation(),
                             bias_attr=False)
           return output

       group = recurrent_group(input=layer,
                               step=step)

    You can see following configs for further usages:

    - time steps: lstmemory_group, paddle/gserver/tests/sequence_layer_group.conf, \
                  demo/seqToseq/seqToseq_net.py
    - sequence steps: paddle/gserver/tests/sequence_nest_layer_group.conf

    :param step: recurrent one time step function.The input of this function is
                 input of the group. The return of this function will be
                 recurrent group's return value.

                 The recurrent group scatter a sequence into time steps. And
                 for each time step, will invoke step function, and return
                 a time step result. Then gather each time step of output into
                 layer group's output.

    :type step: callable

    :param name: recurrent_group's name.
    :type name: basestring

    :param input: Input links array.

                  LayerOutput will be scattered into time steps.
                  SubsequenceInput will be scattered into sequence steps.
                  StaticInput will be imported to each time step, and doesn't change
                  through time. It's a mechanism to access layer outside step function.

    :type input: LayerOutput|StaticInput|SubsequenceInput|list|tuple

2432 2433
    :param reverse: If reverse is set true, the recurrent unit will process the
                    input sequence in a reverse order.
Z
zhangjinchao01 已提交
2434
    :type reverse: bool
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445

    :param targetInlink: the input layer which share info with layer group's output

                         Param input specifies multiple input layers. For
                         SubsequenceInput inputs, config should assign one input
                         layer that share info(the number of sentences and the number
                         of words in each sentence) with all layer group's outputs.
                         targetInlink should be one of the layer group's input.

    :type targetInlink: LayerOutput|SubsequenceInput

D
dangqingqing 已提交
2446
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
    :rtype: LayerOutput
    """
    model_type('recurrent_nn')

    def is_single_input(x):
        return isinstance(x, LayerOutput) or isinstance(x, StaticInput) \
               or isinstance(x, SubsequenceInput)

    if is_single_input(input):
        input = [input]
2457
    assert isinstance(input, collections.Sequence)
Z
zhangjinchao01 已提交
2458 2459 2460 2461 2462 2463

    def is_in_links(x):
        return isinstance(x, LayerOutput) or isinstance(x, SubsequenceInput)

    in_links = filter(is_in_links, input)

2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
    def targetInlink_in_inlinks():
        for inlink in in_links:
            if isinstance(inlink, SubsequenceInput):
                if targetInlink == inlink.input:
                    return True
            elif targetInlink == inlink:
                return True
        return False

    assert(targetInlink == None or targetInlink_in_inlinks())
    targetInlinkName = None if targetInlink == None \
                            else targetInlink.name if isinstance(targetInlink, LayerOutput) \
                                                   else targetInlink.input.name

Z
zhangjinchao01 已提交
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
    contains_sub_seq = [False]

    def map_in_links(x):
        if isinstance(x, SubsequenceInput):
            contains_sub_seq[0] = True
            return Link(name=x.input.name, has_subseq=True)
        else:
            return x.name

    RecurrentLayerGroupWithoutOutLinksBegin(
        name=name, in_links=map(map_in_links, in_links),
2489 2490
        seq_reversed=reverse,
        target_inlinkname=targetInlinkName)
Z
zhangjinchao01 已提交
2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
    in_args = []
    for each_input in input:
        assert is_single_input(each_input)
        if isinstance(each_input, LayerOutput):
            in_args.append(each_input)
        elif isinstance(each_input, SubsequenceInput):
            in_args.append(each_input.input)
        else:
            mem_name = "__%s_memory__" % each_input.input.name
            mem = memory(name=mem_name,
                         is_seq=each_input.is_seq,
                         size=each_input.input.size,
                         boot_layer=each_input.input)
            with mixed_layer(name=mem_name, size=each_input.input.size,
                             act=IdentityActivation()) as mix:
                mix += identity_projection(mem)
            in_args.append(mem)

    layer_outs = step(*in_args)

    if isinstance(layer_outs, LayerOutput):
        layer_outs = [layer_outs]

    for ot in layer_outs:
        assert isinstance(ot, LayerOutput)
2516
        ot.reverse = reverse
Z
zhangjinchao01 已提交
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
        if contains_sub_seq[0]:
            RecurrentLayerGroupSetOutLink(Link(ot.name, has_subseq=True))
        else:
            RecurrentLayerGroupSetOutLink(ot.name)

    RecurrentLayerGroupEnd(name=name)

    if len(layer_outs) == 1:
        return layer_outs[0]
    else:
        return layer_outs

2529

Z
zhangjinchao01 已提交
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
class BaseGeneratedInput(object):
    def __init__(self):
        self.bos_id = None
        self.eos_id = None

    def before_real_step(self):
        raise NotImplementedError()

    def after_real_step(self, *args):
        raise NotImplementedError()


class GeneratedInput(BaseGeneratedInput):
    def after_real_step(self, input):
        return maxid_layer(input=input, name='__beam_search_predict__')

    def before_real_step(self):
        predict_id = memory(name='__beam_search_predict__',
                            size=self.size,
                            boot_with_const_id=self.bos_id)

        trg_emb = embedding_layer(input=predict_id,
                                  size=self.embedding_size,
                                  param_attr=ParamAttr(
                                      name=self.embedding_name))
        return trg_emb

    def __init__(self, size, embedding_name, embedding_size):
2558
        super(GeneratedInput, self).__init__()
Z
zhangjinchao01 已提交
2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581
        self.size = size
        self.embedding_name = embedding_name
        self.embedding_size = embedding_size


@wrap_name_default()
def maxid_layer(input, name=None, layer_attr=None):
    """
    A layer for finding the id which has the maximal value for each sample.
    The result is stored in output.ids.

    The example usage is:

    .. code-block:: python

       maxid = maxid_layer(input=layer)

    :param input: Input layer name.
    :type input: LayerOutput
    :param name: Layer name.
    :type name: basestring
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
2582
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
    :rtype: LayerOutput
    """

    assert isinstance(input, LayerOutput)
    Layer(name=name,
          type='maxid',
          inputs=[input.name],
          **ExtraLayerAttribute.to_kwargs(layer_attr))
    return LayerOutput(name=name,
                       layer_type=LayerType.MAXID_LAYER,
                       parents=[input])

2595

H
Haonan 已提交
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
@wrap_name_default()
def out_prod_layer(input1, input2, name=None, layer_attr=None):
    """
    A layer for computing the outer product of two vectors
    The result is a matrix of size(input1) x size(input2)

    The example usage is:

    .. code-block:: python

       out_prod = out_prod_layer(input1=vec1, input2=vec2)

    :param name: Layer name.
    :type name: basestring
    :param input1: The first input layer name.
    :type input: LayerOutput
    :param input2: The second input layer name.
    :type input2: LayerOutput
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
    :return: LayerOutput object.
    :rtype: LayerOutput
    """

    assert isinstance(input1, LayerOutput)
    assert isinstance(input2, LayerOutput)
    Layer(name=name,
          type="out_prod",
          inputs=[input1.name, input2.name],
          **ExtraLayerAttribute.to_kwargs(layer_attr))
    return LayerOutput(name=name,
                       layer_type=LayerType.OUT_PROD_LAYER,
2628 2629
                       parents=[input1, input2])

Z
zhangjinchao01 已提交
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645

@wrap_name_default()
def eos_layer(input, eos_id, name=None, layer_attr=None):
    """
    A layer for checking EOS for each sample:
    - output_id = (input_id == conf.eos_id)

    The result is stored in output\_.ids.
    It is used by recurrent layer group.

    The example usage is:

    .. code-block:: python

       eos = eos_layer(input=layer, eos_id=id)

L
luotao02 已提交
2646 2647
    :param name: Layer name.
    :type name: basestring
Z
zhangjinchao01 已提交
2648 2649 2650 2651 2652 2653
    :param input: Input layer name.
    :type input: LayerOutput
    :param eos_id: end id of sequence
    :type eos_id: int
    :param layer_attr: extra layer attributes.
    :type layer_attr: ExtraLayerAttribute.
D
dangqingqing 已提交
2654
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
    :rtype: LayerOutput
    """
    Layer(name=name,
          type=LayerType.EOSID_LAYER,
          eos_id=eos_id,
          inputs=[input.name],
          **ExtraLayerAttribute.to_kwargs(layer_attr))
    return LayerOutput(name=name, layer_type=LayerType.EOSID_LAYER,
                       parents=[input])


@wrap_name_default()
def beam_search(step, input, bos_id, eos_id, beam_size,
                max_length=500, name=None,
                num_results_per_sample=None):
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680
    """
    Beam search is a heuristic search algorithm used in sequence generation.
    It explores a graph by expanding the most promising nodes in a limited set
    to maintain tractability.

    The example usage is:

    .. code-block:: python

        def rnn_step(input):
            last_time_step_output = memory(name='rnn', size=512)
2681
            with mixed_layer(size=512, name='rnn') as simple_rnn:
2682 2683 2684 2685 2686 2687
                simple_rnn += full_matrix_projection(input)
                simple_rnn += last_time_step_output
            return simple_rnn

        beam_gen = beam_search(name="decoder",
                               step=rnn_step,
2688
                               input=[StaticInput(encoder_last)],
2689 2690
                               bos_id=0,
                               eos_id=1,
2691
                               beam_size=5)
2692 2693 2694 2695 2696 2697 2698 2699 2700

    Please see the following demo for more details:

    - machine translation : demo/seqToseq/translation/gen.conf \
                            demo/seqToseq/seqToseq_net.py

    :param name: Name of the recurrent unit that generates sequences.
    :type name: base string
    :param step: A callable function that defines the calculation in a time
2701
                 step, and it is applied to sequences with arbitrary length by
2702 2703 2704 2705 2706 2707
                 sharing a same set of weights.

                 You can refer to the first parameter of recurrent_group, or
                 demo/seqToseq/seqToseq_net.py for more details.
    :type step: callable
    :param input: Input data for the recurrent unit
2708
    :type input: list
2709 2710 2711
    :param bos_id: Index of the start symbol in the dictionary. The start symbol
                   is a special token for NLP task, which indicates the
                   beginning of a sequence. In the generation task, the start
2712
                   symbol is essential, since it is used to initialize the RNN
2713 2714 2715 2716 2717 2718 2719 2720
                   internal state.
    :type bos_id: int
    :param eos_id: Index of the end symbol in the dictionary. The end symbol is
                   a special token for NLP task, which indicates the end of a
                   sequence. The generation process will stop once the end
                   symbol is generated, or a pre-defined max iteration number
                   is exceeded.
    :type eos_id: int
2721 2722
    :param max_length: Max generated sequence length.
    :type max_length: int
2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
    :param beam_size: Beam search for sequence generation is an iterative search
                      algorithm. To maintain tractability, every iteration only
                      only stores a predetermined number, called the beam_size,
                      of the most promising next words. The greater the beam
                      size, the fewer candidate words are pruned.
    :type beam_size: int
    :param num_results_per_sample: Number of the generated results per input
                                  sequence. This number must always be less than
                                  beam size.
    :type num_results_per_sample: int
2733 2734
    :return: The generated word index.
    :rtype: LayerOutput
2735 2736
    """

Z
zhangjinchao01 已提交
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
    if num_results_per_sample is None:
        num_results_per_sample = beam_size
    if num_results_per_sample > beam_size:
        logger.warning("num_results_per_sample should be less than beam_size")

    if isinstance(input, StaticInput) or isinstance(input,
                                                    BaseGeneratedInput):
        input = [input]

    generated_input_index = -1

    real_input = []
    for i, each_input in enumerate(input):
2750 2751
        assert isinstance(each_input, StaticInput) or isinstance(
            each_input, BaseGeneratedInput)
Z
zhangjinchao01 已提交
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
        if isinstance(each_input, BaseGeneratedInput):
            assert generated_input_index == -1
            generated_input_index = i
        else:
            real_input.append(each_input)

    assert generated_input_index != -1

    gipt = input[generated_input_index]
    assert isinstance(gipt, BaseGeneratedInput)

    gipt.bos_id = bos_id
    gipt.eos_id = eos_id

    def __real_step__(*args):
        eos_name = "__%s_eos_layer__" % name
        RecurrentLayerGroupSetGenerator(Generator(
            eos_layer_name=eos_name,
            max_num_frames=max_length,
            beam_size=beam_size,
            num_results_per_sample=num_results_per_sample))

        args = list(args)
        args.insert(generated_input_index, gipt.before_real_step())

        predict = gipt.after_real_step(step(*args))

        eos_layer(input=predict, eos_id=eos_id, name=eos_name)

        return predict

    tmp = recurrent_group(step=__real_step__, input=real_input, reverse=False,
                          name=name)
2785

Z
zhangjinchao01 已提交
2786 2787
    return tmp

2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
def __cost_input__(input, label, weight=None):
    """
    inputs and parents for cost layers. 
    """
    ipts = [Input(input.name), Input(label.name)]
    parents = [input, label]
    if weight is not None:
        assert weight.layer_type == LayerType.DATA
        ipts.append(Input(weight.name))
        parents.append(weight)
    return ipts, parents
    
Z
zhangjinchao01 已提交
2800 2801

@wrap_name_default()
2802
def regression_cost(input, label, weight=None, name=None):
Z
zhangjinchao01 已提交
2803 2804 2805 2806 2807 2808
    """
    Regression Layer.

    TODO(yuyang18): Complete this method.

    :param name: layer name.
2809
    :type name: basestring
Z
zhangjinchao01 已提交
2810
    :param input: Network prediction.
2811
    :type input: LayerOutput
Z
zhangjinchao01 已提交
2812
    :param label: Data label.
2813 2814 2815 2816
    :type label: LayerOutput
    :param weight: The weight affects the cost, namely the scale of cost.
                   It is an optional argument.
    :type weight: LayerOutput
D
dangqingqing 已提交
2817
    :return: LayerOutput object.
2818
    :rtype: LayerOutput
Z
zhangjinchao01 已提交
2819
    """
2820 2821
    ipts, parents = __cost_input__(input, label, weight)

2822
    Layer(inputs=ipts, type="square_error", name=name)
2823
    return LayerOutput(name, LayerType.COST, parents=parents)
Z
zhangjinchao01 已提交
2824 2825 2826


@wrap_name_default("cost")
2827
@layer_support()
2828
def classification_cost(input, label, weight=None, name=None,
2829 2830
                        evaluator=classification_error_evaluator,
                        layer_attr=None):
Z
zhangjinchao01 已提交
2831 2832 2833 2834 2835 2836 2837 2838 2839
    """
    classification cost Layer.

    :param name: layer name.
    :type name: basestring
    :param input: input layer name. network output.
    :type input: LayerOutput
    :param label: label layer name. data_layer often.
    :type label: LayerOutput
2840 2841 2842
    :param weight: The weight affects the cost, namely the scale of cost.
                   It is an optional argument.
    :type weight: LayerOutput
Z
zhangjinchao01 已提交
2843
    :param evaluator: Evaluator method.
2844 2845
    :param layer_attr: layer's extra attribute.
    :type layer_attr: ExtraLayerAttribute
D
dangqingqing 已提交
2846
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
2847 2848 2849 2850 2851
    :rtype: LayerOutput
    """
    assert input.layer_type != LayerType.DATA
    assert isinstance(input.activation, SoftmaxActivation)
    assert label.layer_type == LayerType.DATA
2852 2853 2854

    ipts, parents = __cost_input__(input, label, weight)

2855
    Layer(name=name, type="multi-class-cross-entropy", inputs=ipts,
2856
          **ExtraLayerAttribute.to_kwargs(layer_attr))
Z
zhangjinchao01 已提交
2857 2858 2859 2860 2861 2862 2863 2864 2865 2866

    def __add_evaluator__(e):
        assert callable(e)
        assert hasattr(e, 'is_evaluator')
        assert isinstance(e.is_evaluator, bool)
        assert e.is_evaluator
        assert hasattr(e, "for_classification")
        assert isinstance(e.for_classification, bool)
        assert e.for_classification

2867
        e(name=e.__name__, input=input, label=label, weight=weight)
Z
zhangjinchao01 已提交
2868

2869
    if not isinstance(evaluator, collections.Sequence):
Z
zhangjinchao01 已提交
2870 2871 2872 2873 2874
        evaluator = [evaluator]

    for each_evaluator in evaluator:
        __add_evaluator__(each_evaluator)

2875
    return LayerOutput(name, LayerType.COST, parents=parents)
Z
zhangjinchao01 已提交
2876

2877

2878
def conv_operator(img, filter, filter_size, num_filters,
2879
                  num_channel=None, stride=1, padding=0,
Z
zhangjinchao01 已提交
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
                  filter_size_y=None, stride_y=None, padding_y=None):
    """
    Different from img_conv_layer, conv_op is an Operator, which can be used
    in mixed_layer. And conv_op takes two inputs to perform convolution.
    The first input is the image and the second is filter kernel. It only
    support GPU mode.

    The example usage is:

    .. code-block:: python

2891 2892
       op = conv_operator(img=input1,
                          filter=input2,
2893
                          filter_size=3,
Z
zhangjinchao01 已提交
2894 2895 2896
                          num_filters=64,
                          num_channels=64)

2897 2898 2899 2900
    :param img: input image
    :type img: LayerOutput
    :param filter: input filter
    :type filter: LayerOutput
Z
zhangjinchao01 已提交
2901 2902
    :param filter_size: The x dimension of a filter kernel.
    :type filter_size: int
C
caoying03 已提交
2903 2904 2905
    :param filter_size_y: The y dimension of a filter kernel. Since
                        PaddlePaddle now supports rectangular filters,
                        the filter's shape can be (filter_size, filter_size_y).
Z
zhangjinchao01 已提交
2906
    :type filter_size_y: int
2907 2908
    :param num_filters: channel of output data.
    :type num_filters: int
Z
zhangjinchao01 已提交
2909
    :param num_channel: channel of input data.
L
luotao02 已提交
2910
    :type num_channel: int
Z
zhangjinchao01 已提交
2911
    :param stride: The x dimension of the stride.
L
luotao02 已提交
2912
    :type stride: int
Z
zhangjinchao01 已提交
2913
    :param stride_y: The y dimension of the stride.
L
luotao02 已提交
2914
    :type stride_y: int
Z
zhangjinchao01 已提交
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
    :param padding: The x dimension of padding.
    :type padding: int
    :param padding_y: The y dimension of padding.
    :type padding_y: int
    :return: A ConvOperator Object.
    :rtype: ConvOperator
    """
    if filter_size_y is None:
        filter_size_y = filter_size
    if stride_y is None:
        stride_y = stride
    if padding_y is None:
        padding_y = padding
2928 2929 2930 2931 2932 2933 2934 2935

    if num_channel is None:
        num_channel = img.num_filters

    assert isinstance(filter, LayerOutput)
    if filter.size is not None:
        filter.size = filter_size * filter_size_y * num_filters * num_channel

2936
    op = ConvOperator(input_layer_names=[img.name, filter.name],
2937
                      num_filters=num_filters,
Z
zhangjinchao01 已提交
2938 2939 2940 2941 2942 2943
                      conv_conf=Conv(filter_size=filter_size,
                                     padding=padding,
                                     stride=stride,
                                     channels=num_channel,
                                     filter_size_y=filter_size_y,
                                     padding_y=padding_y,
2944
                                     stride_y=stride_y,
2945
                                     groups=1))
2946
    op.origin = [img, filter]
Z
zhangjinchao01 已提交
2947 2948 2949 2950
    return op


@wrap_name_default()
2951
def conv_shift_layer(a, b, name=None):
Z
zhangjinchao01 已提交
2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962
    """
    This layer performs cyclic convolution for two input. For example:
      - a[in]: contains M elements.
      - b[in]: contains N elements (N should be odd).
      - c[out]: contains M elements.

    .. math::

        c[i] = \sum_{j=-(N-1)/2}^{(N-1)/2}a_{i+j} * b_{j}

    In this formular:
2963 2964 2965 2966
     - a's index is computed modulo M. When it is negative, then get item from
       the right side (which is the end of array) to the left.
     - b's index is computed modulo N. When it is negative, then get item from
       the right size (which is the end of array) to the left.
Z
zhangjinchao01 已提交
2967 2968 2969 2970 2971

    The example usage is:

    .. code-block:: python

2972
       conv_shift = conv_shift_layer(input=[layer1, layer2])
Z
zhangjinchao01 已提交
2973 2974 2975

    :param name: layer name
    :type name: basestring
2976 2977 2978 2979
    :param a: Input layer a.
    :type a: LayerOutput
    :param b: input layer b
    :type b: LayerOutput
D
dangqingqing 已提交
2980
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
2981 2982
    :rtype: LayerOutput
    """
2983 2984
    assert isinstance(a, LayerOutput) and isinstance(b, LayerOutput)
    assert b.size is None or b.size % 2 == 1  # size of b must be odd.
Z
zhangjinchao01 已提交
2985 2986 2987
    Layer(
        name=name,
        type=LayerType.CONV_SHIFT_LAYER,
2988
        inputs=[a.name, b.name],
Z
zhangjinchao01 已提交
2989 2990
    )

2991 2992
    return LayerOutput(name, LayerType.CONV_SHIFT_LAYER, parents=[a, b],
                       size=a.size)
Z
zhangjinchao01 已提交
2993 2994 2995 2996 2997


@wrap_name_default()
@wrap_param_attr_default()
@wrap_bias_attr_default()
2998
@wrap_act_default(act=LinearActivation())
Z
zhangjinchao01 已提交
2999
@layer_support(ERROR_CLIPPING, DROPOUT)
3000
def tensor_layer(a, b, size, act=None, name=None,
Z
zhangjinchao01 已提交
3001 3002 3003 3004 3005 3006
                 param_attr=None, bias_attr=None, layer_attr=None):
    """
    This layer performs tensor operation for two input.
    For example, each sample:

    .. math::
3007
       y_{i} = a * W_{i} * {b^\mathrm{T}}, i=0,1,...,K-1
Z
zhangjinchao01 已提交
3008 3009

    In this formular:
3010 3011
      - :math:`a`: the first input contains M elements.
      - :math:`b`: the second input contains N elements.
Z
zhangjinchao01 已提交
3012 3013
      - :math:`y_{i}`: the i-th element of y.
      - :math:`W_{i}`: the i-th learned weight, shape if [M, N]
3014
      - :math:`b^\mathrm{T}`: the transpose of :math:`b_{2}`.
Z
zhangjinchao01 已提交
3015 3016 3017 3018 3019

    The simple usage is:

    .. code-block:: python

3020
       tensor = tensor_layer(a=layer1, b=layer2, size=1000)
Z
zhangjinchao01 已提交
3021 3022 3023

    :param name: layer name
    :type name: basestring
3024 3025 3026 3027
    :param a: Input layer a.
    :type a: LayerOutput
    :param b: input layer b.
    :type b: LayerOutput
Z
zhangjinchao01 已提交
3028
    :param size: the layer dimension.
L
luotao02 已提交
3029
    :type size: int.
Z
zhangjinchao01 已提交
3030 3031 3032
    :param act: Activation Type. Default is tanh.
    :type act: BaseActivation
    :param param_attr: The Parameter Attribute.
3033
    :type param_attr: ParameterAttribute
Z
zhangjinchao01 已提交
3034 3035 3036 3037 3038 3039
    :param bias_attr: The Bias Attribute. If no bias, then pass False or
                      something not type of ParameterAttribute. None will get a
                      default Bias.
    :type bias_attr: ParameterAttribute|None|Any
    :param layer_attr: Extra Layer config.
    :type layer_attr: ExtraLayerAttribute|None
D
dangqingqing 已提交
3040
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3041 3042
    :rtype: LayerOutput
    """
3043
    assert isinstance(a, LayerOutput) and isinstance(b, LayerOutput)
Z
zhangjinchao01 已提交
3044 3045 3046 3047 3048 3049
    Layer(
        name=name,
        size=size,
        type=LayerType.TENSOR_LAYER,
        active_type=act.name,
        bias=ParamAttr.to_bias(bias_attr),
3050 3051
        inputs=[Input(a.name, **param_attr.attr),
                Input(b.name)],
Z
zhangjinchao01 已提交
3052 3053
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
3054
    return LayerOutput(name, LayerType.TENSOR_LAYER, parents=[a, b],
Z
zhangjinchao01 已提交
3055 3056 3057 3058 3059 3060 3061
                       activation=act, size=size)


@wrap_name_default()
@wrap_param_attr_default()
@wrap_bias_attr_default()
@wrap_act_default()
3062
def selective_fc_layer(input, select, size, act=None, name=None,
Z
zhangjinchao01 已提交
3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076
                       pass_generation=False,
                       has_selected_colums=True,
                       mul_ratio=0.02,
                       param_attr=None, bias_attr=None, layer_attr=None):
    """
    Selectived fully connected layer. Different from fc_layer, the output
    of this layer maybe sparse. It requires an additional input to indicate
    several selected columns for output. If the selected columns is not
    specified, selective_fc_layer acts exactly like fc_layer.

    The simple usage is:

    .. code-block:: python

3077
       sel_fc = selective_fc_layer(input=input, size=128, act=TanhActivation())
Z
zhangjinchao01 已提交
3078 3079 3080 3081 3082

    :param name: The Layer Name.
    :type name: basestring
    :param input: The input layer.
    :type input: LayerOutput|list|tuple
3083 3084 3085
    :param select: The select layer. The output of select layer should be a
                   sparse binary matrix, and treat as the mask of selective fc.
    :type select: LayerOutput
Z
zhangjinchao01 已提交
3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
    :param size: The layer dimension.
    :type size: int
    :param act: Activation Type. Default is tanh.
    :type act: BaseActivation
    :param param_attr: The Parameter Attribute.
    :type param_attr: ParameterAttribute
    :param bias_attr: The Bias Attribute. If no bias, then pass False or
                      something not type of ParameterAttribute. None will get a
                      default Bias.
    :type bias_attr: ParameterAttribute|None|Any
    :param layer_attr: Extra Layer config.
    :type layer_attr: ExtraLayerAttribute|None
D
dangqingqing 已提交
3098
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3099 3100 3101 3102
    :rtype: LayerOutput
    """
    if isinstance(input, LayerOutput):
        input = [input]
3103
        assert not isinstance(param_attr, collections.Sequence)
Z
zhangjinchao01 已提交
3104 3105
        param_attr = [param_attr]
    else:
3106
        if isinstance(param_attr, collections.Sequence):
Z
zhangjinchao01 已提交
3107 3108 3109 3110
            assert len(input) == len(param_attr)
        else:
            param_attr = [copy.deepcopy(param_attr) for _ in range(len(input))]

3111 3112 3113 3114
    assert isinstance(input, collections.Sequence)
    assert isinstance(select, LayerOutput)
    if select.size is not None:
        assert select.size == size
Z
zhangjinchao01 已提交
3115
    Layer(
3116 3117
        inputs=[Input(ipt.name, **attr.attr) for ipt, attr in zip(
            input, param_attr)] + [select.name],
Z
zhangjinchao01 已提交
3118 3119 3120
        name=name,
        type=LayerType.SEL_FC_LAYER,
        size=size,
3121
        bias=ParameterAttribute.to_bias(bias_attr),
Z
zhangjinchao01 已提交
3122 3123 3124 3125 3126 3127
        active_type=act.name,
        selective_fc_pass_generation=pass_generation,
        has_selected_colums=has_selected_colums,
        selective_fc_full_mul_ratio=mul_ratio,
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
3128 3129
    return LayerOutput(name, LayerType.SEL_FC_LAYER, list(input) + [select],
                       activation=act,
Z
zhangjinchao01 已提交
3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
                       size=size)


@wrap_name_default()
def sampling_id_layer(input, name=None):
    """
    A layer for sampling id from multinomial distribution from the input layer.
    Sampling one id for one sample.

    The simple usage is:

    .. code-block:: python

       samping_id = sampling_id_layer(input=input)

    :param input: The input layer.
    :type input: LayerOutput
    :param name: The Layer Name.
    :type name: basestring
D
dangqingqing 已提交
3149
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182
    :rtype: LayerOutput
    """
    Layer(
        name=name,
        type=LayerType.SAMPLING_ID_LAYER,
        inputs=[Input(input.name)],
    )
    return LayerOutput(name, LayerType.SAMPLING_ID_LAYER, input)


@wrap_name_default()
def slope_intercept_layer(input, name=None, slope=1.0, intercept=0.0):
    """
    This layer for applying a slope and an intercept to the input
    element-wise. There is no activation and weight.

    ..  math::
        y = slope * x + intercept

    The simple usage is:

    .. code-block:: python

       scale = slope_intercept_layer(input=input, slope=-1.0, intercept=1.0)

    :param input: The input layer.
    :type input: LayerOutput
    :param name: The Layer Name.
    :type name: basestring
    :param slope: the scale factor.
    :type slope: float.
    :param intercept: the offset.
    :type intercept: float.
D
dangqingqing 已提交
3183
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196
    :rtype: LayerOutput
    """
    Layer(
        name=name,
        type=LayerType.SLOPE_INTERCEPT_LAYER,
        slope=slope,
        intercept=intercept,
        inputs=[Input(input.name)],
    )
    return LayerOutput(name, LayerType.SLOPE_INTERCEPT_LAYER, input)


@wrap_name_default()
3197
def linear_comb_layer(weights, vectors, size=None, name=None):
Z
zhangjinchao01 已提交
3198
    """
3199 3200 3201 3202
    A layer for weighted sum of vectors takes two inputs.
      - Input: size of weights is M
               size of vectors is M*N
      - Output: a vector of size=N
Z
zhangjinchao01 已提交
3203 3204 3205

    .. math::

3206 3207 3208 3209 3210 3211
       z(i) = \sum_{j=0}^{M-1} x(j) y(i+Nj)
    where :math:`0 \le i \le N-1`

    Or in the matrix notation:

    .. math::
Z
zhangjinchao01 已提交
3212

3213
       z = x^\mathrm{T} Y
Z
zhangjinchao01 已提交
3214 3215

    In this formular:
3216 3217 3218 3219 3220 3221
      - :math:`x`: weights
      - :math:`y`: vectors.
      - :math:`z`: the output.

    Note that the above computation is for one sample. Multiple samples are
    processed in one batch.
Z
zhangjinchao01 已提交
3222 3223 3224 3225 3226

    The simple usage is:

    .. code-block:: python

3227
       linear_comb = linear_comb_layer(weights=weight, vectors=vectors,
Z
zhangjinchao01 已提交
3228 3229
                                       size=elem_dim)

3230 3231 3232 3233
    :param weights: The weight layer.
    :type weights: LayerOutput
    :param vectors: The vector layer.
    :type vectors: LayerOutput
Z
zhangjinchao01 已提交
3234 3235 3236 3237
    :param size: the dimension of this layer.
    :type size: int
    :param name: The Layer Name.
    :type name: basestring
D
dangqingqing 已提交
3238
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3239 3240
    :rtype: LayerOutput
    """
3241 3242 3243 3244 3245 3246 3247
    assert isinstance(weights, LayerOutput) and isinstance(vectors, LayerOutput)
    if vectors.size is not None and weights.size is not None:
        assert vectors.size % weights.size == 0
        if size is None:
                size = vectors.size / weights.size
        else:
            assert size == vectors.size / weights.size
Z
zhangjinchao01 已提交
3248 3249
    Layer(
        name=name,
3250
        type=LayerType.LINEAR_COMBINATION_LAYER,
Z
zhangjinchao01 已提交
3251
        size=size,
3252
        inputs=[Input(weights.name), Input(vectors.name)],
Z
zhangjinchao01 已提交
3253
    )
3254 3255 3256
    return LayerOutput(name, LayerType.LINEAR_COMBINATION_LAYER,
                       [weights, vectors], size=size)

3257

3258
convex_comb_layer = linear_comb_layer
Z
zhangjinchao01 已提交
3259

3260

Z
zhangjinchao01 已提交
3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272
@wrap_name_default()
def block_expand_layer(input,
                       channel=0,
                       block_x=0,
                       block_y=0,
                       stride_x=0,
                       stride_y=0,
                       padding_x=0,
                       padding_y=0,
                       name=None):
    """
    Expand feature map to minibatch matrix.
L
luotao02 已提交
3273 3274
       - matrix width is: block_y * block_x * channel
       - matirx height is: outputH * outputW
Z
zhangjinchao01 已提交
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287

    .. math::

       outputH = 1 + (2 * padding_y + imgSizeH - block_y + stride_y - 1) / stride_y

       outputW = 1 + (2 * padding_x + imgSizeW - block_x + stride_x - 1) / stride_x

    The expand method is the same with ExpandConvLayer, but saved the transposed
    value. After expanding, output.sequenceStartPositions will store timeline.
    The number of time steps are outputH * outputW and the dimension of each
    time step is block_y * block_x * channel. This layer can be used after
    convolution neural network, and before recurrent neural network.

3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
    The simple usage is:

    .. code-block:: python

       block_expand = block_expand_layer(input,
                                         channel=128,
                                         stride_x=1,
                                         stride_y=1,
                                         block_x=1,
                                         block_x=3)

Z
zhangjinchao01 已提交
3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316
    :param input: The input layer.
    :type input: LayerOutput
    :param channel: The channel number of input layer.
    :type channel: int
    :param block_x: The width of sub block.
    :type block_x: int
    :param block_y: The width of sub block.
    :type block_y: int
    :param stride_x: The stride size in horizontal direction.
    :type stride_x: int
    :param stride_y: The stride size in vertical direction.
    :type stride_y: int
    :param padding_x: The padding size in horizontal direction.
    :type padding_x: int
    :param padding_y: The padding size in vertical direction.
    :type padding_y: int
    :param name: The name of this layer, which can not specify.
    :type name: None|basestring.
D
dangqingqing 已提交
3317
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3318 3319 3320 3321
    :rtype: LayerOutput
    """
    Layer(name=name,
          input=Input(input.name,
3322
                      block_expand=BlockExpand(channels=channel,
Z
zhangjinchao01 已提交
3323 3324 3325 3326 3327 3328
                                               block_x=block_x,
                                               block_y=block_y,
                                               stride_x=stride_x,
                                               stride_y=stride_y,
                                               padding_x=padding_x,
                                               padding_y=padding_y)
3329
                      ),
Z
zhangjinchao01 已提交
3330
          type=LayerType.BLOCK_EXPAND,
3331 3332 3333
          )

    return LayerOutput(name, LayerType.BLOCK_EXPAND, parents=[input])
Z
zhangjinchao01 已提交
3334 3335 3336


@wrap_name_default()
3337
def ctc_layer(input, label, size=None, name=None, norm_by_times=False):
Z
zhangjinchao01 已提交
3338 3339 3340 3341 3342
    """
    Connectionist Temporal Classification (CTC) is designed for temporal
    classication task. That is, for sequence labeling problems where the
    alignment between the inputs and the target labels is unknown.

3343 3344
    More details can be found by referring to `Connectionist Temporal
    Classification: Labelling Unsegmented Sequence Data with Recurrent
3345 3346
    Neural Networks <http://machinelearning.wustl.edu/mlpapers/paper_files/
    icml2006_GravesFGS06.pdf>`_
3347 3348 3349 3350 3351 3352 3353 3354

    Note:
        Considering the 'blank' label needed by CTC, you need to use
        (num_classes + 1) as the input size. num_classes is the category number.
        And the 'blank' is the last category index. So the size of 'input' layer, such as
        fc_layer with softmax activation, should be num_classes + 1. The size of ctc_layer
        should also be num_classes + 1.

Z
zhangjinchao01 已提交
3355 3356 3357 3358 3359 3360 3361 3362 3363
    The simple usage:

    .. code-block:: python

      ctc = ctc_layer(input=input,
                      label=label,
                      size=9055,
                      norm_by_times=True)

3364
    :param input: The input layer.
Z
zhangjinchao01 已提交
3365 3366 3367
    :type input: LayerOutput
    :param label: The data layer of label with variable length.
    :type label: LayerOutput
3368
    :param size: category numbers + 1.
Z
zhangjinchao01 已提交
3369
    :type size: int
3370 3371
    :param name: The name of this layer
    :type name: basestring|None
Z
zhangjinchao01 已提交
3372 3373
    :param norm_by_times: Whether to normalization by times. False by default.
    :type norm_by_times: bool
D
dangqingqing 已提交
3374
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3375 3376 3377 3378
    :rtype: LayerOutput
    """
    assert isinstance(input, LayerOutput)
    assert isinstance(label, LayerOutput)
3379 3380 3381 3382 3383
    if label.size is not None:
        if size is not None:
            assert size == label.size + 1
        else:
            size = label.size + 1
Z
zhangjinchao01 已提交
3384
    Layer(
3385 3386 3387 3388 3389
        name=name,
        type=LayerType.CTC_LAYER,
        size=size,
        norm_by_times=norm_by_times,
        inputs=[input.name, label.name]
Z
zhangjinchao01 已提交
3390 3391 3392
    )
    return LayerOutput(name, LayerType.CTC_LAYER, [input, label], size=size)

3393

Z
zhangjinchao01 已提交
3394
@wrap_name_default()
3395
@wrap_param_attr_default()
3396
def crf_layer(input, label, size=None, weight=None, param_attr=None, name=None):
Z
zhangjinchao01 已提交
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411
    """
    A layer for calculating the cost of sequential conditional random
    field model.

    The simple usage:

    .. code-block:: python

      crf = crf_layer(input=input,
                      label=label,
                      size=label_dim)

    :param input: The first input layer is the feature.
    :type input: LayerOutput
    :param label: The second input layer is label.
3412
    :type label: LayerOutput
Z
zhangjinchao01 已提交
3413 3414 3415 3416 3417 3418 3419 3420 3421
    :param size: The category number.
    :type size: int
    :param weight: The third layer is "weight" of each sample, which is an
                  optional argument.
    :type weight: LayerOutput
    :param param_attr: Parameter attribute. None means default attribute
    :type param_attr: ParameterAttribute
    :param name: The name of this layers. It is not necessary.
    :type name: None|basestring
D
dangqingqing 已提交
3422
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3423 3424 3425 3426 3427
    :rtype: LayerOutput
    """
    assert isinstance(input, LayerOutput)
    assert isinstance(label, LayerOutput)
    assert weight is None or isinstance(weight, LayerOutput)
3428 3429 3430 3431 3432 3433
    if input.size is not None and label.size is not None:
        assert input.size == label.size
        if size is None:
            size = input.size
        else:
            assert size == input.size
Z
zhangjinchao01 已提交
3434

3435
    ipts = [Input(input.name, **param_attr.attr),
Z
zhangjinchao01 已提交
3436 3437 3438 3439 3440
            Input(label.name)]
    if weight is not None:
        ipts.append(Input(weight.name))

    Layer(
3441 3442 3443 3444
        name=name,
        type=LayerType.CRF_LAYER,
        size=size,
        inputs=ipts,
Z
zhangjinchao01 已提交
3445 3446 3447 3448 3449 3450
    )
    parents = [input, label]
    if weight is not None:
        parents.append(weight)
    return LayerOutput(name, LayerType.CRF_LAYER, parents, size=size)

3451

Z
zhangjinchao01 已提交
3452
@wrap_name_default()
3453
@wrap_param_attr_default()
Z
zhangjinchao01 已提交
3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471
def crf_decoding_layer(input, size, label=None, param_attr=None, name=None):
    """
    A layer for calculating the decoding sequence of sequential conditional
    random field model. The decoding sequence is stored in output.ids.
    If a second input is provided, it is treated as the ground-truth label, and
    this layer will also calculate error. output.value[i] is 1 for incorrect
    decoding or 0 for correct decoding.

    :param input: The first input layer.
    :type input: LayerOutput
    :param size: size of this layer.
    :type size: int
    :param label: None or ground-truth label.
    :type label: LayerOutput or None
    :param param_attr: Parameter attribute. None means default attribute
    :type param_attr: ParameterAttribute
    :param name: The name of this layers. It is not necessary.
    :type name: None|basestring
D
dangqingqing 已提交
3472
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3473 3474 3475 3476 3477 3478
    :rtype: LayerOutput
    """

    assert isinstance(input, LayerOutput)
    assert label is None or isinstance(label, LayerOutput)

3479
    ipts = [Input(input.name, **param_attr.attr)]
Z
zhangjinchao01 已提交
3480 3481 3482 3483
    if label is not None:
        ipts.append(Input(label.name))

    Layer(
3484 3485 3486 3487
        name=name,
        type=LayerType.CRF_DECODING_LAYER,
        size=size,
        inputs=ipts,
Z
zhangjinchao01 已提交
3488 3489 3490 3491 3492 3493
    )
    parents = [input]
    if label is not None:
        parents.append(label)
    return LayerOutput(name, LayerType.CRF_DECODING_LAYER, parents, size=size)

3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570
@wrap_bias_attr_default(has_bias=True)
@wrap_name_default()
@layer_support()
def nce_layer(input, label, num_classes, weight=None,
              num_neg_samples=10, neg_distribution=None,
              name=None, bias_attr=None, layer_attr=None):
    """
    Noise-contrastive estimation.
    Implements the method in the following paper:
    A fast and simple algorithm for training neural probabilistic language models.

    The example usage is:

    .. code-block:: python

       cost = nce_layer(input=layer1, label=layer2, weight=layer3,
                        num_classes=3, neg_distribution=[0.1,0.3,0.6])

    :param name: layer name
    :type name: basestring
    :param input: input layers. It could be a LayerOutput of list/tuple of LayerOutput.
    :type input: LayerOutput|list|tuple|collections.Sequence
    :param label: label layer
    :type label: LayerOutput
    :param weight: weight layer, can be None(default)
    :type weight: LayerOutput
    :param num_classes: number of classes.
    :type num_classes: int 
    :param num_neg_samples: number of negative samples. Default is 10.
    :type num_neg_samples: int 
    :param neg_distribution: The distribution for generating the random negative labels.
                             A uniform distribution will be used if not provided.
                             If not None, its length must be equal to num_classes.
    :type neg_distribution: list|tuple|collections.Sequence|None
    :param bias_attr: Bias parameter attribute. True if no bias.
    :type bias_attr: ParameterAttribute|None|False
    :param layer_attr: Extra Layer Attribute.
    :type layer_attr: ExtraLayerAttribute
    :return: layer name.
    :rtype: LayerOutput
    """
    if isinstance(input, LayerOutput):
        input = [input]
    assert isinstance(input, collections.Sequence)
    assert isinstance(label, LayerOutput)
    assert label.layer_type == LayerType.DATA
    if neg_distribution is not None:
        assert isinstance(neg_distribution, collections.Sequence)
        assert len(neg_distribution) == num_classes
        assert sum(neg_distribution) == 1
    
    ipts_for_layer = []
    parents = []
    for each_input in input:
        assert isinstance(each_input, LayerOutput)
        ipts_for_layer.append(each_input.name)
        parents.append(each_input)
    ipts_for_layer.append(label.name)
    parents.append(label)

    if weight is not None:
        assert isinstance(weight, LayerOutput)
        assert weight.layer_type == LayerType.DATA
        ipts_for_layer.append(weight.name)
        parents.append(weight)

    Layer(
        name=name,
        type=LayerType.NCE_LAYER,
        num_classes=num_classes,
        neg_sampling_dist=neg_distribution,
        num_neg_samples=num_neg_samples,
        inputs=ipts_for_layer,
        bias=ParamAttr.to_bias(bias_attr),
        **ExtraLayerAttribute.to_kwargs(layer_attr)
    )
    return LayerOutput(name, LayerType.NCE_LAYER, parents=parents)
3571

Z
zhangjinchao01 已提交
3572 3573 3574
"""
following are cost Layers.
"""
3575 3576


Z
zhangjinchao01 已提交
3577
@wrap_name_default()
3578
def rank_cost(left, right, label, weight=None, name=None, coeff=1.0):
Z
zhangjinchao01 已提交
3579
    """
3580
    A cost Layer for learning to rank using gradient descent. Details can refer
3581 3582
    to `papers <http://research.microsoft.com/en-us/um/people/cburges/papers/
    ICML_ranking.pdf>`_.
Z
zhangjinchao01 已提交
3583 3584 3585 3586 3587
    This layer contains at least three inputs. The weight is an optional
    argument, which affects the cost.

    .. math::

L
luotao02 已提交
3588
       C_{i,j} & = -\\tilde{P_{ij}} * o_{i,j} + log(1 + e^{o_{i,j}})
Z
zhangjinchao01 已提交
3589

L
luotao02 已提交
3590
       o_{i,j} & =  o_i - o_j
Z
zhangjinchao01 已提交
3591

L
luotao02 已提交
3592
       \\tilde{P_{i,j}} & = \\{0, 0.5, 1\\} \ or \ \\{0, 1\\}
Z
zhangjinchao01 已提交
3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621

    In this formula:
      - :math:`C_{i,j}` is the cross entropy cost.
      - :math:`\\tilde{P_{i,j}}` is the label. 1 means positive order
        and 0 means reverse order.
      - :math:`o_i` and :math:`o_j`: the left output and right output.
        Their dimension is one.

    The simple usage:

    .. code-block:: python

      cost = rank_cost(left=out_left,
                       right=out_right,
                       label=label)

    :param left: The first input, the size of this layer is 1.
    :type left: LayerOutput
    :param right: The right input, the size of this layer is 1.
    :type right: LayerOutput
    :param label: Label is 1 or 0, means positive order and reverse order.
    :type label: LayerOutput
    :param weight: The weight affects the cost, namely the scale of cost.
                   It is an optional argument.
    :type weight: LayerOutput
    :param name: The name of this layers. It is not necessary.
    :type name: None|basestring
    :param coeff: The coefficient affects the gradient in the backward.
    :type coeff: float
D
dangqingqing 已提交
3622
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638
    :rtype: LayerOutput
    """
    assert left.size == 1
    assert right.size == 1
    assert label.size == 1

    ipts = [left.name, right.name, label.name]
    parents = [left, right, label]
    if weight is not None:
        ipts.append(weight.name)
        parents.append(weight)

    Layer(name=name,
          type=LayerType.RANK_COST,
          inputs=ipts,
          coeff=coeff,
3639
          )
Z
zhangjinchao01 已提交
3640 3641 3642

    return LayerOutput(name, LayerType.RANK_COST, parents=parents)

3643

Z
zhangjinchao01 已提交
3644
@wrap_name_default()
3645
def lambda_cost(input, score, name, NDCG_num=5, max_sort_size=-1):
Z
zhangjinchao01 已提交
3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657
    """
    lambdaCost for lambdaRank LTR approach.

    The simple usage:

    .. code-block:: python

      cost = lambda_cost(input=input,
                         score=score,
                         NDCG_num=8,
                         max_sort_size=-1)

3658
    :param input: Samples of the same query should be loaded as sequence.
Z
zhangjinchao01 已提交
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669
    :type input: LayerOutput
    :param score: The 2nd input. Score of each sample.
    :type input: LayerOutput
    :param NDCG_num: The size of NDCG (Normalized Discounted Cumulative Gain),
                     e.g., 5 for NDCG@5. It must be less than for equal to the
                     minimum size of lists.
    :type NDCG_num: int
    :param max_sort_size: The size of partial sorting in calculating gradient.
                          If max_sort_size = -1, then for each list, the
                          algorithm will sort the entire list to get gradient.
                          In other cases, max_sort_size must be greater than or
C
caoying03 已提交
3670 3671 3672
                          equal to NDCG_num. And if max_sort_size is greater
                          than the size of a list, the algorithm will sort the
                          entire list of get gradient.
Z
zhangjinchao01 已提交
3673 3674 3675
    :type max_sort_size: int
    :param name: The name of this layers. It is not necessary.
    :type name: None|basestring
D
dangqingqing 已提交
3676
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3677 3678
    :rtype: LayerOutput
    """
3679 3680 3681
    assert isinstance(input, LayerOutput) and isinstance(score, LayerOutput)
    if score.size is not None:
        assert score.size == 1
Z
zhangjinchao01 已提交
3682 3683 3684 3685
    Layer(name=name,
          type=LayerType.LAMBDA_COST,
          inputs=[input.name, score.name],
          NDCG_num=NDCG_num,
3686 3687
          max_sort_size=max_sort_size
          )
Z
zhangjinchao01 已提交
3688 3689 3690

    return LayerOutput(name, LayerType.LAMBDA_COST, parents=[input, score])

3691

Z
zhangjinchao01 已提交
3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710
@wrap_name_default()
def cross_entropy(input, label, name=None, coeff=1.0):
    """
    A loss layer for multi class entropy.

    .. code-block:: python

       cost = cross_entropy(input, label)

    :param input: The first input layer.
    :type input: LayerOutput.
    :param label: The input label.
    :type input: LayerOutput.
    :param type: The type of cost.
    :type type: basestring.
    :param name: The name of this layers. It is not necessary.
    :type name: None|basestring.
    :param coeff: The coefficient affects the gradient in the backward.
    :type coeff: float.
D
dangqingqing 已提交
3711
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3712 3713 3714 3715 3716 3717 3718
    :rtype: LayerOutput.
    """

    Layer(name=name,
          type=LayerType.CROSS_ENTROPY,
          inputs=[input.name, label.name],
          coeff=coeff,
3719
          )
Z
zhangjinchao01 已提交
3720 3721
    return LayerOutput(name, LayerType.CROSS_ENTROPY, parents=[input, label])

3722

Z
zhangjinchao01 已提交
3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744
@wrap_name_default()
def cross_entropy_with_selfnorm(input, label, name=None, coeff=1.0,
                                softmax_selfnorm_alpha=0.1):
    """
    A loss layer for multi class entropy with selfnorm.

    .. code-block:: python

       cost = cross_entropy_with_selfnorm(input, label)

    :param input: The first input layer.
    :type input: LayerOutput.
    :param label: The input label.
    :type input: LayerOutput.
    :param type: The type of cost.
    :type type: basestring.
    :param name: The name of this layers. It is not necessary.
    :type name: None|basestring.
    :param coeff: The coefficient affects the gradient in the backward.
    :type coeff: float.
    :param softmax_selfnorm_alpha: The scale factor affects the cost.
    :type softmax_selfnorm_alpha: float.
D
dangqingqing 已提交
3745
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3746 3747 3748 3749 3750 3751 3752
    :rtype: LayerOutput.
    """
    Layer(name=name,
          type=LayerType.CROSS_ENTROPY_WITH_SELFNORM,
          inputs=[input.name, label.name],
          coeff=coeff,
          softmax_selfnorm_alpha=softmax_selfnorm_alpha,
3753
          )
Z
zhangjinchao01 已提交
3754 3755 3756 3757 3758

    return LayerOutput(name,
                       LayerType.CROSS_ENTROPY_WITH_SELFNORM,
                       parents=[input, label])

3759

Z
zhangjinchao01 已提交
3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
@wrap_name_default()
def huber_cost(input, label, name=None, coeff=1.0):
    """
    A loss layer for huber loss.

    .. code-block:: python

       cost = huber_cost(input, label)

    :param input: The first input layer.
    :type input: LayerOutput.
    :param label: The input label.
    :type input: LayerOutput.
    :param name: The name of this layers. It is not necessary.
    :type name: None|basestring.
    :param coeff: The coefficient affects the gradient in the backward.
    :type coeff: float.
D
dangqingqing 已提交
3777
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3778 3779
    :rtype: LayerOutput.
    """
3780 3781 3782
    assert isinstance(input, LayerOutput)
    if input.size is not None:
        assert input.size == 1
Z
zhangjinchao01 已提交
3783 3784 3785 3786
    Layer(name=name,
          type=LayerType.HUBER,
          inputs=[input.name, label.name],
          coeff=coeff,
3787
          )
Z
zhangjinchao01 已提交
3788 3789
    return LayerOutput(name, LayerType.HUBER, parents=[input, label])

3790

Z
zhangjinchao01 已提交
3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809
@wrap_name_default()
def multi_binary_label_cross_entropy(input, label, name=None, coeff=1.0):
    """
    A loss layer for multi binary label cross entropy.

    .. code-block:: python

       cost = multi_binary_label_cross_entropy(input, label)

    :param input: The first input layer.
    :type input: LayerOutput
    :param label: The input label.
    :type input: LayerOutput
    :param type: The type of cost.
    :type type: basestring
    :param name: The name of this layers. It is not necessary.
    :type name: None|basestring
    :param coeff: The coefficient affects the gradient in the backward.
    :type coeff: float
D
dangqingqing 已提交
3810
    :return: LayerOutput object.
Z
zhangjinchao01 已提交
3811 3812 3813
    :rtype: LayerOutput
    """

3814 3815
    if input.activation is None or \
            not isinstance(input.activation, SigmoidActivation):
Z
zhangjinchao01 已提交
3816
        logger.log(logging.WARN,
3817 3818
                   "%s is not recommend for multi_binary_label_cross_entropy's activation, "
                   "maybe the sigmoid is better" % repr(input.activation))
Z
zhangjinchao01 已提交
3819 3820 3821 3822 3823

    Layer(name=name,
          type=LayerType.MULTI_BIN_LABEL_CROSS_ENTROPY,
          inputs=[input.name, label.name],
          coeff=coeff,
3824
          )
Z
zhangjinchao01 已提交
3825 3826
    return LayerOutput(name, LayerType.MULTI_BIN_LABEL_CROSS_ENTROPY,
                       parents=[input, label])