o
    Qe                    @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlmZm	Z	 d dl
Zd dlZd dlmZ d dlmZ d dlmZmZ d dlmZ d dl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$ d dl%m&Z& d dl'm(Z( d dl)m*Z* d dl)m+Z+ zd dl,m-Z- W n
   d dlm-Z- Y g Z.d,ddZ/d,ddZ0G dd deZ1G dd de1Z2G dd de1Z3G dd de1Z4G d d! d!eZ5G d"d# d#eZ6G d$d% d%eZ7G d&d' d'e7Z8G d(d) d)e7Z9G d*d+ d+e7Z:dS )-    N)partialreduce)	framework)
get_deviceget_cudnn_version)
functional)initializer)Layer	LayerList)utils)map_structureflattenpack_sequence_as)convert_dtype)_C_ops_legacy_C_ops)in_dynamic_mode)in_dygraph_mode)core)default_startup_program)program_guard)SequenceF   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   N   c                 S      g | ]}t |qS  )paddleunstack.0itemr   r   CD:\Projects\ConvertPro\env\Lib\site-packages\paddle/nn/layer/rnn.py
<listcomp>^       z split_states.<locals>.<listcomp>)r   r   listziplentuple)statesbidirectionalstate_componentsr   r   r!   split_states1   s   %
""r+   c                 C   sV   |dkrt t| S t| } 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   )r   stackr   r   r   r!   r"      r#   z!concat_states.<locals>.<listcomp>)r   r,   r   rangeappendr'   )r(   r)   r*   Z
componnetsir   r   r!   concat_statesf   s    r0   c                   @   s:   e Zd ZdZ				dddZedd Zed	d
 ZdS )RNNCellBasez
    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   c                    s   t d dd }G dd dt |du r| jn|}tj}|t_t fdd|}|t_zdu r5| jn}	W n tyE   t	 }	Y nw t
t |	d	kr]t |	d tfd
d|}	t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, 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, 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                    sn   t jdk r
ttf ntf 	 t| tst| tr$t fdd| dr$dS t| tr+dS t| t	o6t| t
j S )N)   c                    s   t | o| S N)
isinstance)flagxinteger_typesr   r!   <lambda>   s    zLRNNCellBase.get_initial_states.<locals>._is_shape_sequence.<locals>.<lambda>TF)sysversion_infointlongr5   r$   r'   r   dictr   sixstring_types)seqr   r8   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|| _d S dgt | | _d S )Nr   )r$   shape)selfrE   r   r   r!   __init__   s   *z6RNNCellBase.get_initial_states.<locals>.Shape.__init__N)__name__
__module____qualname__rG   r   r   r   r!   Shape   s    rK   Nc                    s    | S r4   r   rE   )rK   r   r!   r:      s    z0RNNCellBase.get_initial_states.<locals>.<lambda>r   c                    s    S r4   r   rL   dtyper   r!   r:      s    c                    s   t jjj| j| dS )N)inputrE   rN   valueZinput_dim_idx)r   fluidlayersfill_constant_batch_size_likerE   )rE   rN   )batch_dim_idx	batch_ref
init_valuer   r!   r:      s    )r   objectstate_shaper   Zis_sequencer   state_dtypeNotImplementedErrorr   Zget_default_dtyper&   )rF   rU   rE   rN   rV   rT   rC   Zstates_shapesZis_sequence_oriZstates_dtypesZinit_statesr   )rK   rT   rU   rN   rV   r!   get_initial_states   s*   %zRNNCellBase.get_initial_statesc                 C      t d)a  
        Abstract method (property).
        Used to initialize states.
        A (possiblely 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 implementaion for `state_shape` in the used cell.rZ   rF   r   r   r!   rX         zRNNCellBase.state_shapec                 C   r\   )a  
        Abstract method (property).
        Used to initialize states.
        A (possiblely 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 signle 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 implementaion for `state_dtype` in the used cell.r]   r^   r   r   r!   rY      r_   zRNNCellBase.state_dtype)NNr2   r   )rH   rI   rJ   __doc__r[   propertyrX   rY   r   r   r   r!   r1      s    
Y
r1   c                       sL   e Zd ZdZ						d fdd	ZdddZedd	 Z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, optional): The parameter attribute for 
            :math:`weight_ih`. Default: None.
        weight_hh_attr(ParamAttr, optional): The parameter attribute for 
            :math:`weight_hh`. Default: None.
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the 
            :math:`bias_ih`. Default: None.
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the 
            :math:`bias_hh`. Default: None.
        name (str, 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_fluid_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]

    tanhNc	           
         s   t t|   |dkrtd| jj|dt| }	| j	||f|t
|	 |	d| _| j	||f|t
|	 |	d| _| j	|f|dt
|	 |	d| _| j	|f|dt
|	 |	d| _|| _|| _|dvrmtd||| _|d	krztj| _d S tj| _d S )
Nr   >hidden_size of {} must be greater than 0, but now equals to {}      ?default_initializerTZis_biasrg   )rc   reluz?activation for SimpleRNNCell should be tanh or relu, but get {}rc   )superrb   rG   
ValueErrorformat	__class__rH   mathsqrtcreate_parameterIUniform	weight_ih	weight_hhbias_ihbias_hh
input_sizehidden_size
activationr   rc   Fri   _activation_fn)
rF   rw   rx   ry   weight_ih_attrweight_hh_attrbias_ih_attrbias_hh_attrnamestdrm   r   r!   rG   R  sR   	zSimpleRNNCell.__init__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)	r[   rX   r   matmulrs   ru   rt   rv   r{   )rF   inputsr(   Zpre_hZi2hZh2hhr   r   r!   forward  s   



zSimpleRNNCell.forwardc                 C      | j fS r4   rx   r^   r   r   r!   rX     s   zSimpleRNNCell.state_shapec                 C   s(   d}| j dkr|d7 }|jdi | jS )N{input_size}, {hidden_size}rc   z, activation={activation}r   )ry   rl   __dict__)rF   sr   r   r!   
extra_repr  s   
zSimpleRNNCell.extra_repr)rc   NNNNNr4   
rH   rI   rJ   r`   rG   r   ra   rX   r   __classcell__r   r   r   r!   rb     s    E
-
rb   c                       J   e Zd ZdZ					d fdd	ZdddZedd Z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}

    where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise 
    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, optional): The parameter attribute for 
            `weight_ih`. Default: None.
        weight_hh_attr(ParamAttr, optional): The parameter attribute for 
            `weight_hh`. Default: None.
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the 
            `bias_ih`. Default: None.
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the 
            `bias_hh`. Default: None.
        name (str, 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.
        - **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, swhich 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.
        - **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.

    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_fluid_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)
            print(h.shape)
            print(c.shape)

            #[4,32]
            #[4,32]
            #[4,32]

    Nc           	            t t|   |dkrtd| jj|dt| }| j	d| |f|t
| |d| _| j	d| |f|t
| |d| _| j	d| f|dt
| |d| _| j	d| f|dt
| |d| _|| _|| _tj| _tj| _d S )Nr   rd   re      rf   Trh   )rj   r   rG   rk   rl   rm   rH   rn   ro   rp   rq   rr   rs   rt   ru   rv   rx   rw   rz   sigmoid_gate_activationr   rc   _activation	rF   rw   rx   r|   r}   r~   r   r   r   r   r   r!   rG     B   

zLSTMCell.__init__c                 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	   }
|	| 
|
 }|||
ffS )
NTr   r   rD   Znum_or_sectionsZaxisr   r   r3   r   r[   rX   r   r   rs   ru   rt   rv   splitr   r   )rF   r   r(   
pre_hiddenZpre_cellZgatesZchunked_gatesr/   focr   r   r   r!   r     s    



zLSTMCell.forwardc                 C   s   | j f| 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!   rX   &  s   zLSTMCell.state_shapec                 C      dj di | jS Nr   r   rl   r   r^   r   r   r!   r   0     zLSTMCell.extra_reprNNNNNr4   r   r   r   r   r!   r     s    V
&
	r   c                       r   )GRUCellaE  
    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 fucntion, and * is the elemetwise 
    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, optional): The parameter attribute for 
            `weight_ih`. Default: None.
        weight_hh_attr(ParamAttr, optional): The parameter attribute for 
            `weight_hh`. Default: None.
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the 
            `bias_ih`. Default: None.
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the 
            `bias_hh`. Default: None.
        name (str, 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, swhich 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_fluid_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)
            print(h.shape)

            #[4,32]
            #[4,32]

    Nc           	         r   )Nr   rd   re   r3   rf   Trh   )rj   r   rG   rk   rl   rm   rH   rn   ro   rp   rq   rr   rs   rt   ru   rv   rx   rw   rz   r   r   r   rc   r   r   r   r   r!   rG     r   zGRUCell.__init__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   r3   r   r   r   )rF   r   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.forwardc                 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!   rX     s   zGRUCell.state_shapec                 C   r   r   r   r^   r   r   r!   r     r   zGRUCell.extra_reprr   r4   r   r   r   r   r!   r   4  s    P
&
r   c                       0   e Zd ZdZd fdd	Z		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. 

    Returns:
        - **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 intial 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)
            print(final_states.shape)

            #[4,23,32]
            #[4,32]

    Fc                    s<   t t|   || _t| jds| jj| j_|| _|| _d S )Ncall)	rj   r   rG   cellhasattrr   r   
is_reverse
time_major)rF   r   r   r   r   r   r!   rG     s   
zRNN.__init__Nc                 K   s4   t jjj| j|f||| j| jd|\}}||fS )N)initial_statessequence_lengthr   r   )r   rQ   rR   rnnr   r   r   )rF   r   r   r   kwargsZfinal_outputsfinal_statesr   r   r!   r     s   
zRNN.forward)FFNNrH   rI   rJ   r`   rG   r   r   r   r   r   r!   r     s    1r   c                       r   )
BiRNNa
  
    Wrapper for bidirectional RNN, which builds a bidiretional RNN given the 
    forward rnn cell and backward rnn cell. A BiRNN applies forward RNN and 
    backward RNN with coresponding 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): 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, 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, 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)
            print(final_states[0][0].shape,len(final_states),len(final_states[0]))

            #[4,23,64]
            #[2,32] 2 2

    Fc                    sh   t t|   || _|| _|j|jkrtd|j|j| j| jfD ]}t|ds.|j	|_
q#|| _d S )NzGinput size of forward cell({}) does not equalsthat of backward cell({})r   )rj   r   rG   cell_fwcell_bwrw   rk   rl   r   r   r   r   )rF   r   r   r   r   r   r   r!   rG   H  s   

zBiRNN.__init__Nc                 K   sT   t |ttfrt|dksJ dtjjj| j| j	|||| j
fi |\}}||fS )Nr   z<length of initial_states should be 2 when it is a list/tuple)r5   r$   r'   r&   r   rQ   rR   Zbirnnr   r   r   )rF   r   r   r   r   outputsr   r   r   r!   r   V  s   
zBiRNN.forward)Fr   r   r   r   r   r!   r     s    1r   c                       sT   e Zd ZdZ								d fdd	Zd	d
 Zdd ZdddZdd Z  Z	S )RNNBasez
    RNNBase class for RNN networks. It provides `forward`, `flatten_parameters`
    and other common methods for SimpleRNN, LSTM and GRU.
    r   r   Fr2   Nc                    s|  t t|   ddg}|| _|| _|| _|| _||v rdnd| _|| _|| _	|dkr,dnd| _
||	|
|d}|dkr=t}n|dkrDt}nt}| j|d< |d	v r~d
}|||fi |}| t||| td|D ]}|||fi |}| t||| qhnN||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 rdnd kM  _g }t| j	D ]7 t| jD ]/}|dkrdnd|ddg |
d
kr|d |d
kr|d  fdd|D }qqt||  D ]\}}t| || q,|   d S )Nr)   Zbidirectr   r   LSTM)r|   r}   r~   r   GRUry   )r   FzSdirection 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   )rl   )r   r7   layersuffixr   r!   r"         z$RNNBase.__init__.<locals>.<listcomp>)rj   r   rG   moderw   rx   dropoutnum_directionsr   
num_layersr*   r   r   rb   ry   r.   r   r-   r   rk   rl   could_use_cudnnr&   
parametersextendr%   setattrflatten_parameters)rF   r   rw   rx   r   	directionr   r   r|   r}   r~   r   Zbidirectional_listr   Zrnn_clsr   r   r/   r   r   Zparam_namesr   paramr   r   r!   rG   k  st   

zRNNBase.__init__c                 C   s  | 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| _| jtjjjd| _t rt  t| j| j| jd ddddd|d j
	 	 W d   dS 1 sw   Y  tt t > t ! | jjdd| ji| j| jddd|d j
dd W d   n1 sw   Y  W d   dS W d   dS 1 sw   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prodrE   )r   r   r   r   r!   r"     r   z.RNNBase.flatten_parameters.<locals>.<listcomp>Nr   r   r   r2   )rE   rN   rg   rM   	copy_dataT	use_alignrN   coalesce_tensorInput)OutputZFusedOutput)r   r   rN   typer   r   attrs)r   r   r&   _all_weights	enumerater   r   rp   r   sumrN   rq   ConstantZ_flat_weightZcreate_variabler   VarDescVarTypeUINT8_dropout_stater   r   Zno_gradr   r   r   r   _helper	append_op)rF   paramsrE   r/   r   offsetZ	layer_idxr   r   r!   r     s`   
 	
"zRNNBase.flatten_parametersc           
         sJ  j stj g d t r9t |j|jj	dj
djdkdjdjdjd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   r   dropout_prob
is_bidirecr   rw   rx   r   r   is_testc                    s   g | ]	}j  jqS r   )r   "create_variable_for_type_inferencerN   )r   r/   r   rF   r   r!   r"     s    z'RNNBase._cudnn_impl.<locals>.<listcomp>T)rN   Zstop_gradient)r   Z
WeightListZPreStateZSequenceLength)r   r   rw   rx   r   r   r   )ZOutStateZReserveZDropoutStater   r   r   r   )r   r   ZtensorZ	transposer   r   r   r   r   r*   r   r   rw   rx   r   r   trainingr   r   rN   r-   r   r   r   r   r   r&   r'   )
rF   r   r   r   _outstateZreserver   r   r   r   r!   _cudnn_impl  s`   



"zRNNBase._cudnn_implc           
         s  | j rdnd j|d u r*| j| j d| jft fddt| jD }nt|t	j
jr4|gn|}| jrIt	j rB|d u rI| ||S t|| jdk| j}g }t| D ]$\}}|dkrltj| j| jdd||| |\}}	||	 |qYt|| jdk| j}||fS )	Nr   r   rD   c              
      s$   g | ]}t jjd  dqS )r   r   )r   rQ   rR   rS   )r   r   Zbatch_indexrN   r   rX   r   r!   r"   .  s    z#RNNBase.forward.<locals>.<listcomp>r   Zupscale_in_train)r   r   )r   rN   r   r   rx   r'   r-   r*   r5   r   ZstaticVariabler   ZdeviceZis_compiled_with_rocmr   r+   r   rz   r   r   r.   r0   )
rF   r   r   r   r(   r   r/   Z	rnn_layerr   Zfinal_stater   r   r!   r   (  sF   


zRNNBase.forwardc                 C   sL   d}| j dkr|d7 }| jdk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   r   r   rl   r   )rF   Zmain_strr   r   r!   r   N  s   


zRNNBase.extra_repr)r   r   Fr2   NNNNr   )
rH   rI   rJ   r`   rG   r   r   r   r   r   r   r   r   r!   r   e  s    	P8
5&r   c                       s6   e Zd ZdZ										d
 fdd		Z  ZS )	SimpleRNNak  
    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 droput 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, optional): The parameter attribute for 
            `weight_ih` of each cell. Defaults to None.
        weight_hh_attr (ParamAttr, optional): The parameter attribute for 
            `weight_hh` of each cell. Defaults to None.
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the 
            `bias_ih` of each cells. Defaults to None.
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the 
            `bias_hh` of each cells. Defaults to None.
        name (str, 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)
            print(h.shape)

            #[4,23,32]
            #[2,4,32]

    r   r   Fr2   rc   Nc                    sX   |dkrd}n|dkrd}nt d||| _tt| |||||||||	|
| d S )Nrc   ZRNN_TANHri   ZRNN_RELUzUnknown activation '{}')rk   rl   ry   rj   r   rG   )rF   rw   rx   r   r   r   r   ry   r|   r}   r~   r   r   r   r   r   r!   rG     s   
zSimpleRNN.__init__)
r   r   Fr2   rc   NNNNNrH   rI   rJ   r`   rG   r   r   r   r   r!   r   Y  s    Wr   c                       4   e Zd ZdZ									d	 fdd	Z  ZS )
r   a   
    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}

    where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise 
    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 droput 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, optional): The parameter attribute for 
            `weight_ih` of each cell. Default: None.
        weight_hh_attr (ParamAttr, optional): The parameter attribute for 
            `weight_hh` of each cell. Default: None.
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the 
            `bias_ih` of each cells. Default: None.
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the 
            `bias_hh` of each cells. Default: None.
        name (str, 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 whos 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 `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]`. 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, swith 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)
            print(h.shape)
            print(c.shape)

            #[4,23,32]
            #[2,4,32]
            #[2,4,32]

    r   r   Fr2   Nc                    (   t t| d|||||||||	|
 d S )Nr   )rj   r   rG   rF   rw   rx   r   r   r   r   r|   r}   r~   r   r   r   r   r!   rG   )     
zLSTM.__init__	r   r   Fr2   NNNNNr   r   r   r   r!   r     s    cr   c                       r   )
r   a  
    Multilayer GRU. It takes input sequencse 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 fucntion, and * is the elemetwise 
    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 droput 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, optional): The parameter attribute for 
            `weight_ih` of each cell. Default: None.
        weight_hh_attr (ParamAttr, optional): The parameter attribute for 
            `weight_hh` of each cell. Default: None.
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the 
            `bias_ih` of each cells. Default: None.
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the 
            `bias_hh` of each cells. Default: None.
        name (str, 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 whos 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)
            print(h.shape)

            #[4,23,32]
            #[2,4,32]

    r   r   Fr2   Nc                    r   )Nr   )rj   r   rG   r   r   r   r!   rG     r   zGRU.__init__r   r   r   r   r   r!   r   ;  s    \r   )Fr   );copycollections	itertoolsr@   rn   r;   warnings	functoolsr   r   numpyr   r   Zpaddle.fluidrQ   r   Zpaddle.devicer   r   Z	paddle.nnr   rz   r   rq   r	   r
   Zpaddle.fluid.layersr   Zpaddle.fluid.layers.utilsr   r   r   Zpaddle.fluid.data_feederr   r   r   r   Zpaddle.fluid.frameworkr   Zpaddle.frameworkr   Zpaddle.staticr   r   collections.abcr   __all__r+   r0   r1   rb   r   r   r   r   r   r   r   r   r   r   r   r!   <module>   s\   

5* 	  KO uos