o
    hZ                     @   s<  d dl Z d dlmZ d dlmZmZmZmZmZm	Z	m
Z
 d dlmZ d dlZd dlmZmZ g dZe	dZe	dZG d	d
 d
eZdee deegef dee fddZG dd deZ			d8dedee dee dee deeeee ee f f
ddZ			d8dedee dee dee def
ddZdee dee fddZ		d9ded e
eee f d!ed"edef
d#d$Z		%	d:d&ed!ed'ed(ee deeef f
d)d*Z		%	+d;d,e
eee f d!ed'ed-e def
d.d/Z!	d<d0ed ed!edee fd1d2Z"	d=d,ee d"edefd3d4Z#d5edee fd6d7Z$dS )>    N)Iterable)AnyCallable
NamedTupleOptionaloverloadTypeVarUnion)Self)_VFTensor)PackedSequenceinvert_permutationpack_padded_sequencepad_packed_sequencepad_sequenceunpad_sequencepack_sequenceunpack_sequence_T_Rc                   @   s>   e Zd ZU ejed< ejed< eej ed< eej ed< dS )PackedSequence_databatch_sizessorted_indicesunsorted_indicesN)__name__
__module____qualname__torchr   __annotations__r    r!   r!   f/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/nn/utils/rnn.pyr      s
   
 

r   optionalfnreturnc                 C   s   | d u rd S || S Nr!   )r#   r$   r!   r!   r"   bind    s   r'   c                       s  e Zd ZdZ			d1dedee dee dee def
 fdd	Zdefd
dZe			d2de
jdededefddZe					d3deeee
jef  dee
j dededef
ddZe			d2dedededefddZdededefddZdededefddZdededefddZdefddZdefdd Zdefd!d"Zdefd#d$Zdefd%d&Zdefd'd(Zdefd)d*Zdefd+d,Zedefd-d.Zdefd/d0Z  ZS )4r   ap  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).
    Nr   r   r   r   r%   c                    s   t  j| gt||||R  S r&   )super__new___packed_sequence_init_args)clsr   r   r   r   	__class__r!   r"   r)   J   s   zPackedSequence.__new__c                 C   s2   t | | j | jt| jdd t| jdd S )Nc                 S      |   S r&   
pin_memorytr!   r!   r"   <lambda>b       z+PackedSequence.pin_memory.<locals>.<lambda>c                 S   r.   r&   r/   r1   r!   r!   r"   r3   c   r4   )typer   r0   r   r'   r   r   selfr!   r!   r"   r0   \   s   zPackedSequence.pin_memory.dtypenon_blockingcopyc                 C      d S r&   r!   )r7   r8   r9   r:   r!   r!   r"   tof      zPackedSequence.todevicec                 C   r;   r&   r!   )r7   r>   r8   r9   r:   r!   r!   r"   r<   o   s   otherc                 C   r;   r&   r!   )r7   r?   r9   r:   r!   r!   r"   r<   y   r=   argskwargsc                    sv   | j j|i   | j u r| S ttdd  t| j fdd}t| j fdd}t|  | j	||S )a
  Perform 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   | d dko| d dkS )Nr   r>   r8   r!   r1   r!   r!   r"   r3      s    z#PackedSequence.to.<locals>.<lambda>c                       | j  jfi S r&   r<   r>   r1   r   rA   r!   r"   r3          c                    rB   r&   rC   r1   rD   r!   r"   r3      rE   )
r   r<   dictfilteritemsr'   r   r   r5   r   )r7   r@   rA   r   r   r!   rD   r"   r<      s   
c                 O   sR   t jd| jj| jjdj|i |}|jr| j|i |S d|d< | j|i |S )Nr!   r8   r>   cudar>   )r   tensorr   r8   r>   r<   is_cudar7   r@   rA   exr!   r!   r"   rJ      s   zPackedSequence.cudac                 O   sX   t jd| jj| jjdj|i |}|jjdkr | j|i |S d|d< | j|i |S )Nr!   rI   cpur>   )r   rK   r   r8   r>   r<   r5   rM   r!   r!   r"   rO      s   zPackedSequence.cpuc                 C      | j tjdS Nr8   )r<   r   doubler6   r!   r!   r"   rS         zPackedSequence.doublec                 C   rP   rQ   )r<   r   floatr6   r!   r!   r"   rU      rT   zPackedSequence.floatc                 C   rP   rQ   )r<   r   halfr6   r!   r!   r"   rV      rT   zPackedSequence.halfc                 C   rP   rQ   )r<   r   longr6   r!   r!   r"   rW      rT   zPackedSequence.longc                 C   rP   rQ   )r<   r   intr6   r!   r!   r"   rX      rT   zPackedSequence.intc                 C   rP   rQ   )r<   r   shortr6   r!   r!   r"   rY      rT   zPackedSequence.shortc                 C   rP   rQ   )r<   r   int8r6   r!   r!   r"   char   rT   zPackedSequence.charc                 C   rP   rQ   )r<   r   uint8r6   r!   r!   r"   byte   rT   zPackedSequence.bytec                 C   s   | j jS )z+Return true if `self.data` stored on a gpu.)r   rL   r6   r!   r!   r"   rL      s   zPackedSequence.is_cudac                 C   s
   | j  S )z6Return true if `self.data` stored on in pinned memory.)r   	is_pinnedr6   r!   r!   r"   r^      s   
zPackedSequence.is_pinnedNNN)..)....) r   r   r   __doc__r   r   r
   r)   r0   r   r   r8   boolr<   r	   strr>   rX   r   rJ   rO   rS   rU   rV   rW   rY   r[   r]   propertyrL   r^   __classcell__r!   r!   r,   r"   r   &   s    &
	
	r   r   r   r   r   c                 C   sj   |d u rt |}|d ur|jjdkrtd| |||fS t| ttfr)t| dks+J | d | d ||fS )NrO   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      )r   r>   r5   
ValueError
isinstancelisttuplelenr   r   r   r   r!   r!   r"   r*      s   
r*   c                 C   s$   t | |||\} }}}t| |||S r&   )r*   r   rl   r!   r!   r"   _packed_sequence_init   s   rm   permutationc              	   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>   )rn   outputr!   r!   r"   r     s   r   FTinputlengthsbatch_firstenforce_sortedc                 C   s   t |tjstj rtjddd tj|tjdd}n|j	tjd}|r(d}ntj
|dd	\}}|	| j}|r;d
nd}| ||} t| ||\}}t|||dS )a  Packs a Tensor containing padded sequences of variable length.

    :attr:`input` can be of size ``T x B x *`` (if :attr:`batch_first` is ``False``)
    or ``B x T x *`` (if :attr:`batch_first` is ``True``) where ``T`` is the length
    of the longest sequence, ``B`` is the batch size, and ``*`` is any number of dimensions
    (including 0).

    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.

    It is an inverse operation to :func:`pad_packed_sequence`, and hence :func:`pad_packed_sequence`
    can be used to recover the underlying tensor packed in :class:`PackedSequence`.

    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, ``T x B x *`` otherwise. Default: ``False``.
        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``.

    .. warning::
        The dim of ``input`` tensor will be truncated if its length larger than
        correspond value in ``length``.

    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.re   )
stacklevelrO   rI   rR   NT)
descendingr   rf   )rh   r   r   _C_get_tracing_statewarningswarn	as_tensorint64r<   sortr>   index_selectr   _pack_padded_sequencerm   )rw   rx   ry   rz   r   	batch_dimr   r   r!   r!   r"   r     s    ,
r           sequencepadding_valuetotal_lengthc           	      C   s   | j d}|dur||k rtd| d| |}t| j| j |||\}}| j}|dur@|r2dnd}|||||  fS ||fS )a  Pad 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 *`` (if :attr:`batch_first` is ``False``)
    or ``B x T x *`` (if :attr:`batch_first` is ``True``) , where ``T`` is the length of the longest
    sequence and ``B`` is the batch size.

    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, ``T x B x *`` otherwise.
        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   NzgExpected total_length to be at least the length of the longest sequence in input, but got total_length=z and max sequence length being rf   )	r   sizerg   r   _pad_packed_sequencer   r   r   rO   )	r   ry   r   r   max_seq_lengthpadded_outputrx   r   r   r!   r!   r"   r   S  s*   5

r   right	sequencespadding_sidec                 C   sh   t j st j st| tsdt|  }t|t| } nt| t j	r*| 
d} t jj| |||S )aO  Pad a list of variable length Tensors with :attr:`padding_value`.

    ``pad_sequence`` stacks a list of Tensors along a new dimension, and pads them
    to equal length. :attr:`sequences` can be list of sequences with size ``L x *``,
    where `L` is length of the sequence and ``*`` is any number of dimensions
    (including ``0``). If :attr:`batch_first` is ``False``, the output is of size
    ``T x B x *``, and ``B x T x *`` otherwise, where ``B`` is the batch size
    (the number of elements in :attr:`sequences`), ``T`` is the length of the longest
    sequence.

    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): if ``True``, the output will be in ``B x T x *``
            format, ``T x B x *`` otherwise.
        padding_value (float, optional): value for padded elements. Default: ``0``.
        padding_side (str, optional): the side to pad the sequences on.
            Default: ``'right'``.

    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_scriptingrh   r   r5   RuntimeErrorrj   r   unbindr}   _nnr   )r   ry   r   r   msgr!   r!   r"   r     s   )


r   padded_sequencesc           
      C   s`   g }|s
|  dd | jd }tj||jd}t| |D ]\}}||k }|| }	||	 q|S )aE  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   rf   rp   )
transpose_shaper   rt   r>   zipappend)
r   rx   ry   unpadded_sequences
max_lengthidxseqlengthmaskunpacked_seqr!   r!   r"   r     s   !
r   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 ``0``.

    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]), sorted_indices=None, unsorted_indices=None)

    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   )r   ).0vr!   r!   r"   
<listcomp>2  s    z!pack_sequence.<locals>.<listcomp>)rz   )r   r   r   r   )r   rz   rx   r!   r!   r"   r     s   !
r   packed_sequencesc                 C   s"   t | dd\}}t||dd}|S )a  Unpack 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]
        >>> print(sequences)
        [tensor([1, 2, 3]), tensor([4, 5]), tensor([6])]
        >>> packed_sequences = pack_sequence(sequences)
        >>> print(packed_sequences)
        PackedSequence(data=tensor([1, 4, 6, 2, 5, 3]), batch_sizes=tensor([3, 2, 1]), sorted_indices=None, unsorted_indices=None)
        >>> unpacked_sequences = unpack_sequence(packed_sequences)
        >>> print(unpacked_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)ry   )r   r   )r   r   rx   unpacked_sequencesr!   r!   r"   r   8  s   r   r_   )FT)Fr   N)Fr   r   )F)T)%r   collections.abcr   typingr   r   r   r   r   r   r	   typing_extensionsr
   r   r   r   __all__r   r   r   r'   r   rj   r*   rm   r   ri   rX   ra   r   rU   r   rb   r   r   r   r   r!   r!   r!   r"   <module>   s    $( 5
"

G

N
D
3
'