o
    pif                    @  sx  d dl mZ d dlZd dlmZ d dlmZmZ d dlm	Z	m
Z
 d dlZd dlmZ d dlZd dlmZmZmZmZ d dlmZmZ d d	lmZ d d
lmZmZmZ d dlmZ d dlm Z m!Z! d dl"m#Z$m%Z& d dl'm(Z( ddl)m*Z* ddl+m,Z, e	rd dlm-Z- d dlm.Z. d dl/m0Z0m1Z1m2Z2m3Z3m4Z4 e-d Z5e-d Z6e-d Z7g Z8				d]d^d(d)Z9G d*d+ d+Z:d_d/d0Z;d`d2d3Z<				d]d4d5Z=				d]d6d7Z>			dadbd<d=Z?		dcdddDdEZ@		dcdedHdIZAG dJd de,ZBG dKdL dLeBZCG dMdN dNeBZDG dOdP dPeBZEG dQdR dRe,ZFG dSdT dTe,ZGG dUdV dVe*ZHG dWdX dXeHZIG dYdZ dZeHZJG d[d\ d\eHZKdS )f    )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reluFcellRNNCellBaseinputsr   initial_statesTensorOrTensors | Nonesequence_lengthTensor | None
time_majorbool
is_reversekwargsr   return?tuple[Tensor | tuple[Tensor, ...], Tensor | tuple[Tensor, ...]]c                 K  s:   t  rt| |||||fi |S t| |||||fi |S )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:: python

            >>> 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)
            [4, 23, 32]
            >>> print(final_states.shape)
            [4, 32]

    )r   _rnn_dynamic_graph_rnn_static_graph)r.   r0   r1   r3   r5   r7   r8    r=   Z/home/app/PaddleOCR-VL/.venv_paddleocr/lib/python3.10/site-packages/paddle/nn/layer/rnn.pyrnn@   s*   A
r?   c                   @  s*   e Zd ZdddZddd	ZdddZdS )ArrayWrapperxr   r9   Nonec                 C  s   |g| _ d S N)arrayselfrA   r=   r=   r>   __init__      zArrayWrapper.__init__r   c                 C  s   | j | | S rC   )rD   appendrE   r=   r=   r>   rI      s   zArrayWrapper.appenditemintc                 C  s   | j |S rC   )rD   __getitem__)rF   rJ   r=   r=   r>   rL      rH   zArrayWrapper.__getitem__N)rA   r   r9   rB   )rA   r   r9   r   )rJ   rK   r9   r   )__name__
__module____qualname__rG   rI   rL   r=   r=   r=   r>   r@      s    

r@   state	new_state	step_maskc                 C  s0   t jjj||ddt jjj| d| dd }|S )z3update rnn state or just pass the old state throughr   axisr   )paddletensormathZ_multiply_with_axis)rP   rQ   rR   r=   r=   r>   _maybe_copy   s   rX   rA   c                 C  s(   ddgt tdt| j}t| |S )Nr   r      )listrangelenshaperU   	transpose)rA   permr=   r=   r>   _transpose_batch_time   s   r`   c                   s  |rdndt j|}|d j }|d u r"| j||rdndd}|s+t jt|}|d urCt jjj	j
|||jd}	t |	ddg}	|r\t jdd |}|d urZt j|	dgdnd }	|}
g }t|D ]C t j fdd|}| ||
fi |\}}|d urt jtt|	  d	|
|}|}
 dkrt jd
d |n	t jdd ||}qdt jfdd|}|rt jfdd|}|}||fS )Nr   r   	batch_refbatch_dim_idxmaxlendtypec                 S     t j| dgdS Nr   rS   rU   reverserA   r=   r=   r>   <lambda>       z$_rnn_dynamic_graph.<locals>.<lambda>rS   c                   s   |   S rC   r=   rk   )ir=   r>   rl          rR   c                 S  s   t | S rC   )r@   rk   r=   r=   r>   rl      ro   c                 S  s
   | | S rC   )rI   )rA   Zx_arrayr=   r=   r>   rl      s   
 c                   s   t j| j dS NrS   )rU   stackrD   rk   time_step_indexr=   r>   rl      rm   c                   s   t j|  dS rq   ri   rk   rs   r=   r>   rl          )rU   utilsflattenr]   get_initial_statesmap_structurer`   staticnnsequence_lodsequence_maskrf   r^   rj   r[   r   rX   )r.   r0   r1   r3   r5   r7   r8   Zflat_inputsZ
time_stepsmaskstatesoutputsZstep_inputsZstep_outputs
new_statesfinal_outputsfinal_statesr=   )rn   rt   r>   r;      s^   	

r;   c              	     s  t |dttttjjfd t|ttfr,t|D ]\}}t	|dt
| d ddgd qt |dttttd tjjfd t |dttd tjjfd d!d
d}	|d u r^| j||rZdndd}tj|	|}|sntjt|}ttj|d d }
t|
tj}
|d urtjjjj||
tj|d jd}t|ddg}|rtjdd |}|d urtj|dgdnd }tjjd tjg dd |
}t|d} |k }W d    n1 sw   Y  tjjj |}tj!j"tj|d jd}tjdd |}tj fdd|| |#  |  }tj fdd|}| ||fi |\}}t|tjjjtjjfs<J tj$|| |d ur\t%|  dtjfdd||}tj!&| | tjjd tj!j' dd W d    n	1 sw   Y  tj fdd|| tjjd tj!( |}t)|| W d    n	1 sw   Y  W d    n	1 sw   Y  t*|ddd\}}tjdd |}|}tjdd |}|rtjd d |}|stjt|}||fS )"Nr0   r?   zinputs[]Zfloat32Zfloat64r1   r3   Fc                 S  s
   || _ | S rC   )stop_gradient)rA   stopr=   r=   r>   _switch_grad  s   z'_rnn_static_graph.<locals>._switch_gradr   r   ra   rd   c                 S  rg   rh   ri   rk   r=   r=   r>   rl   +  rm   z#_rnn_static_graph.<locals>.<lambda>rS   cpuZint64rf   c                 S  s   t jj| jdS )Nr   )rU   rV   create_arrayrf   rk   r=   r=   r>   rl   @  rm   c                      t j|  |S rC   rU   rV   array_writerA   ystart_ir=   r>   rl   D  rm   c                   s   t j|  S rC   )rU   rV   Z
array_readrk   r   r=   r>   rl   M  ru   c                   s   |   |d    S )N      ?r=   r   rp   r=   r>   rl   [  s    )rA   valuec                   r   rC   r   r   r   r=   r>   rl   e  rm   TrT   Z	use_stackc                 S  s   t | dddd S )Nr   Tr   r   rk   r=   r=   r>   rl   q  s    c                 S  s   | d S Nr=   rk   r=   r=   r>   rl   u  ro   c                 S  rg   rh   ri   rk   r=   r=   r>   rl   y  rm   F)+r   r   rZ   tuplerU   pirValue
isinstance	enumerater   strtyperx   rv   ry   r`   r]   rw   castZint32rz   r{   r|   r}   rf   r^   rj   baser   Zdevice_guardZzerosZcontrol_flowWhilerV   r   blockZassert_same_structureZ	unsqueezer   	increment	less_thanZassignr   )r.   r0   r1   r3   r5   r7   r8   rn   Zinput_xr   Zmax_seq_lenr~   endZcondZwhile_opZ	out_arrayZ
init_arrayZstep_inZ	pre_stater   r   Znew_condout_Z	all_stater   r   r=   )r   rR   r>   r<      s   	








%r<   cell_fwcell_bw+tuple[Tensor, Tensor] | list[Tensor] | None$tuple[Tensor, tuple[Tensor, Tensor]]c                 K  s   |du r| j ||rdndd}| j ||rdndd}n|\}}t| |||fd|i|\}	}t||||f|dd|\}
}tjdd	 |	|
}||f}||fS )
a	  
    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:: python

            >>> 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)
            [2, 23, 64]
            >>> print(final_states[0][0].shape)
            [2, 32]

    Nr   r   ra   r5   T)r5   r7   c                 S  s   t | |gdS r   )rU   concatr   r=   r=   r>   rl     rm   zbirnn.<locals>.<lambda>)rx   r?   rU   rv   ry   )r   r   r0   r1   r3   r5   r8   Z	states_fwZ	states_bwZ
outputs_fwZ
outputs_bwr   r   r=   r=   r>   birnn  sD   @
	


r   r   r#   r&   state_componentsrK   !list[Tensor] | list[list[Tensor]]c                 C  s   |dkrt | } |s| S tt| ddd | ddd S t| |ks&J tdd | D } |s7tt|  S tt|  } tt| ddd | ddd S )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   NrY   c                 S     g | ]}t |qS r=   )rU   unstack.0rJ   r=   r=   r>   
<listcomp>      z split_states.<locals>.<listcomp>)rU   r   rZ   zipr\   r   )r   r&   r   r=   r=   r>   split_states  s   )
""r   Sequence[Tensor]Tensor | tuple[Tensor, Tensor]c                 C  s^   |dkrt t j| S t j| } g }t|D ]}|| |d|  qtdd |D S )a  
    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   Nc                 S  r   r=   )rU   rr   r   r=   r=   r>   r   L  r   z!concat_states.<locals>.<listcomp>)rU   rr   rv   rw   r[   rI   r   )r   r&   r   
componentsrn   r=   r=   r>   concat_states!  s   $r   c                   @  s@   e Zd ZdZ				ddddZedddZedddZdS )r/   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.
    N        r   rb   r   r]   !NestedStructure[ShapeLike] | Nonerf   !NestedStructure[DTypeLike] | None
init_valuefloatrc   rK   r9   NestedStructure[Tensor]c                   s  t j|d }dd }G dd d |du r| jn|}t jjj}|t jj_t j fdd|}|t jj_zdu r>| jn}	W n tyN   t	
 }	Y nw tt j|	d	krlt j|	d t jfd
d|}	|}
|j| dkrt|
tr|
d D ]
}|j| |jd< q~nXt|
tr|
D ]
}|j| |jd< qnE|j| |
jd< n<t|
tr|
d D ]}t ||  |jd< qn#t|
tr|
D ]}t ||  |jd< qnt ||  |
jd< t jfdd|
|	}|S )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                 S  sF   t | ttfrtdd | drdS t | trdS t | to"t | t S )z@For shape, list/tuple of integer is the finest-grained objectionc                 S  s   t |to| S rC   )r   rK   )flagrA   r=   r=   r>   rl     ru   zLRNNCellBase.get_initial_states.<locals>._is_shape_sequence.<locals>.<lambda>TF)r   rZ   r   r   dictr   r   )seqr=   r=   r>   _is_shape_sequence  s   

z:RNNCellBase.get_initial_states.<locals>._is_shape_sequencec                   @  s   e Zd Zdd ZdS )z-RNNCellBase.get_initial_states.<locals>.Shapec                 S  s.   |d dkrt || _d S dgt || _d S )Nr   r   )rZ   r]   )rF   r]   r=   r=   r>   rG     s   z6RNNCellBase.get_initial_states.<locals>.Shape.__init__N)rM   rN   rO   rG   r=   r=   r=   r>   Shape  s    r   Nc                   s    | S rC   r=   r]   )r   r=   r>   rl     ro   z0RNNCellBase.get_initial_states.<locals>.<lambda>r   c                   s    S rC   r=   r   r   r=   r>   rl     s    c                   s   t j| j |dS )Nr]   Z
fill_valuerf   )rU   fullr]   )r]   rf   )r   r=   r>   rl     s
    )rU   rv   rw   state_shapeZlayers_utilsZis_sequencery   state_dtypeNotImplementedErrorr   Zget_default_dtyper\   r]   r   rZ   r   rJ   )rF   rb   r]   rf   r   rc   r   Zstates_shapesZis_sequence_oriZstates_dtypesZfill_shapessZinit_statesr=   )r   rf   r   r>   rx   V  sd   '







	zRNNCellBase.get_initial_statesrB   c                 C     t d)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   rF   r=   r=   r>   r        zRNNCellBase.state_shapec                 C  r   )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   r=   r=   r>   r     r   zRNNCellBase.state_dtype)NNr   r   )rb   r   r]   r   rf   r   r   r   rc   rK   r9   r   r9   rB   )rM   rN   rO   __doc__rx   propertyr   r   r=   r=   r=   r>   r/   O  s    	oc                      sT   e Zd ZdZ						d d! fddZd"d#ddZed$ddZd%ddZ  Z	S )&SimpleRNNCella  
    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:: python

            >>> 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)
            [4, 32]

    r,   N
input_sizerK   hidden_size
activation_ActivationType | strweight_ih_attrParamAttrLike | Noneweight_hh_attrbias_ih_attrbias_hh_attrname
str | Noner9   rB   c	           
        s  t    |dkrtd| jj d| dt| }	|dur1| j||f|t	|	 |	d| _
n| j||fd tdd| _
d| j
_|durX| j||f|t	|	 |	d| _n| j||fd tdd| _d| j_|dur| j|f|dt	|	 |	d| _n| j|fd dtd	d| _d| j_|dur| j|f|dt	|	 |	d| _n| j|fd dtd	d| _d| j_|| _|| _|d
vrtd| || _|dkrtj| _d S tj| _d S )Nr   hidden_size of + must be greater than 0, but now equals to r   Fdefault_initializerTZis_biasr   r   r+   z=activation for SimpleRNNCell should be tanh or relu, but get r,   )superrG   
ValueError	__class__rM   rW   sqrtcreate_parameterIUniform	weight_ihConstantr   	weight_hhbias_ihbias_hhr   r   r   rU   r,   Fr-   _activation_fn)
rF   r   r   r   r   r   r   r   r   stdr   r=   r>   rG   (  s   




 zSimpleRNNCell.__init__r0   r   r   r4   c                 C  s|   |d u r|  || j}|}tj|| jdd}| jd ur || j7 }tj|| jdd}| jd ur3|| j7 }| || }||fS )NTZtranspose_y)	rx   r   rU   matmulr   r   r   r   r   )rF   r0   r   Zpre_hZi2hZh2hhr=   r=   r>   r$     s   



zSimpleRNNCell.forward
tuple[int]c                 C     | j fS rC   r   r   r=   r=   r>   r     s   zSimpleRNNCell.state_shaper   c                 C  s(   d}| j dkr|d7 }|jdi | jS )N{input_size}, {hidden_size}r,   z, activation={activation}r=   )r   format__dict__)rF   r   r=   r=   r>   
extra_repr  s   
zSimpleRNNCell.extra_repr)r,   NNNNN)r   rK   r   rK   r   r   r   r   r   r   r   r   r   r   r   r   r9   rB   rC   )r0   r   r   r4   r9   r   r9   r   
rM   rN   rO   r   rG   r$   r   r   r   __classcell__r=   r=   r   r>   r     s    EWr   c                      sT   e Zd ZdZ						dd  fddZd!d"ddZed#ddZd$ddZ  Z	S )%LSTMCella  
    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:: python

            >>> 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)
            [4, 32]
            >>> print(h.shape)
            [4, 32]
            >>> print(c.shape)
            [4, 32]

    Nr   r   rK   r   r   r   r   r   r   	proj_sizer   r   r9   rB   c	           
        s  t    |dkrtd| jj d| |dk r%td| jj d| ||kr-tddt| }	|durK| jd| |f|t	|	 |	d	| _
n| jd| |fd tdd	| _
d
| j
_|durx| jd| |pk|f|t	|	 |	d	| _n| jd| |p|fd tdd	| _d
| j_|dur| jd| f|d
t	|	 |	d| _n| jd| fd d
tdd| _d
| j_|dur| jd| f|d
t	|	 |	d| _n| jd| fd d
tdd| _d
| j_|| _|dkr| j||f|t	|	 |	d	| _|| _|| _tj| _tj| _d S )Nr   r   r   zproj_size of z*proj_size must be smaller than hidden_sizer   F   r   Tr   r   )r   rG   r   r   rM   rW   r   r   r   r   r   r   r   r   r   r   r  	weight_hor   r   r   sigmoid_gate_activationrU   r,   _activation)
rF   r   r   r   r   r   r   r  r   r   r   r=   r>   rG     s   






zLSTMCell.__init__r0   r   r   Sequence[Tensor] | Nonec                 C  s   |d u r|  || j}|\}}tj|| jdd}| jd ur"|| j }|tj|| jdd7 }| jd ur7|| j }tj|ddd}| 	|d }| 	|d }| 	|d }	|| || 
|d	   }
|	| 
|
 }| jdkrtt|| j}|||
ffS )
NTr   r  r   Znum_or_sectionsrT   r   r      rY   )rx   r   rU   r   r   r   r   r   splitr	  r
  r  r  )rF   r0   r   
pre_hiddenZpre_cellZgatesZchunked_gatesrn   focr   r=   r=   r>   r$   T  s$   




zLSTMCell.forwardtuple[tuple[int], tuple[int]]c                 C  s   | j f| jp| j ffS )a  
        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.
        )r   r  r   r=   r=   r>   r   k  s   zLSTMCell.state_shaper   c                 C     dj di | jS Nr   r=   r   r   r   r=   r=   r>   r   u     zLSTMCell.extra_repr)NNNNr   N)r   rK   r   rK   r   r   r   r   r   r   r   r   r  rK   r   r   r9   rB   rC   )r0   r   r   r  )r9   r  r  r  r=   r=   r   r>   r    s    a_	r  c                      sT   e Zd ZdZ					dd fddZ	d d!ddZed"ddZd#ddZ  Z	S )$GRUCellaj  
    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:: python

            >>> 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)
            [4, 32]
            >>> print(h.shape)
            [4, 32]


    Nr   rK   r   r   r   r   r   r   r   r   r9   rB   c           	        s  t    |dkrtd| jj d| dt| }|dur3| jd| |f|t	| |d| _
n| jd| |fd tdd| _
d| j
_|dur^| jd| |f|t	| |d| _n| jd| |fd tdd| _d| j_|dur| jd| f|dt	| |d	| _n| jd| fd dtd
d	| _d| j_|dur| jd| f|dt	| |d	| _n| jd| fd dtd
d	| _d| j_|| _|| _tj| _tj| _d S )Nr   r   r   r   Fr  r   Tr   r   )r   rG   r   r   rM   rW   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r	  rU   r,   r
  )	rF   r   r   r   r   r   r   r   r   r   r=   r>   rG     s|   









zGRUCell.__init__r0   r   r   r4   tuple[Tensor, Tensor]c                 C  s   |d u r|  || j}|}tj|| jdd}| jd ur || j }tj|| jdd}| jd ur3|| j }tj|ddd\}}}tj|ddd\}	}
}| 	||	 }| 	||
 }| 
|||  }|| | | }||fS )NTr   r  r   r  )rx   r   rU   r   r   r   r   r   r  r	  r
  )rF   r0   r   r  Zx_gatesZh_gatesZx_rZx_zZx_cZh_rZh_zZh_crzr  r   r=   r=   r>   r$     s    



zGRUCell.forwardr   c                 C  r   )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}`.
        r   r   r=   r=   r>   r   /  s   zGRUCell.state_shaper   c                 C  r  r  r  r   r=   r=   r>   r   8  r  zGRUCell.extra_repr)NNNNN)r   rK   r   rK   r   r   r   r   r   r   r   r   r   r   r9   rB   rC   )r0   r   r   r4   r9   r  r   r  r  r=   r=   r   r>   r  y  s    QQr  c                      s8   e Zd ZdZ		dd fd
dZ		ddddZ  ZS )RNNa
  
    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:: python

            >>> 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)
            [4, 23, 32]
            >>> print(final_states.shape)
            [4, 32]

    Fr.   r/   r7   r6   r5   r9   rB   c                   s8   t    || _t| jds| jj| j_|| _|| _d S )Ncall)r   rG   r.   hasattrr$   r  r7   r5   )rF   r.   r7   r5   r   r=   r>   rG   m  s   

zRNN.__init__Nr0   r   r1   r2   r3   r8   r   c                 K  s.   t | j|f||| j| jd|\}}||fS )N)r1   r3   r5   r7   )r?   r.   r5   r7   )rF   r0   r1   r3   r8   r   r   r=   r=   r>   r$   {  s   
	zRNN.forward)FF)r.   r/   r7   r6   r5   r6   r9   rB   NN)r0   r   r1   r2   r3   r   r8   r   rM   rN   rO   r   rG   r$   r  r=   r=   r   r>   r  <  s    3r  c                      s6   e Zd ZdZ	dd fd
dZ		ddddZ  ZS )BiRNNa
  
    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:: python

            >>> 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)
            [2, 23, 64]
            >>> print(final_states[0][0].shape,len(final_states),len(final_states[0]))
            [2, 32] 2 2

    Fr   r/   r   r5   r6   r9   rB   c                   sj   t    || _|| _|j|jkrtd|j d|j d| j| jfD ]}t|ds/|j|_q$|| _	d S )Nzinput size of forward cell(z') does not equalsthat of backward cell()r  )
r   rG   r   r   r   r   r  r$   r  r5   )rF   r   r   r5   r.   r   r=   r>   rG     s   



zBiRNN.__init__Nr0   r   r1   r   r3   r4   r8   r   r   c                 K  sN   t |ttfrt|dksJ dt| j| j|||| jfi |\}}||fS )NrY   z<length of initial_states should be 2 when it is a list/tuple)r   rZ   r   r\   r   r   r   r5   )rF   r0   r1   r3   r8   r   r   r=   r=   r>   r$     s   
	zBiRNN.forwardr   )r   r/   r   r/   r5   r6   r9   rB   r  )
r0   r   r1   r   r3   r4   r8   r   r9   r   r   r=   r=   r   r>   r!    s    4r!  c                      sd   e Zd ZdZ									d.d/ fddZd0ddZd1d'd(Z		d2d1d)d*Zd3d,d-Z  Z	S )4RNNBasez
    RNNBase class for RNN networks. It provides `forward`, `flatten_parameters`
    and other common methods for SimpleRNN, LSTM and GRU.
    r   r$   Fr   Nr   mode_RNNType | strr   rK   r   
num_layers	direction_DirectionType | strr5   r6   dropoutr   r   r   r   r   r   r  r9   rB   c                   s  t    ddg}|| _|| _|| _|| _||v rdnd| _|| _|| _|dkr*dnd| _	||	|
|d}|| _
|dkrA|dksAJ |dkrLt}||d< n$|d	krSt}n|d
kr^t}d|d< n|dkrit}d|d< nt}| j|d< |ps|}|dv rd}|||fi |}| t||| td|D ]}|||fi |}| t||| qnN||v r|||fi |}|||fi |}| t||| td|D ]!}|d| |fi |}|d| |fi |}| t||| qntd| d| _|  jt|  |d ||v r
dnd kM  _g }t| jD ]: t| jD ]1}|dkr'dnd|ddg |
dur:|d |durD|d  fdd|D }qqt||  D ]\}}t| || qY|   d S )Nr&   r%   rY   r   r'   )r   r   r   r   r   r  r(   r)   r-   r   r*   r,   )r$   FzQdirection should be forward or bidirect (or bidirectional), received direction = Tr  Z_reverse zweight_ih_l{}{}zweight_hh_l{}{}zbias_ih_l{}{}zbias_hh_l{}{}c                   s   g | ]}|  qS r=   )r   )r   rA   layersuffixr=   r>   r   N      z$RNNBase.__init__.<locals>.<listcomp>)r   rG   r$  r   r   r)  num_directionsr5   r&  r   r  r  r  r   r   rI   r  r[   r!  r   could_use_cudnnr\   
parametersextendr   setattrflatten_parameters)rF   r$  r   r   r&  r'  r5   r)  r   r   r   r   r  Zbidirectional_listr8   Zrnn_clsZin_sizer7   r.   r   r   r   Zparam_namesnumr   paramr   r+  r>   rG     s   





	



zRNNBase.__init__c                 C  sV  | j r)| jdd}dd |D }dgt| | _t|D ]%\}}|d dk r)dnd| j | j }|d }|| j||d  |d  < q| jt	|g|d j
td	d
g| _t rvtjjjddgdt tjjjdddd| _d| j_n| jtjjjdt d| _t rt . |d j
}t|tjrtjj j!| }t"#| j| j| jd ddddd|	 	 W d   dS 1 sw   Y  t$t% t% V t 8 t rt&#| j|d j
dddd	dddg g  n| j'j(dd| ji| j| jddd|d j
dd W d   n1 s	w   Y  W d   dS W d   dS 1 s"w   Y  dS dS )zn
        Resets parameter data pointer to address in continuous memory block for
        cudnn usage.
        F)Zinclude_sublayersc                 S  s   g | ]}t |jqS r=   )npprodr]   )r   r6  r=   r=   r>   r   _  r.  z.RNNBase.flatten_parameters.<locals>.<listcomp>Nr  rY   r   r   )r]   rf   r   Zuint8Zdropout_state)r   )rf   r]   r   r   Z	trainableT)rf   r   	copy_data	use_alignrf   r   coalesce_tensorInput)OutputZFusedOutput)r9  r:  rf   r   r0   r   attrs))r0  r1  r\   _all_weightsr   r&  r/  r   r7  sumrf   r   r   Z_flat_weightr   rU   r   r   r   r{   r   _dropout_stater   Zcreate_variableVarDescVarTypeUINT8r   Zno_gradr   ZDataTyper   r   Zpaddle_type_to_proto_typer
   r;  r   r   r	   _helper	append_op)rF   paramsr]   rn   r6  offsetZ	layer_idxrf   r=   r=   r>   r4  T  s   
	


 TzRNNBase.flatten_parametersr0   r   r1   r2   r3   
int | None-tuple[Tensor, Tensor | tuple[Tensor, Tensor]]c           
        s8  j stj g d t r0t |j|jj	j
dkjjjjdj \}}}nMj j} fddtjD }jjtjjjdd} j||d j	j
dkjjjjj d	}|||jd
}	jjd |	|d j stj|g dn|}|t|dkrt|fS |d fS )N)r   r   rY   rY   r   c                   s   g | ]	}j  jqS r=   )rF  "create_variable_for_type_inferencerf   r   rn   r0   rF   r=   r>   r     s    z'RNNBase._cudnn_impl.<locals>.<listcomp>T)rf   r   )r<  Z
WeightListZPreStateZSequenceLength)Zdropout_probZ
is_bidirecr   r   r&  r$  Zis_test)ZOutStateZReserveZDropoutStater?   r>  r   )r5   rU   rV   r^   r   r	   r?   r@  rB  r)  r/  r   r   r&  r$  trainingrF  rL  rf   r[   r   r   rC  rD  rE  rG  r\   r   )
rF   r0   r1   r3   r   r   rP   Zreserver?  r   r=   rN  r>   _cudnn_impl  sf   
"zRNNBase._cudnn_implc                   sd  | j rdnd}|j|d u rL| jp| jg| jgf | j| j dg|j| dkr0|j| d< nt||  d< t	 fddt
| jD }nt|tjjtjjfrZ|gn|}| jrotj rh|d u ro| |||S t|| jdk| j}g }t| D ]$\}}|dkrtj|| j| jdd}|||| |\}	}
||
 |	}qt|| jdk| j}|	|fS )	Nr   r   r   c                   s$   g | ]}t j |  d dqS )r   r   )rU   r   rM  dimsrf   Z
fill_shaper=   r>   r     s    z#RNNBase.forward.<locals>.<listcomp>rY   Zupscale_in_train)rP  r$  )r5   rf   r  r   r&  r/  r]   rU   rJ   r   r[   r   r   rz   r   r   r   r0  ZdeviceZis_compiled_with_rocmrQ  r   r   r   r)  rP  rI   r   )rF   r0   r1   r3   Zbatch_indexr   r   rn   Z	rnn_layerr   Zfinal_stater=   rR  r>   r$     sV   
zRNNBase.forwardr   c                 C  sL   d}| j dkr|d7 }| jdur|d7 }| jdkr|d7 }|jdi | jS )	Nr   r   z, num_layers={num_layers}Fz, time_major={time_major}r   z, dropout={dropout}r=   )r&  r5   r)  r   r   )rF   Zmain_strr=   r=   r>   r   ;  s   


zRNNBase.extra_repr)	r   r$   Fr   NNNNr   )r$  r%  r   rK   r   rK   r&  rK   r'  r(  r5   r6   r)  r   r   r   r   r   r   r   r   r   r  rK   r9   rB   r   )r0   r   r1   r2   r3   rJ  r9   rK  r  r  )
rM   rN   rO   r   rG   r4  rQ  r$   r   r  r=   r=   r   r>   r#    s$    

c
gG<r#  c                      s8   e Zd ZdZ										dd  fddZ  ZS )!	SimpleRNNa  
    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:: python

            >>> 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)
            [4, 23, 32]
            >>> print(h.shape)
            [2, 4, 32]


    r   r$   Fr   r,   Nr   rK   r   r&  r'  r(  r5   r6   r)  r   r   r   r   r   r   r   r   r   r   r9   rB   c                   sX   |dkrd}n|dkrd}nt d| d|| _t |||||||||	|
|d d S )Nr,   r*   r-   r)   zUnknown activation ''r   )r   r   r   rG   )rF   r   r   r&  r'  r5   r)  r   r   r   r   r   r   r$  r   r=   r>   rG     s(   zSimpleRNN.__init__)
r   r$   Fr   r,   NNNNN)r   rK   r   rK   r&  rK   r'  r(  r5   r6   r)  r   r   r   r   r   r   r   r   r   r   r   r   r   r9   rB   rM   rN   rO   r   rG   r  r=   r=   r   r>   rT  F  s    XrT  c                      s8   e Zd ZdZ										dd fddZ  ZS ) r'   an  
    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:: python

            >>> 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)
            [4, 23, 32]
            >>> print(h.shape)
            [2, 4, 32]
            >>> print(c.shape)
            [2, 4, 32]


    r   r$   Fr   Nr   r   rK   r   r&  r'  r(  r5   r6   r)  r   r   r   r   r   r   r  r   r   r9   rB   c                   s&   t  d|||||||||	|
| d S )Nr'   r   rG   )rF   r   r   r&  r'  r5   r)  r   r   r   r   r  r   r   r=   r>   rG   +  s   zLSTM.__init__)
r   r$   Fr   NNNNr   N)r   rK   r   rK   r&  rK   r'  r(  r5   r6   r)  r   r   r   r   r   r   r   r   r   r  rK   r   r   r9   rB   rV  r=   r=   r   r>   r'     s    mr'   c                      s6   e Zd ZdZ									dd fddZ  ZS )r(   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:: python

            >>> 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)
            [4, 23, 32]
            >>> print(h.shape)
            [2, 4, 32]


    r   r$   Fr   Nr   rK   r   r&  r'  r(  r5   r6   r)  r   r   r   r   r   r   r   r   r9   rB   c                   s&   t  d|||||||||	|
d d S )Nr(   r   rW  )rF   r   r   r&  r'  r5   r)  r   r   r   r   r   r   r=   r>   rG     s   zGRU.__init__)	r   r$   Fr   NNNNN)r   rK   r   rK   r&  rK   r'  r(  r5   r6   r)  r   r   r   r   r   r   r   r   r   r   r   r9   rB   rV  r=   r=   r   r>   r(   J  s    ]r(   )NNFF)r.   r/   r0   r   r1   r2   r3   r4   r5   r6   r7   r6   r8   r   r9   r:   )rP   r   rQ   r   rR   r   r9   r   )rA   r   r9   r   )NNF)r   r/   r   r/   r0   r   r1   r   r3   r4   r5   r6   r8   r   r9   r   )Fr   )r   r#   r&   r6   r   rK   r9   r   )r   r   r&   r6   r   rK   r9   r   )L
__future__r   rW   collections.abcr   	functoolsr   r   typingr   r   numpyr7  Ztyping_extensionsr   rU   r	   r
   r   r   Zpaddle.base.data_feederr   r   Zpaddle.base.dygraph.baser   Zpaddle.base.frameworkr   r   r   Zpaddle.common_ops_importr   Zpaddle.frameworkr   r   Z	paddle.nnr   r   r   r   Zpaddle.tensor.manipulationr   	containerr   Zlayersr   r   r   Zpaddle._typingr   r    r!   r"   r#   Z_DirectionTypeZ_RNNTypeZ_ActivationType__all__r?   r@   rX   r`   r;   r<   r   r   r   r/   r   r  r  r  r!  r#  rT  r'   r(   r=   r=   r=   r>   <module>   s   W


G
 f;.  2 c DR]  ]{ 
