a
    8SicR                     @   s  d dl 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 d dl	m
Z
mZmZmZ edg d	Zejejeej eej d	e_d
d ZG dd deZd+eee ee ee eeeee ee f dddZd,eee ee ee edddZee ee dddZd-eeeeedddZd.eeeee eeef dddZd/eee
e f eeedd d!Zd0eeee
e d"d#d$Zd1e
e eed%d&d'Zee
e d(d)d*ZdS )2    )
namedtupleN)Tensor   )_VF)Optional)ListTupleUnionIterablePackedSequence_databatch_sizessorted_indicesunsorted_indicesc                 C   s   | d u rd S || S N )optionalfnr   r   N/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/nn/utils/rnn.pybind   s    r   c                       s   e Zd ZdZd! fdd	Zdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zedd Zdd  Z  ZS )"PackedSequenceaq  Holds the data and list of :attr:`batch_sizes` of a packed sequence.

    All RNN modules accept packed sequences as inputs.

    Note:
        Instances of this class should never be created manually. They are meant
        to be instantiated by functions like :func:`pack_padded_sequence`.

        Batch sizes represent the number elements at each sequence step in
        the batch, not the varying sequence lengths passed to
        :func:`pack_padded_sequence`.  For instance, given data ``abc`` and ``x``
        the :class:`PackedSequence` would contain data ``axbc`` with
        ``batch_sizes=[2,1,1]``.

    Attributes:
        data (Tensor): Tensor containing packed sequence
        batch_sizes (Tensor): Tensor of integers holding
            information about the batch size at each sequence step
        sorted_indices (Tensor, optional): Tensor of integers holding how this
            :class:`PackedSequence` is constructed from sequences.
        unsorted_indices (Tensor, optional): Tensor of integers holding how this
            to recover the original sequences with correct order.

    .. note::
        :attr:`data` can be on arbitrary device and of arbitrary dtype.
        :attr:`sorted_indices` and :attr:`unsorted_indices` must be ``torch.int64``
        tensors on the same device as :attr:`data`.

        However, :attr:`batch_sizes` should always be a CPU ``torch.int64`` tensor.

        This invariant is maintained throughout :class:`PackedSequence` class,
        and all functions that construct a `:class:PackedSequence` in PyTorch
        (i.e., they only pass in tensors conforming to this constraint).

    Nc                    s"   t t| j| gt||||R  S r   )superr   __new___packed_sequence_init_args)clsr   r   r   r   	__class__r   r   r   ?   s    
zPackedSequence.__new__c                 C   s2   t | | j | jt| jdd t| jdd S )Nc                 S   s   |   S r   
pin_memorytr   r   r   <lambda>M       z+PackedSequence.pin_memory.<locals>.<lambda>c                 S   s   |   S r   r   r    r   r   r   r"   N   r#   )typer   r   r   r   r   r   selfr   r   r   r   I   s    zPackedSequence.pin_memoryc                 O   sN   t jd| jj| jjdj|i |}|jr:| j|i |S | j|ddi|S )Nr   dtypedevicer)   cuda)torchtensorr   r(   r)   tois_cudar&   argskwargsexr   r   r   r*   P   s    $zPackedSequence.cudac                 O   sT   t jd| jj| jjdj|i |}|jjdkr@| j|i |S | j|ddi|S )Nr   r'   cpur)   )r+   r,   r   r(   r)   r-   r$   r/   r   r   r   r3   W   s    $zPackedSequence.cpuc                 C   s   | j tjdS Nr(   )r-   r+   doubler%   r   r   r   r6   ^   s    zPackedSequence.doublec                 C   s   | j tjdS r4   )r-   r+   floatr%   r   r   r   r7   a   s    zPackedSequence.floatc                 C   s   | j tjdS r4   )r-   r+   halfr%   r   r   r   r8   d   s    zPackedSequence.halfc                 C   s   | j tjdS r4   )r-   r+   longr%   r   r   r   r9   g   s    zPackedSequence.longc                 C   s   | j tjdS r4   )r-   r+   intr%   r   r   r   r:   j   s    zPackedSequence.intc                 C   s   | j tjdS r4   )r-   r+   shortr%   r   r   r   r;   m   s    zPackedSequence.shortc                 C   s   | j tjdS r4   )r-   r+   int8r%   r   r   r   charp   s    zPackedSequence.charc                 C   s   | j tjdS r4   )r-   r+   uint8r%   r   r   r   bytes   s    zPackedSequence.bytec                    s   | j j|i   | j u r | S dd tdd  D t| j fdd}t| j fdd}t|  | j||S dS )a  Performs dtype and/or device conversion on `self.data`.

        It has similar signature as :meth:`torch.Tensor.to`, except optional
        arguments like `non_blocking` and `copy` should be passed as kwargs,
        not args, or they will not apply to the index tensors.

        .. note::

            If the ``self.data`` Tensor already has the correct :class:`torch.dtype`
            and :class:`torch.device`, then ``self`` is returned.
            Otherwise, returns a copy with the desired configuration.
        c                 S   s   i | ]\}}||qS r   r   ).0kvr   r   r   
<dictcomp>   r#   z%PackedSequence.to.<locals>.<dictcomp>c                 S   s   | d dko| d dkS )Nr   r)   r(   r   r    r   r   r   r"      r#   z#PackedSequence.to.<locals>.<lambda>c                    s   | j  jfi S r   r-   r)   r    r   r1   r   r   r"      r#   c                    s   | j  jfi S r   rD   r    rE   r   r   r"      r#   N)	r   r-   filteritemsr   r   r   r$   r   )r&   r0   r1   r   r   r   rE   r   r-   v   s    
zPackedSequence.toc                 C   s   | j jS )z+Returns true if `self.data` stored on a gpu)r   r.   r%   r   r   r   r.      s    zPackedSequence.is_cudac                 C   s
   | j  S )z6Returns true if `self.data` stored on in pinned memory)r   	is_pinnedr%   r   r   r   rH      s    zPackedSequence.is_pinned)NNN)__name__
__module____qualname____doc__r   r   r*   r3   r6   r7   r8   r9   r:   r;   r=   r?   r-   propertyr.   rH   __classcell__r   r   r   r   r      s"   #

r   )r   r   r   r   returnc                 C   sn   |d u rt |}|d ur8|jjdkr,td| |||fS t| ttfrRt| dksVJ | d | d ||fS d S )Nr3   a  batch_sizes should always be on CPU. Instances of PackedSequence should never be created manually. They should be instantiated by functions like pack_sequence and pack_padded_sequences in nn.utils.rnn. https://pytorch.org/docs/stable/nn.html#torch.nn.utils.rnn.pack_sequence   r      )invert_permutationr)   r$   
ValueError
isinstancelisttuplelenr   r   r   r   r      s    
r   c                 C   s$   t | |||\} }}}t| |||S r   )r   r   r   r   r   r   _packed_sequence_init   s    rX   )permutationrO   c              	   C   s@   | d u rd S t j| t jd}|d| t jd|  | jd |S )N)memory_formatr   )r)   )r+   
empty_likelegacy_contiguous_formatscatter_arangenumelr)   )rY   outputr   r   r   rR      s    rR   FT)inputlengthsbatch_firstenforce_sortedrO   c                 C   s   t j r$t|t js$tjddd t j|t jd}|r>d}n6t j	|dd\}}|
| j}|rddnd	}| ||} t| ||\}}t|||dS )
aS  Packs a Tensor containing padded sequences of variable length.

    :attr:`input` can be of size ``T x B x *`` where `T` is the length of the
    longest sequence (equal to ``lengths[0]``), ``B`` is the batch size, and
    ``*`` is any number of dimensions (including 0). If ``batch_first`` is
    ``True``, ``B x T x *`` :attr:`input` is expected.

    For unsorted sequences, use `enforce_sorted = False`. If :attr:`enforce_sorted` is
    ``True``, the sequences should be sorted by length in a decreasing order, i.e.
    ``input[:,0]`` should be the longest sequence, and ``input[:,B-1]`` the shortest
    one. `enforce_sorted = True` is only necessary for ONNX export.

    Note:
        This function accepts any input that has at least two dimensions. You
        can apply it to pack the labels, and use the output of the RNN with
        them to compute the loss directly. A Tensor can be retrieved from
        a :class:`PackedSequence` object by accessing its ``.data`` attribute.

    Args:
        input (Tensor): padded batch of variable length sequences.
        lengths (Tensor or list(int)): list of sequence lengths of each batch
            element (must be on the CPU if provided as a tensor).
        batch_first (bool, optional): if ``True``, the input is expected in ``B x T x *``
            format.
        enforce_sorted (bool, optional): if ``True``, the input is expected to
            contain sequences sorted by length in a decreasing order. If
            ``False``, the input will get sorted unconditionally. Default: ``True``.

    Returns:
        a :class:`PackedSequence` object
    zpack_padded_sequence has been called with a Python list of sequence lengths. The tracer cannot track the data flow of Python values, and it will treat them as constants, likely rendering the trace incorrect for any other combination of lengths.rP   )
stacklevelr5   NT)
descendingr   rQ   )r+   _C_get_tracing_staterT   r   warningswarn	as_tensorint64sortr-   r)   index_selectr   Z_pack_padded_sequencerX   )ra   rb   rc   rd   r   	batch_dimr   r   r   r   r   pack_padded_sequence   s    %rp           )sequencerc   padding_valuetotal_lengthrO   c           	      C   s   | j d}|dur0||k r,td|||}t| j| j |||\}}| j}|durx|r`dnd}||||| fS ||fS )a  Pads a packed batch of variable length sequences.

    It is an inverse operation to :func:`pack_padded_sequence`.

    The returned Tensor's data will be of size ``T x B x *``, where `T` is the length
    of the longest sequence and `B` is the batch size. If ``batch_first`` is True,
    the data will be transposed into ``B x T x *`` format.

    Example:
        >>> from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
        >>> seq = torch.tensor([[1,2,0], [3,0,0], [4,5,6]])
        >>> lens = [2, 1, 3]
        >>> packed = pack_padded_sequence(seq, lens, batch_first=True, enforce_sorted=False)
        >>> packed
        PackedSequence(data=tensor([4, 1, 3, 5, 2, 6]), batch_sizes=tensor([3, 2, 1]),
                       sorted_indices=tensor([2, 0, 1]), unsorted_indices=tensor([1, 2, 0]))
        >>> seq_unpacked, lens_unpacked = pad_packed_sequence(packed, batch_first=True)
        >>> seq_unpacked
        tensor([[1, 2, 0],
                [3, 0, 0],
                [4, 5, 6]])
        >>> lens_unpacked
        tensor([2, 1, 3])

    .. note::
        :attr:`total_length` is useful to implement the
        ``pack sequence -> recurrent network -> unpack sequence`` pattern in a
        :class:`~torch.nn.Module` wrapped in :class:`~torch.nn.DataParallel`.
        See :ref:`this FAQ section <pack-rnn-unpack-with-data-parallelism>` for
        details.

    Args:
        sequence (PackedSequence): batch to pad
        batch_first (bool, optional): if ``True``, the output will be in ``B x T x *``
            format.
        padding_value (float, optional): values for padded elements.
        total_length (int, optional): if not ``None``, the output will be padded to
            have length :attr:`total_length`. This method will throw :class:`ValueError`
            if :attr:`total_length` is less than the max sequence length in
            :attr:`sequence`.

    Returns:
        Tuple of Tensor containing the padded sequence, and a Tensor
        containing the list of lengths of each sequence in the batch.
        Batch elements will be re-ordered as they were ordered originally when
        the batch was passed to ``pack_padded_sequence`` or ``pack_sequence``.




    r   NzExpected total_length to be at least the length of the longest sequence in input, but got total_length={} and max sequence length being {}rQ   )	r   sizerS   formatr   Z_pad_packed_sequencer   r   rn   )	rr   rc   rs   rt   Zmax_seq_lengthZpadded_outputrb   r   ro   r   r   r   pad_packed_sequence  s    9rw   )	sequencesrc   rs   rO   c                 C   sf   t j s>t j s>t| ts4dt|  }t|t| } nt| t j	rT| 
d} t jj| ||S )a  Pad a list of variable length Tensors with ``padding_value``

    ``pad_sequence`` stacks a list of Tensors along a new dimension,
    and pads them to equal length. For example, if the input is list of
    sequences with size ``L x *`` and if batch_first is False, and ``T x B x *``
    otherwise.

    `B` is batch size. It is equal to the number of elements in ``sequences``.
    `T` is length of the longest sequence.
    `L` is length of the sequence.
    `*` is any number of trailing dimensions, including none.

    Example:
        >>> from torch.nn.utils.rnn import pad_sequence
        >>> a = torch.ones(25, 300)
        >>> b = torch.ones(22, 300)
        >>> c = torch.ones(15, 300)
        >>> pad_sequence([a, b, c]).size()
        torch.Size([25, 3, 300])

    Note:
        This function returns a Tensor of size ``T x B x *`` or ``B x T x *``
        where `T` is the length of the longest sequence. This function assumes
        trailing dimensions and type of all the Tensors in sequences are same.

    Args:
        sequences (list[Tensor]): list of variable length sequences.
        batch_first (bool, optional): output will be in ``B x T x *`` if True, or in
            ``T x B x *`` otherwise. Default: False.
        padding_value (float, optional): value for padded elements. Default: 0.

    Returns:
        Tensor of size ``T x B x *`` if :attr:`batch_first` is ``False``.
        Tensor of size ``B x T x *`` otherwise
    zJpad_sequence: Expected iterable for input sequences, but got arg of type: r   )r+   jit
is_tracingis_scriptingrT   r
   r$   RuntimeErrorrV   r   unbindrg   _nnpad_sequence)rx   rc   rs   msgr   r   r   r   R  s    )


r   )padded_sequencesrb   rc   rO   c           
      C   sZ   g }|s|  dd | jd }t|}t| |D ]"\}}||k }|| }	||	 q2|S )a@  Unpad padded Tensor into a list of variable length Tensors

    ``unpad_sequence`` unstacks padded Tensor into a list of variable length Tensors.

    Example:
        >>> from torch.nn.utils.rnn import pad_sequence, unpad_sequence
        >>> a = torch.ones(25, 300)
        >>> b = torch.ones(22, 300)
        >>> c = torch.ones(15, 300)
        >>> sequences = [a, b, c]
        >>> padded_sequences = pad_sequence(sequences)
        >>> lengths = torch.as_tensor([v.size(0) for v in sequences])
        >>> unpadded_sequences = unpad_sequence(padded_sequences, lengths)
        >>> torch.allclose(sequences[0], unpadded_sequences[0])
        True
        >>> torch.allclose(sequences[1], unpadded_sequences[1])
        True
        >>> torch.allclose(sequences[2], unpadded_sequences[2])
        True

    Args:
        padded_sequences (Tensor): padded sequences.
        lengths (Tensor): length of original (unpadded) sequences.
        batch_first (bool, optional): whether batch dimension first or not. Default: False.

    Returns:
        a list of :class:`Tensor` objects
    r   rQ   )
transpose_shaper+   r^   zipappend)
r   rb   rc   Zunpadded_sequences
max_lengthidxseqlengthmaskZunpacked_seqr   r   r   unpad_sequence  s    "

r   )rx   rd   rO   c                 C   s&   t dd | D }tt| ||dS )a  Packs a list of variable length Tensors

    Consecutive call of the next functions: ``pad_sequence``, ``pack_padded_sequence``.

    ``sequences`` should be a list of Tensors of size ``L x *``, where `L` is
    the length of a sequence and `*` is any number of trailing dimensions,
    including zero.

    For unsorted sequences, use `enforce_sorted = False`. If ``enforce_sorted``
    is ``True``, the sequences should be sorted in the order of decreasing length.
    ``enforce_sorted = True`` is only necessary for ONNX export.


    Example:
        >>> from torch.nn.utils.rnn import pack_sequence
        >>> a = torch.tensor([1,2,3])
        >>> b = torch.tensor([4,5])
        >>> c = torch.tensor([6])
        >>> pack_sequence([a, b, c])
        PackedSequence(data=tensor([ 1,  4,  6,  2,  5,  3]), batch_sizes=tensor([ 3,  2,  1]))


    Args:
        sequences (list[Tensor]): A list of sequences of decreasing length.
        enforce_sorted (bool, optional): if ``True``, checks that the input
            contains sequences sorted by length in a decreasing order. If
            ``False``, this condition is not checked. Default: ``True``.

    Returns:
        a :class:`PackedSequence` object
    c                 S   s   g | ]}| d qS )r   )ru   )r@   rB   r   r   r   
<listcomp>  r#   z!pack_sequence.<locals>.<listcomp>)rd   )r+   rk   rp   r   )rx   rd   rb   r   r   r   pack_sequence  s     r   )packed_sequencesrO   c                 C   s"   t | dd\}}t||dd}|S )aG  Unpacks PackedSequence into a list of variable length Tensors

    ``packed_sequences`` should be a PackedSequence object.


    Example:
        >>> from torch.nn.utils.rnn import pack_sequence, unpack_sequence
        >>> a = torch.tensor([1,2,3])
        >>> b = torch.tensor([4,5])
        >>> c = torch.tensor([6])
        >>> sequences = [a, b, c]
        [tensor([ 1,  2,  3]), tensor([ 4,  5]), tensor([ 6])]
        >>> packed_sequences = pack_sequence(sequences)
        PackedSequence(data=tensor([ 1,  4,  6,  2,  5,  3]), batch_sizes=tensor([ 3,  2,  1]))
        >>> unpacked_sequences = unpack_sequence(packed_sequences)
        [tensor([ 1,  2,  3]), tensor([ 4,  5]), tensor([ 6])]


    Args:
        packed_sequences (PackedSequence): A PackedSequence object.

    Returns:
        a list of :class:`Tensor` objects
    T)rc   )rw   r   )r   r   rb   Zunpacked_sequencesr   r   r   unpack_sequence  s    r   )NNN)NNN)FT)Frq   N)Frq   )F)T)collectionsr   ri   r+   r    r   _jit_internalr   typingr   r   r	   r
   r   __annotations__r   r   r   rX   rR   boolrp   r7   r:   rw   r   r   r   r   r   r   r   r   <module>   s       !     ;   
L  @ 2$