layers.py 48.1 KB
Newer Older
Q
Qiao Longfei 已提交
1 2 3
import paddle.v2.fluid.core as core
import paddle.v2.fluid.proto.framework_pb2 as framework_pb2
from paddle.v2.fluid.framework import OpProtoHolder, Variable, Program, \
Y
Yu Yang 已提交
4
    Operator
Q
Qiao Longfei 已提交
5
from paddle.v2.fluid.initializer import ConstantInitializer, \
Y
Yu Yang 已提交
6
    NormalInitializer
Q
Qiao Longfei 已提交
7
from paddle.v2.fluid.layer_helper import LayerHelper, unique_name
Y
Yu Yang 已提交
8
import re
9
import cStringIO
Y
Yu Yang 已提交
10

Q
QI JUN 已提交
11
__all__ = [
Y
Yu Yang 已提交
12
    'fc', 'data', 'cross_entropy', 'conv2d', 'pool2d', 'embedding', 'concat',
D
dzhwinter 已提交
13
    'StaticRNN', 'cast', 'sequence_conv', 'sequence_pool', 'sums', 'cos_sim',
14
    'batch_norm', 'accuracy', 'split_lod_tensor'
Q
QI JUN 已提交
15
]
Y
Yu Yang 已提交
16 17


F
fengjiayi 已提交
18 19 20
def fc(input,
       size,
       param_attr=None,
Q
QI JUN 已提交
21
       bias_attr=None,
F
fengjiayi 已提交
22 23 24
       name=None,
       act=None,
       num_flatten_dims=1,
25 26
       main_program=None,
       startup_program=None):
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    """
    Fully Connected Layer.

    Args:
       input: The input tensor to the function
       size: The size of the layer
       param_attr: The parameters/weights to the FC Layer
       bias_attr: The bias parameter for the FC layer
       name: Name/alias of the function
       act: Activation to be applied to the output of FC layer
       num_flatten_dims: Number of columns in input
       main_program: Name of the main program that calls this
       startup_program: Name of the startup program

    This function can take in multiple inputs and performs the Fully Connected
    function (linear transformation) on top of each of them.
    So for input x, the output will be : Wx + b. Where W is the parameter,
    b the bias and x is the input.

    The function also applies an activation (non-linearity) on top of the
    output, if activation is passed in the input.

    All the input variables of this function are passed in as local variables
    to the LayerHelper constructor.

    """
Y
Yu Yang 已提交
53 54 55 56 57 58 59
    helper = LayerHelper('fc', **locals())

    dtype = helper.input_dtype()

    mul_results = []
    for input_var, param_attr in helper.iter_inputs_and_params():
        input_shape = input_var.shape
Y
Yu Yang 已提交
60 61 62
        param_shape = [
            reduce(lambda a, b: a * b, input_shape[num_flatten_dims:], 1)
        ] + [size]
Y
Yu Yang 已提交
63 64 65 66 67 68 69 70 71 72
        w = helper.create_parameter(
            attr=param_attr, shape=param_shape, dtype=dtype)
        tmp = helper.create_tmp_variable(dtype)
        helper.append_op(
            type="mul",
            inputs={
                "X": input_var,
                "Y": w,
            },
            outputs={"Out": tmp},
Y
Yu Yang 已提交
73 74
            attrs={'x_num_col_dims': num_flatten_dims,
                   'y_num_col_dims': 1})
Y
Yu Yang 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        mul_results.append(tmp)

    # sum
    if len(mul_results) == 1:
        pre_bias = mul_results[0]
    else:
        pre_bias = helper.create_tmp_variable(dtype)
        helper.append_op(
            type="sum", inputs={"X": mul_results}, outputs={"Out": pre_bias})
    # add bias
    pre_activation = helper.append_bias_op(pre_bias)
    # add activation
    return helper.append_activation(pre_activation)


Q
QI JUN 已提交
90 91 92
def embedding(input,
              size,
              data_type='float32',
93
              is_sparse=False,
Q
QI JUN 已提交
94
              param_attr=None,
95 96
              main_program=None,
              startup_program=None):
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    """
    Embedding Layer.

    Args:
       input: The input to the function
       size: The size of the layer
       data_type: The type of data : float32, float_16, int etc
       is_sparse: A flag that decleares whether the input is sparse
       param_attr: Parameters for this layer
       main_program: Name of the main program that calls this
       startup_program: Name of the startup program

    This function can take in the input (which is a vector of IDs) and
    performs a lookup in the lookup_table using these IDs, to result into
    the embedding of each ID in the input.

    All the input variables of this function are passed in as local variables
    to the LayerHelper constructor.

    """
Q
QI JUN 已提交
117 118 119 120 121 122 123 124
    helper = LayerHelper('embedding', **locals())
    w = helper.create_parameter(
        attr=helper.param_attr, shape=size, dtype=data_type)
    tmp = helper.create_tmp_variable(data_type)
    helper.append_op(
        type='lookup_table',
        inputs={'Ids': input,
                'W': w},
125 126
        outputs={'Out': tmp},
        attrs={'is_sparse': is_sparse})
Q
QI JUN 已提交
127 128 129
    return tmp


Q
QI JUN 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
# TODO(qijun): expose H0 and C0
def dynamic_lstm(input,
                 size,
                 data_type='float32',
                 param_attr=None,
                 bias_attr=None,
                 use_peepholes=True,
                 is_reverse=False,
                 gate_activation='sigmoid',
                 cell_activation='tanh',
                 candidate_activation='tanh',
                 main_program=None,
                 startup_program=None):
    helper = LayerHelper('lstm', **locals())
    size = size / 4
    weight = helper.create_parameter(
        attr=helper.param_attr, shape=[size, 4 * size], dtype=data_type)
    bias_size = [1, 7 * size]
    if not use_peepholes:
        bias_size[1] = 4 * size
    bias = helper.create_parameter(
        attr=helper.bias_attr, shape=bias_size, dtype=data_type, suffix='b')

    hidden = helper.create_tmp_variable(data_type)
    cell = helper.create_tmp_variable(data_type)
    batch_gate = helper.create_tmp_variable(data_type)
    batch_cell_pre_act = helper.create_tmp_variable(data_type)

    helper.append_op(
        type='lstm',
        inputs={'Input': input,
                'Weight': weight,
                'Bias': bias},
        outputs={
            'Hidden': hidden,
            'Cell': cell,
            'BatchGate': batch_gate,
            'BatchCellPreAct': batch_cell_pre_act
        },
        attrs={
            'use_peepholes': use_peepholes,
            'is_reverse': is_reverse,
            'gate_activation': gate_activation,
            'cell_activation': cell_activation,
            'candidate_activation': candidate_activation
        })
    return hidden, cell


F
fengjiayi 已提交
179 180 181 182
def data(name,
         shape,
         data_type='float32',
         type=core.VarDesc.VarType.LOD_TENSOR,
Y
Yu Yang 已提交
183
         append_batch_size=True,
184
         main_program=None,
185 186
         startup_program=None,
         stop_gradient=True):
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    """
    Data Layer.

    Args:
       name: The name/alias of the function
       shape: Tuple declaring the shape.
       data_type: The type of data : float32, float_16, int etc
       type: The output type. By default it is LOD_TENSOR.
       append_batch_size: Whether or not to append the data as a batch.
       main_program: Name of the main program that calls this
       startup_program: Name of the startup program
       stop_gradient: A boolean that mentions whether gradient should flow.

    This function takes in input and based on whether data has
    to be returned back as a minibatch, it creates the global variable using
    the helper functions. The global variables can be accessed by all the
    following operations and layers in the graph.

    All the input variables of this function are passed in as local variables
    to the LayerHelper constructor.

    """
Y
Yu Yang 已提交
209
    helper = LayerHelper('data', **locals())
Y
Yu Yang 已提交
210 211 212 213 214 215 216 217
    shape = list(shape)
    for i in xrange(len(shape)):
        if shape[i] is None:
            shape[i] = -1
            append_batch_size = False
        elif shape[i] < 0:
            append_batch_size = False

Y
Yu Yang 已提交
218 219
    if append_batch_size:
        shape = [-1] + shape  # append batch size as -1
Y
Yu Yang 已提交
220

Y
Yu Yang 已提交
221
    return helper.create_global_variable(
222 223 224 225 226
        name=name,
        shape=shape,
        dtype=data_type,
        type=type,
        stop_gradient=stop_gradient)
Y
Yu Yang 已提交
227 228


Y
Yu Yang 已提交
229 230 231
def create_tensor(dtype, name=None, main_program=None):
    helper = LayerHelper("create_tensor", **locals())
    return helper.create_variable(name=helper.name, dtype=dtype)
Y
Yu Yang 已提交
232 233 234


def _convert_(name):
235 236 237 238 239 240 241 242 243 244 245
    """
    Formatting.

    Args:
       name: The name/alias

    This function takes in a name and converts it to a standard format of
    group1_group2. Where as per the regular expression, group1 can have
    alphabets and numbers and group2 has capital alphabets.

    """
Y
Yu Yang 已提交
246 247 248 249
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()


250 251 252
def _generate_doc_string_(op_proto):
    """
    Generate docstring by OpProto
X
xuwei06 已提交
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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
    Args:
        op_proto (framework_pb2.OpProto): a protobuf message typed OpProto

    Returns:
        str: the document string
    """

    def _type_to_str_(tp):
        return framework_pb2.AttrType.Name(tp)

    if not isinstance(op_proto, framework_pb2.OpProto):
        raise TypeError("OpProto should be `framework_pb2.OpProto`")

    buf = cStringIO.StringIO()
    buf.write(op_proto.comment)
    buf.write('\nArgs:\n')
    for each_input in op_proto.inputs:
        line_begin = '    {0}: '.format(_convert_(each_input.name))
        buf.write(line_begin)
        buf.write(each_input.comment)
        buf.write('\n')
        buf.write(' ' * len(line_begin))
        buf.write('Duplicable: ')
        buf.write(str(each_input.duplicable))
        buf.write('  Optional: ')
        buf.write(str(each_input.dispensable))
        buf.write('\n')

    for each_attr in op_proto.attrs:
        buf.write('    ')
        buf.write(each_attr.name)
        buf.write(' (')
        buf.write(_type_to_str_(each_attr.type))
        buf.write('): ')
        buf.write(each_attr.comment)
        buf.write('\n')

    if len(op_proto.outputs) != 0:
        buf.write('\nReturns:\n')
        buf.write('    ')
        for each_opt in op_proto.outputs:
            if not each_opt.intermediate:
                break
        buf.write(each_opt.comment)

    return buf.getvalue()


Y
Yu Yang 已提交
302
def _create_op_func_(op_type):
303 304 305 306 307 308 309 310 311 312
    """
    Create an Operator for a Function.

    Args:
       op_type: The name of the operator to be created

    This function takes in the operator type (sigmoid, mean , average etc) and
    creates the operator functionality.

    """
Y
Yu Yang 已提交
313
    op_proto = OpProtoHolder.instance().get_op_proto(op_type)
314 315 316 317 318 319
    not_intermediate_outputs = \
        filter(lambda output: not output.intermediate, op_proto.outputs)
    intermediate_outputs = \
        filter(lambda output: output.intermediate, op_proto.outputs)

    if len(not_intermediate_outputs) != 1:
320 321
        raise ValueError("Only one non intermediate output operator can be",
                         "automatically generated")
Y
Yu Yang 已提交
322

323
    if not_intermediate_outputs[0].duplicable:
Y
Yu Yang 已提交
324
        raise ValueError(
325
            "Only non duplicable op can be automatically generated")
Y
Yu Yang 已提交
326

327 328
    for output in intermediate_outputs:
        if output.duplicable:
329 330
            raise ValueError("The op can be automatically generated only when ",
                             "all intermediate ops are not duplicable")
331 332 333

    o_name = not_intermediate_outputs[0].name
    intermediate_output_names = [output.name for output in intermediate_outputs]
Y
Yu Yang 已提交
334

Y
Yang Yang(Tony) 已提交
335
    def infer_and_check_data_type(op_proto, **kwargs):
336 337 338 339
        """
        This function performs the sanity check for data_type and
        instance type.
        """
Y
Yu Yang 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        dtype = None
        for ipt in op_proto.inputs:
            name = _convert_(ipt.name)
            val = kwargs.pop(name, [])
            if not isinstance(val, list) and not isinstance(val, tuple):
                val = [val]
            for each in val:
                if not isinstance(each, Variable):
                    raise ValueError("input of {0} must be variable".format(
                        op_type))

                if dtype is None:
                    dtype = each.data_type
                elif dtype != each.data_type:
                    raise ValueError(
                        "operator {0} must input same dtype".format(op_type))
Y
Yang Yang(Tony) 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369

        return dtype

    def func(**kwargs):
        helper = LayerHelper(op_type, **kwargs)

        dtype = infer_and_check_data_type(op_proto, **kwargs)

        inputs = dict()
        for ipt in op_proto.inputs:
            name = _convert_(ipt.name)
            val = kwargs.pop(name, [])
            if not isinstance(val, list) and not isinstance(val, tuple):
                val = [val]
Y
Yu Yang 已提交
370 371
            inputs[ipt.name] = val

372
        outputs = dict()
Y
Yu Yang 已提交
373
        out = helper.create_tmp_variable(dtype=dtype)
374 375 376
        outputs[o_name] = [out]
        for name in intermediate_output_names:
            outputs[name] = [helper.create_tmp_variable(dtype=dtype)]
Y
Yu Yang 已提交
377
        helper.append_op(
378
            type=op_type, inputs=inputs, outputs=outputs, attrs=kwargs)
Q
Qiao Longfei 已提交
379
        return helper.append_activation(out)
Y
Yu Yang 已提交
380 381 382

    func.__name__ = op_type
    globals()[op_type] = func
383
    func.__doc__ = _generate_doc_string_(op_proto)
Y
Yu Yang 已提交
384 385 386 387 388
    global __all__
    __all__.append(op_type)


_create_op_func_('mean')
Y
Yu Yang 已提交
389
_create_op_func_('mul')
Q
Qiao Longfei 已提交
390
_create_op_func_('elementwise_add')
391
_create_op_func_('dropout')
Q
Qiao Longfei 已提交
392
_create_op_func_('reshape')
Y
Yu Yang 已提交
393 394 395
_create_op_func_('elementwise_add')
_create_op_func_('sigmoid')
_create_op_func_('scale')
Y
Yang Yang(Tony) 已提交
396 397 398 399 400
_create_op_func_('reshape')
_create_op_func_('transpose')


def fill_constant(data_type, shape, value=None, program=None):
401 402 403 404 405
    """
    This function creates a tensor , with shape as mentioned in the input and
    specified data_type and fills this up with a constant value that
    comes in the input.
    """
Y
Yang Yang(Tony) 已提交
406 407 408 409 410 411 412 413 414
    helper = LayerHelper('fill_constant', **locals())
    out = helper.create_tmp_variable(dtype=data_type)
    helper.append_op(
        type='fill_constant',
        outputs={'Out': [out]},
        attrs={'data_type': data_type,
               'shape': shape,
               'value': value})
    return out
Y
Yu Yang 已提交
415 416


417
def cast(x, data_type, main_program=None):
418 419 420 421
    """
    This function takes in the input with input_data_type
    and casts it to the output_data_type as the output.
    """
Y
Yu Yang 已提交
422 423 424 425 426 427 428 429 430 431 432
    helper = LayerHelper('cast', **locals())
    out = helper.create_tmp_variable(dtype=data_type)
    helper.append_op(
        type='cast',
        inputs={'X': [x]},
        outputs={'Out': [out]},
        attrs={'in_data_type': x.data_type,
               'out_data_type': out.data_type})
    return out


433
def concat(input, axis, main_program=None, startup_program=None):
434 435 436 437
    """
    This function concats the input along the axis mentioned
    and returns that as the output.
    """
Q
QI JUN 已提交
438
    helper = LayerHelper('concat', **locals())
D
dzhwinter 已提交
439
    out = helper.create_tmp_variable(dtype=helper.input_dtype())
Q
QI JUN 已提交
440 441 442 443 444 445 446 447
    helper.append_op(
        type='concat',
        inputs={'X': input},
        outputs={'Out': [out]},
        attrs={'axis': axis})
    return out


448
def sums(input, main_program=None, startup_program=None):
449 450 451 452
    """
    This function takes in the input and performs the sum operation on it
    and returns that as the output.
    """
D
dzhwinter 已提交
453 454
    helper = LayerHelper('sum', **locals())
    out = helper.create_tmp_variable(dtype=helper.input_dtype())
Y
Yu Yang 已提交
455
    helper.append_op(type='sum', inputs={'X': input}, outputs={'Out': out})
D
dzhwinter 已提交
456 457 458
    return out


Y
Yu Yang 已提交
459 460 461 462 463 464 465 466 467 468
def assign(input, output, main_program=None):
    helper = LayerHelper('assign', **locals())
    helper.append_op(
        type='scale',
        inputs={'X': [input]},
        outputs={'Out': [output]},
        attrs={'scale': 1.0})
    return output


469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
def split_lod_tensor(input,
                     mask,
                     level,
                     main_program=None,
                     startup_program=None):
    helper = LayerHelper('split_lod_tensor', **locals())
    out_true = helper.create_tmp_variable(dtype=input.data_type)
    out_false = helper.create_tmp_variable(dtype=input.data_type)
    helper.append_op(
        type='split_lod_tensor',
        inputs={
            'X': input,
            'Mask': mask,
        },
        outputs={'OutTrue': out_true,
                 'OutFalse': out_false},
        attrs={'level': level})
    return out_true, out_false


def merge_lod_tensor(in_true,
                     in_false,
                     x,
                     mask,
                     level,
                     main_program=None,
                     startup_program=None):
    helper = LayerHelper('merge_lod_tensor', **locals())
    out = helper.create_tmp_variable(dtype=x.data_type)
    helper.append_op(
        type='merge_lod_tensor',
        inputs={'X': x,
                'Mask': mask,
                'InTrue': in_true,
                'InFalse': in_false},
        outputs={'Out': out},
        attrs={'level': level})
    return out


509
def cos_sim(X, Y, **kwargs):
510 511 512 513
    """
    This function performs the cosine similarity between two tensors
    X and Y and returns that as the output.
    """
514 515 516 517
    helper = LayerHelper('cos_sim', **kwargs)
    out = helper.create_tmp_variable(dtype=X.data_type)
    xnorm = helper.create_tmp_variable(dtype=X.data_type)
    ynorm = helper.create_tmp_variable(dtype=X.data_type)
D
dzhwinter 已提交
518 519 520 521 522 523 524
    helper.append_op(
        type='cos_sim',
        inputs={'X': [X],
                'Y': [Y]},
        outputs={'Out': [out],
                 'XNorm': [xnorm],
                 'YNorm': [ynorm]})
525
    return out
D
dzhwinter 已提交
526 527


Y
Yu Yang 已提交
528
def cross_entropy(input, label, **kwargs):
529 530 531
    """
    This function computes cross_entropy using the input and label.
    """
Y
Yu Yang 已提交
532 533 534 535 536 537 538 539 540 541 542 543
    helper = LayerHelper('cross_entropy', **kwargs)
    out = helper.create_tmp_variable(dtype=input.data_type)
    helper.append_op(
        type='cross_entropy',
        inputs={'X': [input],
                'Label': [label]},
        outputs={'Y': [out]},
        attrs=kwargs)
    return out


def square_error_cost(input, label, **kwargs):
544 545 546 547
    """
    This functions returns the squared error cost using the input and label.
    The output is appending the op to do the above.
    """
Y
Yu Yang 已提交
548 549 550 551 552 553 554 555 556 557
    helper = LayerHelper('square_error_cost', **kwargs)
    minus_out = helper.create_tmp_variable(dtype=input.data_type)
    helper.append_op(
        type='elementwise_sub',
        inputs={'X': [input],
                'Y': [label]},
        outputs={'Out': [minus_out]})

    square_out = helper.create_tmp_variable(dtype=input.data_type)
    helper.append_op(
Q
QI JUN 已提交
558
        type='square', inputs={'X': [minus_out]}, outputs={'Y': [square_out]})
Y
Yu Yang 已提交
559
    return square_out
560 561


F
fengjiayi 已提交
562
def accuracy(input, label, k=1, **kwargs):
563 564 565 566
    """
    This function computes the accuracy using the input and label.
    The output is the top_k inputs and their indices.
    """
F
fengjiayi 已提交
567 568 569 570 571 572 573 574 575 576
    helper = LayerHelper("accuracy", **kwargs)
    topk_out = helper.create_tmp_variable(dtype=input.data_type)
    topk_indices = helper.create_tmp_variable(dtype="int64")
    helper.append_op(
        type="top_k",
        inputs={"X": [input]},
        outputs={"Out": [topk_out],
                 "Indices": [topk_indices]},
        attrs={"k": k})
    acc_out_dtype = kwargs.get("out_dtype", "float32")
D
Dong Zhihong 已提交
577 578 579
    acc_out = helper.create_tmp_variable(dtype="float32")
    correct = helper.create_tmp_variable(dtype="int64")
    total = helper.create_tmp_variable(dtype="int64")
F
fengjiayi 已提交
580 581
    helper.append_op(
        type="accuracy",
武毅 已提交
582 583 584 585 586
        inputs={
            "Out": [topk_out],
            "Indices": [topk_indices],
            "Label": [label]
        },
D
Dong Zhihong 已提交
587 588 589 590 591
        outputs={
            "Accuracy": [acc_out],
            "Correct": [correct],
            "Total": [total],
        })
F
fengjiayi 已提交
592 593 594
    return acc_out


D
dzhwinter 已提交
595 596 597
def sequence_conv(input,
                  num_filters,
                  filter_size=3,
598
                  filter_stride=1,
599
                  act=None,
D
dzhwinter 已提交
600 601 602
                  padding=None,
                  bias_attr=None,
                  param_attr=None,
603 604
                  main_program=None,
                  startup_program=None):
605 606 607 608 609
    """
    This function creates the op for sequence_conv, using the inputs and
    other convolutional configurations for the filters and stride as given
    in the input parameters to the function.
    """
D
dzhwinter 已提交
610 611 612 613 614 615 616
    # FIXME(dzh) : want to unify the argument of python layer
    # function. So we ignore some unecessary attributes.
    # such as, padding_trainable, context_start.

    helper = LayerHelper('sequence_conv', **locals())
    dtype = helper.input_dtype()

D
dzhwinter 已提交
617
    filter_shape = [filter_size * input.shape[1], num_filters]
D
dzhwinter 已提交
618 619 620 621 622 623 624 625
    filter = helper.create_parameter(
        attr=helper.param_attr, shape=filter_shape, dtype=dtype)
    pre_bias = helper.create_tmp_variable(dtype)

    helper.append_op(
        type='sequence_conv',
        inputs={
            'X': [input],
D
dzhwinter 已提交
626
            'Filter': [filter],
D
dzhwinter 已提交
627 628 629
        },
        outputs={"Out": pre_bias},
        attrs={
630
            'contextStride': filter_stride,
631
            'contextStart': -int(filter_size / 2),
632
            'contextLength': filter_size
D
dzhwinter 已提交
633 634 635 636 637
        })
    pre_act = helper.append_bias_op(pre_bias)
    return helper.append_activation(pre_act)


F
fengjiayi 已提交
638 639 640 641 642 643 644 645 646 647
def conv2d(input,
           num_filters,
           name=None,
           filter_size=[1, 1],
           act=None,
           groups=None,
           stride=[1, 1],
           padding=None,
           bias_attr=None,
           param_attr=None,
648 649
           main_program=None,
           startup_program=None):
650 651 652 653 654 655 656
    """
    This function creates the op for a 2-dimensional Convolution.
    This is performed using the parameters of filters(size, dimensionality etc)
    , stride and other configurations for a Convolution operation.
    This funciton can also append an activation on top of the
    conv-2d output, if mentioned in the input parameters.
    """
657 658 659 660 661 662 663 664 665 666 667
    helper = LayerHelper('conv2d', **locals())
    dtype = helper.input_dtype()

    num_channels = input.shape[1]
    if groups is None:
        num_filter_channels = num_channels
    else:
        if num_channels % groups is not 0:
            raise ValueError("num_channels must be divisible by groups.")
        num_filter_channels = num_channels / groups

F
fengjiayi 已提交
668 669 670 671 672 673 674
    if isinstance(filter_size, int):
        filter_size = [filter_size, filter_size]
    if isinstance(stride, int):
        stride = [stride, stride]
    if isinstance(padding, int):
        padding = [padding, padding]

675 676
    input_shape = input.shape
    filter_shape = [num_filters, num_filter_channels] + filter_size
677 678

    std = (2.0 / (filter_size[0]**2 * num_channels))**0.5
679
    filter = helper.create_parameter(
680 681 682 683
        attr=helper.param_attr,
        shape=filter_shape,
        dtype=dtype,
        initializer=NormalInitializer(0.0, std, 0))
684 685 686 687 688 689 690 691 692 693 694 695 696
    pre_bias = helper.create_tmp_variable(dtype)

    helper.append_op(
        type='conv2d',
        inputs={
            'Input': input,
            'Filter': filter,
        },
        outputs={"Output": pre_bias},
        attrs={'strides': stride,
               'paddings': padding,
               'groups': groups})

X
xuwei06 已提交
697
    pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2)
698 699

    return helper.append_activation(pre_act)
F
fengjiayi 已提交
700 701


D
dzhwinter 已提交
702
def sequence_pool(input, pool_type, **kwargs):
703 704 705 706 707
    """
    This function add the operator for sequence pooling.
    This is applied on top of the input using pool_type mentioned
    in the parameters.
    """
708
    helper = LayerHelper('sequence_pool', input=input, **kwargs)
D
dzhwinter 已提交
709 710
    dtype = helper.input_dtype()
    pool_out = helper.create_tmp_variable(dtype)
D
dangqingqing 已提交
711
    max_index = helper.create_tmp_variable(dtype)
D
dzhwinter 已提交
712 713 714

    helper.append_op(
        type="sequence_pool",
D
dangqingqing 已提交
715 716 717
        inputs={"X": input},
        outputs={"Out": pool_out,
                 "MaxIndex": max_index},
D
dzhwinter 已提交
718
        attrs={"pooltype": pool_type.upper()})
D
dzhwinter 已提交
719 720 721 722

    return pool_out


F
fengjiayi 已提交
723 724 725 726 727 728
def pool2d(input,
           pool_size,
           pool_type,
           pool_stride=[1, 1],
           pool_padding=[0, 0],
           global_pooling=False,
729 730
           main_program=None,
           startup_program=None):
731 732 733 734
    """
    This function adds the operator for pooling in 2 dimensions, using the
    pooling configurations mentioned in input parameters.
    """
F
fengjiayi 已提交
735 736 737 738 739 740 741 742 743 744 745
    if pool_type not in ["max", "avg"]:
        raise ValueError(
            "Unknown pool_type: '%s'. It can only be 'max' or 'avg'.",
            str(pool_type))
    if isinstance(pool_size, int):
        pool_size = [pool_size, pool_size]
    if isinstance(pool_stride, int):
        pool_stride = [pool_stride, pool_stride]
    if isinstance(pool_padding, int):
        pool_padding = [pool_padding, pool_padding]

D
dzhwinter 已提交
746
    helper = LayerHelper('pool2d', **locals())
F
fengjiayi 已提交
747 748 749 750 751 752 753 754
    dtype = helper.input_dtype()
    pool_out = helper.create_tmp_variable(dtype)

    helper.append_op(
        type="pool2d",
        inputs={"X": input},
        outputs={"Out": pool_out},
        attrs={
C
chengduoZH 已提交
755
            "pooling_type": pool_type,
F
fengjiayi 已提交
756
            "ksize": pool_size,
C
chengduoZH 已提交
757
            "global_pooling": global_pooling,
F
fengjiayi 已提交
758 759 760 761 762
            "strides": pool_stride,
            "paddings": pool_padding
        })

    return pool_out
Y
Yu Yang 已提交
763 764


Q
Qiao Longfei 已提交
765 766 767 768
def batch_norm(input,
               act=None,
               is_test=False,
               momentum=0.9,
769
               epsilon=1e-05,
Q
Qiao Longfei 已提交
770 771 772
               param_attr=None,
               bias_attr=None,
               data_layout='NCHW',
773 774
               main_program=None,
               startup_program=None):
775 776 777 778
    """
    This function helps create an operator to implement
    the BatchNorm layer using the configurations from the input parameters.
    """
Q
Qiao Longfei 已提交
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
    helper = LayerHelper('batch_norm', **locals())
    dtype = helper.input_dtype()

    input_shape = input.shape
    if data_layout == 'NCHW':
        channel_num = input_shape[1]
    else:
        if data_layout == 'NHWC':
            channel_num = input_shape[-1]
        else:
            raise ValueError("unsupported data layout:" + data_layout)

    param_shape = [channel_num]

    # create parameter
    scale = helper.create_parameter(
795 796 797 798
        attr=helper.param_attr,
        shape=param_shape,
        dtype=dtype,
        initializer=ConstantInitializer(1.0))
Q
Qiao Longfei 已提交
799
    bias = helper.create_parameter(
800 801 802 803 804 805 806 807 808 809 810 811 812 813
        attr=helper.param_attr,
        shape=param_shape,
        dtype=dtype,
        initializer=ConstantInitializer(0.0))

    mean = helper.create_global_variable(
        dtype=input.data_type, shape=param_shape, persistable=True)
    helper.set_variable_initializer(
        var=mean, initializer=ConstantInitializer(0.0))

    variance = helper.create_global_variable(
        dtype=input.data_type, shape=param_shape, persistable=True)
    helper.set_variable_initializer(
        var=variance, initializer=ConstantInitializer(1.0))
Q
Qiao Longfei 已提交
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847

    # create output
    # mean and mean_out share the same memory
    mean_out = mean
    # variance and variance out share the same memory
    variance_out = variance
    saved_mean = helper.create_tmp_variable(dtype)
    saved_variance = helper.create_tmp_variable(dtype)

    batch_norm_out = helper.create_tmp_variable(dtype)

    helper.append_op(
        type="batch_norm",
        inputs={
            "X": input,
            "Scale": scale,
            "Bias": bias,
            "Mean": mean,
            "Variance": variance
        },
        outputs={
            "Y": batch_norm_out,
            "MeanOut": mean_out,
            "VarianceOut": variance_out,
            "SavedMean": saved_mean,
            "SavedVariance": saved_variance
        },
        attrs={"momentum": momentum,
               "epsilon": epsilon,
               "is_test": is_test})

    return helper.append_activation(batch_norm_out)


848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
def beam_search_decode(ids, scores, main_program=None, startup_program=None):
    helper = LayerHelper('beam_search_decode', **locals())
    sentence_ids = helper.create_tmp_variable(dtype=ids.data_type)
    sentence_scores = helper.create_tmp_variable(dtype=ids.data_type)

    helper.append_op(
        type="beam_search_decode",
        inputs={"Ids": ids,
                "Scores": scores},
        outputs={
            "SentenceIds": sentence_ids,
            "SentenceScores": sentence_scores
        })

    return sentence_ids, sentence_scores


Y
Yu Yang 已提交
865 866
class BlockGuard(object):
    """
867 868 869 870
    BlockGuard class.

    BlockGuard class is used to create a sub-block in a program by
    using the Python `with` keyword.
Y
Yu Yang 已提交
871 872
    """

873 874
    def __init__(self, main_program):
        if not isinstance(main_program, Program):
Y
Yu Yang 已提交
875
            raise TypeError("BlockGuard takes a program")
876
        self.main_program = main_program
Y
Yu Yang 已提交
877 878

    def __enter__(self):
879
        self.main_program.create_block()
Y
Yu Yang 已提交
880 881

    def __exit__(self, exc_type, exc_val, exc_tb):
882
        self.main_program.rollback()
Y
Yu Yang 已提交
883 884 885 886 887 888
        if exc_type is not None:
            return False  # re-raise exception
        return True


class StaticRNNGuard(BlockGuard):
889 890 891 892 893 894
    """
    StaticRNNGuard class.

    StaticRNNGuard class is used to create a StaticRNN block in a program.
    """

Y
Yu Yang 已提交
895 896
    def __init__(self, rnn):
        if not isinstance(rnn, StaticRNN):
Y
Yang Yang(Tony) 已提交
897
            raise TypeError("StaticRNNGuard takes a StaticRNN")
898
        super(StaticRNNGuard, self).__init__(rnn.helper.main_program)
Y
Yu Yang 已提交
899 900 901 902 903 904 905
        self.rnn = rnn

    def __enter__(self):
        self.rnn.status = StaticRNN.IN_RNN_BLOCK
        return super(StaticRNNGuard, self).__enter__()

    def __exit__(self, exc_type, exc_val, exc_tb):
Y
Yu Yang 已提交
906 907
        if exc_type is not None:
            return False
Y
Yu Yang 已提交
908 909 910 911 912 913 914
        self.rnn.status = StaticRNN.AFTER_RNN_BLOCK
        self.rnn.complete_rnn_op()
        return super(StaticRNNGuard, self).__exit__(exc_type, exc_val, exc_tb)


class StaticRNNMemoryLink(object):
    """
915 916 917 918 919 920 921 922 923 924 925 926
    StaticRNNMemoryLink class.

    Args:
        init: the initial variable for Memory
        init: Variable
        pre_mem: the memory variable in previous time step
        pre_mem: Variable
        mem: the memory variable in current time step
        mem: Variable

    StaticRNNMemoryLink class is used to create a link between two
    memory cells of a StaticRNN.
Y
Yu Yang 已提交
927 928 929 930 931 932 933 934 935
    """

    def __init__(self, init, pre_mem, mem=None):
        self.init = init
        self.pre_mem = pre_mem
        self.mem = mem


class StaticRNN(object):
936 937 938 939 940 941
    """
    StaticRNN class.

    StaticRNN class is used to create a StaticRNN. The RNN will have its
    own parameters like inputs, outputs, memories, status and length.
    """
Y
Yu Yang 已提交
942 943 944 945
    BEFORE_RNN_BLOCK = 0
    IN_RNN_BLOCK = 1
    AFTER_RNN_BLOCK = 2

946 947 948
    def __init__(self, name=None, main_program=None):
        self.helper = LayerHelper(
            "static_rnn", name=name, main_program=main_program)
Y
Yu Yang 已提交
949 950 951 952 953 954 955 956 957 958 959 960 961 962
        self.memories = {}  # memory map, from pre_mem.name --> MemoryLink
        self.inputs = []  # input variable list in current block
        self.outputs = []  # output variable list in parent block
        self.status = StaticRNN.BEFORE_RNN_BLOCK  # status flag.
        # sequence length, since it is a static RNN, sequence length are fixed.
        self.seq_len = None

    def step(self):
        return StaticRNNGuard(self)

    def _assert_in_rnn_block_(self, method):
        if self.status != StaticRNN.IN_RNN_BLOCK:
            raise ValueError("You must invoke {0} in rnn block".format(method))

963 964 965 966 967 968 969
    def memory(self,
               init=None,
               shape=None,
               batch_ref=None,
               init_value=0.0,
               init_batch_dim_idx=0,
               ref_batch_dim_idx=1):
970 971 972 973 974 975 976 977 978
        """
        Args:
            init: boot memory, if not set, a shape, batch_ref must be provided
            shape: shape of the boot memory
            batch_ref: batch size reference variable
            init_value: the init value of boot memory
            init_batch_dim_idx: the index of batch size in init's dimension
            ref_batch_dim_idx: the index of batch size in batch_ref's dimension
        """
Y
Yu Yang 已提交
979 980
        self._assert_in_rnn_block_('memory')
        if init is None:
981
            if shape is None or batch_ref is None:
Y
Yu Yang 已提交
982
                raise ValueError(
983
                    "if init is None, memory at least need shape and batch_ref")
Y
Yu Yang 已提交
984 985 986
            parent_block = self.parent_block()
            var_name = unique_name("@".join([self.helper.name, "memory_boot"]))
            boot_var = parent_block.create_var(
987 988 989 990
                name=var_name,
                shape=shape,
                dtype=batch_ref.data_type,
                persistable=False)
Y
Yu Yang 已提交
991 992

            parent_block.append_op(
993 994
                type="fill_constant_batch_size_like",
                inputs={'Input': [batch_ref]},
Y
Yu Yang 已提交
995 996 997
                outputs={'Out': [boot_var]},
                attrs={
                    'value': init_value,
998 999 1000 1001
                    'shape': boot_var.shape,
                    'data_type': boot_var.data_type,
                    'input_dim_idx': ref_batch_dim_idx,
                    'output_dim_idx': init_batch_dim_idx
Y
Yu Yang 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
                })

            return self.memory(init=boot_var)
        else:
            pre_mem = self.helper.create_variable(
                name=unique_name("@".join([self.helper.name, "mem"])),
                dtype=init.data_type,
                shape=init.shape)
            self.memories[pre_mem.name] = StaticRNNMemoryLink(
                init=init, pre_mem=pre_mem)
            return pre_mem

    def step_input(self, x):
        self._assert_in_rnn_block_('step_input')
        if not isinstance(x, Variable):
            raise TypeError("step input takes a Variable")
        if self.seq_len is None:
Y
Yu Yang 已提交
1019 1020
            self.seq_len = x.shape[0]
        elif self.seq_len != x.shape[0]:
Y
Yu Yang 已提交
1021 1022 1023 1024 1025
            raise ValueError("Static RNN only take fix seq_len input")

        ipt = self.helper.create_variable(
            name=x.name,
            dtype=x.data_type,
Y
Yu Yang 已提交
1026
            shape=list(x.shape[1:]),
Y
Yu Yang 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035
            type=x.type)
        self.inputs.append(ipt)
        return ipt

    def step_output(self, o):
        self._assert_in_rnn_block_('step_output')
        if not isinstance(o, Variable):
            raise TypeError("step output takes a Variable")

Y
Yu Yang 已提交
1036 1037 1038 1039 1040 1041 1042
        tmp_o = self.helper.create_tmp_variable(dtype=o.data_type)
        self.helper.append_op(
            type='rnn_memory_helper',
            inputs={'X': [o]},
            outputs={'Out': tmp_o},
            attrs={'data_type': o.data_type})

Y
Yu Yang 已提交
1043
        out_var = self.parent_block().create_var(
Y
Yu Yang 已提交
1044 1045 1046
            name=tmp_o.name,
            shape=[self.seq_len] + list(tmp_o.shape),
            dtype=tmp_o.data_type)
Y
Yu Yang 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

        self.outputs.append(out_var)

    def output(self, *outputs):
        for each in outputs:
            self.step_output(each)

    def update_memory(self, mem, var):
        if not isinstance(mem, Variable) or not isinstance(var, Variable):
            raise TypeError("update memory should take variables")
        self.memories[mem.name].mem = var

    def parent_block(self):
1060
        prog = self.helper.main_program
Y
Yu Yang 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
        parent_idx = prog.current_block().parent_idx
        assert parent_idx >= 0
        parent_block = prog.block(parent_idx)
        return parent_block

    def __call__(self, *args, **kwargs):
        if self.status != StaticRNN.AFTER_RNN_BLOCK:
            raise ValueError("RNN output can only be retrieved after rnn block")
        if len(self.outputs) == 0:
            raise ValueError("RNN has no output")
        elif len(self.outputs) == 1:
            return self.outputs[0]
        else:
            return self.outputs

    def complete_rnn_op(self):
1077 1078
        main_program = self.helper.main_program
        rnn_block = main_program.current_block()
Y
Yu Yang 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 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 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
        parent_block = self.parent_block()

        local_inputs = set()

        for op in rnn_block.ops:
            assert isinstance(op, Operator)
            for oname in op.output_names:
                for out_var_name in op.output(oname):
                    local_inputs.add(out_var_name)

        for var in self.inputs:
            local_inputs.add(var.name)
        for m in self.memories:
            local_inputs.add(m)

        params = list()
        for op in rnn_block.ops:
            assert isinstance(op, Operator)
            for iname in op.input_names:
                for in_var_name in op.input(iname):
                    if in_var_name not in local_inputs:
                        params.append(in_var_name)

        parameters = [parent_block.var(name) for name in params]

        step_scope = parent_block.create_var(
            type=core.VarDesc.VarType.STEP_SCOPES)

        inlinks = [parent_block.var(i.name) for i in self.inputs]
        outlinks = self.outputs

        boot_memories = []
        pre_memories = []
        memories = []
        for _, mem in self.memories.iteritems():
            boot_memories.append(mem.init)
            pre_memories.append(mem.pre_mem.name)
            mem_var = rnn_block.var(mem.mem.name)
            assert isinstance(mem_var, Variable)
            new_mem = self.helper.create_tmp_variable(dtype=mem_var.data_type)

            rnn_block.append_op(
                type='rnn_memory_helper',
                inputs={'X': [mem_var]},
                outputs={'Out': [new_mem]},
                attrs={'data_type': mem_var.data_type})

            memories.append(new_mem.name)

        parent_block.append_op(
            type='recurrent',
            inputs={
                'inputs': inlinks,
                'initial_states': boot_memories,
                'parameters': parameters
            },
            outputs={'outputs': outlinks,
                     'step_scopes': [step_scope]},
            attrs={
                'ex_states': pre_memories,
                'states': memories,
                'step_block': rnn_block
            })
Y
Yu Yang 已提交
1142 1143


Y
Yang Yang(Tony) 已提交
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 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 1188 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
class WhileGuard(BlockGuard):
    def __init__(self, while_op):
        if not isinstance(while_op, While):
            raise TypeError("WhileGuard takes a while op")
        super(WhileGuard, self).__init__(while_op.helper.main_program)
        self.while_op = while_op

    def __enter__(self):
        self.while_op.status = While.IN_WHILE_BLOCK
        return super(WhileGuard, self).__enter__()

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is not None:
            return False
        self.while_op.status = While.AFTER_WHILE_BLOCK
        self.while_op.complete()
        return super(WhileGuard, self).__exit__(exc_type, exc_val, exc_tb)


class While(object):
    BEFORE_WHILE_BLOCK = 0
    IN_WHILE_BLOCK = 1
    AFTER_WHILE_BLOCK = 2

    def __init__(self, cond, name=None, main_program=None):
        self.helper = LayerHelper("while", name=name, main_program=main_program)
        self.status = While.BEFORE_WHILE_BLOCK
        if not isinstance(cond, Variable):
            raise TypeError("condition should be a variable")
        assert isinstance(cond, Variable)
        if cond.data_type != core.DataType.BOOL:
            raise TypeError("condition should be a bool variable")
        if reduce(lambda a, b: a * b, cond.shape, 1) != 1:
            raise TypeError("condition should be a bool scalar")
        self.cond_var = cond

    def block(self):
        return WhileGuard(self)

    def complete(self):
        main_program = self.helper.main_program
        while_block = main_program.current_block()
        parent_block = main_program.block(main_program.current_block()
                                          .parent_idx)

        inner_outputs = {self.cond_var.name}
        x_name_list = set()
        for op in while_block.ops:
            for iname in op.input_names:
                for in_var_name in op.input(iname):
                    if in_var_name not in inner_outputs:
                        x_name_list.add(in_var_name)

            for oname in op.output_names:
                for out_var_name in op.output(oname):
                    inner_outputs.add(out_var_name)

        out_vars = []
        for inner_out_name in inner_outputs:
            if inner_out_name in parent_block.vars:
                out_vars.append(parent_block.var(inner_out_name))

        step_scope = parent_block.create_var(
            type=core.VarDesc.VarType.STEP_SCOPES)

        parent_block.append_op(
            type='while',
            inputs={
                'X': [parent_block.var(x_name) for x_name in x_name_list],
                'Condition': [self.cond_var]
            },
            outputs={'Out': out_vars,
                     'StepScopes': [step_scope]},
            attrs={'step_block': while_block})


Y
Yang Yang(Tony) 已提交
1220 1221 1222 1223 1224 1225
def lstm(x,
         c_pre_init,
         hidden_dim,
         forget_bias=None,
         main_program=None,
         startup_program=None):
1226 1227 1228 1229
    """
    This function helps create an operator for the LSTM (Long Short Term
    Memory) cell that can be used inside an RNN.
    """
Y
Yang Yang(Tony) 已提交
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    helper = LayerHelper('lstm_unit', **locals())
    rnn = StaticRNN()
    with rnn.step():
        c_pre = rnn.memory(init=c_pre_init)
        x_t = rnn.step_input(x)

        before_fc = concat(
            input=[x_t, c_pre],
            axis=1,
            main_program=main_program,
            startup_program=startup_program)
        after_fc = fc(input=before_fc,
                      size=hidden_dim * 4,
                      main_program=main_program,
                      startup_program=startup_program)

        data_type = x.data_type
        c = helper.create_tmp_variable(data_type)
        h = helper.create_tmp_variable(data_type)

        helper.append_op(
            type='lstm_unit',
            inputs={"X": after_fc,
                    "C_prev": c_pre},
            outputs={"C": c,
                     "H": h},
            attrs={"forget_bias": forget_bias})

        rnn.update_memory(c_pre, c)
        rnn.output(h)

    return rnn()


1264
def lod_rank_table(x, level=0, main_program=None):
1265 1266 1267 1268
    """
    This function creates an operator for creating a LOD_RANK_TABLE
    using the input x.
    """
Y
Yu Yang 已提交
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
    helper = LayerHelper("lod_rank_table", **locals())
    table = helper.create_variable(
        type=core.VarDesc.VarType.LOD_RANK_TABLE,
        name=unique_name("lod_rank_table"))
    helper.append_op(
        type='lod_rank_table',
        inputs={'X': x},
        outputs={'Out': table},
        attrs={'level': level})
    return table
Y
Yu Yang 已提交
1279 1280


1281
def lod_tensor_to_array(x, table, main_program=None):
1282 1283 1284 1285
    """
    This function creates an operator to convert an LOD_Tensor to
    an array.
    """
1286 1287 1288
    helper = LayerHelper("lod_tensor_to_array", **locals())
    array = helper.create_variable(
        name=unique_name("lod_tensor_to_array"),
1289 1290
        type=core.VarDesc.VarType.LOD_TENSOR_ARRAY,
        dtype=x.data_type)
1291 1292 1293 1294 1295 1296 1297 1298 1299
    helper.append_op(
        type='lod_tensor_to_array',
        inputs={'X': x,
                'RankTable': table},
        outputs={'Out': array})
    return array


def array_to_lod_tensor(x, table, main_program=None):
1300 1301 1302 1303
    """
    This function creates an operator to convert an array to a
    LOD_Tensor.
    """
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    helper = LayerHelper("array_to_lod_tensor", **locals())
    tmp = helper.create_tmp_variable(dtype=x.data_type)
    helper.append_op(
        type="array_to_lod_tensor",
        inputs={'X': x,
                'RankTable': table},
        outputs={'Out': tmp})
    return tmp


Y
Yu Yang 已提交
1314
def fill_constant(shape, dtype, value, main_program=None):
1315 1316 1317 1318 1319
    """
    This function creates a tensor , with shape as mentioned in the input and
    specified data_type and fills this up with a constant value that
    comes in the input. It also sets the stop_gradient to be True.
    """
Y
Yang Yu 已提交
1320
    helper = LayerHelper("fill_constant", **locals())
Y
Yu Yang 已提交
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
    out = helper.create_tmp_variable(dtype=dtype)
    helper.append_op(
        type='fill_constant',
        inputs={},
        outputs={'Out': [out]},
        attrs={
            'shape': shape,
            'data_type': out.data_type,
            'value': float(value)
        })
    out.stop_gradient = True
    return out


def ones(shape, dtype, main_program=None):
1336 1337 1338 1339
    """
    This function performs the same function as fill_constant() declared above
    with the constant value being 1.0.
    """
Y
Yu Yang 已提交
1340 1341 1342 1343
    return fill_constant(value=1.0, **locals())


def zeros(shape, dtype, main_program=None):
1344 1345 1346 1347
    """
    This function performs the same function as fill_constant() declared above
    with the constant value being 0.0.
    """
Y
Yu Yang 已提交
1348 1349 1350
    return fill_constant(value=0.0, **locals())


1351
def increment(x, value=1.0, in_place=True, main_program=None):
1352 1353 1354 1355 1356
    """
    This function creates an operator to increment each value in the input
    `x` by an amount: `value` as mentioned in the input parameter. This
    operation is performed in-place by default.
    """
Y
Yu Yang 已提交
1357
    helper = LayerHelper("increment", **locals())
Y
Yang Yang(Tony) 已提交
1358
    if not in_place:
1359
        out = helper.create_tmp_variable(dtype=x.data_type)
Y
Yang Yang(Tony) 已提交
1360 1361
    else:
        out = x
Y
Yu Yang 已提交
1362 1363 1364
    helper.append_op(
        type='increment',
        inputs={'X': [x]},
Y
Yang Yu 已提交
1365
        outputs={'Out': [out]},
Y
Yu Yang 已提交
1366
        attrs={'step': value})
Y
Yang Yu 已提交
1367
    return out
Y
Yu Yang 已提交
1368 1369 1370


def array_write(x, i, array=None, main_program=None):
1371 1372 1373 1374
    """
    This function creates an operator to write the data out as a
    LOD_TENSOR_ARRAY.
    """
Y
Yu Yang 已提交
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
    helper = LayerHelper('array_write', **locals())
    if array is None:
        array = helper.create_variable(
            name="{0}.out".format(helper.name),
            type=core.VarDesc.VarType.LOD_TENSOR_ARRAY,
            dtype=x.data_type)
    helper.append_op(
        type='write_to_array',
        inputs={'X': [x],
                'I': [i]},
        outputs={'Out': [array]})
    return array


Y
Yang Yang(Tony) 已提交
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
def create_array(dtype, main_program=None):
    helper = LayerHelper("array", **locals())
    return helper.create_variable(
        name="{0}.out".format(helper.name),
        type=core.VarDesc.VarType.LOD_TENSOR_ARRAY,
        dtype=dtype)


def less_than(x, y, cond=None, main_program=None):
    helper = LayerHelper("less_than", **locals())
    if cond is None:
        cond = helper.create_tmp_variable(dtype='bool')
        cond.stop_gradient = True

    helper.append_op(
        type='less_than', inputs={'X': [x],
                                  'Y': [y]}, outputs={'Out': [cond]})
    return cond


Y
Yu Yang 已提交
1409
def array_read(array, i, main_program=None):
1410 1411 1412 1413
    """
    This function creates an operator to read the data in as a
    LOD_TENSOR_ARRAY.
    """
Y
Yu Yang 已提交
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
    helper = LayerHelper('array_read', **locals())
    if not isinstance(
            array,
            Variable) or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY:
        raise TypeError("array should be tensor array vairable")
    out = helper.create_tmp_variable(dtype=array.data_type)
    helper.append_op(
        type='read_from_array',
        inputs={'X': [array],
                'I': [i]},
        outputs={'Out': [out]})
    return out
Y
Yang Yu 已提交
1426 1427 1428


def shrink_memory(x, i, table, main_program=None):
1429 1430 1431 1432
    """
    This function creates an operator to shrink_rnn_memory using the RankTable
    as mentioned in the input parameter.
    """
Y
Yang Yu 已提交
1433 1434 1435
    helper = LayerHelper('shrink_memory', **locals())
    out = helper.create_tmp_variable(dtype=x.data_type)
    helper.append_op(
Y
Yang Yu 已提交
1436
        type='shrink_rnn_memory',
Y
Yang Yu 已提交
1437 1438 1439 1440 1441 1442
        inputs={'X': [x],
                'I': [i],
                'RankTable': [table]},
        outputs={'Out': [out]},
        attrs={})
    return out
Y
Yang Yu 已提交
1443 1444 1445


def array_length(array, main_program=None):
1446 1447 1448 1449
    """
    This function creates an operator to find the length of the
    LOD_TENSOR_ARRAY.
    """
Y
Yang Yu 已提交
1450 1451 1452 1453 1454 1455
    helper = LayerHelper('array_length', **locals())
    tmp = helper.create_tmp_variable(dtype='int64')
    tmp.stop_gradient = True
    helper.append_op(
        type='lod_array_length', inputs={'X': [array]}, outputs={'Out': [tmp]})
    return tmp
Y
Yu Yang 已提交
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525


class ConditionalBlockGuard(BlockGuard):
    def __init__(self, block):
        if not isinstance(block, ConditionalBlock):
            raise TypeError("block should be conditional block")
        super(ConditionalBlockGuard, self).__init__(block.helper.main_program)
        self.block = block

    def __enter__(self):
        return super(ConditionalBlockGuard, self).__enter__()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.block.complete()
        return super(ConditionalBlockGuard, self).__exit__(exc_type, exc_val,
                                                           exc_tb)


class ConditionalBlock(object):
    def __init__(self, inputs, name=None, main_program=None):
        for each_input in inputs:
            if not isinstance(each_input, Variable):
                raise TypeError("Each input should be variable")
        self.inputs = inputs
        self.helper = LayerHelper(
            'conditional_block', name=name, main_program=main_program)

    def block(self):
        return ConditionalBlockGuard(self)

    def complete(self):
        inside_block = self.helper.main_program.current_block()
        parent_block = self.helper.main_program.block(inside_block.parent_idx)

        intermediate = set()
        params = set()

        for each_op in inside_block.ops:
            assert isinstance(each_op, Operator)
            for iname in each_op.input_names:
                for in_var_name in each_op.input(iname):
                    if in_var_name not in intermediate:
                        params.add(in_var_name)

            for oname in each_op.output_names:
                for out_var_name in each_op.output(oname):
                    intermediate.add(out_var_name)
        input_set = set([ipt.name for ipt in self.inputs])

        param_list = [
            parent_block.var(each_name) for each_name in params
            if each_name not in input_set
        ]

        out_list = [
            parent_block.var(var_name) for var_name in parent_block.vars
            if var_name not in intermediate
        ]

        step_scope = parent_block.create_var(
            type=core.VarDesc.VarType.STEP_SCOPES)
        parent_block.append_op(
            type='conditional_block',
            inputs={
                'X': self.inputs,
                'Params': param_list,
            },
            outputs={'Out': out_list,
                     'Scope': [step_scope]},
            attrs={'block': inside_block})