
    ёi.h                   *   S SK Jr  S SKrS SKJr  S SKJrJr  S SKJ	r	J
r
  S SKrS SKJr  S SKrS SKJrJrJrJr  S SKJrJr  S S	KJr  S S
KJrJrJr  S SKJr  S SKJ r J!r!  S SK"J#r$J%r&  S SK'J(r(  SSK)J*r*  SSK+J,r,  \	(       a)  S SKJ-r-  S SKJ.r.  S SK/J0r0J1r1J2r2J3r3J4r4  \-S   r5\-S   r6\-S   r7/ r8    S6               S7S jjr9 " S S5      r:S8S jr;S9S jr<    S6S jr=    S6S jr>   S:               S;S  jjr?  S<       S=S! jjr@  S<       S>S" jjrA " S# S\,5      rB " S$ S%\B5      rC " S& S'\B5      rD " S( S)\B5      rE " S* S+\,5      rF " S, S-\,5      rG " S. S/\*5      rH " S0 S1\H5      rI " S2 S3\H5      rJ " S4 S5\H5      rKg)?    )annotationsN)Sequence)partialreduce)TYPE_CHECKINGAny)Self)_C_ops_legacy_C_ops	frameworkin_dynamic_mode)
check_typecheck_variable_and_dtype)NON_PERSISTABLE_VAR_NAME_SUFFIX)default_startup_programin_dynamic_or_pir_modeprogram_guard)Variable)corein_pir_mode)
functionalinitializertensor_array_to_tensor   )	LayerList)Layer)Literal)Tensor)	DTypeLikeNestedStructureParamAttrLike	ShapeLikeTensorOrTensors)forwardbidirectbidirectional)LSTMGRURNN_RELURNN_TANHtanhreluRNNCellBasec                d    [        5       (       a  [        U UUUUU40 UD6$ [        U UUUUU40 UD6$ )a	  
rnn creates a recurrent neural network specified by RNNCell `cell`,
which performs :code:`cell.call()` (for dygraph mode :code:`cell.forward`)
repeatedly until reaches to the maximum length of `inputs`.

Parameters:
    cell(RNNCellBase): An instance of `RNNCellBase`.
    inputs(Tensor): the input sequences.
        If time_major is True, the shape is
        `[time_steps, batch_size, input_size]`
        else the shape is `[batch_size, time_steps, input_size]`.
    initial_states(Tensor|tuple|list, optional): the initial state of the
        rnn cell. Tensor or a possibly nested structure of tensors. If not
        provided, `cell.get_initial_states` would be called to produce
        the initial state. Defaults to None.
    sequence_length (Tensor|None, optional): shape `[batch_size]`, dtype: int64
        or int32. The valid lengths of input sequences. Defaults to None.
        If `sequence_length` is not None, the inputs are treated as
        padded sequences. In each input sequence, elements whose time step
        index are not less than the valid length are treated as paddings.
    time_major (bool, optional): Whether the first dimension of the input means the
        time steps. Defaults to False.
    is_reverse (bool, optional): Indicate whether to calculate in the reverse
        order of input sequences. Defaults to False.
    **kwargs: Additional keyword arguments to pass to `forward` of the cell.

Returns:
    outputs (Tensor|list|tuple): the output sequence. Tensor or nested
        structure of Tensors.
        If `time_major` is True, the shape of each tensor in outputs is
        `[time_steps, batch_size, hidden_size]`, else
        `[batch_size, time_steps, hidden_size]`.
    final_states (Tensor|list|tuple): final states. A (possibly nested structure of)
        tensor[s], representing the final state for RNN. It has the same
        structure of initial state. Each tensor in final states has the same
        shape and dtype as the corresponding tensor in initial states.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> inputs = paddle.rand((4, 23, 16))
        >>> prev_h = paddle.randn((4, 32))

        >>> cell = paddle.nn.SimpleRNNCell(16, 32)
        >>> rnn = paddle.nn.RNN(cell)
        >>> outputs, final_states = rnn(inputs, prev_h)
        >>> print(outputs.shape)
        paddle.Size([4, 23, 32])
        >>> print(final_states.shape)
        paddle.Size([4, 32])

)r   _rnn_dynamic_graph_rnn_static_graph)cellinputsinitial_statessequence_length
time_major
is_reversekwargss          S/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/nn/layer/rnn.pyrnnr;   @   sb    B !
 
 	
 !
 
 	
    c                  2    \ rS rSrSS jrSS jrS	S jrSrg)
ArrayWrapper   c                    U/U l         g Narrayselfxs     r:   __init__ArrayWrapper.__init__   s    S
r<   c                <    U R                   R                  U5        U $ rA   )rC   appendrD   s     r:   rJ   ArrayWrapper.append   s    

!r<   c                8    U R                   R                  U5      $ rA   )rC   __getitem__)rE   items     r:   rM   ArrayWrapper.__getitem__   s    zz%%d++r<   rB   N)rF   r   returnNone)rF   r   rP   r	   )rN   intrP   r   )__name__
__module____qualname____firstlineno__rG   rJ   rM   __static_attributes__ r<   r:   r>   r>      s    ,r<   r>   c                    [         R                  R                  R                  XSS9[         R                  R                  R                  U SU-
  SS9-   nU$ )z3update rnn state or just pass the old state throughr   axisr   )paddletensormath_multiply_with_axis)state	new_state	step_masks      r:   _maybe_copyrc      sW    ""661 7 ..uq9}A.NOI r<   c           	         SS/[        [        S[        U R                  5      5      5      Qn[        R
                  " X5      $ )Nr   r      )listrangelenshaper\   	transpose)rF   perms     r:   _transpose_batch_timerl      s6    q04aQWW./0DA$$r<   c                l  ^^ U(       a  SOSm[         R                  R                  U5      nUS   R                  T   nUc  U R	                  X(       a  SOSS9nU(       d$  [         R                  R                  [        U5      nUbU  [         R                  R                  R                  R                  X8UR                  S9n	[         R                  " U	SS/5      n	U(       a<  [         R                  R                  S U5      nUb  [         R                  " W	S/S9OS n	Un
/ n[        U5       H  m[         R                  R                  U4S jU5      nU " X40 UD6u  pUb/  [         R                  R                  [        [         W	T   S9X5      nUn
TS:X  a!  [         R                  R                  S	 U5      O [         R                  R                  S
 X5      nM     [         R                  R                  U4S jU5      nU(       a$  [         R                  R                  U4S jU5      nWnUU4$ )Nr   r   	batch_refbatch_dim_idxmaxlendtypec                .    [         R                  " U S/S9$ Nr   rZ   r\   reverserF   s    r:   <lambda>$_rnn_dynamic_graph.<locals>.<lambda>       fnnQaS1r<   rZ   c                   > U T   $ rA   rX   )rF   is    r:   ry   rz      s	    1Q4r<   )rb   c                    [        U 5      $ rA   )r>   rx   s    r:   ry   rz      s    ar<   c                $    UR                  U 5      $ rA   )rJ   )rF   x_arrays     r:   ry   rz      s    7>>!#4r<   c                B   > [         R                  " U R                  TS9$ NrZ   )r\   stackrC   rF   time_step_indexs    r:   ry   rz      s    &,,qww_=r<   c                .   > [         R                  " U TS9$ r   rv   r   s    r:   ry   rz      s    fnnQ_=r<   )r\   utilsflattenri   get_initial_statesmap_structurerl   staticnnsequence_lodsequence_maskrs   rj   rw   rg   r   rc   )r3   r4   r5   r6   r7   r8   r9   flat_inputs
time_stepsmaskstatesoutputsstep_inputsstep_outputs
new_statesfinal_outputsfinal_statesr}   r   s                    @@r:   r1   r1      s    &a1O,,&&v.KQ%%o6J00A 1 
 ++,A6J"}},,::fll ; 
 q!f-++16

 * NN4qc* 	 FG:ll00H#'#Fv#F &33tAw7J  Av LL&&'@,O++4l 	   LL..=wM 22=}
 L,&&r<   c           
     (  ^^ [        US[        [        [        [        R
                  R                  4S5        [        U[        [        45      (       a3  [        U5       H$  u  px[        US[        U5      -   S-   SS/S5        M&     [        US[        [        [        [        S 5      [        R
                  R                  4S5        [        US[        [        S 5      [        R
                  R                  4S5        SS	 jn	Uc  U R                  X(       a  S
OSS9n[        R                  R                  X5      nU(       d$  [        R                  R                  [        U5      n[        R                   " [        R                  R#                  U5      S   5      S   n
[        R$                  " U
[        R&                  5      n
Ubv  [        R(                  R*                  R,                  R/                  UU
[        R                  R#                  U5      S   R0                  S9n[        R2                  " US
S/5      nU(       a<  [        R                  R                  S U5      nUb  [        R4                  " WS/S9OS n[        R6                  R8                  R;                  S5         [        R<                  " / SS9mU
n[        R$                  " US5      nTU:  nS S S 5        [        R(                  R*                  R>                  RA                  W5      n[        RB                  RE                  [        R                  R#                  U5      S   R0                  S9n[        R                  R                  S U5      n[        R                  R                  U4S jUU5        URG                  5          UT   n[        R                  R                  U4S jU5      nU " UU40 UD6u  nn[        U[        R6                  R8                  R                  [        R
                  R                  45      (       d   e[        R                  RI                  UU5        Ub?  [        RJ                  " WT   S
5      m[        R                  R                  U4S jUU5      n[        RB                  RM                  UTU5        [        R6                  R8                  R;                  S5         [        RB                  RO                  TS
S9mS S S 5        [        R                  R                  U4S jUU5        [        R6                  R8                  R;                  S5         [        RB                  RQ                  TW5      n[        RR                  " UU5        S S S 5        S S S 5        [U        USSS9u  nn[        R                  R                  S U5      nUn[        R                  R                  S U5      nU(       a!  [        R                  R                  S U5      nU(       d$  [        R                  R                  [        U5      nUU4$ ! , (       d  f       GNw= f! , (       d  f       GN`= f! , (       d  f       N= f! , (       d  f       N= f)Nr4   r;   zinputs[]float32float64r5   r6   c                    Xl         U $ rA   )stop_gradient)rF   stops     r:   _switch_grad'_rnn_static_graph.<locals>._switch_grad  s    r<   r   r   rn   rq   c                .    [         R                  " U S/S9$ ru   rv   rx   s    r:   ry   #_rnn_static_graph.<locals>.<lambda>+  r{   r<   rZ   cpuint64rs   c                P    [         R                  R                  U R                  S9$ )Nr   )r\   r]   create_arrayrs   rx   s    r:   ry   r   @  s    &--,,177,;r<   c                F   > [         R                  R                  U TU5      $ rA   r\   r]   array_writerF   ystart_is     r:   ry   r   D  s    V]]..q'1=r<   c                D   > [         R                  R                  U T5      $ rA   )r\   r]   
array_read)rF   r   s    r:   ry   r   M  s    fmm..q':r<   c                    > U T-  UST-
  -  -   $ )N      ?rX   )rF   r   rb   s     r:   ry   r   [  s    a)ma3?.CCr<   )rF   valuec                F   > [         R                  R                  U TU5      $ rA   r   r   s     r:   ry   r   e  s    221gqAr<   Tr[   	use_stackc                    [        U SSS9S   $ )Nr   Tr   r   rx   s    r:   ry   r   q  s    (dCAFr<   c                    U S   $ NrX   rx   s    r:   ry   r   u  s    "r<   c                .    [         R                  " U S/S9$ ru   rv   rx   s    r:   ry   r   y  r{   r<   F)+r   r   rf   tupler\   pirValue
isinstance	enumerater   strtyper   r   r   rl   ri   r   castint32r   r   r   r   rs   rj   rw   baser   device_guardzeroscontrol_flowWhiler]   r   blockassert_same_structure	unsqueezer   	increment	less_thanassignr   )r3   r4   r5   r6   r7   r8   r9   r}   input_xr   max_seq_lenr   endcondwhile_op	out_array
init_arraystep_in	pre_stater   r   new_condout_	all_stater   r   r   rb   s                              @@r:   r2   r2      s     8T5&**2B2BCU &4-((#F+JA$SV+c1Iy3I5 , 	4T
FJJ,<,<=	 	4:vzz//0	 00A 1 
 \\//MN++,A6J,,v||33F;A>?BK++k6<<8K"}},,::,,&&~6q9?? ; 

 q!f-++16

 * NN4qc* 	 
			+	+E	2,,r1kk#w'} 
3 }},,2248H**ll""6*1-33 + I ++;^J LL= 
	/LL..:J
	 #7I@@fkk++44fjj6F6FG
 
 	
 
 	**:yA&((g:I
  33DJ 	!!'7I>[[""//6mm--q-AG 7""A	
 [[""//6}}..w<HMM(D) 7C 
J $IAFFC**FI M<<--oyIL221=
 22!=
 <((] 
3	2^ 76 76C 
	sJ   *4Y6D2Z(Y AZ8Y2Z
Y 
Y/	*Z2
Z 	<Z
Zc                   Uc1  U R                  X%(       a  SOSS9nU R                  X%(       a  SOSS9nOUu  px[        U UUU4SU0UD6u  p[        UUUU4USS.UD6u  p[        R                  R	                  S X5      nXx4nX4$ )a9	  
birnn creates a bidirectional recurrent neural network specified by
RNNCell `cell_fw` and `cell_bw`, which performs :code:`cell.call()`
(for dygraph mode :code:`cell.forward`) repeatedly until reaches to
the maximum length of `inputs` and then concat the outputs for both RNNs
along the last axis.

Parameters:
    cell_fw(RNNCellBase): An instance of `RNNCellBase`.
    cell_bw(RNNCellBase): An instance of `RNNCellBase`.
    inputs(Tensor): the input sequences.
        If time_major is True, the shape is
        `[time_steps, batch_size, input_size]`
        else the shape is `[batch_size, time_steps, input_size]`.
    initial_states(tuple|None, optional): A tuple of initial states of
        `cell_fw` and `cell_bw`.
        If not provided, `cell.get_initial_states` would be called to
        produce initial state for each cell. Defaults to None.
    sequence_length (Tensor|None, optional): shape `[batch_size]`, dtype: int64
        or int32. The valid lengths of input sequences. Defaults to None.
        If `sequence_length` is not None, the inputs are treated as
        padded sequences. In each input sequence, elements whose time step
        index are not less than the valid length are treated as paddings.
    time_major (bool): Whether the first dimension of the input means the
        time steps. Defaults to False.
    **kwargs: Additional keyword arguments to pass to `forward` of each cell.

Returns:
    outputs (Tensor): the outputs of the bidirectional RNN. It is the
        concatenation of the outputs from the forward RNN and backward
        RNN along the last axis.
        If time_major is True, the shape is `[time_steps, batch_size, size]`,
        else the shape is `[batch_size, time_steps, size]`, where size is
        `cell_fw.hidden_size + cell_bw.hidden_size`.
    final_states (tuple): A tuple of the final states of the forward
        cell and backward cell.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> cell_fw = paddle.nn.LSTMCell(16, 32)
        >>> cell_bw = paddle.nn.LSTMCell(16, 32)
        >>> rnn = paddle.nn.BiRNN(cell_fw, cell_bw)
        >>> inputs = paddle.rand((2, 23, 16))
        >>> outputs, final_states = rnn(inputs)
        >>> print(outputs.shape)
        paddle.Size([2, 23, 64])
        >>> print(final_states[0][0].shape)
        paddle.Size([2, 32])

r   r   rn   r7   T)r7   r8   c                2    [         R                  " X/S5      $ r   )r\   concat)rF   r   s     r:   ry   birnn.<locals>.<lambda>  s    V]]A62.r<   )r   r;   r\   r   r   )cell_fwcell_bwr4   r5   r6   r7   r9   	states_fw	states_bw
outputs_fw
outputs_bwr   r   s                r:   birnnr     s    @ ..A / 
	 ..A / 
	  .		
  J  	
  J ll((.
G )L  r<   c           	        US:X  a@  [         R                  " U 5      n U(       d  U $ [        [        U SSS2   U SSS2   5      5      $ [	        U 5      U:X  d   e[        U  Vs/ s H  n[         R                  " U5      PM     sn5      n U(       d  [        [        U 6 5      $ [        [        U 6 5      n [        [        U SSS2   U SSS2   5      5      $ s  snf )a{  
Split states of RNN network into possibly nested list or tuple of
states of each RNN cells of the RNN network.

Parameters:
    states (Tensor|tuple|list): the concatenated states for RNN network.
        When `state_components` is 1, states in a Tensor with shape
        `(L*D, N, C)` where `L` is the number of layers of the RNN
        network, `D` is the number of directions of the RNN network(1
        for unidirectional RNNs and 2 for bidirectional RNNs), `N` is
        the batch size of the input to the RNN network, `C` is the
        hidden size of the RNN network.

        When `state_components` is larger than 1, `states` is a tuple of
        `state_components` Tensors that meet the requirements described
        above.

        For SimpleRNNs and GRUs, `state_components` is 1, and for LSTMs,
        `state_components` is 2.
    bidirectional (bool): whether the state is of a bidirectional RNN
        network. Defaults to False.
    state_components (int): the number of the components of the states. see
        `states` above. Defaults to 1.

Returns:
    A nested list or tuple of RNN cell states.
    If `bidirectional` is True, it can be indexed twice to get an RNN
    cell state. The first index indicates the layer, the second index
    indicates the direction.
    If `bidirectional` is False, it can be indexed once to get an RNN
    cell state. The index indicates the layer.
    Note that if `state_components` is larger than 1, an RNN cell state
    can be indexed one more time to get a tensor of shape(N, C), where
    `N` is the batch size of the input to the RNN cell, and `C` is the
    hidden size of the RNN cell.
r   Nre   )r\   unstackrf   ziprh   r   )r   r'   state_componentsrN   s       r:   split_statesr     s    R 1'MF3Q3K16776{....@t,@AV%%#v,'FF3Q3K1677 As   ! Cc                p   US:X  a3  [         R                  " [         R                  R                  U 5      5      $ [         R                  R                  U 5      n / n[	        U5       H  nUR                  XSU2   5        M     [        U Vs/ s H  n[         R                  " U5      PM     sn5      $ s  snf )ah  
Concatenate a possibly nested list or tuple of RNN cell states into a
compact form.

Parameters:
    states (list|tuple): a possibly nested list or tuple of RNN cell
        states.
        If `bidirectional` is True, it can be indexed twice to get an
        RNN cell state. The first index indicates the layer, the second
        index indicates the direction.
        If `bidirectional` is False, it can be indexed once to get an RNN
        cell state. The index indicates the layer.
        Note that if `state_components` is larger than 1, an RNN cell
        state can be indexed one more time to get a tensor of shape(N, C),
        where `N` is the batch size of the input to the RNN cell, and
        `C` is the hidden size of the RNN cell.
    bidirectional (bool): whether the state is of a bidirectional RNN
        network. Defaults to False.
    state_components (int): the number of the components of the states. see
        `states` above. Defaults to 1.

Returns:
    Concatenated states for RNN network.
    When `state_components` is 1, states in a Tensor with shape
    `(L\*D, N, C)` where `L` is the number of layers of the RNN
    network, `D` is the number of directions of the RNN network(1 for
    unidirectional RNNs and 2 for bidirectional RNNs), `N` is the batch
    size of the input to the RNN network, `C` is the hidden size of the
    RNN network.

r   N)r\   r   r   r   rg   rJ   r   )r   r'   r   
componentsr}   rN   s         r:   concat_statesr   !  s    H 1||FLL00899%%f-
'(Af%8(8%89: )Z@ZTfll4(Z@AA@s    B3c                  l    \ rS rSrSr    S           S	S jjr\S
S j5       r\S
S j5       rSr	g)r/   iO  z
RNNCellBase is the base class for abstraction representing the calculations
mapping the input and state to the output and new state. It is suitable to
and mostly used in RNN.
Nc                H  ^^^ [         R                  R                  U5      S   nS n " S S5      mUc  U R                  OUn[         R                  R                  R
                  nU[         R                  R                  l        [         R                  R                  U4S jU5      nU[         R                  R                  l         Tc  U R                  OTn	[        [         R                  R                  U	5      5      S:X  aF  [         R                  R                  U	5      S   m[         R                  R                  U4S jU5      n	Un
UR                  U   S:  a  [        U
[        5      (       a*  U
S    H  nUR                  U   UR                  S'   M!     GO5[        U
[        5      (       a&  U
 H  nUR                  U   UR                  S'   M!     OUR                  U   U
R                  S'   O[        U
[        5      (       aA  U
S    H7  n[         R                  " U5      U   R!                  5       UR                  S'   M9     O[        U
[        5      (       a>  U
 H7  n[         R                  " U5      U   R!                  5       UR                  S'   M9     O4[         R                  " U5      U   R!                  5       U
R                  S'   [         R                  R                  U4S jU
U	5      nU$ ! [         a    [        R                  " 5       n	 GNDf = f)	a  
Generate initialized states according to provided shape, data type and
value.

Parameters:
    batch_ref (Tensor): A tensor, which shape would be used to
        determine the batch size, which is used to generate initial
        states. For `batch_ref`'s shape d, `d[batch_dim_idx]` is
        treated as batch size.
    shape (list|tuple|None, optional): A (possibly nested structure of) shape[s],
        where a shape is a list/tuple of integer. `-1` (for batch size)
        will be automatically prepended if a shape does not starts with
        it. If None, property `state_shape` will be used. Defaults to
        None.
    dtype (str|list|tuple|None, optional): A (possibly nested structure of)
        data type[s]. The structure must be same as that of `shape`,
        except when all tensors' in states has the same data type, a
        single data type can be used. If None and property `cell.state_shape`
        is not available, current default floating type of paddle is
        used. Defaults to None.
    init_value (float, optional): A float value used to initialize states.
        Defaults to 0.
    batch_dim_idx (int, optional): An integer indicating which
        dimension of the of `batch_ref` represents batch. Defaults to 0.

Returns:
    init_states (Tensor|tuple|list): tensor of the provided shape and
        dtype, or list of tensors that each satisfies the requirements,
        packed in the same structure as `shape` and `type` does.
r   c                    [        U [        [        45      (       a  [        S U S5      (       a  g[        U [        5      (       a  g[        U [
        5      =(       a    [        U [        5      (       + $ )z@For shape, list/tuple of integer is the finest-grained objectionc                4    [        U[        5      =(       a    U $ rA   )r   rR   )flagrF   s     r:   ry   LRNNCellBase.get_initial_states.<locals>._is_shape_sequence.<locals>.<lambda>  s    Jq#$6$?4$?r<   TF)r   rf   r   r   dictr   r   )seqs    r:   _is_shape_sequence:RNNCellBase.get_initial_states.<locals>._is_shape_sequence  sX    #e}--?d  !#t$$c8,IZS5I1IIr<   c                      \ rS rSrS rSrg)-RNNCellBase.get_initial_states.<locals>.Shapei  c                ^    US   S:X  a  [        U5      U l        g S/[        U5      QU l        g )Nr   r   )rf   ri   )rE   ri   s     r:   rG   6RNNCellBase.get_initial_states.<locals>.Shape.__init__  s0    #(8r>DK 
9;8Jd5k8J 
r<   )ri   N)rS   rT   rU   rV   rG   rW   rX   r<   r:   Shaper     s    r<   r   c                   > T" U 5      $ rA   rX   )ri   r   s    r:   ry   0RNNCellBase.get_initial_states.<locals>.<lambda>  s	    %,r<   r   c                   > T$ rA   rX   )ri   rs   s    r:   ry   r    s    er<   c                D   > [         R                  " U R                  TUS9$ )Nri   
fill_valuers   )r\   fullri   )ri   rs   
init_values     r:   ry   r    s    kk%"r<   )r\   r   r   state_shapelayers_utilsis_sequencer   state_dtypeNotImplementedErrorr   get_default_dtyperh   ri   r   rf   r   rN   )rE   ro   ri   rs   r  rp   r   states_shapesis_sequence_oristates_dtypesfill_shapessinit_statesr   s      ``        @r:   r   RNNCellBase.get_initial_statesV  s   N LL((3A6	
	J	 	 -2M((u ,,33??0B!!-22&
 1@!!-	:05D,,5M v||##M23q8LL((7:E"LL66#]M $??=)A-+t,,$QA!*!?AGGAJ (K//$A!*!?AGGAJ % (1}'E!!!$+t,,$QA!'i!8!G!L!L!NAGGAJ (K//$A!'i!8!G!L!L!NAGGAJ % (.||I'>!($& !!!$ ll00
 
 M # 	:%779M	:s   K> >L! L!c                    [        S5      e)a  
Abstract method (property).
Used to initialize states.
A (possibly nested structure of) shape[s], where a shape is a
list/tuple of integers (-1 for batch size would be automatically
inserted into a shape if shape is not started with it).
Not necessary to be implemented if states are not initialized by
`get_initial_states` or the `shape` argument is provided when using
`get_initial_states`.
z=Please add implementation for `state_shape` in the used cell.r  rE   s    r:   r  RNNCellBase.state_shape       "K
 	
r<   c                    [        S5      e)a  
Abstract method (property).
Used to initialize states.
A (possibly nested structure of) data types[s]. The structure must be
same as that of `shape`, except when all tensors' in states has the same
data type, a single data type can be used.
Not necessary to be implemented if states are not initialized
by `get_initial_states` or the `dtype` argument is provided when using
`get_initial_states`.
z=Please add implementation for `state_dtype` in the used cell.r  r  s    r:   r  RNNCellBase.state_dtype  r  r<   rX   )NN        r   )ro   r   ri   z!NestedStructure[ShapeLike] | Noners   z!NestedStructure[DTypeLike] | Noner  floatrp   rR   rP   zNestedStructure[Tensor]rP   rQ   )
rS   rT   rU   rV   __doc__r   propertyr  r  rW   rX   r<   r:   r/   r/   O  s     4837mm 1m 1	m
 m m 
!m^ 
 
 
 
r<   c                     ^  \ rS rSrSr      S                 S	U 4S jjjrS
SS jjr\SS j5       rSS jr	Sr
U =r$ )SimpleRNNCelli  aU  
Elman RNN (SimpleRNN) cell. Given the inputs and previous states, it
computes the outputs and updates states.

The formula used is as follows:

.. math::
    h_{t} & = act(W_{ih}x_{t} + b_{ih} + W_{hh}h_{t-1} + b_{hh})

    y_{t} & = h_{t}

where :math:`act` is for :attr:`activation`.

Please refer to `Finding Structure in Time
<https://crl.ucsd.edu/~elman/Papers/fsit.pdf>`_ for more details.

Parameters:
    input_size (int): The input size.
    hidden_size (int): The hidden size.
    activation (str, optional): The activation in the SimpleRNN cell.
        It can be `tanh` or `relu`. Defaults to `tanh`.
    weight_ih_attr (ParamAttr|None, optional): The parameter attribute for
        :math:`weight_ih`. Default: None.
    weight_hh_attr(ParamAttr|None, optional): The parameter attribute for
        :math:`weight_hh`. Default: None.
    bias_ih_attr (ParamAttr|None, optional): The parameter attribute for the
        :math:`bias_ih`. Default: None.
    bias_hh_attr (ParamAttr|None, optional): The parameter attribute for the
        :math:`bias_hh`. Default: None.
    name (str|None, optional): Name for the operation (optional, default is
        None). For more information, please refer to :ref:`api_guide_Name`.

Variables:
    - **weight_ih** (Parameter): shape (hidden_size, input_size), input to hidden weight, corresponding to :math:`W_{ih}` in the formula.
    - **weight_hh** (Parameter): shape (hidden_size, hidden_size), hidden to hidden weight, corresponding to :math:`W_{hh}` in the formula.
    - **bias_ih** (Parameter): shape (hidden_size, ), input to hidden bias, corresponding to :math:`b_{ih}` in the formula.
    - **bias_hh** (Parameter): shape (hidden_size, ), hidden to hidden bias, corresponding to :math:`b_{hh}` in the formula.

Inputs:
    - **inputs** (Tensor): shape `[batch_size, input_size]`, the input, corresponding to :math:`x_{t}` in the formula.
    - **states** (Tensor, optional): shape `[batch_size, hidden_size]`, the previous hidden state, corresponding to :math:`h_{t-1}` in the formula. When states is None, zero state is used. Defaults to None.

Returns:
    - **outputs** (Tensor): shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula.
    - **states** (Tensor): shape `[batch_size, hidden_size]`, the new hidden state, corresponding to :math:`h_{t}` in the formula.

Notes:
    All the weights and bias are initialized with `Uniform(-std, std)` by default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more information about parameter initialization, please refer to :ref:`api_paddle_ParamAttr`.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> x = paddle.randn((4, 16))
        >>> prev_h = paddle.randn((4, 32))

        >>> cell = paddle.nn.SimpleRNNCell(16, 32)
        >>> y, h = cell(x, prev_h)
        >>> print(y.shape)
        paddle.Size([4, 32])

c	           	       > [         T
U ]  5         US::  a%  [        SU R                  R                   SU 35      eS[
        R                  " U5      -  n	USLa.  U R                  X!4U[        R                  " U	* U	5      S9U l
        O<U R                  X!4S [        R                  " S5      S9U l
        SU R                  l        USLa.  U R                  X"4U[        R                  " U	* U	5      S9U l        O<U R                  X"4S [        R                  " S5      S9U l        SU R                  l        USLa/  U R                  U4US[        R                  " U	* U	5      S9U l        O=U R                  U4S S[        R                  " S	5      S9U l        SU R                  l        USLa/  U R                  U4US[        R                  " U	* U	5      S9U l        O=U R                  U4S S[        R                  " S	5      S9U l        SU R                  l        Xl        X l        US
;  a  [        SU 35      eX0l        US:X  a  [&        R(                  U l        g [*        R,                  U l        g )Nr   hidden_size of + must be greater than 0, but now equals to r   Fdefault_initializerTis_biasr'  r  r,   z=activation for SimpleRNNCell should be tanh or relu, but get r-   )superrG   
ValueError	__class__rS   r^   sqrtcreate_parameterIUniform	weight_ihConstantr   	weight_hhbias_ihbias_hh
input_sizehidden_size
activationr\   r-   Fr.   _activation_fn)rE   r6  r7  r8  weight_ih_attrweight_hh_attrbias_ih_attrbias_hh_attrnamestdr,  s             r:   rG   SimpleRNNCell.__init__(  s    	!!$.."9"9!::efqers  DIIk**&!22)$%IIsdC$8 3 DN "22)$%JJsO 3 DN
 ,0DNN(&!22*$%IIsdC$8 3 DN "22*$%JJsO 3 DN
 ,0DNN(u$00$%IIsdC$8	 1 DL  00$%JJsO	 1 DL *.DLL&u$00$%IIsdC$8	 1 DL  00$%JJsO	 1 DL *.DLL&$&--%,(  %-76-Afkkqvvr<   c                V   Uc  U R                  XR                  5      nUn[        R                  " XR                  SS9nU R
                  b  X@R
                  -  n[        R                  " X0R                  SS9nU R                  b  XPR                  -  nU R                  XE-   5      nXf4$ )NTtranspose_y)	r   r  r\   matmulr1  r4  r3  r5  r:  )rE   r4   r   pre_hi2hh2hhs          r:   r%   SimpleRNNCell.forward  s    >,,V5E5EFFmmFNNE<<#<<CmmE>>tD<<#<<C	*tr<   c                    U R                   4$ rA   r7  r  s    r:   r  SimpleRNNCell.state_shape  s      ""r<   c                h    SnU R                   S:w  a  US-  nUR                  " S0 U R                  D6$ )N{input_size}, {hidden_size}r-   z, activation={activation}rX   )r8  format__dict__)rE   r  s     r:   
extra_reprSimpleRNNCell.extra_repr  s4    )??f$,,Axx($--((r<   )r:  r8  r5  r4  r7  r6  r3  r1  )r-   NNNNN)r6  rR   r7  rR   r8  _ActivationType | strr;  ParamAttrLike | Noner<  rU  r=  rU  r>  rU  r?  
str | NonerP   rQ   rA   )r4   r   r   Tensor | NonerP   z
tuple[int]rP   r   rS   rT   rU   rV   r  rG   r%   r   r  rR  rW   __classcell__r,  s   @r:   r"  r"    s    ?J -3/3/3-1-1UNUN UN *	UN
 -UN -UN +UN +UN UN 
UN UNn # #) )r<   r"  c                     ^  \ rS rSrSr      S                 S	U 4S jjjrS
SS jjr\SS j5       rSS jr	Sr
U =r$ )LSTMCelli  a  
Long-Short Term Memory(LSTM) RNN cell. Given the inputs and previous states,
it computes the outputs and updates states.

The formula used is as follows:

.. math::
    i_{t} & = \sigma(W_{ii}x_{t} + b_{ii} + W_{hi}h_{t-1} + b_{hi})

    f_{t} & = \sigma(W_{if}x_{t} + b_{if} + W_{hf}h_{t-1} + b_{hf})

    o_{t} & = \sigma(W_{io}x_{t} + b_{io} + W_{ho}h_{t-1} + b_{ho})

    \widetilde{c}_{t} & = \tanh (W_{ig}x_{t} + b_{ig} + W_{hg}h_{t-1} + b_{hg})

    c_{t} & = f_{t} * c_{t-1} + i_{t} * \widetilde{c}_{t}

    h_{t} & = o_{t} * \tanh(c_{t})

    y_{t} & = h_{t}

If `proj_size` is specified, the dimension of hidden state :math:`h_{t}` will be projected to `proj_size`:

.. math::

    h_{t} = h_{t}W_{proj\_size}

where :math:`\sigma` is the sigmoid function, and * is the elementwise
multiplication operator.

Please refer to `An Empirical Exploration of Recurrent Network Architectures
<http://proceedings.mlr.press/v37/jozefowicz15.pdf>`_ for more details.

Parameters:
    input_size (int): The input size.
    hidden_size (int): The hidden size.
    weight_ih_attr(ParamAttr|None, optional): The parameter attribute for
        `weight_ih`. Default: None.
    weight_hh_attr(ParamAttr|None, optional): The parameter attribute for
        `weight_hh`. Default: None.
    bias_ih_attr (ParamAttr|None, optional): The parameter attribute for the
        `bias_ih`. Default: None.
    bias_hh_attr (ParamAttr|None, optional): The parameter attribute for the
        `bias_hh`. Default: None.
    proj_size (int, optional): If specified, the output hidden state
        will be projected to `proj_size`. `proj_size` must be smaller than
        `hidden_size`. Default: None.
    name (str|None, optional): Name for the operation (optional, default is
        None). For more information, please refer to :ref:`api_guide_Name`.

Variables:
    - **weight_ih** (Parameter): shape (4 * hidden_size, input_size), input to hidden weight, which corresponds to the concatenation of :math:`W_{ii}, W_{if}, W_{ig}, W_{io}` in the formula.
    - **weight_hh** (Parameter): shape (4 * hidden_size, hidden_size), hidden to hidden weight, which corresponds to the concatenation of :math:`W_{hi}, W_{hf}, W_{hg}, W_{ho}` in the formula. If proj_size was specified, the shape will be (4 * hidden_size, proj_size).
    - **weight_ho** (Parameter, optional): shape (hidden_size, proj_size), project the hidden state.
    - **bias_ih** (Parameter): shape (4 * hidden_size, ), input to hidden bias, which corresponds to the concatenation of :math:`b_{ii}, b_{if}, b_{ig}, b_{io}` in the formula.
    - **bias_hh** (Parameter): shape (4 * hidden_size, ), hidden to hidden bias, which corresponds to the concatenation of :math:`b_{hi}, b_{hf}, b_{hg}, b_{ho}` in the formula.

Inputs:
    - **inputs** (Tensor): shape `[batch_size, input_size]`, the input, corresponding to :math:`x_t` in the formula.
    - **states** (list|tuple, optional): a list/tuple of two tensors, each of shape `[batch_size, hidden_size]`, the previous hidden state, corresponding to :math:`h_{t-1}, c_{t-1}` in the formula. When states is None, zero state is used. Defaults to None.

Returns:
    - **outputs** (Tensor). Shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula. If `proj_size` is specified, output shape will be `[batch_size, proj_size]`.
    - **states** (tuple). A tuple of two tensors, each of shape `[batch_size, hidden_size]`, the new hidden states, corresponding to :math:`h_{t}, c_{t}` in the formula.
        If `proj_size` is specified, shape of :math:`h_{t}` will be `[batch_size, proj_size]`.

Notes:
    All the weights and bias are initialized with `Uniform(-std, std)` by
    default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more
    information about parameter initialization, please refer to :ref:`api_paddle_ParamAttr`.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> x = paddle.randn((4, 16))
        >>> prev_h = paddle.randn((4, 32))
        >>> prev_c = paddle.randn((4, 32))

        >>> cell = paddle.nn.LSTMCell(16, 32)
        >>> y, (h, c) = cell(x, (prev_h, prev_c))

        >>> print(y.shape)
        paddle.Size([4, 32])
        >>> print(h.shape)
        paddle.Size([4, 32])
        >>> print(c.shape)
        paddle.Size([4, 32])

c	           	       > [         T
U ]  5         US::  a%  [        SU R                  R                   SU 35      eUS:  a%  [        SU R                  R                   SU 35      eXr:  a  [        S5      eS[
        R                  " U5      -  n	USLa2  U R                  SU-  U4U[        R                  " U	* U	5      S	9U l
        O@U R                  SU-  U4S [        R                  " S5      S	9U l
        S
U R                  l        USLa;  U R                  SU-  U=(       d    U4U[        R                  " U	* U	5      S	9U l        OIU R                  SU-  U=(       d    U4S [        R                  " S5      S	9U l        S
U R                  l        USLa2  U R                  SU-  4US
[        R                  " U	* U	5      S9U l        O@U R                  SU-  4S S
[        R                  " S5      S9U l        S
U R                  l        USLa2  U R                  SU-  4US
[        R                  " U	* U	5      S9U l        O@U R                  SU-  4S S
[        R                  " S5      S9U l        S
U R                  l        Xpl        US:  a-  U R                  X'4U[        R                  " U	* U	5      S	9U l        X l        Xl        [(        R*                  U l        [.        R0                  U l        g )Nr   r$  r%  zproj_size of z*proj_size must be smaller than hidden_sizer   F   r&  Tr(  r  )r*  rG   r+  r,  rS   r^   r-  r.  r/  r0  r1  r2  r   r3  r4  r5  	proj_size	weight_hor7  r6  r9  sigmoid_gate_activationr\   r-   _activation)rE   r6  r7  r;  r<  r=  r>  ra  r?  r@  r,  s             r:   rG   LSTMCell.__init__  s	    	!!$.."9"9!::efqers  q= 7 788cdocpq  #IJJDIIk**&!22[*-$%IIsdC$8 3 DN "22[*-$%JJsO 3 DN
 ,0DNN(&!22[)":{;$%IIsdC$8 3 DN "22[)":{;$%JJsO 3 DN
 ,0DNN(u$00["$%IIsdC$8	 1 DL  00["$%JJsO	 1 DL *.DLL&u$00["$%IIsdC$8	 1 DL  00["$%JJsO	 1 DL *.DLL&"q=!22($%IIsdC$8 3 DN '$ !		!;;r<   c                   Uc  U R                  XR                  5      nUu  p4[        R                  " XR                  SS9nU R
                  b  XPR
                  -   nU[        R                  " X0R                  SS9-  nU R                  b  XPR                  -   n[        R                  " USSS9nU R                  US   5      nU R                  US   5      nU R                  US   5      n	X-  XpR                  US	   5      -  -   n
XR                  U
5      -  nU R                  S:  a   [        R                  " XR                  5      nXU
44$ )
NTrC  r`  r   num_or_sectionsr[   r   r      re   )r   r  r\   rE  r1  r4  r3  r5  splitrd  re  ra  rb  )rE   r4   r   
pre_hiddenpre_cellgateschunked_gatesr}   focrI  s               r:   r%   LSTMCell.forwardT  s+   >,,V5E5EFF%
fnn$G<<#LL(Ez>>tLL<<#LL(EUABG!!-"23!!-"23!!-"23L1//a0@AAA  ##>>Aa0Aa&yr<   c                \    U R                   4U R                  =(       d    U R                   44$ )z
The `state_shape` of LSTMCell is a tuple with two shapes:
`((hidden_size, ), (hidden_size,))`. (-1 for batch size would be
automatically inserted into shape). These two shapes correspond
to :math:`h_{t-1}` and :math:`c_{t-1}` separately.
)r7  ra  r  s    r:   r  LSTMCell.state_shapek  s*     !!#dnn&H8H8H%JKKr<   c                :    SR                   " S0 U R                  D6$ NrO  rX   rP  rQ  r  s    r:   rR  LSTMCell.extra_repru      ,33DdmmDDr<   )
re  rd  r5  r4  r7  r6  ra  r3  rb  r1  )NNNNr   N)r6  rR   r7  rR   r;  rU  r<  rU  r=  rU  r>  rU  ra  rR   r?  rV  rP   rQ   rA   )r4   r   r   zSequence[Tensor] | None)rP   ztuple[tuple[int], tuple[int]]rY  rZ  r\  s   @r:   r^  r^    s    [B 04/3-1-1]']' ]' -	]'
 -]' +]' +]' ]' ]' 
]' ]'~. L LE Er<   r^  c                     ^  \ rS rSrSr     S               S	U 4S jjjr S
     SS jjr\SS j5       rSS jr	Sr
U =r$ )GRUCelliy  a  
Gated Recurrent Unit (GRU) RNN cell. Given the inputs and previous states,
it computes the outputs and updates states.

The formula for GRU used is as follows:

..  math::

    r_{t} & = \sigma(W_{ir}x_{t} + b_{ir} + W_{hr}h_{t-1} + b_{hr})

    z_{t} & = \sigma(W_{iz}x_{t} + b_{iz} + W_{hz}h_{t-1} + b_{hz})

    \widetilde{h}_{t} & = \tanh(W_{ic}x_{t} + b_{ic} + r_{t} * (W_{hc}h_{t-1} + b_{hc}))

    h_{t} & = z_{t} * h_{t-1} + (1 - z_{t}) * \widetilde{h}_{t}

    y_{t} & = h_{t}

where :math:`\sigma` is the sigmoid function, and * is the elementwise
multiplication operator.

Please refer to `An Empirical Exploration of Recurrent Network Architectures
<http://proceedings.mlr.press/v37/jozefowicz15.pdf>`_ for more details.

Parameters:
    input_size (int): The input size.
    hidden_size (int): The hidden size.
    weight_ih_attr(ParamAttr|None, optional): The parameter attribute for
        `weight_ih`. Default: None.
    weight_hh_attr(ParamAttr|None, optional): The parameter attribute for
        `weight_hh`. Default: None.
    bias_ih_attr (ParamAttr|None, optional): The parameter attribute for the
        `bias_ih`. Default: None.
    bias_hh_attr (ParamAttr|None, optional): The parameter attribute for the
        `bias_hh`. Default: None.
    name (str|None, optional): Name for the operation (optional, default is
        None). For more information, please refer to :ref:`api_guide_Name`.

Variables:
    - **weight_ih** (Parameter): shape (3 * hidden_size, input_size), input to hidden weight, which corresponds to the concatenation of :math:`W_{ir}, W_{iz}, W_{ic}` in the formula.
    - **weight_hh** (Parameter): shape (3 * hidden_size, hidden_size), hidden to hidden weight, which corresponds to the concatenation of :math:`W_{hr}, W_{hz}, W_{hc}` in the formula.
    - **bias_ih** (Parameter): shape (3 * hidden_size, ), input to hidden bias, which corresponds to the concatenation of :math:`b_{ir}, b_{iz}, b_{ic}` in the formula.
    - **bias_hh** (Parameter): shape (3 * hidden_size, ), hidden to hidden bias, which corresponds to the concatenation of :math:`b_{hr}, b_{hz}, b_{hc}` in the formula.

Inputs:
    - **inputs** (Tensor): A tensor with shape `[batch_size, input_size]`, corresponding to :math:`x_t` in the formula.
    - **states** (Tensor): A tensor with shape `[batch_size, hidden_size]`, corresponding to :math:`h_{t-1}` in the formula.

Returns:
    - **outputs** (Tensor): shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula.
    - **states** (Tensor): shape `[batch_size, hidden_size]`, the new hidden state, corresponding to :math:`h_{t}` in the formula.

Notes:
    All the weights and bias are initialized with `Uniform(-std, std)` by
    default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more
    information about parameter initialization, please refer to s:ref:`api_paddle_ParamAttr`.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> x = paddle.randn((4, 16))
        >>> prev_h = paddle.randn((4, 32))

        >>> cell = paddle.nn.GRUCell(16, 32)
        >>> y, h = cell(x, prev_h)

        >>> print(y.shape)
        paddle.Size([4, 32])
        >>> print(h.shape)
        paddle.Size([4, 32])


c           	       > [         T	U ]  5         US::  a%  [        SU R                  R                   SU 35      eS[
        R                  " U5      -  nUSLa2  U R                  SU-  U4U[        R                  " U* U5      S9U l
        O@U R                  SU-  U4S [        R                  " S5      S9U l
        SU R                  l        USLa2  U R                  SU-  U4U[        R                  " U* U5      S9U l        O@U R                  SU-  U4S [        R                  " S5      S9U l        SU R                  l        USLa2  U R                  SU-  4US[        R                  " U* U5      S	9U l        O@U R                  SU-  4S S[        R                  " S
5      S	9U l        SU R                  l        USLa2  U R                  SU-  4US[        R                  " U* U5      S	9U l        O@U R                  SU-  4S S[        R                  " S
5      S	9U l        SU R                  l        X l        Xl        [$        R&                  U l        [*        R,                  U l        g )Nr   r$  r%  r   Frj  r&  Tr(  r  )r*  rG   r+  r,  rS   r^   r-  r.  r/  r0  r1  r2  r   r3  r4  r5  r7  r6  r9  rc  rd  r\   r-   re  )
rE   r6  r7  r;  r<  r=  r>  r?  r@  r,  s
            r:   rG   GRUCell.__init__  s{    	!!$.."9"9!::efqers  DIIk**&!22[*-$%IIsdC$8 3 DN "22[*-$%JJsO 3 DN
 ,0DNN(&!22[+.$%IIsdC$8 3 DN "22[+.$%JJsO 3 DN
 ,0DNN(u$00["$%IIsdC$8	 1 DL  00["$%JJsO	 1 DL *.DLL&u$00["$%IIsdC$8	 1 DL  00["$%JJsO	 1 DL *.DLL&&$ !		!;;r<   c                    Uc  U R                  XR                  5      nUn[        R                  " XR                  SS9nU R
                  b  X@R
                  -   n[        R                  " X0R                  SS9nU R                  b  XPR                  -   n[        R                  " USSS9u  pgn[        R                  " USSS9u  pnU R                  Xi-   5      nU R                  Xz-   5      nU R                  XU-  -   5      nX>-
  U-  U-   nX4$ )NTrC  rj  r   rh  )r   r  r\   rE  r1  r4  r3  r5  rk  rd  re  )rE   r4   r   rl  x_gatesh_gatesx_rx_zx_ch_rh_zh_crzrr  rI  s                   r:   r%   GRUCell.forward  s     >,,V5E5EFF
--DI<<#,G--
NNM<<#,GWaaH#WaaH#!!#),!!#),Ss7]+^q 1$tr<   c                    U R                   4$ )z
The `state_shape` of GRUCell is a shape `[hidden_size]` (-1 for batch
size would be automatically inserted into shape). The shape corresponds
to the shape of :math:`h_{t-1}`.
rL  r  s    r:   r  GRUCell.state_shape/  s       ""r<   c                :    SR                   " S0 U R                  D6$ rw  rx  r  s    r:   rR  GRUCell.extra_repr8  rz  r<   )re  rd  r5  r4  r7  r6  r3  r1  )NNNNN)r6  rR   r7  rR   r;  rU  r<  rU  r=  rU  r>  rU  r?  rV  rP   rQ   rA   )r4   r   r   rW  rP   ztuple[Tensor, Tensor]rX  rY  rZ  r\  s   @r:   r|  r|  y  s    Kb 04/3-1-1N'N' N' -	N'
 -N' +N' +N' N' 
N' N'b 7;&3	0 # #E Er<   r|  c                  f   ^  \ rS rSrSr  S       SU 4S jjjr  S       S	S jjrSrU =r$ )
RNNi<  aF
  
Wrapper for RNN, which creates a recurrent neural network with an RNN cell.
It performs :code:`cell.forward()` repeatedly until reaches to the maximum
length of `inputs`.

Parameters:
    cell(RNNCellBase): An instance of `RNNCellBase`.
    is_reverse (bool, optional): Indicate whether to calculate in the reverse
        order of input sequences. Defaults to False.
    time_major (bool): Whether the first dimension of the input means the
        time steps. Defaults to False.

Inputs:
    - **inputs** (Tensor): A (possibly nested structure of) tensor[s]. The input sequences. If time_major is False, the shape is `[batch_size, time_steps, input_size]`. If time_major is True, the shape is `[time_steps, batch_size, input_size]` where `input_size` is the input size of the cell.
    - **initial_states** (Tensor|list|tuple, optional): Tensor of a possibly nested structure of tensors, representing the initial state for the rnn cell. If not provided, `cell.get_initial_states` would be called to produce the initial states. Defaults to None.
    - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None.If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings.
    - **kwargs**: Additional keyword arguments to pass to `forward` of the cell.

Outputs:
    - **outputs** (Tensor|list|tuple): the output sequences. If `time_major` is True, the shape is `[time_steps, batch_size, hidden_size]`, else `[batch_size, time_steps, hidden_size]`.
    - **final_states** (Tensor|list|tuple): final states of the cell. Tensor or a possibly nested structure of tensors which has the same structure with initial state. Each tensor in final states has the same shape and dtype as the corresponding tensor in initial states.

Notes:
    This class is a low-level API for wrapping rnn cell into a RNN network.
    Users should take care of the state of the cell. If `initial_states` is
    passed to the `forward` method, make sure that it satisfies the
    requirements of the cell.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> inputs = paddle.rand((4, 23, 16))
        >>> prev_h = paddle.randn((4, 32))

        >>> cell = paddle.nn.SimpleRNNCell(16, 32)
        >>> rnn = paddle.nn.RNN(cell)
        >>> outputs, final_states = rnn(inputs, prev_h)

        >>> print(outputs.shape)
        paddle.Size([4, 23, 32])
        >>> print(final_states.shape)
        paddle.Size([4, 32])

c                   > [         TU ]  5         Xl        [        U R                  S5      (       d%  U R                  R                  U R                  l        X l        X0l        g )Ncall)r*  rG   r3   hasattrr%   r  r8   r7   )rE   r3   r8   r7   r,  s       r:   rG   RNN.__init__m  sE     		tyy&))!YY..DIIN$$r<   c                l    [        U R                  U4UUU R                  U R                  S.UD6u  pVXV4$ )N)r5   r6   r7   r8   )r;   r3   r7   r8   )rE   r4   r5   r6   r9   r   r   s          r:   r%   RNN.forward{  sK     '*II'
 *+'
 '
# **r<   )r3   r8   r7   )FF)r3   r/   r8   boolr7   r  rP   rQ   NN)r4   r   r5   TensorOrTensors | Noner6   r   r9   r   	rS   rT   rU   rV   r  rG   r%   rW   r[  r\  s   @r:   r  r  <  sy    .f ! 	%% % 	%
 
% %" 26"&	++ /+  	+
 + +r<   r  c                  h   ^  \ rS rSrSr S       SU 4S jjjr  S         S	S jjrSrU =r$ )
BiRNNi  a
  
Wrapper for bidirectional RNN, which builds a bidirectional RNN given the
forward rnn cell and backward rnn cell. A BiRNN applies forward RNN and
backward RNN with corresponding cells separately and concats the outputs
along the last axis.

Parameters:
    cell_fw (RNNCellBase): A RNNCellBase instance used for forward RNN.
    cell_bw (RNNCellBase): A RNNCellBase instance used for backward RNN.
    time_major (bool, optional): Whether the first dimension of the input means the
        time steps. Defaults to False.

Inputs:
    - **inputs** (Tensor): the input sequences of both RNN. If time_major is True, the shape of is `[time_steps, batch_size, input_size]`, else the shape is `[batch_size, time_steps, input_size]`, where input_size is the input size of both cells.
    - **initial_states** (list|tuple|None, optional): A tuple/list of the initial states of the forward cell and backward cell. Defaults to None. If not provided, `cell.get_initial_states` would be called to produce the initial states for each cell. Defaults to None.
    - **sequence_length** (Tensor|None, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings.
    - **kwargs**: Additional keyword arguments. Arguments passed to `forward` for each cell.

Outputs:
    - **outputs** (Tensor): the outputs of the bidirectional RNN. It is the concatenation of the outputs from the forward RNN and backward RNN along the last axis. If time_major is True, the shape is `[time_steps, batch_size, size]`, else the shape is `[batch_size, time_steps, size]`, where size is `cell_fw.hidden_size + cell_bw.hidden_size`.
    - **final_states** (tuple): A tuple of the final states of the forward cell and backward cell.

Notes:
    This class is a low level API for wrapping rnn cells into a BiRNN
    network. Users should take care of the states of the cells.
    If `initial_states` is passed to the `forward` method, make sure that
    it satisfies the requirements of the cells.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> cell_fw = paddle.nn.LSTMCell(16, 32)
        >>> cell_bw = paddle.nn.LSTMCell(16, 32)
        >>> rnn = paddle.nn.BiRNN(cell_fw, cell_bw)

        >>> inputs = paddle.rand((2, 23, 16))
        >>> outputs, final_states = rnn(inputs)

        >>> print(outputs.shape)
        paddle.Size([2, 23, 64])
        >>> print(
        ...     final_states[0][0].shape,
        ...     len(final_states),
        ...     len(final_states[0]),
        ... )
        paddle.Size([2, 32]) 2 2

c                L  > [         TU ]  5         Xl        X l        UR                  UR                  :w  a&  [        SUR                   SUR                   S35      eU R                  U R                  4 H'  n[        US5      (       a  M  UR                  Ul        M)     X0l	        g )Nzinput size of forward cell(z') does not equalsthat of backward cell()r  )
r*  rG   r   r   r6  r+  r  r%   r  r7   )rE   r   r   r7   r3   r,  s        r:   rG   BiRNN.__init__  s     	!3!33-g.@.@-A B))0););(<A?  \\4<<0D4(( LL	 1 %r<   c                    [        U[        [        45      (       a  [        U5      S:X  d   S5       e[	        U R
                  U R                  UUUU R                  40 UD6u  pVXV4$ )Nre   z<length of initial_states should be 2 when it is a list/tuple)r   rf   r   rh   r   r   r   r7   )rE   r4   r5   r6   r9   r   r   s          r:   r%   BiRNN.forward  st     ntUm44~&!+ N+ !&LLLLOO!
 !
 $$r<   )r   r   r7   r   )r   r/   r   r/   r7   r  rP   rQ   r  )
r4   r   r5   +tuple[Tensor, Tensor] | list[Tensor] | Noner6   rW  r9   r   rP   $tuple[Tensor, tuple[Tensor, Tensor]]r  r\  s   @r:   r  r    s    2p !	%% % 	%
 
% %. GK)-	%% D% '	%
 % 
.% %r<   r  c                     ^  \ rS rSrSr         S	                         S
U 4S jjjrSS jr        SS jr  S       SS jjrSS jr	Sr
U =r$ )RNNBasei  z
RNNBase class for RNN networks. It provides `forward`, `flatten_parameters`
and other common methods for SimpleRNN, LSTM and GRU.
c           	       > [         TU ]  5         SS/nXl        X l        X0l        Xpl        X];   a  SOSU l        X`l        X@l        US:X  a  SOSU l	        UU	U
US.nXl
        US:  a  US:X  d   eUS:X  a  [        nXS'   OFUS	:X  a  [        nO9US
:X  a  [        nSUS'   O'US:X  a  [        nSUS'   O[        nU R                  US'   U=(       d    UnUS;   aa  SnU" X#40 UD6nU R                  [!        UUU5      5        [#        SU5       H)  nU" UU40 UD6nU R                  [!        UUU5      5        M+     OX];   ax  U" X#40 UD6nU" X#40 UD6nU R                  [%        UUU5      5        [#        SU5       H9  nU" SU-  U40 UD6nU" SU-  U40 UD6nU R                  [%        UUU5      5        M;     O['        SU 35      eSU l        U =R(                  [+        U R-                  5       5      US-  X];   a  SOS-  :H  -  sl        / n[#        U R                  5       H  n[#        U R                  5       Hn  nUS:X  a  SOSnUR/                  SS/5        U
SLa  UR                  S5        USLa  UR                  S5        U Vs/ s H  nUR1                  UU5      PM     nnMp     M     [3        UU R-                  5       5       H  u  nn[5        U UU5        M     U R7                  5         g s  snf )Nr'   r&   re   r   r(   )r;  r<  r=  r>  r   ra  r)   r*   r.   r8  r+   r-   )r%   FzQdirection should be forward or bidirect (or bidirectional), received direction = Tr`  _reverse zweight_ih_l{}{}zweight_hh_l{}{}zbias_ih_l{}{}zbias_hh_l{}{})r*  rG   moder6  r7  dropoutnum_directionsr7   
num_layersr   ra  r^  r|  r"  r8  rJ   r  rg   r  r+  could_use_cudnnrh   
parametersextendrP  r   setattrflatten_parameters)rE   r  r6  r7  r  	directionr7   r  r;  r<  r=  r>  ra  bidirectional_listr9   rnn_clsin_sizer8   r3   r   r   r   param_nameslayernumsuffixrF   r?  paramr,  s                                r:   rG   RNNBase.__init__  s#    	)8*(E	$&#,#Ba$$%)V^ -,((	"
 #q=6>!>6>G"+;U]GZ#G#)F< Z#G#)F< #G#'??F< *{#J:=f=DKKD*j9:1j)w>v>Cj*=> * ,j@@Gj@@GKKgw
;<1j)!!g+{EfE!!g+{EfEE'7J?@ *
 ((1{4 
  $DOO$5 6*q.0Aa;
 !
 	
 4??+ET001'*axR""$57H#IJu,&&7u,&&7@KL1qxxv6L 2 , {DOO,=>KD%D$& ? 	!	 Ms   K.c                >   U R                   (       GaS  U R                  SS9nU Vs/ s H#  n[        R                  " UR                  5      PM%     nnS/[        U5      -  U l        [        U5       HJ  u  pBUS-  S:  a  SOSU R                  -  U R                  -  nUS-  nX R                  XVS-  -   US-  -   '   ML     U R                  [        R                  " U5      /US   R                  [        R                  " S5      S9/U l        [!        5       (       ao  ["        R$                  R&                  R                  S	S/S
[(         3["        R*                  R,                  R                  SS9SS9U l        SU R.                  l        O>U R3                  [&        R4                  R6                  R8                  S
[(         3S9U l        [;        5       (       a  ["        R<                  " 5          US   R                  n[?        U[&        R@                  5      (       a'  ["        RB                  RD                  RF                  U   n[H        RJ                  " U R                  U R                  U R                  S   SSSSSU5	         SSS5        g[M        [O        5       [O        5       5         ["        R<                  " 5          [!        5       (       a8  [P        RJ                  " U R                  US   R                  SSSSSSS/ / 5        OPU RR                  RU                  SSU R                  0U R                  U R                  S.SSUS   R                  S.S9  SSS5        SSS5        ggs  snf ! , (       d  f       N= f! , (       d  f       N.= f! , (       d  f       g= f)zV
Resets parameter data pointer to address in continuous memory block for
cudnn usage.
F)include_sublayersNr`  re   r   r  )ri   rs   r'  uint8dropout_state)r   )rs   ri   r?  r   	trainableT)rs   r?  	copy_data	use_alignrs   r   coalesce_tensorInput)OutputFusedOutput)r  r  rs   r   r4   r   attrs)+r  r  npprodri   rh   _all_weightsr   r  r  r.  sumrs   r/  r2  _flat_weightr   r\   r   r   r   r   r   _dropout_stater   create_variableVarDescVarTypeUINT8r   no_gradr   DataTyper   r   paddle_type_to_proto_typer   r  r   r   r
   _helper	append_op)rE   paramsr  ri   r}   offset	layer_idxrs   s           r:   r  RNNBase.flatten_parametersX  s9   
 
 __u_=F7=>veRWWU[[)vE>!%V 4D%f- 1uqy doo-0C0CC 
 F	DI!!&q="81q5"@A . %%66%=/ )//()

3 & !D }}&,jjoo&F&F!#()H(IJ &		 5 5 > >Q > G# 'G '# 59##1&*&:&:,,..44()H(IJ '; '#   ^^%"1IOOE!%77 & 5 5 O O!! "11))))))!,##
 # &%( +-/F/H  ==**))q	 LL**. '):):;&*&7&7+/+<+<!
 *.).%+AY__ + # ! A   ?L &%. !  s7   *M',BM,'N=BM=N,
M:=
N	N
Nc                   U R                   (       d"  [        R                  R                  U/ SQ5      n[	        5       (       a  [
        R                  " UUU R                  UU R                  U R                  U R                  S:H  U R                  U R                  U R                  U R                  SU R                  (       + 5      u  pEnGO>U R                   R#                  UR$                  5      n['        U R(                  5       Vs/ s H(  nU R                   R#                  UR$                  5      PM*     nnU R                   R#                  [*        R,                  R.                  R0                  SS9nUU R                  UUS.nU R                  U R                  S:H  U R                  U R                  U R                  U R                  U R                  (       + S.n	UUUU R                  S.n
U R                   R3                  S	XU	S
9  U R                   (       d"  [        R                  R                  U/ SQ5      OUnU[5        U5      S:  a  [7        U5      4$ US   4$ s  snf )N)r   r   re   re   r   T)rs   r   )r  
WeightListPreStateSequenceLength)dropout_prob
is_bidirecr6  r7  r  r  is_test)OutStateReserveDropoutStater;   r  r   )r7   r\   r]   rj   r   r
   r;   r  r  r  r  r6  r7  r  r  trainingr  "create_variable_for_type_inferencers   rg   r   r   r  r  r  r  rh   r   )rE   r4   r5   r6   r   r   r`   r}   reserver  r   s              r:   _cudnn_implRNNBase._cudnn_impl  s    ]],,VY?F!##"JJ!!####q(  		MM!MCE  ,,AA&,,OC t4455A ??M5   llEEll**00 F G
  "//*"1	F !%"11Q6"oo#//"oo		#}},E " $ 3 3	G LL""6% #  ?? MM##C3 	
 CJNE%L@@a@@Os   /I!c                   U R                   (       a  SOSnUR                  nUc  U R                  =(       d    U R                  /U R                  /4nU R                  U R
                  -  S/nUR                  U   S:  a  UR                  U   US'   O*[        R                  " U5      U   R                  5       US'   [        [        U R                  5       Vs/ s H  n[        R                  " XvU   -   SUS9PM      sn5      nOH[        U[        R                  R                  [        R                   R"                  45      (       a  U/OUnU R$                  (       a8  [        R&                  R)                  5       (       a  Uc  U R+                  XU5      $ [-        X R
                  S:H  U R                  5      n	/ n
[/        U 5       HW  u  pUS:  a+  [0        R2                  " UU R2                  U R4                  SS9nU" XU   U5      u  pU
R7                  U5        UnMY     [9        XR
                  S:H  U R                  5      n
WU
4$ s  snf )Nr   r   r   r  re   upscale_in_train)r  r  )r7   rs   ra  r7  r  r  ri   r\   rN   r   rg   r   r  r   r   r   r   r   r  deviceis_compiled_with_rocmr  r   r   r9  r  r  rJ   r   )rE   r4   r5   r6   batch_indexrs   dims
fill_shaper}   r   r   	rnn_layerr   final_states                 r:   r%   RNNBase.forward  s"     ??a!^^7t'7'784;K;K:LMD//D,?,??DJ||K(1, &[ 9
1 &V 4[ A F F H
1"
 #4#8#89	 : KK(72q :	N "V]]%;%;VZZ=M=M$N     $  33559P ##FOLL//14d6K6K
 %dOLA1uLL!]]+	 $-VAY#P G,F , %--2D4I4I
 $$Us   %I	c                    SnU R                   S:w  a  US-  nU R                  SLa  US-  nU R                  S:w  a  US-  nUR                  " S0 U R                  D6$ )	NrO  r   z, num_layers={num_layers}Fz, time_major={time_major}r   z, dropout={dropout}rX   )r  r7   r  rP  rQ  )rE   main_strs     r:   rR  RNNBase.extra_repr?  sb    0??a33H??%'33H<<1--H///r<   )r  r  r  r  r  r7  r6  r  r  r  ra  r   r7   )	r   r%   Fr  NNNNr   )r  z_RNNType | strr6  rR   r7  rR   r  rR   r  _DirectionType | strr7   r  r  r  r;  rU  r<  rU  r=  rU  r>  rU  ra  rR   rP   rQ   r  )r4   r   r5   r  r6   z
int | NonerP   z-tuple[Tensor, Tensor | tuple[Tensor, Tensor]]r  rY  )rS   rT   rU   rV   r  rG   r  r  r%   rR  rW   r[  r\  s   @r:   r  r    s:    *3 /3/3-1-1a"a" a" 	a"
 a" (a" a" a" -a" -a" +a" +a" a" 
a" a"FeNBABA /BA $	BA
 
7BAN 26&*	:%:% /:% $	:%
 
7:%x0 0r<   r  c                  z   ^  \ rS rSrSr          S                         SU 4S jjjrSrU =r$ )	SimpleRNNiJ  a  
Multilayer Elman network(SimpleRNN). It takes input sequences and initial
states as inputs, and returns the output sequences and the final states.

Each layer inside the SimpleRNN maps the input sequences and initial states
to the output sequences and final states in the following manner: at each
step, it takes step inputs(:math:`x_{t}`) and previous
states(:math:`h_{t-1}`) as inputs, and returns step outputs(:math:`y_{t}`)
and new states(:math:`h_{t}`).

.. math::

    h_{t} & = act(W_{ih}x_{t} + b_{ih} + W_{hh}h_{t-1} + b_{hh})

    y_{t} & = h_{t}

where :math:`act` is for :attr:`activation`.

Using key word arguments to construct is recommended.

Parameters:
    input_size (int): The input size of :math:`x` for the first layer's cell.
    hidden_size (int): The hidden size of :math:`h` for each layer's cell.
    num_layers (int, optional): Number of recurrent layers. Defaults to 1.
    direction (str, optional): The direction of the network. It can be "forward"
        or "bidirect"(or "bidirectional"). When "bidirect", the way to merge
        outputs of forward and backward is concatenating. Defaults to "forward".
    time_major (bool, optional): Whether the first dimension of the input
        means the time steps. If time_major is True, the shape of Tensor is
        [time_steps,batch_size,input_size], otherwise [batch_size, time_steps,input_size].
        Defaults to False. `time_steps` means the length of input sequence.
    dropout (float, optional): The dropout probability. Dropout is applied
        to the input of each layer except for the first layer. The range of
        dropout from 0 to 1. Defaults to 0.
    activation (str, optional): The activation in each SimpleRNN cell. It can be
        `tanh` or `relu`. Defaults to `tanh`.
    weight_ih_attr (ParamAttr|None, optional): The parameter attribute for
        `weight_ih` of each cell. Defaults to None.
    weight_hh_attr (ParamAttr|None, optional): The parameter attribute for
        `weight_hh` of each cell. Defaults to None.
    bias_ih_attr (ParamAttr|None, optional): The parameter attribute for the
        `bias_ih` of each cells. Defaults to None.
    bias_hh_attr (ParamAttr|None, optional): The parameter attribute for the
        `bias_hh` of each cells. Defaults to None.
    name (str|None, optional): Name for the operation (optional, default is
        None). For more information, please refer to :ref:`api_guide_Name`.

Inputs:
    - **inputs** (Tensor): the input sequence. If `time_major` is True, the shape is `[time_steps, batch_size, input_size]`, else, the shape is `[batch_size, time_steps, input_size]`. `time_steps` means the length of the input sequence.
    - **initial_states** (Tensor, optional): the initial state. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. If initial_state is not given, zero initial states are used.
    - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings.

Returns:

    - **outputs** (Tensor): the output sequence. If `time_major` is True, the shape is `[time_steps, batch_size, num_directions * hidden_size]`, else, the shape is `[batch_size, time_steps, num_directions * hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" else 1. `time_steps` means the length of the output sequence.

    - **final_states** (Tensor): final states. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" (the index of forward states are 0, 2, 4, 6... and the index of backward states are 1, 3, 5, 7...), else 1.

Variables:
    - **weight_ih_l[k]**: the learnable input-hidden weights of the k-th layer. If `k = 0`, the shape is `[hidden_size, input_size]`. Otherwise, the shape is `[hidden_size, num_directions * hidden_size]`.
    - **weight_hh_l[k]**: the learnable hidden-hidden weights of the k-th layer, with shape `[hidden_size, hidden_size]`.
    - **bias_ih_l[k]**: the learnable input-hidden bias of the k-th layer, with shape `[hidden_size]`.
    - **bias_hh_l[k]**: the learnable hidden-hidden bias of the k-th layer, with shape `[hidden_size]`.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> rnn = paddle.nn.SimpleRNN(16, 32, 2)

        >>> x = paddle.randn((4, 23, 16))
        >>> prev_h = paddle.randn((2, 4, 32))
        >>> y, h = rnn(x, prev_h)

        >>> print(y.shape)
        paddle.Size([4, 23, 32])
        >>> print(h.shape)
        paddle.Size([2, 4, 32])


c                   > US:X  a  SnOUS:X  a  SnO[        SU S35      eXpl        [        TU ]  UUUUUUUUU	U
US5        g )Nr-   r+   r.   r*   zUnknown activation ''r   )r+  r8  r*  rG   )rE   r6  r7  r  r  r7   r  r8  r;  r<  r=  r>  r?  r  r,  s                 r:   rG   SimpleRNN.__init__  sj     D6!D3J<qABB$	
r<   )r8  )
r   r%   Fr  r-   NNNNN)r6  rR   r7  rR   r  rR   r  r  r7   r  r  r  r8  rT  r;  rU  r<  rU  r=  rU  r>  rU  r?  rV  rP   rQ   rS   rT   rU   rV   r  rG   rW   r[  r\  s   @r:   r  r  J  s    Rp *3 ,2/3/3-1-1#
#
 #
 	#

 (#
 #
 #
 *#
 -#
 -#
 +#
 +#
 #
 
#
 #
r<   r  c                  z   ^  \ rS rSrSr          S                         SU 4S jjjrSrU =r$ )r(   i  ad  
Multilayer LSTM. It takes a sequence and an initial state as inputs, and
returns the output sequences and the final states.

Each layer inside the LSTM maps the input sequences and initial states
to the output sequences and final states in the following manner: at each
step, it takes step inputs(:math:`x_{t}`) and previous
states(:math:`h_{t-1}, c_{t-1}`) as inputs, and returns step
outputs(:math:`y_{t}`) and new states(:math:`h_{t}, c_{t}`).

.. math::

    i_{t} & = \sigma(W_{ii}x_{t} + b_{ii} + W_{hi}h_{t-1} + b_{hi})

    f_{t} & = \sigma(W_{if}x_{t} + b_{if} + W_{hf}h_{t-1} + b_{hf})

    o_{t} & = \sigma(W_{io}x_{t} + b_{io} + W_{ho}h_{t-1} + b_{ho})

    \widetilde{c}_{t} & = \tanh (W_{ig}x_{t} + b_{ig} + W_{hg}h_{t-1} + b_{hg})

    c_{t} & = f_{t} * c_{t-1} + i_{t} * \widetilde{c}_{t}

    h_{t} & = o_{t} * \tanh(c_{t})

    y_{t} & = h_{t}

If `proj_size` is specified, the dimension of hidden state :math:`h_{t}` will be projected to `proj_size`:

.. math::

    h_{t} = h_{t}W_{proj\_size}

where :math:`\sigma` is the sigmoid function, and * is the elementwise
multiplication operator.

Using key word arguments to construct is recommended.

Parameters:
    input_size (int): The input size of :math:`x` for the first layer's cell.
    hidden_size (int): The hidden size of :math:`h` for each layer's cell.
    num_layers (int, optional): Number of recurrent layers. Defaults to 1.
    direction (str, optional): The direction of the network. It can be "forward"
        or "bidirect"(or "bidirectional"). When "bidirect", the way to merge
        outputs of forward and backward is concatenating. Defaults to "forward".
    time_major (bool, optional): Whether the first dimension of the input
        means the time steps. If time_major is True, the shape of Tensor is
        [time_steps,batch_size,input_size], otherwise [batch_size, time_steps,input_size].
        Defaults to False. `time_steps` means the length of input sequence.
    dropout (float, optional): The dropout probability. Dropout is applied
        to the input of each layer except for the first layer. The range of
        dropout from 0 to 1. Defaults to 0.
    weight_ih_attr (ParamAttr|None, optional): The parameter attribute for
        `weight_ih` of each cell. Default: None.
    weight_hh_attr (ParamAttr|None, optional): The parameter attribute for
        `weight_hh` of each cell. Default: None.
    bias_ih_attr (ParamAttr|None, optional): The parameter attribute for the
        `bias_ih` of each cells. Default: None.
    bias_hh_attr (ParamAttr|None, optional): The parameter attribute for the
        `bias_hh` of each cells. Default: None.
    proj_size (int, optional): If specified, the output hidden state of each layer
        will be projected to `proj_size`. `proj_size` must be smaller than `hidden_size`.
        Default: 0.
    name (str|None, optional): Name for the operation (optional, default is
        None). For more information, please refer to :ref:`api_guide_Name`.

Inputs:
    - **inputs** (Tensor): the input sequence. If `time_major` is True, the shape is `[time_steps, batch_size, input_size]`, else, the shape is `[batch_size, time_steps, input_size]`. `time_steps` means the length of the input sequence.
    - **initial_states** (list|tuple, optional): the initial state, a list/tuple of (h, c), the shape of each is `[num_layers * num_directions, batch_size, hidden_size]`. If initial_state is not given, zero initial states are used.
    - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings.

Returns:

    - **outputs** (Tensor). The output sequence. If `time_major` is True, the shape is `[time_steps, batch_size, num_directions * hidden_size]`. If `proj_size` is specified, shape will be `[time_major, batch_size, num_directions * proj_size]`. If `time_major` is False, the shape is `[batch_size, time_steps, num_directions * hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" else 1. `time_steps` means the length of the output sequence.
    - **final_states** (tuple). The final state, a tuple of two tensors, h and c. The shape of each is `[num_layers * num_directions, batch_size, hidden_size]`. If `proj_size` is specified, the last dimension of h will be proj_size.
        Note that `num_directions` is 2 if direction is "bidirectional" (the index of forward states are 0, 2, 4, 6... and the index of backward states are 1, 3, 5, 7...), else 1.

Variables:
    - **weight_ih_l[k]**: the learnable input-hidden weights of the k-th layer. If `k = 0`, the shape is `[hidden_size, input_size]`. Otherwise, the shape is `[hidden_size, num_directions * hidden_size]`.
    - **weight_hh_l[k]**: the learnable hidden-hidden weights of the k-th layer, with shape `[hidden_size, hidden_size]`.
    - **bias_ih_l[k]**: the learnable input-hidden bias of the k-th layer, with shape `[hidden_size]`.
    - **bias_hh_l[k]**: the learnable hidden-hidden bias of the k-th layer, with shape `[hidden_size]`.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> rnn = paddle.nn.LSTM(16, 32, 2)

        >>> x = paddle.randn((4, 23, 16))
        >>> prev_h = paddle.randn((2, 4, 32))
        >>> prev_c = paddle.randn((2, 4, 32))
        >>> y, (h, c) = rnn(x, (prev_h, prev_c))

        >>> print(y.shape)
        paddle.Size([4, 23, 32])
        >>> print(h.shape)
        paddle.Size([2, 4, 32])
        >>> print(c.shape)
        paddle.Size([2, 4, 32])


c                :   > [         TU ]  SUUUUUUUUU	U
U5        g )Nr(   r*  rG   )rE   r6  r7  r  r  r7   r  r;  r<  r=  r>  ra  r?  r,  s                r:   rG   LSTM.__init__/  s6     		
r<   rX   )
r   r%   Fr  NNNNr   N)r6  rR   r7  rR   r  rR   r  r  r7   r  r  r  r;  rU  r<  rU  r=  rU  r>  rU  ra  rR   r?  rV  rP   rQ   r  r\  s   @r:   r(   r(     s    gZ *3 /3/3-1-1

 
 	

 (
 
 
 -
 -
 +
 +
 
 
 

 
r<   r(   c                  t   ^  \ rS rSrSr         S                       SU 4S jjjrSrU =r$ )r)   iN  a%  
Multilayer GRU. It takes input sequence and initial states as inputs, and
returns the output sequences and the final states.

Each layer inside the GRU maps the input sequences and initial states
to the output sequences and final states in the following manner: at each
step, it takes step inputs(:math:`x_{t}`) and previous
states(:math:`h_{t-1}`) as inputs, and returns step outputs(:math:`y_{t}`)
and new states(:math:`h_{t}`).

.. math::

    r_{t} & = \sigma(W_{ir}x_{t} + b_{ir} + W_{hr}h_{t-1} + b_{hr})

    z_{t} & = \sigma(W_{iz}x_{t} + b_{iz} + W_{hz}h_{t-1} + b_{hz})

    \widetilde{h}_{t} & = \tanh(W_{ic}x_{t} + b_{ic} + r_{t} * (W_{hc}h_{t-1} + b_{hc}))

    h_{t} & = z_{t} * h_{t-1} + (1 - z_{t}) * \widetilde{h}_{t}

    y_{t} & = h_{t}

where :math:`\sigma` is the sigmoid function, and * is the elementwise
multiplication operator.

Using key word arguments to construct is recommended.

Parameters:
    input_size (int): The input size of :math:`x` for the first layer's cell.
    hidden_size (int): The hidden size of :math:`h` for each layer's cell.
    num_layers (int, optional): Number of recurrent layers. Defaults to 1.
    direction (str, optional): The direction of the network. It can be "forward"
        or "bidirect"(or "bidirectional"). When "bidirect", the way to merge
        outputs of forward and backward is concatenating. Defaults to "forward".
    time_major (bool, optional): Whether the first dimension of the input
        means the time steps. If time_major is True, the shape of Tensor is
        [time_steps,batch_size,input_size], otherwise [batch_size, time_steps,input_size].
        Defaults to False. `time_steps` means the length of input sequence.
    dropout (float, optional): The dropout probability. Dropout is applied
        to the input of each layer except for the first layer. The range of
        dropout from 0 to 1. Defaults to 0.
    weight_ih_attr (ParamAttr|None, optional): The parameter attribute for
        `weight_ih` of each cell. Default: None.
    weight_hh_attr (ParamAttr|None, optional): The parameter attribute for
        `weight_hh` of each cell. Default: None.
    bias_ih_attr (ParamAttr|None, optional): The parameter attribute for the
        `bias_ih` of each cells. Default: None.
    bias_hh_attr (ParamAttr|None, optional): The parameter attribute for the
        `bias_hh` of each cells. Default: None.
    name (str|None, optional): Name for the operation (optional, default is
        None). For more information, please refer to :ref:`api_guide_Name`.

Inputs:
    - **inputs** (Tensor): the input sequence. If `time_major` is True, the shape is `[time_steps, batch_size, input_size]`, else, the shape is `[batch_size, time_steps, input_size]`. `time_steps` means the length of the input sequence.
    - **initial_states** (Tensor, optional): the initial state. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. If initial_state is not given, zero initial states are used. Defaults to None.
    - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings.

Returns:

    - **outputs** (Tensor): the output sequence. If `time_major` is True, the shape is `[time_steps, batch_size, num_directions * hidden_size]`, else, the shape is `[batch_size, time_steps, num_directions * hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" else 1. `time_steps` means the length of the output sequence.

    - **final_states** (Tensor): final states. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" (the index of forward states are 0, 2, 4, 6... and the index of backward states are 1, 3, 5, 7...), else 1.

Variables:
    - **weight_ih_l[k]**: the learnable input-hidden weights of the k-th layer. If `k = 0`, the shape is `[hidden_size, input_size]`. Otherwise, the shape is `[hidden_size, num_directions * hidden_size]`.
    - **weight_hh_l[k]**: the learnable hidden-hidden weights of the k-th layer, with shape `[hidden_size, hidden_size]`.
    - **bias_ih_l[k]**: the learnable input-hidden bias of the k-th layer, with shape `[hidden_size]`.
    - **bias_hh_l[k]**: the learnable hidden-hidden bias of the k-th layer, with shape `[hidden_size]`.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> rnn = paddle.nn.GRU(16, 32, 2)

        >>> x = paddle.randn((4, 23, 16))
        >>> prev_h = paddle.randn((2, 4, 32))
        >>> y, h = rnn(x, prev_h)

        >>> print(y.shape)
        paddle.Size([4, 23, 32])
        >>> print(h.shape)
        paddle.Size([2, 4, 32])


c                :   > [         TU ]  SUUUUUUUUU	U
S5        g )Nr)   r   r  )rE   r6  r7  r  r  r7   r  r;  r<  r=  r>  r?  r,  s               r:   rG   GRU.__init__  s6     		
r<   rX   )	r   r%   Fr  NNNNN)r6  rR   r7  rR   r  rR   r  r  r7   r  r  r  r;  rU  r<  rU  r=  rU  r>  rU  r?  rV  rP   rQ   r  r\  s   @r:   r)   r)   N  s    Wz *3 /3/3-1-1

 
 	

 (
 
 
 -
 -
 +
 +
 
 

 
r<   r)   )NNFF)r3   r/   r4   r   r5   r  r6   rW  r7   r  r8   r  r9   r   rP   z?tuple[Tensor | tuple[Tensor, ...], Tensor | tuple[Tensor, ...]])r`   r   ra   r   rb   r   rP   r   )rF   r   rP   r   )NNF)r   r/   r   r/   r4   r   r5   r  r6   rW  r7   r  r9   r   rP   r  )Fr   )r   r$   r'   r  r   rR   rP   z!list[Tensor] | list[list[Tensor]])r   zSequence[Tensor]r'   r  r   rR   rP   zTensor | tuple[Tensor, Tensor])L
__future__r   r^   collections.abcr   	functoolsr   r   typingr   r   numpyr  typing_extensionsr	   r\   r
   r   r   r   paddle.base.data_feederr   r   paddle.base.dygraph.baser   paddle.base.frameworkr   r   r   paddle.common_ops_importr   paddle.frameworkr   r   	paddle.nnr   r9  r   r/  paddle.tensor.manipulationr   	containerr   layersr   r   r   paddle._typingr    r!   r"   r#   r$   _DirectionType_RNNType_ActivationType__all__r;   r>   rc   rl   r1   r2   r   r   r   r/   r"  r^  r|  r  r  r  r  r(   r)   rX   r<   r:   <module>r     s   #  $ % %  "  D D H D 
 . . >     CDN<=Hn-O
 .2%)T

T
T
 +T
 #	T

 T
 T
 T
 ET
n	, 	,% A'N M)h CG%)a!a!a! a! @	a!
 #a! a! a! *a!L  686868 68 '	68v  +B+B+B +B $	+B\T
% T
nn)K n)b_E{ _ED@Ek @EFO+% O+d^%E ^%BX0i X0v
x
 x
vF
7 F
Ru
' u
r<   