a
    ßñh½¼  ã                   @   s(  d dl Z d dlZd dlZd dlmZmZmZmZ d dl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 d
dlmZ ejejdœZd e	e	ee	dœdd„ZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZdS )!é    N)ÚListÚTupleÚOptionalÚoverload)ÚTensoré   )ÚModuleé   )Ú	Parameter)ÚPackedSequence)Úinité   )Ú_VF)ÚRNN_TANHÚRNN_RELU)ÚtensorÚpermutationÚdimÚreturnc                 C   s   |   ||¡S ©N)Zindex_select)r   r   r   © r   úT/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/nn/modules/rnn.pyÚapply_permutation   s    r   c                       s”  e Zd ZU g d¢ZdgZeed< eed< eed< eed< eed< eed< e	ed	< eed
< d6eeeeeee	eddœ	‡ fdd„Z
‡ fdd„Zddœdd„Z‡ fdd„Zddœdd„Zeee ddœdd„Zeee eeeef dœdd „Zd7eeeeef edd"œd#d$„Zeeee d%œd&d'„Zeee d(œd)d*„Zd8eee eeef d+œd,d-„Zedœd.d/„Z‡ fd0d1„Zeee dœd2d3„ƒZ‡ fd4d5„Z‡  ZS )9ÚRNNBase)ÚmodeÚ
input_sizeÚhidden_sizeÚ
num_layersÚbiasÚbatch_firstÚdropoutÚbidirectionalÚall_weightsr   r   r   r   r   r   r    r!   r   TFç        N)	r   r   r   r   r   r   r    r!   r   c	                    s   t tˆƒ ¡  |ˆ_|ˆ_|ˆ_|ˆ_|ˆ_|ˆ_t	|ƒˆ_
|ˆ_|rJdnd}	t|tjƒr|d|  krndkr|n n
t|tƒr„tdƒ‚|dkr¦|dkr¦t d ||¡¡ |dkr¸d| }
n:|dkrÊd	| }
n(|d
krØ|}
n|dkræ|}
ntd| ƒ‚g ˆ_g ˆ_t|ƒD ]î‰ t|	ƒD ]Þ}ˆ dk�r$|n||	 }tt |
|¡ƒ}tt |
|¡ƒ}tt |
¡ƒ}tt |
¡ƒ}||||f}|dk�r‚dnd‰ddg}|�r |ddg7 }‡ ‡fdd„|D ƒ}t||ƒD ]\}}tˆ||ƒ �q¾ˆj |¡ ˆj |¡ �q�q‡fdd„ˆjD ƒˆ_ˆ ¡  ˆ  ¡  d S )Nr	   r   r   zbdropout should be a number in range [0, 1] representing the probability of an element being zeroedz›dropout option adds dropout after all but last recurrent layer, so non-zero dropout expects num_layers greater than 1, but got dropout={} and num_layers={}ÚLSTMé   ÚGRUr   r   r   zUnrecognized RNN mode: Ú_reverseÚ úweight_ih_l{}{}úweight_hh_l{}{}úbias_ih_l{}{}úbias_hh_l{}{}c                    s   g | ]}|  ˆ ˆ¡‘qS r   ©Úformat©Ú.0Úx©ÚlayerÚsuffixr   r   Ú
<listcomp>\   ó    z$RNNBase.__init__.<locals>.<listcomp>c                    s   g | ]}‡ fd d„|ƒ‘qS )c                    s   t ˆ | ƒrtˆ | ƒS d S r   ©ÚhasattrÚgetattr©Úwn©Úselfr   r   Ú<lambda>c   r6   z-RNNBase.__init__.<locals>.<listcomp>.<lambda>r   ©r0   r;   r<   r   r   r5   c   r6   )!Úsuperr   Ú__init__r   r   r   r   r   r   Úfloatr    r!   Ú
isinstanceÚnumbersÚNumberÚboolÚ
ValueErrorÚwarningsÚwarnr.   Ú_flat_weights_namesÚ_all_weightsÚranger
   Útorchr   ÚzipÚsetattrÚextendÚappendÚ_flat_weightsÚflatten_parametersÚreset_parameters)r=   r   r   r   r   r   r   r    r!   Únum_directionsZ	gate_sizeÚ	directionZlayer_input_sizeZw_ihZw_hhZb_ihZb_hhZlayer_paramsZparam_namesÚnameÚparam©Ú	__class__©r3   r=   r4   r   rA   &   sb    
$ÿý

zRNNBase.__init__c                    s@   t | dƒr*|| jv r*| j |¡}|| j|< tt| ƒ ||¡ d S )NrJ   )r8   rJ   ÚindexrR   r@   r   Ú__setattr__)r=   ÚattrÚvalueÚidxrY   r   r   r]   g   s    
zRNNBase.__setattr__©r   c                 C   sh  t | jƒt | jƒkrdS | jD ]}t|tƒs dS q| jd }|j}| jD ]:}t|jtƒr~|jj|kr~|jjr~tj	j
 |j¡sJ dS qJtdd„ | jD ƒƒ}t |ƒt | jƒkr°dS tj |¡�– ddlm	  m
  m} t ¡ �T t ¡ �r$t | j| jrüdnd| j| | j¡| j| j| jt| jƒ¡ W d  ƒ n1 �s:0    Y  W d  ƒ n1 �sZ0    Y  dS )zÅResets parameter data pointer so that they can use faster code paths.

        Right now, this works only if the module is on the GPU and cuDNN is enabled.
        Otherwise, it's a no-op.
        Nr   c                 s   s   | ]}|  ¡ V  qd S r   )Zdata_ptr)r0   Úpr   r   r   Ú	<genexpr>Š   r6   z-RNNBase.flatten_parameters.<locals>.<genexpr>r%   r	   )ÚlenrR   rJ   rC   r   ÚdtypeÚdataZis_cudarM   ÚbackendsZcudnnZis_acceptableÚsetZcudaZ	device_ofZtorch.backends.cudnn.rnnÚrnnZno_gradZ_use_cudnn_rnn_flatten_weightZ_cudnn_rnn_flatten_weightr   r   Zget_cudnn_moder   r   r   r   rF   r!   )r=   ÚwZfirst_fwre   ÚfwZunique_data_ptrsri   r   r   r   rS   n   s4    



ÿþ

ýzRNNBase.flatten_parametersc                    s2   t tˆ ƒ |¡}‡ fdd„ˆ jD ƒˆ _ˆ  ¡  |S )Nc                    s   g | ]}‡ fd d„|ƒ‘qS )c                    s   t ˆ | ƒrtˆ | ƒS d S r   r7   r:   r<   r   r   r>       r6   z+RNNBase._apply.<locals>.<listcomp>.<lambda>r   r?   r<   r   r   r5       r6   z"RNNBase._apply.<locals>.<listcomp>)r@   r   Ú_applyrJ   rR   rS   )r=   ÚfnÚretrY   r<   r   rl   š   s    zRNNBase._applyc                 C   s2   dt  | j¡ }|  ¡ D ]}t || |¡ qd S ©Ng      ð?©ÚmathÚsqrtr   Ú
parametersr   Zuniform_©r=   ZstdvÚweightr   r   r   rT   ¦   s    zRNNBase.reset_parameters)ÚinputÚbatch_sizesr   c                 C   s\   |d urdnd}|  ¡ |kr0td ||  ¡ ¡ƒ‚| j| d¡krXtd | j| d¡¡ƒ‚d S )Nr	   r   z%input must have {} dimensions, got {}éÿÿÿÿz?input.size(-1) must be equal to input_size. Expected {}, got {})r   ÚRuntimeErrorr.   r   Úsize)r=   rv   rw   Zexpected_input_dimr   r   r   Úcheck_input«   s    ÿÿÿÿzRNNBase.check_inputc                 C   sX   |d ur|d }t |ƒ}n| jr*| d¡n| d¡}| jr>dnd}| j| || jf}|S )Nr   r   r	   )Úintr   rz   r!   r   r   )r=   rv   rw   Z
mini_batchrU   Úexpected_hidden_sizer   r   r   Úget_expected_hidden_size¶   s    
ÿz RNNBase.get_expected_hidden_sizeúExpected hidden size {}, got {})Úhxr}   Úmsgr   c                 C   s(   |  ¡ |kr$t| |t|  ¡ ƒ¡ƒ‚d S r   )rz   ry   r.   Úlist)r=   r€   r}   r�   r   r   r   Úcheck_hidden_sizeÁ   s    zRNNBase.check_hidden_size©rv   Úhiddenrw   c                 C   s(   |   ||¡ |  ||¡}|  ||¡ d S r   ©r{   r~   rƒ   ©r=   rv   r…   rw   r}   r   r   r   Úcheck_forward_argsÆ   s    zRNNBase.check_forward_args)r€   r   c                 C   s   |d u r|S t ||ƒS r   ©r   ©r=   r€   r   r   r   r   Úpermute_hiddenÌ   s    zRNNBase.permute_hidden©rv   r€   r   c              
   C   s6  t |tƒ}|r,|\}}}}|d }t|ƒ}n&d }| jr@| d¡n| d¡}d }d }|d u rŠ| jrddnd}tj| j| || j	|j
|jd�}n|  ||¡}|  |||¡ t| j }	|d u rÞ|	||| j| j| j| j| j| j| jƒ	}
n$|	|||| j| j| j| j| j| jƒ	}
|
d }|
d }|�r&t||||ƒ}||  ||¡fS ©Nr   r   r	   ©re   Údevice)rC   r   r|   r   rz   r!   rM   Úzerosr   r   re   r�   r‹   rˆ   Ú
_rnn_implsr   rR   r   r    Útraining)r=   rv   r€   Z	is_packedrw   Úsorted_indicesÚunsorted_indicesÚmax_batch_sizerU   Ú_implÚresultÚoutputr…   r   r   r   ÚforwardÑ   s<    

þ
ÿÿzRNNBase.forwardc                 C   sp   d}| j dkr|d7 }| jdur(|d7 }| jdur:|d7 }| jdkrL|d	7 }| jdur^|d
7 }|jf i | j¤ŽS )Nú{input_size}, {hidden_size}r   z, num_layers={num_layers}Tú, bias={bias}Fz, batch_first={batch_first}r   z, dropout={dropout}z, bidirectional={bidirectional})r   r   r   r    r!   r.   Ú__dict__©r=   Úsr   r   r   Ú
extra_reprö   s    




zRNNBase.extra_reprc                    s  t tˆƒ |¡ d|v r"|d ˆ_tˆjd d tƒr:d S ˆj}ˆjrJdnd}g ˆ_g ˆ_t	|ƒD ]Ž‰ t	|ƒD ]€}|dkr~dnd‰g d¢}‡ ‡fdd	„|D ƒ}ˆj
rÂˆ j|g7  _ˆj |¡ qnˆ j|d d… g7  _ˆj |d d… ¡ qnqb‡fd
d	„ˆjD ƒˆ_d S )Nr"   r   r	   r   r'   r(   )r)   r*   r+   r,   c                    s   g | ]}|  ˆ ˆ¡‘qS r   r-   r/   r2   r   r   r5     r6   z(RNNBase.__setstate__.<locals>.<listcomp>c                    s   g | ]}‡ fd d„|ƒ‘qS )c                    s   t ˆ | ƒrtˆ | ƒS d S r   r7   r:   r<   r   r   r>     r6   z1RNNBase.__setstate__.<locals>.<listcomp>.<lambda>r   r?   r<   r   r   r5     r6   )r@   r   Ú__setstate__rK   rC   Ústrr   r!   rJ   rL   r   rP   rR   )r=   Údr   rU   rV   ÚweightsrY   r[   r   r      s(    
zRNNBase.__setstate__c                    s   ‡ fdd„ˆ j D ƒS )Nc                    s   g | ]}‡ fd d„|D ƒ‘qS )c                    s   g | ]}t ˆ |ƒ‘qS r   )r9   )r0   ru   r<   r   r   r5     r6   z2RNNBase.all_weights.<locals>.<listcomp>.<listcomp>r   )r0   r£   r<   r   r   r5     r6   z'RNNBase.all_weights.<locals>.<listcomp>)rK   r<   r   r<   r   r"     s    zRNNBase.all_weightsc                    s2   t t| ƒ ¡ }|jd d … |_|jd d … |_|S r   )r@   r   Ú_replicate_for_data_parallelrR   rJ   )r=   ZreplicarY   r   r   r¤      s    z$RNNBase._replicate_for_data_parallel)r   TFr#   F)r   )N) Ú__name__Ú
__module__Ú__qualname__Ú__constants__Z__jit_unused_properties__r¡   Ú__annotations__r|   rF   rB   rA   r]   rS   rl   rT   r   r   r{   r   r~   rƒ   rˆ   r‹   r™   rŸ   r    Úpropertyr   r
   r"   r¤   Ú__classcell__r   r   rY   r   r      sD   
  þþA,  ÿÿ %r   c                       s    e Zd ZdZ‡ fdd„Z‡  ZS )ÚRNNa»  Applies a multi-layer Elman RNN with :math:`\tanh` or :math:`\text{ReLU}` non-linearity to an
    input sequence.


    For each element in the input sequence, each layer computes the following
    function:

    .. math::
        h_t = \tanh(W_{ih} x_t + b_{ih} + W_{hh} h_{(t-1)} + b_{hh})

    where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is
    the input at time `t`, and :math:`h_{(t-1)}` is the hidden state of the
    previous layer at time `t-1` or the initial hidden state at time `0`.
    If :attr:`nonlinearity` is ``'relu'``, then :math:`\text{ReLU}` is used instead of :math:`\tanh`.

    Args:
        input_size: The number of expected features in the input `x`
        hidden_size: The number of features in the hidden state `h`
        num_layers: Number of recurrent layers. E.g., setting ``num_layers=2``
            would mean stacking two RNNs together to form a `stacked RNN`,
            with the second RNN taking in outputs of the first RNN and
            computing the final results. Default: 1
        nonlinearity: The non-linearity to use. Can be either ``'tanh'`` or ``'relu'``. Default: ``'tanh'``
        bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`.
            Default: ``True``
        batch_first: If ``True``, then the input and output tensors are provided
            as `(batch, seq, feature)`. Default: ``False``
        dropout: If non-zero, introduces a `Dropout` layer on the outputs of each
            RNN layer except the last layer, with dropout probability equal to
            :attr:`dropout`. Default: 0
        bidirectional: If ``True``, becomes a bidirectional RNN. Default: ``False``

    Inputs: input, h_0
        - **input** of shape `(seq_len, batch, input_size)`: tensor containing the features
          of the input sequence. The input can also be a packed variable length
          sequence. See :func:`torch.nn.utils.rnn.pack_padded_sequence`
          or :func:`torch.nn.utils.rnn.pack_sequence`
          for details.
        - **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
          containing the initial hidden state for each element in the batch.
          Defaults to zero if not provided. If the RNN is bidirectional,
          num_directions should be 2, else it should be 1.

    Outputs: output, h_n
        - **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor
          containing the output features (`h_t`) from the last layer of the RNN,
          for each `t`.  If a :class:`torch.nn.utils.rnn.PackedSequence` has
          been given as the input, the output will also be a packed sequence.

          For the unpacked case, the directions can be separated
          using ``output.view(seq_len, batch, num_directions, hidden_size)``,
          with forward and backward being direction `0` and `1` respectively.
          Similarly, the directions can be separated in the packed case.
        - **h_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
          containing the hidden state for `t = seq_len`.

          Like *output*, the layers can be separated using
          ``h_n.view(num_layers, num_directions, batch, hidden_size)``.

    Shape:
        - Input1: :math:`(L, N, H_{in})` tensor containing input features where
          :math:`H_{in}=\text{input\_size}` and `L` represents a sequence length.
        - Input2: :math:`(S, N, H_{out})` tensor
          containing the initial hidden state for each element in the batch.
          :math:`H_{out}=\text{hidden\_size}`
          Defaults to zero if not provided. where :math:`S=\text{num\_layers} * \text{num\_directions}`
          If the RNN is bidirectional, num_directions should be 2, else it should be 1.
        - Output1: :math:`(L, N, H_{all})` where :math:`H_{all}=\text{num\_directions} * \text{hidden\_size}`
        - Output2: :math:`(S, N, H_{out})` tensor containing the next hidden state
          for each element in the batch

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

    .. note::
        All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
        where :math:`k = \frac{1}{\text{hidden\_size}}`

    .. include:: ../cudnn_rnn_determinism.rst

    .. include:: ../cudnn_persistent_rnn.rst

    Examples::

        >>> rnn = nn.RNN(10, 20, 2)
        >>> input = torch.randn(5, 3, 10)
        >>> h0 = torch.randn(2, 3, 20)
        >>> output, hn = rnn(input, h0)
    c                    s`   |  dd¡| _| jdkrd}n | jdkr.d}ntd | j¡ƒ‚tt| ƒj|g|¢R i |¤Ž d S )NÚnonlinearityÚtanhr   Úrelur   zUnknown nonlinearity '{}')Úpopr­   rG   r.   r@   r¬   rA   )r=   ÚargsÚkwargsr   rY   r   r   rA   Œ  s    

zRNN.__init__)r¥   r¦   r§   Ú__doc__rA   r«   r   r   rY   r   r¬   )  s   br¬   c                
       sæ   e Zd ZdZ‡ fdd„Zeeeef ee dœdd„Zeeef ee eeef dœdd	„Z	e
ejjdeeeeef  eeeeef f dœdd„ƒƒZe
ejjdeeeeef  eeeeef f dœdd„ƒƒZddd„Z‡  ZS )r$   aí  Applies a multi-layer long short-term memory (LSTM) RNN to an input
    sequence.


    For each element in the input sequence, each layer computes the following
    function:

    .. math::
        \begin{array}{ll} \\
            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}) \\
            g_t = \tanh(W_{ig} x_t + b_{ig} + W_{hg} h_{t-1} + b_{hg}) \\
            o_t = \sigma(W_{io} x_t + b_{io} + W_{ho} h_{t-1} + b_{ho}) \\
            c_t = f_t \odot c_{t-1} + i_t \odot g_t \\
            h_t = o_t \odot \tanh(c_t) \\
        \end{array}

    where :math:`h_t` is the hidden state at time `t`, :math:`c_t` is the cell
    state at time `t`, :math:`x_t` is the input at time `t`, :math:`h_{t-1}`
    is the hidden state of the layer at time `t-1` or the initial hidden
    state at time `0`, and :math:`i_t`, :math:`f_t`, :math:`g_t`,
    :math:`o_t` are the input, forget, cell, and output gates, respectively.
    :math:`\sigma` is the sigmoid function, and :math:`\odot` is the Hadamard product.

    In a multilayer LSTM, the input :math:`x^{(l)}_t` of the :math:`l` -th layer
    (:math:`l >= 2`) is the hidden state :math:`h^{(l-1)}_t` of the previous layer multiplied by
    dropout :math:`\delta^{(l-1)}_t` where each :math:`\delta^{(l-1)}_t` is a Bernoulli random
    variable which is :math:`0` with probability :attr:`dropout`.

    Args:
        input_size: The number of expected features in the input `x`
        hidden_size: The number of features in the hidden state `h`
        num_layers: Number of recurrent layers. E.g., setting ``num_layers=2``
            would mean stacking two LSTMs together to form a `stacked LSTM`,
            with the second LSTM taking in outputs of the first LSTM and
            computing the final results. Default: 1
        bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`.
            Default: ``True``
        batch_first: If ``True``, then the input and output tensors are provided
            as (batch, seq, feature). Default: ``False``
        dropout: If non-zero, introduces a `Dropout` layer on the outputs of each
            LSTM layer except the last layer, with dropout probability equal to
            :attr:`dropout`. Default: 0
        bidirectional: If ``True``, becomes a bidirectional LSTM. Default: ``False``

    Inputs: input, (h_0, c_0)
        - **input** of shape `(seq_len, batch, input_size)`: tensor containing the features
          of the input sequence.
          The input can also be a packed variable length sequence.
          See :func:`torch.nn.utils.rnn.pack_padded_sequence` or
          :func:`torch.nn.utils.rnn.pack_sequence` for details.
        - **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
          containing the initial hidden state for each element in the batch.
          If the LSTM is bidirectional, num_directions should be 2, else it should be 1.
        - **c_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
          containing the initial cell state for each element in the batch.

          If `(h_0, c_0)` is not provided, both **h_0** and **c_0** default to zero.


    Outputs: output, (h_n, c_n)
        - **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor
          containing the output features `(h_t)` from the last layer of the LSTM,
          for each `t`. If a :class:`torch.nn.utils.rnn.PackedSequence` has been
          given as the input, the output will also be a packed sequence.

          For the unpacked case, the directions can be separated
          using ``output.view(seq_len, batch, num_directions, hidden_size)``,
          with forward and backward being direction `0` and `1` respectively.
          Similarly, the directions can be separated in the packed case.
        - **h_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
          containing the hidden state for `t = seq_len`.

          Like *output*, the layers can be separated using
          ``h_n.view(num_layers, num_directions, batch, hidden_size)`` and similarly for *c_n*.
        - **c_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
          containing the cell state for `t = seq_len`.

    Attributes:
        weight_ih_l[k] : the learnable input-hidden weights of the :math:`\text{k}^{th}` layer
            `(W_ii|W_if|W_ig|W_io)`, of shape `(4*hidden_size, input_size)` for `k = 0`.
            Otherwise, the shape is `(4*hidden_size, num_directions * hidden_size)`
        weight_hh_l[k] : the learnable hidden-hidden weights of the :math:`\text{k}^{th}` layer
            `(W_hi|W_hf|W_hg|W_ho)`, of shape `(4*hidden_size, hidden_size)`
        bias_ih_l[k] : the learnable input-hidden bias of the :math:`\text{k}^{th}` layer
            `(b_ii|b_if|b_ig|b_io)`, of shape `(4*hidden_size)`
        bias_hh_l[k] : the learnable hidden-hidden bias of the :math:`\text{k}^{th}` layer
            `(b_hi|b_hf|b_hg|b_ho)`, of shape `(4*hidden_size)`

    .. note::
        All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
        where :math:`k = \frac{1}{\text{hidden\_size}}`

    .. include:: ../cudnn_rnn_determinism.rst

    .. include:: ../cudnn_persistent_rnn.rst

    Examples::

        >>> rnn = nn.LSTM(10, 20, 2)
        >>> input = torch.randn(5, 3, 10)
        >>> h0 = torch.randn(2, 3, 20)
        >>> c0 = torch.randn(2, 3, 20)
        >>> output, (hn, cn) = rnn(input, (h0, c0))
    c                    s"   t t| ƒjdg|¢R i |¤Ž d S )Nr$   )r@   r$   rA   ©r=   r±   r²   rY   r   r   rA     s    zLSTM.__init__r„   c                 C   s@   |   ||¡ |  ||¡}|  |d |d¡ |  |d |d¡ d S )Nr   z"Expected hidden[0] size {}, got {}r   z"Expected hidden[1] size {}, got {}r†   r‡   r   r   r   rˆ     s    ÿÿzLSTM.check_forward_args)r€   r   r   c                 C   s(   |d u r|S t |d |ƒt |d |ƒfS )Nr   r   r‰   rŠ   r   r   r   r‹     s    zLSTM.permute_hiddenNrŒ   c                 C   s   d S r   r   ©r=   rv   r€   r   r   r   r™     s    zLSTM.forwardc                 C   s   d S r   r   rµ   r   r   r   r™   %  s    c                 C   sV  |}t |tƒr,|\}}}}|d }t|ƒ}n&d }| jr@| d¡n| d¡}d }d }|d u r’| jrddnd}tj| j| || j	|j
|jd�}	|	|	f}n|  ||¡}|  |||¡ |d u rÞt ||| j| j| j| j| j| j| j¡	}
n&t |||| j| j| j| j| j| j¡	}
|
d }|
dd … }t |tƒ�rBt||||ƒ}||  ||¡fS ||  ||¡fS d S r�   )rC   r   r|   r   rz   r!   rM   r�   r   r   re   r�   r‹   rˆ   r   ZlstmrR   r   r    r’   )r=   rv   r€   Ú
orig_inputrw   r“   r”   r•   rU   r�   r—   r˜   r…   Úoutput_packedr   r   r   r™   +  s>    

þ
ÿÿ)N)N)N)r¥   r¦   r§   r³   rA   r   r   r   rˆ   r‹   r   rM   Ú_jit_internalÚ_overload_methodr™   r   r«   r   r   rY   r   r$   £  s   j	&ÿÿr$   c                       s‚   e Zd ZdZ‡ fdd„Zeejjd
e	e
e	 ee	e	f dœdd„ƒƒZeejjdee
e	 eee	f dœdd„ƒƒZdd	d„Z‡  ZS )r&   að  Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence.


    For each element in the input sequence, each layer computes the following
    function:

    .. math::
        \begin{array}{ll}
            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}) \\
            n_t = \tanh(W_{in} x_t + b_{in} + r_t * (W_{hn} h_{(t-1)}+ b_{hn})) \\
            h_t = (1 - z_t) * n_t + z_t * h_{(t-1)}
        \end{array}

    where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is the input
    at time `t`, :math:`h_{(t-1)}` is the hidden state of the layer
    at time `t-1` or the initial hidden state at time `0`, and :math:`r_t`,
    :math:`z_t`, :math:`n_t` are the reset, update, and new gates, respectively.
    :math:`\sigma` is the sigmoid function, and :math:`*` is the Hadamard product.

    In a multilayer GRU, the input :math:`x^{(l)}_t` of the :math:`l` -th layer
    (:math:`l >= 2`) is the hidden state :math:`h^{(l-1)}_t` of the previous layer multiplied by
    dropout :math:`\delta^{(l-1)}_t` where each :math:`\delta^{(l-1)}_t` is a Bernoulli random
    variable which is :math:`0` with probability :attr:`dropout`.

    Args:
        input_size: The number of expected features in the input `x`
        hidden_size: The number of features in the hidden state `h`
        num_layers: Number of recurrent layers. E.g., setting ``num_layers=2``
            would mean stacking two GRUs together to form a `stacked GRU`,
            with the second GRU taking in outputs of the first GRU and
            computing the final results. Default: 1
        bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`.
            Default: ``True``
        batch_first: If ``True``, then the input and output tensors are provided
            as (batch, seq, feature). Default: ``False``
        dropout: If non-zero, introduces a `Dropout` layer on the outputs of each
            GRU layer except the last layer, with dropout probability equal to
            :attr:`dropout`. Default: 0
        bidirectional: If ``True``, becomes a bidirectional GRU. Default: ``False``

    Inputs: input, h_0
        - **input** of shape `(seq_len, batch, input_size)`: tensor containing the features
          of the input sequence. The input can also be a packed variable length
          sequence. See :func:`torch.nn.utils.rnn.pack_padded_sequence`
          for details.
        - **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
          containing the initial hidden state for each element in the batch.
          Defaults to zero if not provided. If the RNN is bidirectional,
          num_directions should be 2, else it should be 1.

    Outputs: output, h_n
        - **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor
          containing the output features h_t from the last layer of the GRU,
          for each `t`. If a :class:`torch.nn.utils.rnn.PackedSequence` has been
          given as the input, the output will also be a packed sequence.
          For the unpacked case, the directions can be separated
          using ``output.view(seq_len, batch, num_directions, hidden_size)``,
          with forward and backward being direction `0` and `1` respectively.

          Similarly, the directions can be separated in the packed case.
        - **h_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
          containing the hidden state for `t = seq_len`

          Like *output*, the layers can be separated using
          ``h_n.view(num_layers, num_directions, batch, hidden_size)``.

    Shape:
        - Input1: :math:`(L, N, H_{in})` tensor containing input features where
          :math:`H_{in}=\text{input\_size}` and `L` represents a sequence length.
        - Input2: :math:`(S, N, H_{out})` tensor
          containing the initial hidden state for each element in the batch.
          :math:`H_{out}=\text{hidden\_size}`
          Defaults to zero if not provided. where :math:`S=\text{num\_layers} * \text{num\_directions}`
          If the RNN is bidirectional, num_directions should be 2, else it should be 1.
        - Output1: :math:`(L, N, H_{all})` where :math:`H_{all}=\text{num\_directions} * \text{hidden\_size}`
        - Output2: :math:`(S, N, H_{out})` tensor containing the next hidden state
          for each element in the batch

    Attributes:
        weight_ih_l[k] : the learnable input-hidden weights of the :math:`\text{k}^{th}` layer
            (W_ir|W_iz|W_in), of shape `(3*hidden_size, input_size)` for `k = 0`.
            Otherwise, the shape is `(3*hidden_size, num_directions * hidden_size)`
        weight_hh_l[k] : the learnable hidden-hidden weights of the :math:`\text{k}^{th}` layer
            (W_hr|W_hz|W_hn), of shape `(3*hidden_size, hidden_size)`
        bias_ih_l[k] : the learnable input-hidden bias of the :math:`\text{k}^{th}` layer
            (b_ir|b_iz|b_in), of shape `(3*hidden_size)`
        bias_hh_l[k] : the learnable hidden-hidden bias of the :math:`\text{k}^{th}` layer
            (b_hr|b_hz|b_hn), of shape `(3*hidden_size)`

    .. note::
        All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
        where :math:`k = \frac{1}{\text{hidden\_size}}`

    .. include:: ../cudnn_persistent_rnn.rst

    Examples::

        >>> rnn = nn.GRU(10, 20, 2)
        >>> input = torch.randn(5, 3, 10)
        >>> h0 = torch.randn(2, 3, 20)
        >>> output, hn = rnn(input, h0)
    c                    s"   t t| ƒjdg|¢R i |¤Ž d S )Nr&   )r@   r&   rA   r´   rY   r   r   rA   ½  s    zGRU.__init__NrŒ   c                 C   s   d S r   r   rµ   r   r   r   r™   À  s    zGRU.forwardc                 C   s   d S r   r   rµ   r   r   r   r™   Å  s    c                 C   sJ  |}t |tƒr,|\}}}}|d }t|ƒ}n&d }| jr@| d¡n| d¡}d }d }|d u rŠ| jrddnd}tj| j| || j	|j
|jd�}n|  ||¡}|  |||¡ |d u rÖt ||| j| j| j| j| j| j| j¡	}	n&t |||| j| j| j| j| j| j¡	}	|	d }
|	d }t |tƒ�r6t|
|||ƒ}||  ||¡fS |
|  ||¡fS d S r�   )rC   r   r|   r   rz   r!   rM   r�   r   r   re   r�   r‹   rˆ   r   ZgrurR   r   r    r’   )r=   rv   r€   r¶   rw   r“   r”   r•   rU   r—   r˜   r…   r·   r   r   r   r™   Ê  s<    

þÿÿ)N)N)N)r¥   r¦   r§   r³   rA   r   rM   r¸   r¹   r   r   r   r™   r   r«   r   r   rY   r   r&   T  s   h$$r&   c                       sž   e Zd ZU g d¢Zeed< eed< eed< eed< eed< eeeeddœ‡ fd	d
„Ze	dœdd„Z
eddœdd„Zdeee	ddœdd„Zddœdd„Z‡  ZS )ÚRNNCellBase)r   r   r   r   r   r   Ú	weight_ihÚ	weight_hhN)r   r   r   Ú
num_chunksr   c                    sž   t t| ƒ ¡  || _|| _|| _tt || |¡ƒ| _	tt || |¡ƒ| _
|rztt || ¡ƒ| _tt || ¡ƒ| _n|  dd ¡ |  dd ¡ |  ¡  d S )NÚbias_ihÚbias_hh)r@   rº   rA   r   r   r   r
   rM   r   r»   r¼   r¾   r¿   Zregister_parameterrT   )r=   r   r   r   r½   rY   r   r   rA   þ  s    zRNNCellBase.__init__ra   c                 C   sN   d}d| j v r | jdur |d7 }d| j v r<| jdkr<|d7 }|jf i | j ¤ŽS )Nrš   r   Tr›   r­   r®   z, nonlinearity={nonlinearity})rœ   r   r­   r.   r�   r   r   r   rŸ     s    zRNNCellBase.extra_repr)rv   r   c                 C   s,   |  d¡| jkr(td |  d¡| j¡ƒ‚d S )Nr   z6input has inconsistent input_size: got {}, expected {})rz   r   ry   r.   )r=   rv   r   r   r   Úcheck_forward_input  s    ÿÿzRNNCellBase.check_forward_inputr(   )rv   r€   Úhidden_labelr   c                 C   s`   |  d¡|  d¡kr2td |  d¡||  d¡¡ƒ‚|  d¡| jkr\td ||  d¡| j¡ƒ‚d S )Nr   z8Input batch size {} doesn't match hidden{} batch size {}r   z:hidden{} has inconsistent hidden_size: got {}, expected {})rz   ry   r.   r   )r=   rv   r€   rÁ   r   r   r   Úcheck_forward_hidden  s    ÿÿÿÿz RNNCellBase.check_forward_hiddenc                 C   s2   dt  | j¡ }|  ¡ D ]}t || |¡ qd S ro   rp   rt   r   r   r   rT   &  s    zRNNCellBase.reset_parameters)r(   )r¥   r¦   r§   r¨   r|   r©   rF   r   rA   r¡   rŸ   rÀ   rÂ   rT   r«   r   r   rY   r   rº   ó  s   
rº   c                       sZ   e Zd ZU dZg d¢Zeed< deeeeddœ‡ fdd	„Z	de
ee
 e
d
œdd„Z‡  ZS )ÚRNNCellaê  An Elman RNN cell with tanh or ReLU non-linearity.

    .. math::

        h' = \tanh(W_{ih} x + b_{ih}  +  W_{hh} h + b_{hh})

    If :attr:`nonlinearity` is `'relu'`, then ReLU is used in place of tanh.

    Args:
        input_size: The number of expected features in the input `x`
        hidden_size: The number of features in the hidden state `h`
        bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`.
            Default: ``True``
        nonlinearity: The non-linearity to use. Can be either ``'tanh'`` or ``'relu'``. Default: ``'tanh'``

    Inputs: input, hidden
        - **input** of shape `(batch, input_size)`: tensor containing input features
        - **hidden** of shape `(batch, hidden_size)`: tensor containing the initial hidden
          state for each element in the batch.
          Defaults to zero if not provided.

    Outputs: h'
        - **h'** of shape `(batch, hidden_size)`: tensor containing the next hidden state
          for each element in the batch

    Shape:
        - Input1: :math:`(N, H_{in})` tensor containing input features where
          :math:`H_{in}` = `input_size`
        - Input2: :math:`(N, H_{out})` tensor containing the initial hidden
          state for each element in the batch where :math:`H_{out}` = `hidden_size`
          Defaults to zero if not provided.
        - Output: :math:`(N, H_{out})` tensor containing the next hidden state
          for each element in the batch

    Attributes:
        weight_ih: the learnable input-hidden weights, of shape
            `(hidden_size, input_size)`
        weight_hh: the learnable hidden-hidden weights, of shape
            `(hidden_size, hidden_size)`
        bias_ih: the learnable input-hidden bias, of shape `(hidden_size)`
        bias_hh: the learnable hidden-hidden bias, of shape `(hidden_size)`

    .. note::
        All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
        where :math:`k = \frac{1}{\text{hidden\_size}}`

    Examples::

        >>> rnn = nn.RNNCell(10, 20)
        >>> input = torch.randn(6, 3, 10)
        >>> hx = torch.randn(3, 20)
        >>> output = []
        >>> for i in range(6):
                hx = rnn(input[i], hx)
                output.append(hx)
    )r   r   r   r­   r­   Tr®   N)r   r   r   r­   r   c                    s"   t t| ƒj|||dd� || _d S )Nr   ©r½   )r@   rÃ   rA   r­   )r=   r   r   r   r­   rY   r   r   rA   h  s    zRNNCell.__init__rŒ   c                 C   s¦   |   |¡ |d u r0tj| d¡| j|j|jd�}|  ||d¡ | jdkrft	 
||| j| j| j| j¡}n<| jdkrŽt	 ||| j| j| j| j¡}n|}td | j¡ƒ‚|S )Nr   rŽ   r(   r®   r¯   zUnknown nonlinearity: {})rÀ   rM   r�   rz   r   re   r�   rÂ   r­   r   Zrnn_tanh_cellr»   r¼   r¾   r¿   Zrnn_relu_cellry   r.   )r=   rv   r€   rn   r   r   r   r™   l  s*    

ý
ý
ÿzRNNCell.forward)Tr®   )N)r¥   r¦   r§   r³   r¨   r¡   r©   r|   rF   rA   r   r   r™   r«   r   r   rY   r   rÃ   ,  s
   
8rÃ   c                       sV   e Zd ZdZd
eeeddœ‡ fdd„Zdeee	eef  e	eef dœdd	„Z
‡  ZS )ÚLSTMCellaH	  A long short-term memory (LSTM) cell.

    .. math::

        \begin{array}{ll}
        i = \sigma(W_{ii} x + b_{ii} + W_{hi} h + b_{hi}) \\
        f = \sigma(W_{if} x + b_{if} + W_{hf} h + b_{hf}) \\
        g = \tanh(W_{ig} x + b_{ig} + W_{hg} h + b_{hg}) \\
        o = \sigma(W_{io} x + b_{io} + W_{ho} h + b_{ho}) \\
        c' = f * c + i * g \\
        h' = o * \tanh(c') \\
        \end{array}

    where :math:`\sigma` is the sigmoid function, and :math:`*` is the Hadamard product.

    Args:
        input_size: The number of expected features in the input `x`
        hidden_size: The number of features in the hidden state `h`
        bias: If ``False``, then the layer does not use bias weights `b_ih` and
            `b_hh`. Default: ``True``

    Inputs: input, (h_0, c_0)
        - **input** of shape `(batch, input_size)`: tensor containing input features
        - **h_0** of shape `(batch, hidden_size)`: tensor containing the initial hidden
          state for each element in the batch.
        - **c_0** of shape `(batch, hidden_size)`: tensor containing the initial cell state
          for each element in the batch.

          If `(h_0, c_0)` is not provided, both **h_0** and **c_0** default to zero.

    Outputs: (h_1, c_1)
        - **h_1** of shape `(batch, hidden_size)`: tensor containing the next hidden state
          for each element in the batch
        - **c_1** of shape `(batch, hidden_size)`: tensor containing the next cell state
          for each element in the batch

    Attributes:
        weight_ih: the learnable input-hidden weights, of shape
            `(4*hidden_size, input_size)`
        weight_hh: the learnable hidden-hidden weights, of shape
            `(4*hidden_size, hidden_size)`
        bias_ih: the learnable input-hidden bias, of shape `(4*hidden_size)`
        bias_hh: the learnable hidden-hidden bias, of shape `(4*hidden_size)`

    .. note::
        All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
        where :math:`k = \frac{1}{\text{hidden\_size}}`

    Examples::

        >>> rnn = nn.LSTMCell(10, 20)
        >>> input = torch.randn(3, 10)
        >>> hx = torch.randn(3, 20)
        >>> cx = torch.randn(3, 20)
        >>> output = []
        >>> for i in range(6):
                hx, cx = rnn(input[i], (hx, cx))
                output.append(hx)
    TN©r   r   r   r   c                    s   t t| ƒj|||dd� d S )Nr%   rÄ   )r@   rÅ   rA   ©r=   r   r   r   rY   r   r   rA   Á  s    zLSTMCell.__init__rŒ   c                 C   sx   |   |¡ |d u r8tj| d¡| j|j|jd�}||f}|  ||d d¡ |  ||d d¡ t 	||| j
| j| j| j¡S )Nr   rŽ   z[0]r   z[1])rÀ   rM   r�   rz   r   re   r�   rÂ   r   Z	lstm_cellr»   r¼   r¾   r¿   )r=   rv   r€   r�   r   r   r   r™   Ä  s    
ýzLSTMCell.forward)T)N)r¥   r¦   r§   r³   r|   rF   rA   r   r   r   r™   r«   r   r   rY   r   rÅ   „  s   <rÅ   c                       sF   e Zd ZdZd
eeeddœ‡ fdd„Zdeee edœdd	„Z	‡  Z
S )ÚGRUCellaP	  A gated recurrent unit (GRU) cell

    .. math::

        \begin{array}{ll}
        r = \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\
        z = \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\
        n = \tanh(W_{in} x + b_{in} + r * (W_{hn} h + b_{hn})) \\
        h' = (1 - z) * n + z * h
        \end{array}

    where :math:`\sigma` is the sigmoid function, and :math:`*` is the Hadamard product.

    Args:
        input_size: The number of expected features in the input `x`
        hidden_size: The number of features in the hidden state `h`
        bias: If ``False``, then the layer does not use bias weights `b_ih` and
            `b_hh`. Default: ``True``

    Inputs: input, hidden
        - **input** of shape `(batch, input_size)`: tensor containing input features
        - **hidden** of shape `(batch, hidden_size)`: tensor containing the initial hidden
          state for each element in the batch.
          Defaults to zero if not provided.

    Outputs: h'
        - **h'** of shape `(batch, hidden_size)`: tensor containing the next hidden state
          for each element in the batch

    Shape:
        - Input1: :math:`(N, H_{in})` tensor containing input features where
          :math:`H_{in}` = `input_size`
        - Input2: :math:`(N, H_{out})` tensor containing the initial hidden
          state for each element in the batch where :math:`H_{out}` = `hidden_size`
          Defaults to zero if not provided.
        - Output: :math:`(N, H_{out})` tensor containing the next hidden state
          for each element in the batch

    Attributes:
        weight_ih: the learnable input-hidden weights, of shape
            `(3*hidden_size, input_size)`
        weight_hh: the learnable hidden-hidden weights, of shape
            `(3*hidden_size, hidden_size)`
        bias_ih: the learnable input-hidden bias, of shape `(3*hidden_size)`
        bias_hh: the learnable hidden-hidden bias, of shape `(3*hidden_size)`

    .. note::
        All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
        where :math:`k = \frac{1}{\text{hidden\_size}}`

    Examples::

        >>> rnn = nn.GRUCell(10, 20)
        >>> input = torch.randn(6, 3, 10)
        >>> hx = torch.randn(3, 20)
        >>> output = []
        >>> for i in range(6):
                hx = rnn(input[i], hx)
                output.append(hx)
    TNrÆ   c                    s   t t| ƒj|||dd� d S )Nr   rÄ   )r@   rÈ   rA   rÇ   rY   r   r   rA     s    zGRUCell.__init__rŒ   c                 C   sZ   |   |¡ |d u r0tj| d¡| j|j|jd�}|  ||d¡ t 	||| j
| j| j| j¡S )Nr   rŽ   r(   )rÀ   rM   r�   rz   r   re   r�   rÂ   r   Zgru_cellr»   r¼   r¾   r¿   rµ   r   r   r   r™     s    
ýzGRUCell.forward)T)N)r¥   r¦   r§   r³   r|   rF   rA   r   r   r™   r«   r   r   rY   r   rÈ   Ò  s   =rÈ   )r   ) rq   rH   rD   Útypingr   r   r   r   rM   r   Úmoduler   Z	parameterr
   Z	utils.rnnr   r(   r   r   Zrnn_tanhZrnn_relur‘   r|   r   r   r¬   r$   r&   rº   rÃ   rÅ   rÈ   r   r   r   r   Ú<module>   s4   þ  z 2  9XN