layers.py 66.8 KB
Newer Older
D
dzhwinter 已提交
1 2
import contextlib

3
import proto.framework_pb2 as framework_pb2
D
dzhwinter 已提交
4
import core
5
from framework import OpProtoHolder, Variable, Program, Operator
6
from initializer import Constant, Normal, Xavier, Initializer
Q
Qiao Longfei 已提交
7
from paddle.v2.fluid.layer_helper import LayerHelper, unique_name
D
dzhwinter 已提交
8
from registry import register_layer
Y
Yu Yang 已提交
9
from param_attr import ParamAttr
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', 'While'
Q
QI JUN 已提交
15
]
Y
Yu Yang 已提交
16

D
dzhwinter 已提交
17 18 19 20 21 22 23 24 25
_REGISTER_LAYER_FROM_OPS = [
    'mean', 'mul', 'elementwise_add', 'elementwise_div', 'dropout', 'reshape',
    'sigmoid', 'scale', 'transpose', 'sigmoid_cross_entropy_with_logits'
]

for _OP in set(_REGISTER_LAYER_FROM_OPS):
    globals()[_OP] = register_layer(_OP)
    __all__.append(_OP)

Y
Yu Yang 已提交
26

F
fengjiayi 已提交
27 28
def fc(input,
       size,
C
chengduoZH 已提交
29
       num_flatten_dims=1,
F
fengjiayi 已提交
30
       param_attr=None,
Q
QI JUN 已提交
31
       bias_attr=None,
F
fengjiayi 已提交
32
       act=None,
C
chengduoZH 已提交
33
       name=None,
34 35
       main_program=None,
       startup_program=None):
36 37 38 39 40 41
    """
    Fully Connected Layer.

    Args:
       input: The input tensor to the function
       size: The size of the layer
C
chengduoZH 已提交
42
       num_flatten_dims: Number of columns in input
43
       param_attr: The parameters/weights to the FC Layer
Q
QI JUN 已提交
44
       param_initializer: Initializer used for the weight/parameter. If None, XavierInitializer() is used
45
       bias_attr: The bias parameter for the FC layer
Q
QI JUN 已提交
46
       bias_initializer: Initializer used for the bias. If None, then ConstantInitializer() is used
47
       act: Activation to be applied to the output of FC layer
C
chengduoZH 已提交
48
       name: Name/alias of the function
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
       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 已提交
64 65 66 67 68 69 70
    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 已提交
71 72 73
        param_shape = [
            reduce(lambda a, b: a * b, input_shape[num_flatten_dims:], 1)
        ] + [size]
Y
Yu Yang 已提交
74
        w = helper.create_parameter(
Y
Yu Yang 已提交
75
            attr=param_attr, shape=param_shape, dtype=dtype, is_bias=False)
Y
Yu Yang 已提交
76 77 78 79 80 81 82 83
        tmp = helper.create_tmp_variable(dtype)
        helper.append_op(
            type="mul",
            inputs={
                "X": input_var,
                "Y": w,
            },
            outputs={"Out": tmp},
Y
Yu Yang 已提交
84 85
            attrs={'x_num_col_dims': num_flatten_dims,
                   'y_num_col_dims': 1})
Y
Yu Yang 已提交
86 87 88 89 90 91 92 93 94 95
        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
Y
Yu Yang 已提交
96
    pre_activation = helper.append_bias_op(pre_bias)
Y
Yu Yang 已提交
97 98 99 100
    # add activation
    return helper.append_activation(pre_activation)


Q
QI JUN 已提交
101 102
def embedding(input,
              size,
103
              is_sparse=False,
Q
QI JUN 已提交
104
              param_attr=None,
F
fengjiayi 已提交
105
              dtype='float32',
106 107
              main_program=None,
              startup_program=None):
108 109 110 111
    """
    Embedding Layer.

    Args:
Y
Yu Yang 已提交
112
       param_initializer:
113 114 115 116
       input: The input to the function
       size: The size of the layer
       is_sparse: A flag that decleares whether the input is sparse
       param_attr: Parameters for this layer
F
fengjiayi 已提交
117
       dtype: The type of data : float32, float_16, int etc
118 119 120 121 122 123 124 125 126 127 128
       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
Qiao Longfei 已提交
129

Q
QI JUN 已提交
130 131
    helper = LayerHelper('embedding', **locals())
    w = helper.create_parameter(
Y
Yu Yang 已提交
132
        attr=helper.param_attr, shape=size, dtype=dtype, is_bias=False)
F
fengjiayi 已提交
133
    tmp = helper.create_tmp_variable(dtype)
Q
QI JUN 已提交
134 135 136 137
    helper.append_op(
        type='lookup_table',
        inputs={'Ids': input,
                'W': w},
138 139
        outputs={'Out': tmp},
        attrs={'is_sparse': is_sparse})
Q
QI JUN 已提交
140 141 142
    return tmp


Q
QI JUN 已提交
143 144 145 146 147 148 149 150 151 152
# TODO(qijun): expose H0 and C0
def dynamic_lstm(input,
                 size,
                 param_attr=None,
                 bias_attr=None,
                 use_peepholes=True,
                 is_reverse=False,
                 gate_activation='sigmoid',
                 cell_activation='tanh',
                 candidate_activation='tanh',
F
fengjiayi 已提交
153
                 dtype='float32',
Q
QI JUN 已提交
154 155 156 157 158
                 main_program=None,
                 startup_program=None):
    helper = LayerHelper('lstm', **locals())
    size = size / 4
    weight = helper.create_parameter(
F
fengjiayi 已提交
159
        attr=helper.param_attr, shape=[size, 4 * size], dtype=dtype)
Q
QI JUN 已提交
160 161 162 163
    bias_size = [1, 7 * size]
    if not use_peepholes:
        bias_size[1] = 4 * size
    bias = helper.create_parameter(
Y
Yu Yang 已提交
164
        attr=helper.bias_attr, shape=bias_size, dtype=dtype, is_bias=True)
Q
QI JUN 已提交
165

F
fengjiayi 已提交
166 167 168 169
    hidden = helper.create_tmp_variable(dtype)
    cell = helper.create_tmp_variable(dtype)
    batch_gate = helper.create_tmp_variable(dtype)
    batch_cell_pre_act = helper.create_tmp_variable(dtype)
Q
QI JUN 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

    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


Y
Yan Chunwei 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 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
def gru_unit(input,
             hidden,
             size,
             weight=None,
             bias=None,
             activation='tanh',
             gate_activation='sigmoid',
             main_program=None,
             startup_program=None):
    """
    GRUUnit Operator implements partial calculations of the GRU unit as following:

    $$
    update \ gate: u_t = actGate(xu_t + W_u * h_{t-1} + b_u) \\
    reset \ gate: r_t = actGate(xr_t + W_r * h_{t-1} + b_r)  \\
    output \ candidate: {h}_t = actNode(xc_t + W_c * dot(r_t, h_{t-1}) + b_c) \\
    output: h_t = dot((1 - u_t), h_{t-1}) + dot(u_t, {h}_t)
    $$

    which is same as one time step of GRU Operator.

    @note To implement the complete GRU unit, fully-connected operator must be
    used before to feed xu, xr and xc as the Input of GRUUnit operator.

    TODO(ChunweiYan) add more document here
    """
    activation_dict = dict(
        identity=0,
        sigmoid=1,
        tanh=2,
        relu=3, )
    activation = activation_dict[activation]
    gate_activation = activation_dict[gate_activation]

    helper = LayerHelper('gru_unit', **locals())
    dtype = helper.input_dtype()
    size = size / 3

    # create weight
    if weight is None:
        weight = helper.create_parameter(
            attr=helper.param_attr, shape=[size, 3 * size], dtype=dtype)

    # create bias
    if bias is None:
        bias_size = [1, 3 * size]
        bias = helper.create_parameter(
            attr=helper.bias_attr, shape=bias_size, dtype=dtype, is_bias=True)

    gate = helper.create_tmp_variable(dtype)
    reset_hidden_pre = helper.create_tmp_variable(dtype)
    updated_hidden = helper.create_tmp_variable(dtype)

    helper.append_op(
        type='gru_unit',
        inputs={'Input': input,
                'HiddenPrev': hidden,
                'Weight': weight},
        outputs={
            'Gate': gate,
            'ResetHiddenPrev': reset_hidden_pre,
            'Hidden': updated_hidden,
        },
        attrs={
            'activation': 0,
            'gate_activation': 1,
        })

    return updated_hidden, reset_hidden_pre, gate


F
fengjiayi 已提交
263 264
def data(name,
         shape,
C
chengduoZH 已提交
265
         append_batch_size=True,
F
fengjiayi 已提交
266
         dtype='float32',
Y
Yu Yang 已提交
267
         lod_level=0,
F
fengjiayi 已提交
268
         type=core.VarDesc.VarType.LOD_TENSOR,
269
         main_program=None,
270 271
         startup_program=None,
         stop_gradient=True):
272 273 274 275 276 277
    """
    Data Layer.

    Args:
       name: The name/alias of the function
       shape: Tuple declaring the shape.
C
chengduoZH 已提交
278
       append_batch_size: Whether or not to append the data as a batch.
F
fengjiayi 已提交
279
       dtype: The type of data : float32, float_16, int etc
280
       type: The output type. By default it is LOD_TENSOR.
Y
Yu Yang 已提交
281
       lod_level(int): The LoD Level. 0 means the input data is not a sequence.
282 283 284 285 286 287 288 289 290 291 292 293 294
       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 已提交
295
    helper = LayerHelper('data', **locals())
Y
Yu Yang 已提交
296 297 298 299 300 301 302 303
    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 已提交
304 305
    if append_batch_size:
        shape = [-1] + shape  # append batch size as -1
Y
Yu Yang 已提交
306

Y
Yu Yang 已提交
307
    return helper.create_global_variable(
308 309
        name=name,
        shape=shape,
F
fengjiayi 已提交
310
        dtype=dtype,
311
        type=type,
Y
Yu Yang 已提交
312 313
        stop_gradient=stop_gradient,
        lod_level=lod_level)
Y
Yu Yang 已提交
314 315


Y
Yu Yang 已提交
316
def create_tensor(dtype, name=None, main_program=None, startup_program=None):
Y
Yu Yang 已提交
317 318
    helper = LayerHelper("create_tensor", **locals())
    return helper.create_variable(name=helper.name, dtype=dtype)
Y
Yu Yang 已提交
319 320


F
fengjiayi 已提交
321
def cast(x, dtype, main_program=None):
322
    """
F
fengjiayi 已提交
323 324
    This function takes in the input with input_dtype
    and casts it to the output_dtype as the output.
325
    """
Y
Yu Yang 已提交
326
    helper = LayerHelper('cast', **locals())
F
fengjiayi 已提交
327
    out = helper.create_tmp_variable(dtype=dtype)
Y
Yu Yang 已提交
328 329 330 331
    helper.append_op(
        type='cast',
        inputs={'X': [x]},
        outputs={'Out': [out]},
F
fengjiayi 已提交
332 333
        attrs={'in_dtype': x.dtype,
               'out_dtype': out.dtype})
Y
Yu Yang 已提交
334 335 336
    return out


337
def concat(input, axis, main_program=None, startup_program=None):
338 339 340 341
    """
    This function concats the input along the axis mentioned
    and returns that as the output.
    """
Q
QI JUN 已提交
342
    helper = LayerHelper('concat', **locals())
D
dzhwinter 已提交
343
    out = helper.create_tmp_variable(dtype=helper.input_dtype())
Q
QI JUN 已提交
344 345 346 347 348 349 350 351
    helper.append_op(
        type='concat',
        inputs={'X': input},
        outputs={'Out': [out]},
        attrs={'axis': axis})
    return out


Y
Yu Yang 已提交
352
def sums(input, out=None, main_program=None, startup_program=None):
353 354 355 356
    """
    This function takes in the input and performs the sum operation on it
    and returns that as the output.
    """
D
dzhwinter 已提交
357
    helper = LayerHelper('sum', **locals())
Y
Yu Yang 已提交
358 359
    if out is None:
        out = helper.create_tmp_variable(dtype=helper.input_dtype())
Y
Yu Yang 已提交
360
    helper.append_op(type='sum', inputs={'X': input}, outputs={'Out': out})
D
dzhwinter 已提交
361 362 363
    return out


Q
Qiao Longfei 已提交
364 365 366 367 368 369 370 371 372 373
def linear_chain_crf(input,
                     label,
                     param_attr=None,
                     main_program=None,
                     startup_program=None):
    helper = LayerHelper('linear_chain_crf', **locals())
    size = input.shape[1]
    transition = helper.create_parameter(
        attr=helper.param_attr,
        shape=[size + 2, size],
Y
Yu Yang 已提交
374
        dtype=helper.input_dtype())
Q
Qiao Longfei 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    alpha = helper.create_tmp_variable(dtype=helper.input_dtype())
    emission_exps = helper.create_tmp_variable(dtype=helper.input_dtype())
    transition_exps = helper.create_tmp_variable(dtype=helper.input_dtype())
    log_likelihood = helper.create_tmp_variable(dtype=helper.input_dtype())
    helper.append_op(
        type='linear_chain_crf',
        inputs={"Emission": [input],
                "Transition": transition,
                "Label": label},
        outputs={
            "Alpha": [alpha],
            "EmissionExps": [emission_exps],
            "TransitionExps": transition_exps,
            "LogLikelihood": log_likelihood
        })

    return log_likelihood


Q
Qiao Longfei 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
def crf_decoding(input,
                 param_attr,
                 label=None,
                 main_program=None,
                 startup_program=None):
    helper = LayerHelper('crf_decoding', **locals())
    transition = helper.get_parameter(param_attr.name)
    viterbi_path = helper.create_tmp_variable(dtype=helper.input_dtype())
    helper.append_op(
        type='crf_decoding',
        inputs={"Emission": [input],
                "Transition": transition,
                "Label": label},
        outputs={"ViterbiPath": [viterbi_path]})

    return viterbi_path


Y
Yu Yang 已提交
412
def assign(input, output, main_program=None, startup_program=None):
Y
Yu Yang 已提交
413 414 415 416 417 418 419 420 421
    helper = LayerHelper('assign', **locals())
    helper.append_op(
        type='scale',
        inputs={'X': [input]},
        outputs={'Out': [output]},
        attrs={'scale': 1.0})
    return output


422 423
def split_lod_tensor(input,
                     mask,
Y
Yu Yang 已提交
424
                     level=0,
425 426 427
                     main_program=None,
                     startup_program=None):
    helper = LayerHelper('split_lod_tensor', **locals())
F
fengjiayi 已提交
428 429
    out_true = helper.create_tmp_variable(dtype=input.dtype)
    out_false = helper.create_tmp_variable(dtype=input.dtype)
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    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,
Y
Yu Yang 已提交
446
                     level=0,
447 448 449
                     main_program=None,
                     startup_program=None):
    helper = LayerHelper('merge_lod_tensor', **locals())
F
fengjiayi 已提交
450
    out = helper.create_tmp_variable(dtype=in_true.dtype)
451 452 453 454 455 456 457 458 459 460 461
    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


462
def cos_sim(X, Y, **kwargs):
463 464 465 466
    """
    This function performs the cosine similarity between two tensors
    X and Y and returns that as the output.
    """
467
    helper = LayerHelper('cos_sim', **kwargs)
F
fengjiayi 已提交
468 469 470
    out = helper.create_tmp_variable(dtype=X.dtype)
    xnorm = helper.create_tmp_variable(dtype=X.dtype)
    ynorm = helper.create_tmp_variable(dtype=X.dtype)
D
dzhwinter 已提交
471 472 473 474 475 476 477
    helper.append_op(
        type='cos_sim',
        inputs={'X': [X],
                'Y': [Y]},
        outputs={'Out': [out],
                 'XNorm': [xnorm],
                 'YNorm': [ynorm]})
478
    return out
D
dzhwinter 已提交
479 480


Y
Yu Yang 已提交
481
def cross_entropy(input, label, **kwargs):
482 483 484
    """
    This function computes cross_entropy using the input and label.
    """
Y
Yu Yang 已提交
485
    helper = LayerHelper('cross_entropy', **kwargs)
F
fengjiayi 已提交
486
    out = helper.create_tmp_variable(dtype=input.dtype)
Y
Yu Yang 已提交
487 488 489 490 491 492 493 494 495 496
    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):
497 498 499 500
    """
    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 已提交
501
    helper = LayerHelper('square_error_cost', **kwargs)
F
fengjiayi 已提交
502
    minus_out = helper.create_tmp_variable(dtype=input.dtype)
Y
Yu Yang 已提交
503 504 505 506 507 508
    helper.append_op(
        type='elementwise_sub',
        inputs={'X': [input],
                'Y': [label]},
        outputs={'Out': [minus_out]})

F
fengjiayi 已提交
509
    square_out = helper.create_tmp_variable(dtype=input.dtype)
Y
Yu Yang 已提交
510
    helper.append_op(
Q
QI JUN 已提交
511
        type='square', inputs={'X': [minus_out]}, outputs={'Y': [square_out]})
Y
Yu Yang 已提交
512
    return square_out
513 514


Y
Yu Yang 已提交
515
def accuracy(input, label, k=1, correct=None, total=None, **kwargs):
516 517 518 519
    """
    This function computes the accuracy using the input and label.
    The output is the top_k inputs and their indices.
    """
F
fengjiayi 已提交
520
    helper = LayerHelper("accuracy", **kwargs)
F
fengjiayi 已提交
521
    topk_out = helper.create_tmp_variable(dtype=input.dtype)
F
fengjiayi 已提交
522 523 524 525 526 527 528
    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})
D
Dong Zhihong 已提交
529
    acc_out = helper.create_tmp_variable(dtype="float32")
Y
Yu Yang 已提交
530 531 532 533
    if correct is None:
        correct = helper.create_tmp_variable(dtype="int64")
    if total is None:
        total = helper.create_tmp_variable(dtype="int64")
F
fengjiayi 已提交
534 535
    helper.append_op(
        type="accuracy",
武毅 已提交
536 537 538 539 540
        inputs={
            "Out": [topk_out],
            "Indices": [topk_indices],
            "Label": [label]
        },
D
Dong Zhihong 已提交
541 542 543 544 545
        outputs={
            "Accuracy": [acc_out],
            "Correct": [correct],
            "Total": [total],
        })
F
fengjiayi 已提交
546 547 548
    return acc_out


Q
Qiao Longfei 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
def chunk_eval(input,
               label,
               chunk_scheme,
               num_chunk_types,
               excluded_chunk_types=None,
               **kwargs):
    """
    This function computes the accuracy using the input and label.
    The output is the top_k inputs and their indices.
    """
    helper = LayerHelper("chunk_eval", **kwargs)

    # prepare output
    precision = helper.create_tmp_variable(dtype="float32")
    recall = helper.create_tmp_variable(dtype="float32")
    f1_score = helper.create_tmp_variable(dtype="float32")

    helper.append_op(
        type="chunk_eval",
        inputs={"Inference": [input],
                "Label": [label]},
        outputs={
            "Precision": [precision],
            "Recall": [recall],
            "F1-Score": [f1_score]
        },
        attrs={
            "num_chunk_types": num_chunk_types,
            'chunk_scheme': chunk_scheme,
            'excluded_chunk_types': excluded_chunk_types or []
        })
    return precision, recall, f1_score


D
dzhwinter 已提交
583 584 585
def sequence_conv(input,
                  num_filters,
                  filter_size=3,
586
                  filter_stride=1,
D
dzhwinter 已提交
587 588 589
                  padding=None,
                  bias_attr=None,
                  param_attr=None,
C
chengduoZH 已提交
590
                  act=None,
591 592
                  main_program=None,
                  startup_program=None):
593 594 595 596 597
    """
    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.
    """
598

D
dzhwinter 已提交
599 600 601 602 603 604
    # 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 已提交
605
    filter_shape = [filter_size * input.shape[1], num_filters]
Y
Yu Yang 已提交
606
    filter_param = helper.create_parameter(
Y
Yu Yang 已提交
607
        attr=helper.param_attr, shape=filter_shape, dtype=dtype)
D
dzhwinter 已提交
608 609 610 611 612 613
    pre_bias = helper.create_tmp_variable(dtype)

    helper.append_op(
        type='sequence_conv',
        inputs={
            'X': [input],
Y
Yu Yang 已提交
614
            'Filter': [filter_param],
D
dzhwinter 已提交
615 616 617
        },
        outputs={"Out": pre_bias},
        attrs={
618
            'contextStride': filter_stride,
619
            'contextStart': -int(filter_size / 2),
620
            'contextLength': filter_size
D
dzhwinter 已提交
621
        })
Y
Yu Yang 已提交
622
    pre_act = helper.append_bias_op(pre_bias)
D
dzhwinter 已提交
623 624 625
    return helper.append_activation(pre_act)


F
fengjiayi 已提交
626 627
def conv2d(input,
           num_filters,
C
chengduoZH 已提交
628
           filter_size,
Y
Yu Yang 已提交
629
           stride=None,
F
fengjiayi 已提交
630
           padding=None,
C
chengduoZH 已提交
631
           groups=None,
F
fengjiayi 已提交
632
           param_attr=None,
C
chengduoZH 已提交
633 634 635
           bias_attr=None,
           act=None,
           name=None,
636 637
           main_program=None,
           startup_program=None):
638 639 640 641 642 643 644
    """
    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.
    """
645

Y
Yu Yang 已提交
646 647
    if stride is None:
        stride = [1, 1]
648 649 650 651 652 653 654
    helper = LayerHelper('conv2d', **locals())
    dtype = helper.input_dtype()

    num_channels = input.shape[1]
    if groups is None:
        num_filter_channels = num_channels
    else:
C
chengduoZH 已提交
655
        if num_channels % groups != 0:
656 657 658
            raise ValueError("num_channels must be divisible by groups.")
        num_filter_channels = num_channels / groups

F
fengjiayi 已提交
659 660 661 662 663 664 665
    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]

666 667
    input_shape = input.shape
    filter_shape = [num_filters, num_filter_channels] + filter_size
668

Y
Yu Yang 已提交
669 670 671
    def _get_default_param_initializer():
        std = (2.0 / (filter_size[0]**2 * num_channels))**0.5
        return Normal(0.0, std, 0)
672

Y
Yu Yang 已提交
673
    filter_param = helper.create_parameter(
674 675 676
        attr=helper.param_attr,
        shape=filter_shape,
        dtype=dtype,
Y
Yu Yang 已提交
677 678
        default_initializer=_get_default_param_initializer())

679 680 681
    pre_bias = helper.create_tmp_variable(dtype)

    helper.append_op(
682
        type='conv2d_cudnn',
683 684
        inputs={
            'Input': input,
Y
Yu Yang 已提交
685
            'Filter': filter_param,
686 687 688 689 690 691
        },
        outputs={"Output": pre_bias},
        attrs={'strides': stride,
               'paddings': padding,
               'groups': groups})

Y
Yu Yang 已提交
692
    pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2)
693 694

    return helper.append_activation(pre_act)
F
fengjiayi 已提交
695 696


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

    helper.append_op(
        type="sequence_pool",
D
dangqingqing 已提交
710 711 712
        inputs={"X": input},
        outputs={"Out": pool_out,
                 "MaxIndex": max_index},
D
dzhwinter 已提交
713
        attrs={"pooltype": pool_type.upper()})
D
dzhwinter 已提交
714 715 716 717

    return pool_out


F
fengjiayi 已提交
718 719 720
def pool2d(input,
           pool_size,
           pool_type,
Y
Yu Yang 已提交
721 722
           pool_stride=None,
           pool_padding=None,
F
fengjiayi 已提交
723
           global_pooling=False,
724 725
           main_program=None,
           startup_program=None):
726 727 728 729
    """
    This function adds the operator for pooling in 2 dimensions, using the
    pooling configurations mentioned in input parameters.
    """
Y
Yu Yang 已提交
730 731 732 733
    if pool_padding is None:
        pool_padding = [0, 0]
    if pool_stride is None:
        pool_stride = [1, 1]
F
fengjiayi 已提交
734 735 736 737 738 739 740 741 742 743 744
    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 已提交
745
    helper = LayerHelper('pool2d', **locals())
F
fengjiayi 已提交
746 747 748 749 750 751 752 753
    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 已提交
754
            "pooling_type": pool_type,
F
fengjiayi 已提交
755
            "ksize": pool_size,
C
chengduoZH 已提交
756
            "global_pooling": global_pooling,
F
fengjiayi 已提交
757 758 759 760 761
            "strides": pool_stride,
            "paddings": pool_padding
        })

    return pool_out
Y
Yu Yang 已提交
762 763


Q
Qiao Longfei 已提交
764 765 766 767
def batch_norm(input,
               act=None,
               is_test=False,
               momentum=0.9,
768
               epsilon=1e-05,
Q
Qiao Longfei 已提交
769 770 771
               param_attr=None,
               bias_attr=None,
               data_layout='NCHW',
772 773
               main_program=None,
               startup_program=None):
774 775 776 777
    """
    This function helps create an operator to implement
    the BatchNorm layer using the configurations from the input parameters.
    """
Q
Qiao Longfei 已提交
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
    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(
794 795 796
        attr=helper.param_attr,
        shape=param_shape,
        dtype=dtype,
Y
Yu Yang 已提交
797 798
        default_initializer=Constant(1.0))

Q
Qiao Longfei 已提交
799
    bias = helper.create_parameter(
Y
Yu Yang 已提交
800
        attr=helper.param_attr, shape=param_shape, dtype=dtype, is_bias=True)
801 802

    mean = helper.create_global_variable(
F
fengjiayi 已提交
803
        dtype=input.dtype, shape=param_shape, persistable=True)
804
    helper.set_variable_initializer(var=mean, initializer=Constant(0.0))
805 806

    variance = helper.create_global_variable(
F
fengjiayi 已提交
807
        dtype=input.dtype, shape=param_shape, persistable=True)
808
    helper.set_variable_initializer(var=variance, initializer=Constant(1.0))
Q
Qiao Longfei 已提交
809 810 811 812 813 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

    # 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)


843 844
def beam_search_decode(ids, scores, main_program=None, startup_program=None):
    helper = LayerHelper('beam_search_decode', **locals())
F
fengjiayi 已提交
845 846
    sentence_ids = helper.create_tmp_variable(dtype=ids.dtype)
    sentence_scores = helper.create_tmp_variable(dtype=ids.dtype)
847 848 849 850 851 852 853 854 855 856 857 858 859

    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 已提交
860 861
class BlockGuard(object):
    """
862 863 864 865
    BlockGuard class.

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

868 869
    def __init__(self, main_program):
        if not isinstance(main_program, Program):
Y
Yu Yang 已提交
870
            raise TypeError("BlockGuard takes a program")
871
        self.main_program = main_program
Y
Yu Yang 已提交
872 873

    def __enter__(self):
874
        self.main_program.create_block()
Y
Yu Yang 已提交
875 876

    def __exit__(self, exc_type, exc_val, exc_tb):
877
        self.main_program.rollback()
Y
Yu Yang 已提交
878 879 880 881 882 883
        if exc_type is not None:
            return False  # re-raise exception
        return True


class StaticRNNGuard(BlockGuard):
884 885 886 887 888 889
    """
    StaticRNNGuard class.

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

Y
Yu Yang 已提交
890 891
    def __init__(self, rnn):
        if not isinstance(rnn, StaticRNN):
Y
Yang Yang(Tony) 已提交
892
            raise TypeError("StaticRNNGuard takes a StaticRNN")
893
        super(StaticRNNGuard, self).__init__(rnn.helper.main_program)
Y
Yu Yang 已提交
894 895 896 897 898 899 900
        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 已提交
901 902
        if exc_type is not None:
            return False
Y
Yu Yang 已提交
903 904 905 906 907 908 909
        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):
    """
910 911 912 913 914 915 916 917 918 919 920 921
    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 已提交
922 923 924 925 926 927 928 929 930
    """

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


class StaticRNN(object):
931 932 933 934 935 936
    """
    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 已提交
937 938 939 940
    BEFORE_RNN_BLOCK = 0
    IN_RNN_BLOCK = 1
    AFTER_RNN_BLOCK = 2

941 942 943
    def __init__(self, name=None, main_program=None):
        self.helper = LayerHelper(
            "static_rnn", name=name, main_program=main_program)
Y
Yu Yang 已提交
944 945 946 947 948 949 950 951 952 953 954 955 956 957
        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))

958 959 960 961 962 963 964
    def memory(self,
               init=None,
               shape=None,
               batch_ref=None,
               init_value=0.0,
               init_batch_dim_idx=0,
               ref_batch_dim_idx=1):
965 966 967 968 969 970 971 972 973
        """
        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 已提交
974 975
        self._assert_in_rnn_block_('memory')
        if init is None:
976
            if shape is None or batch_ref is None:
Y
Yu Yang 已提交
977
                raise ValueError(
978
                    "if init is None, memory at least need shape and batch_ref")
Y
Yu Yang 已提交
979 980 981
            parent_block = self.parent_block()
            var_name = unique_name("@".join([self.helper.name, "memory_boot"]))
            boot_var = parent_block.create_var(
982 983
                name=var_name,
                shape=shape,
F
fengjiayi 已提交
984
                dtype=batch_ref.dtype,
985
                persistable=False)
Y
Yu Yang 已提交
986 987

            parent_block.append_op(
988 989
                type="fill_constant_batch_size_like",
                inputs={'Input': [batch_ref]},
Y
Yu Yang 已提交
990 991 992
                outputs={'Out': [boot_var]},
                attrs={
                    'value': init_value,
993
                    'shape': boot_var.shape,
F
fengjiayi 已提交
994
                    'dtype': boot_var.dtype,
995 996
                    'input_dim_idx': ref_batch_dim_idx,
                    'output_dim_idx': init_batch_dim_idx
Y
Yu Yang 已提交
997 998 999 1000 1001 1002
                })

            return self.memory(init=boot_var)
        else:
            pre_mem = self.helper.create_variable(
                name=unique_name("@".join([self.helper.name, "mem"])),
F
fengjiayi 已提交
1003
                dtype=init.dtype,
Y
Yu Yang 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
                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 已提交
1014 1015
            self.seq_len = x.shape[0]
        elif self.seq_len != x.shape[0]:
Y
Yu Yang 已提交
1016 1017 1018
            raise ValueError("Static RNN only take fix seq_len input")

        ipt = self.helper.create_variable(
F
fengjiayi 已提交
1019
            name=x.name, dtype=x.dtype, shape=list(x.shape[1:]), type=x.type)
Y
Yu Yang 已提交
1020 1021 1022 1023 1024 1025 1026 1027
        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")

F
fengjiayi 已提交
1028
        tmp_o = self.helper.create_tmp_variable(dtype=o.dtype)
Y
Yu Yang 已提交
1029 1030 1031 1032
        self.helper.append_op(
            type='rnn_memory_helper',
            inputs={'X': [o]},
            outputs={'Out': tmp_o},
F
fengjiayi 已提交
1033
            attrs={'dtype': o.dtype})
Y
Yu Yang 已提交
1034

Y
Yu Yang 已提交
1035
        out_var = self.parent_block().create_var(
Y
Yu Yang 已提交
1036 1037
            name=tmp_o.name,
            shape=[self.seq_len] + list(tmp_o.shape),
F
fengjiayi 已提交
1038
            dtype=tmp_o.dtype)
Y
Yu Yang 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

        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):
1052
        prog = self.helper.main_program
Y
Yu Yang 已提交
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        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):
1069 1070
        main_program = self.helper.main_program
        rnn_block = main_program.current_block()
Y
Yu Yang 已提交
1071 1072 1073 1074 1075 1076 1077 1078 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
        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)
F
fengjiayi 已提交
1110
            new_mem = self.helper.create_tmp_variable(dtype=mem_var.dtype)
Y
Yu Yang 已提交
1111 1112 1113 1114 1115

            rnn_block.append_op(
                type='rnn_memory_helper',
                inputs={'X': [mem_var]},
                outputs={'Out': [new_mem]},
F
fengjiayi 已提交
1116
                attrs={'dtype': mem_var.dtype})
Y
Yu Yang 已提交
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

            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 已提交
1134 1135


Y
Yang Yang(Tony) 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
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)
F
fengjiayi 已提交
1166
        if cond.dtype != core.DataType.BOOL:
Y
Yang Yang(Tony) 已提交
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
            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) 已提交
1212 1213 1214 1215 1216 1217
def lstm(x,
         c_pre_init,
         hidden_dim,
         forget_bias=None,
         main_program=None,
         startup_program=None):
1218 1219 1220 1221
    """
    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) 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
    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)

F
fengjiayi 已提交
1238 1239 1240
        dtype = x.dtype
        c = helper.create_tmp_variable(dtype)
        h = helper.create_tmp_variable(dtype)
Y
Yang Yang(Tony) 已提交
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

        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()


1256
def lod_rank_table(x, level=0, main_program=None):
1257 1258 1259 1260
    """
    This function creates an operator for creating a LOD_RANK_TABLE
    using the input x.
    """
Y
Yu Yang 已提交
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
    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 已提交
1271 1272


F
fengjiayi 已提交
1273 1274
def max_sequence_len(rank_table, main_program=None):
    """
Y
Yu Yang 已提交
1275
    This function creates an operator to calculate the length of
F
fengjiayi 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
    max seqence through input rank_table(should be a lod_rank_table)
    """
    helper = LayerHelper("max_seqence_len", **locals())
    res = helper.create_tmp_variable(dtype="int64")
    helper.append_op(
        type="max_sequence_len",
        inputs={"RankTable": rank_table},
        outputs={"Out": res})
    return res


Y
Yu Yang 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
def topk(input, k, main_program=None, startup_program=None):
    helper = LayerHelper('topk', **locals())
    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})
    return topk_out, topk_indices


1300
def lod_tensor_to_array(x, table, main_program=None):
1301 1302 1303 1304
    """
    This function creates an operator to convert an LOD_Tensor to
    an array.
    """
1305 1306 1307
    helper = LayerHelper("lod_tensor_to_array", **locals())
    array = helper.create_variable(
        name=unique_name("lod_tensor_to_array"),
1308
        type=core.VarDesc.VarType.LOD_TENSOR_ARRAY,
F
fengjiayi 已提交
1309
        dtype=x.dtype)
1310 1311 1312 1313 1314 1315 1316 1317
    helper.append_op(
        type='lod_tensor_to_array',
        inputs={'X': x,
                'RankTable': table},
        outputs={'Out': array})
    return array


1318
def array_to_lod_tensor(x, table, main_program=None, startup_program=None):
1319 1320 1321 1322
    """
    This function creates an operator to convert an array to a
    LOD_Tensor.
    """
1323
    helper = LayerHelper("array_to_lod_tensor", **locals())
F
fengjiayi 已提交
1324
    tmp = helper.create_tmp_variable(dtype=x.dtype)
1325 1326 1327 1328 1329 1330 1331 1332
    helper.append_op(
        type="array_to_lod_tensor",
        inputs={'X': x,
                'RankTable': table},
        outputs={'Out': tmp})
    return tmp


Y
Yu Yang 已提交
1333 1334 1335 1336 1337 1338
def fill_constant(shape,
                  dtype,
                  value,
                  out=None,
                  main_program=None,
                  startup_program=None):
1339 1340
    """
    This function creates a tensor , with shape as mentioned in the input and
F
fengjiayi 已提交
1341
    specified dtype and fills this up with a constant value that
1342 1343
    comes in the input. It also sets the stop_gradient to be True.
    """
Y
Yang Yu 已提交
1344
    helper = LayerHelper("fill_constant", **locals())
Y
Yu Yang 已提交
1345 1346
    if out is None:
        out = helper.create_tmp_variable(dtype=dtype)
Y
Yu Yang 已提交
1347 1348 1349 1350
    helper.append_op(
        type='fill_constant',
        inputs={},
        outputs={'Out': [out]},
F
fengjiayi 已提交
1351 1352 1353
        attrs={'shape': shape,
               'dtype': out.dtype,
               'value': float(value)})
Y
Yu Yang 已提交
1354 1355 1356 1357
    out.stop_gradient = True
    return out


Y
Yu Yang 已提交
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
def fill_constant_batch_size_like(input,
                                  shape,
                                  dtype,
                                  value,
                                  input_dim_idx=0,
                                  output_dim_idx=0,
                                  main_program=None,
                                  startup_program=None):
    helper = LayerHelper("fill_constant_batch_size_like", **locals())
    out = helper.create_tmp_variable(dtype=dtype)
    helper.append_op(
        type='fill_constant_batch_size_like',
        inputs={'Input': input},
        outputs={'Out': [out]},
        attrs={
            'shape': shape,
F
fengjiayi 已提交
1374
            'dtype': out.dtype,
Y
Yu Yang 已提交
1375 1376 1377 1378 1379 1380 1381 1382
            'value': float(value),
            'input_dim_idx': input_dim_idx,
            'output_dim_idx': output_dim_idx
        })
    out.stop_gradient = True
    return out


Y
Yu Yang 已提交
1383
def ones(shape, dtype, main_program=None):
1384 1385 1386 1387
    """
    This function performs the same function as fill_constant() declared above
    with the constant value being 1.0.
    """
Y
Yu Yang 已提交
1388 1389 1390 1391
    return fill_constant(value=1.0, **locals())


def zeros(shape, dtype, main_program=None):
1392 1393 1394 1395
    """
    This function performs the same function as fill_constant() declared above
    with the constant value being 0.0.
    """
Y
Yu Yang 已提交
1396 1397 1398
    return fill_constant(value=0.0, **locals())


1399 1400 1401 1402 1403
def increment(x,
              value=1.0,
              in_place=True,
              main_program=None,
              startup_program=None):
1404 1405 1406 1407 1408
    """
    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 已提交
1409
    helper = LayerHelper("increment", **locals())
Y
Yang Yang(Tony) 已提交
1410
    if not in_place:
F
fengjiayi 已提交
1411
        out = helper.create_tmp_variable(dtype=x.dtype)
Y
Yang Yang(Tony) 已提交
1412 1413
    else:
        out = x
Y
Yu Yang 已提交
1414 1415 1416
    helper.append_op(
        type='increment',
        inputs={'X': [x]},
Y
Yang Yu 已提交
1417
        outputs={'Out': [out]},
1418
        attrs={'step': float(value)})
Y
Yang Yu 已提交
1419
    return out
Y
Yu Yang 已提交
1420 1421


1422
def array_write(x, i, array=None, main_program=None, startup_program=None):
1423 1424 1425 1426
    """
    This function creates an operator to write the data out as a
    LOD_TENSOR_ARRAY.
    """
Y
Yu Yang 已提交
1427 1428 1429 1430 1431
    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,
F
fengjiayi 已提交
1432
            dtype=x.dtype)
Y
Yu Yang 已提交
1433 1434 1435 1436 1437 1438 1439 1440
    helper.append_op(
        type='write_to_array',
        inputs={'X': [x],
                'I': [i]},
        outputs={'Out': [array]})
    return array


Y
Yang Yang(Tony) 已提交
1441 1442 1443 1444 1445 1446 1447 1448
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)


Y
Yu Yang 已提交
1449
def less_than(x, y, cond=None, main_program=None, **ignored):
Y
Yang Yang(Tony) 已提交
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    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


1461
def array_read(array, i, main_program=None, startup_program=None):
1462 1463 1464 1465
    """
    This function creates an operator to read the data in as a
    LOD_TENSOR_ARRAY.
    """
Y
Yu Yang 已提交
1466 1467 1468 1469 1470
    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")
F
fengjiayi 已提交
1471
    out = helper.create_tmp_variable(dtype=array.dtype)
Y
Yu Yang 已提交
1472 1473 1474 1475 1476 1477
    helper.append_op(
        type='read_from_array',
        inputs={'X': [array],
                'I': [i]},
        outputs={'Out': [out]})
    return out
Y
Yang Yu 已提交
1478 1479


1480
def shrink_memory(x, i, table, main_program=None, startup_program=None):
1481 1482 1483 1484
    """
    This function creates an operator to shrink_rnn_memory using the RankTable
    as mentioned in the input parameter.
    """
Y
Yang Yu 已提交
1485
    helper = LayerHelper('shrink_memory', **locals())
F
fengjiayi 已提交
1486
    out = helper.create_tmp_variable(dtype=x.dtype)
Y
Yang Yu 已提交
1487
    helper.append_op(
Y
Yang Yu 已提交
1488
        type='shrink_rnn_memory',
Y
Yang Yu 已提交
1489 1490 1491 1492 1493 1494
        inputs={'X': [x],
                'I': [i],
                'RankTable': [table]},
        outputs={'Out': [out]},
        attrs={})
    return out
Y
Yang Yu 已提交
1495 1496 1497


def array_length(array, main_program=None):
1498 1499 1500 1501
    """
    This function creates an operator to find the length of the
    LOD_TENSOR_ARRAY.
    """
Y
Yang Yu 已提交
1502 1503 1504 1505 1506 1507
    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 已提交
1508 1509


1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
def conv2d_transpose(input,
                     num_filters,
                     output_size=None,
                     filter_size=None,
                     padding=None,
                     stride=None,
                     param_attr=None,
                     main_program=None,
                     startup_program=None):
    """
    The transpose of conv2d layer.
Y
Yu Yang 已提交
1521

1522
    This layer is also known as deconvolution layer.
Y
Yu Yang 已提交
1523

1524 1525 1526 1527 1528
    Args:
        input(Variable): The input image with [N, C, H, W] format.
        num_filters(int): The number of filter. It is as same as the output
            image channel.
        output_size(int|tuple|None): The output image size. If output size is a
Y
Yu Yang 已提交
1529
            tuple, it must contain two integers, (image_H, image_W). This
1530 1531 1532 1533 1534 1535
            parameter only works when filter_size is None.
        filter_size(int|tuple|None): The filter size. If filter_size is a tuple,
            it must contain two integers, (filter_size_H, filter_size_W).
            Otherwise, the filter will be a square.  None if use output size to
            calculate filter_size
        padding(int|tuple): The padding size. If padding is a tuple, it must
Y
Yu Yang 已提交
1536
            contain two integers, (padding_H, padding_W). Otherwise, the
1537 1538 1539 1540 1541 1542
            padding_H = padding_W = padding.
        stride(int|tuple): The stride size. If stride is a tuple, it must
            contain two integers, (stride_H, stride_W). Otherwise, the
            stride_H = stride_W = stride.
        param_attr: Parameter Attribute.
        main_program(Program): the main program
Y
Yu Yang 已提交
1543
        startup_program(Program): the startup program
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575

    Returns:
        Variable: Output image.
    """
    helper = LayerHelper("conv2d_transpose", **locals())
    if not isinstance(input, Variable):
        raise TypeError("Input of conv2d_transpose must be Variable")
    input_channel = input.shape[1]

    op_attr = dict()

    if isinstance(padding, int):
        op_attr['paddings'] = [padding, padding]
    elif padding is not None:
        op_attr['paddings'] = padding

    if isinstance(stride, int):
        op_attr['strides'] = stride
    elif stride is not None:
        op_attr['strides'] = stride

    if filter_size is None:
        if output_size is None:
            raise ValueError("output_size must be set when filter_size is None")
        if isinstance(output_size, int):
            output_size = [output_size, output_size]

        padding = op_attr.get('paddings', [0, 0])
        stride = op_attr.get('strides', [1, 1])

        h_in = input.shape[2]
        w_in = input.shape[3]
F
fengjiayi 已提交
1576 1577 1578 1579
        filter_size_h = output_size[0] - \
            (h_in - 1) * stride[0] + 2 * padding[0]
        filter_size_w = output_size[1] - \
            (w_in - 1) * stride[1] + 2 * padding[1]
1580 1581 1582 1583 1584 1585
        filter_size = [filter_size_h, filter_size_w]
    elif isinstance(filter_size, int):
        filter_size = [filter_size, filter_size]

    filter_shape = [input_channel, num_filters] + filter_size
    img_filter = helper.create_parameter(
Y
Yu Yang 已提交
1586
        dtype=input.dtype, shape=filter_shape, attr=helper.param_attr)
1587 1588 1589 1590 1591 1592 1593 1594

    out = helper.create_tmp_variable(dtype=input.dtype)
    helper.append_op(
        type='conv2d_transpose',
        inputs={'Input': [input],
                'Filter': [img_filter]},
        outputs={'Output': out},
        attrs=op_attr)
Y
Yu Yang 已提交
1595

1596 1597 1598
    return out


Y
Yu Yang 已提交
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
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):
Y
Yu Yang 已提交
1616 1617 1618 1619 1620
    def __init__(self,
                 inputs,
                 name=None,
                 main_program=None,
                 startup_program=None):
Y
Yu Yang 已提交
1621 1622 1623 1624 1625
        for each_input in inputs:
            if not isinstance(each_input, Variable):
                raise TypeError("Each input should be variable")
        self.inputs = inputs
        self.helper = LayerHelper(
Y
Yu Yang 已提交
1626 1627 1628 1629
            'conditional_block',
            name=name,
            main_program=main_program,
            startup_program=startup_program)
Y
Yu Yang 已提交
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673

    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})
Y
Yu Yang 已提交
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736


class IfElseBlockGuard(object):
    def __init__(self, is_true, ifelse):
        if not isinstance(ifelse, IfElse):
            raise TypeError("ifelse must be an instance of IfElse class")

        if ifelse.status != IfElse.OUT_IF_ELSE_BLOCKS:
            raise ValueError("You cannot invoke IfElse.block() inside a block")

        self.is_true = is_true
        self.ie = ifelse
        if is_true:
            self.cond_block = ifelse.conditional_true_block
        else:
            self.cond_block = ifelse.conditional_false_block

        if not isinstance(self.cond_block, ConditionalBlock):
            raise TypeError("Unexpected situation")

        self.cond_block = self.cond_block.block()

    def __enter__(self):
        self.ie.status = IfElse.IN_IF_ELSE_TRUE_BLOCKS if self.is_true else IfElse.IN_IF_ELSE_FALSE_BLOCKS
        self.cond_block.__enter__()

    def __exit__(self, exc_type, exc_val, exc_tb):
        if not self.cond_block.__exit__(exc_type, exc_val, exc_tb):
            # re-raise inside exception
            return False
        if len(self.ie.output_table[1 if self.is_true else 0]) == 0:
            raise ValueError("Must set output inside block")
        self.ie.status = IfElse.OUT_IF_ELSE_BLOCKS


class IfElse(object):
    OUT_IF_ELSE_BLOCKS = 0
    IN_IF_ELSE_TRUE_BLOCKS = 1
    IN_IF_ELSE_FALSE_BLOCKS = 2

    def __init__(self, cond, name=None, main_program=None,
                 startup_program=None):
        if not isinstance(cond, Variable):
            raise TypeError("cond must be a Variable")
        self.helper = LayerHelper(
            'ifelse',
            name=name,
            main_program=main_program,
            startup_program=startup_program)
        self.cond = cond
        self.input_table = {}
        self.status = IfElse.OUT_IF_ELSE_BLOCKS
        self.conditional_true_block = ConditionalBlock(inputs=[self.cond])
        self.conditional_false_block = ConditionalBlock(inputs=[self.cond])
        self.output_table = ([], [])  # (true_outs, false_outs)

    def input(self, x):
        if self.status == IfElse.OUT_IF_ELSE_BLOCKS:
            raise ValueError("input must in true/false blocks")
        if id(x) not in self.input_table:
            parent_block = self.parent_block()
            out_true = parent_block.create_var(
                name=unique_name('ifelse_input' + self.helper.name),
F
fengjiayi 已提交
1737
                dtype=x.dtype)
Y
Yu Yang 已提交
1738 1739 1740

            out_false = parent_block.create_var(
                name=unique_name('ifelse_input' + self.helper.name),
F
fengjiayi 已提交
1741
                dtype=x.dtype)
Y
Yu Yang 已提交
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
            parent_block.append_op(
                type='split_lod_tensor',
                inputs={
                    'X': x,
                    'Mask': self.cond,
                },
                outputs={'OutTrue': out_true,
                         'OutFalse': out_false},
                attrs={'level': 0})
            self.input_table[id(x)] = (out_true, out_false)
        else:
            out_true, out_false = self.input_table[id(x)]

        if self.status == IfElse.IN_IF_ELSE_TRUE_BLOCKS:
            return out_true
        else:
            return out_false

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

    def true_block(self):
        return IfElseBlockGuard(True, self)

    def false_block(self):
        return IfElseBlockGuard(False, self)

    def output(self, *outs):
        if self.status == self.OUT_IF_ELSE_BLOCKS:
            raise ValueError("output can only be invoked in the sub-block")

        out_table = self.output_table[1 if self.status ==
                                      self.IN_IF_ELSE_TRUE_BLOCKS else 0]
        parent_block = self.parent_block()
        for each_out in outs:
            if not isinstance(each_out, Variable):
                raise TypeError("Each output should be a variable")
            # create outside tensor
            outside_out = parent_block.create_var(
                name=unique_name("_".join([self.helper.name, 'output'])),
F
fengjiayi 已提交
1783
                dtype=each_out.dtype)
Y
Yu Yang 已提交
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
            out_table.append(outside_out)

            # assign local var to outside
            assign(
                input=each_out,
                output=outside_out,
                main_program=self.helper.main_program,
                startup_program=self.helper.startup_program)

    def __call__(self):
        if self.status != self.OUT_IF_ELSE_BLOCKS:
            raise ValueError("IfElse::__call__ must be out of sub-block")
        false_len, true_len = map(len, self.output_table)
        if false_len == 0 and true_len == 0:
            raise ValueError("Must invoke true_block/false_block before "
                             "__call__")
        elif false_len != true_len and false_len != 0 and true_len != 0:
            raise ValueError("The output side must be same")
        elif false_len == 0 or true_len == 0:
            return self.output_table[0 if false_len != 0 else 1]

        # else none of false_len/true_len is zero
        # merge together
        rlist = []
        for false_var, true_var in zip(*self.output_table):
            rlist.append(
                merge_lod_tensor(
                    in_true=true_var,
                    in_false=false_var,
                    mask=self.cond,
                    x=self.cond,
                    level=0,
                    main_program=self.helper.main_program,
                    startup_program=self.helper.startup_program))
        return rlist
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 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 1897 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 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024


class DynamicRNN(object):
    BEFORE_RNN = 0
    IN_RNN = 1
    AFTER_RNN = 2

    def __init__(self, name=None, main_program=None, startup_program=None):
        self.helper = LayerHelper(
            'dynamic_rnn',
            name=name,
            main_program=main_program,
            startup_program=startup_program)
        self.status = DynamicRNN.BEFORE_RNN
        self.lod_rank_table = None
        self.max_seq_len = None
        self.step_idx = None
        self.zero_idx = fill_constant(shape=[1], value=0, dtype='int64')
        self.mem_dict = dict()
        self.output_array = []
        self.outputs = []
        self.cond = self.helper.create_tmp_variable(dtype='bool')
        self.cond.stop_gradient = False
        self.while_op = While(self.cond)
        self.input_array = []
        self.mem_link = []

    def step_input(self, x):
        self._assert_in_rnn_block_("step_input")
        if not isinstance(x, Variable):
            raise TypeError(
                "step_input() can only take a Variable as its input")
        parent_block = self._parent_block_()
        if self.lod_rank_table is None:
            self.lod_rank_table = parent_block.create_var(
                name=unique_name('lod_rank_table'),
                type=core.VarDesc.VarType.LOD_RANK_TABLE)
            self.lod_rank_table.stop_gradient = True
            parent_block.append_op(
                type='lod_rank_table',
                inputs={"X": x},
                outputs={"Out": self.lod_rank_table})
            self.max_seq_len = parent_block.create_var(
                name=unique_name('dynamic_rnn_max_seq_len'), dtype='int64')
            self.max_seq_len.stop_gradient = False
            parent_block.append_op(
                type='max_sequence_len',
                inputs={'RankTable': self.lod_rank_table},
                outputs={"Out": self.max_seq_len})
            self.cond.stop_gradient = True
            parent_block.append_op(
                type='less_than',
                inputs={'X': self.step_idx,
                        'Y': self.max_seq_len},
                outputs={'Out': self.cond})

        input_array = parent_block.create_var(
            name=unique_name('dynamic_rnn_input_array'),
            type=core.VarDesc.VarType.LOD_TENSOR_ARRAY,
            dtype=x.dtype)
        self.input_array.append((input_array, x.dtype))
        parent_block.append_op(
            type='lod_tensor_to_array',
            inputs={'X': x,
                    'RankTable': self.lod_rank_table},
            outputs={'Out': input_array})
        return array_read(
            array=input_array, i=self.step_idx, **self.helper.to_kwargs)

    @contextlib.contextmanager
    def block(self):
        if self.status != DynamicRNN.BEFORE_RNN:
            raise ValueError("rnn.block() can only be invoke once")
        self.step_idx = fill_constant(shape=[1], dtype='int64', value=0)
        self.step_idx.stop_gradient = False
        self.status = DynamicRNN.IN_RNN
        with self.while_op.block():
            yield
            increment(
                x=self.step_idx,
                value=1.0,
                in_place=True,
                **self.helper.to_kwargs)

            for new_mem, mem_array in self.mem_link:
                array_write(
                    x=new_mem,
                    i=self.step_idx,
                    array=mem_array,
                    **self.helper.to_kwargs)

            less_than(
                x=self.step_idx,
                y=self.max_seq_len,
                cond=self.cond,
                **self.helper.to_kwargs)

        self.status = DynamicRNN.AFTER_RNN
        for each_array in self.output_array:
            self.outputs.append(
                array_to_lod_tensor(
                    x=each_array,
                    table=self.lod_rank_table,
                    **self.helper.to_kwargs))

    def __call__(self, *args, **kwargs):
        if self.status != DynamicRNN.AFTER_RNN:
            raise ValueError(
                "Dynamic RNN outputs can only be retrieved after rnn block")
        if len(self.outputs) == 1:
            return self.outputs[0]
        else:
            return self.outputs

    def memory(self, init=None, shape=None, value=0.0, dtype='float32'):
        self._assert_in_rnn_block_('memory')
        if init is not None:
            if not isinstance(init, Variable):
                raise TypeError(
                    "The input arg `init` of memory() must be a Variable")
            parent_block = self._parent_block_()
            mem_array = parent_block.create_var(
                name=unique_name('dynamic_rnn_mem_array'),
                type=core.VarDesc.VarType.LOD_TENSOR_ARRAY,
                dtype=init.dtype)
            parent_block.append_op(
                type='write_to_array',
                inputs={'X': init,
                        'I': self.zero_idx},
                outputs={'Out': mem_array})
            retv = array_read(
                array=mem_array, i=self.step_idx, **self.helper.to_kwargs)
            retv = shrink_memory(
                x=retv,
                i=self.step_idx,
                table=self.lod_rank_table,
                **self.helper.to_kwargs)
            self.mem_dict[retv.name] = mem_array
            return retv
        else:
            if len(self.input_array) == 0:
                raise ValueError(
                    "step_input should be invoked before memory(shape=..., value=...)"
                )
            parent_block = self._parent_block_()
            init = parent_block.create_var(
                name=unique_name('mem_init'), dtype=dtype)
            arr, dtype = self.input_array[0]
            in0 = parent_block.create_var(name=unique_name('in0'), dtype=dtype)
            parent_block.append_op(
                type='read_from_array',
                inputs={'X': [arr],
                        'I': [self.zero_idx]},
                outputs={'Out': [in0]})
            parent_block.append_op(
                type='fill_constant_batch_size_like',
                inputs={'Input': [in0]},
                outputs={'Out': [init]},
                attrs={
                    'shape': [-1] + shape,
                    'value': float(value),
                    'dtype': init.dtype
                })
            return self.memory(init=init)

    def update_memory(self, ex_mem, new_mem):
        self._assert_in_rnn_block_('update_memory')
        if not isinstance(ex_mem, Variable):
            raise TypeError("The input arg `ex_mem` of update_memory() must "
                            "be a Variable")
        if not isinstance(new_mem, Variable):
            raise TypeError("The input arg `new_mem` of update_memory() must "
                            "be a Variable")

        mem_array = self.mem_dict.get(ex_mem.name, None)
        if mem_array is None:
            raise ValueError("Please invoke memory before update_memory")
        if self.lod_rank_table is None:
            raise ValueError("Please invoke step_input before update_memory")

        self.mem_link.append((new_mem, mem_array))

    def output(self, *outputs):
        self._assert_in_rnn_block_('output')
        parent_block = self._parent_block_()
        for each in outputs:
            outside_array = parent_block.create_var(
                name=unique_name("_".join(
                    [self.helper.name, "output_array", each.name])),
                type=core.VarDesc.VarType.LOD_TENSOR_ARRAY,
                dtype=each.dtype)
            array_write(x=each, i=self.step_idx, array=outside_array)
            self.output_array.append(outside_array)

    def _parent_block_(self):
        prog = self.helper.main_program
        parent_idx = prog.current_block().parent_idx
        assert parent_idx >= 0
        parent_block = prog.block(parent_idx)

        return parent_block

    def _assert_in_rnn_block_(self, method):
        if self.status != DynamicRNN.IN_RNN:
            raise ValueError("{0} can only be invoked inside rnn block.".format(
                method))