a
    ßñhšE  ã                   @   st   d dl 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 G d
d„ deƒZG dd„ deƒZdS )é    )ÚOptionalN)ÚTensor)Ú	Parameteré   )ÚModuleé   )Ú
functional)Úinitc                       sÈ   e Zd ZU dZg d¢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
< deee
e e
e eeee
e	 ddœ	‡ fdd„Zddœdd„Ze	e	dœdd„Zedœdd„Zeddd„ƒZ‡  ZS )Ú	EmbeddingaF  A simple lookup table that stores embeddings of a fixed dictionary and size.

    This module is often used to store word embeddings and retrieve them using indices.
    The input to the module is a list of indices, and the output is the corresponding
    word embeddings.

    Args:
        num_embeddings (int): size of the dictionary of embeddings
        embedding_dim (int): the size of each embedding vector
        padding_idx (int, optional): If given, pads the output with the embedding vector at :attr:`padding_idx`
                                         (initialized to zeros) whenever it encounters the index.
        max_norm (float, optional): If given, each embedding vector with norm larger than :attr:`max_norm`
                                    is renormalized to have norm :attr:`max_norm`.
        norm_type (float, optional): The p of the p-norm to compute for the :attr:`max_norm` option. Default ``2``.
        scale_grad_by_freq (boolean, optional): If given, this will scale gradients by the inverse of frequency of
                                                the words in the mini-batch. Default ``False``.
        sparse (bool, optional): If ``True``, gradient w.r.t. :attr:`weight` matrix will be a sparse tensor.
                                 See Notes for more details regarding sparse gradients.

    Attributes:
        weight (Tensor): the learnable weights of the module of shape (num_embeddings, embedding_dim)
                         initialized from :math:`\mathcal{N}(0, 1)`

    Shape:
        - Input: :math:`(*)`, LongTensor of arbitrary shape containing the indices to extract
        - Output: :math:`(*, H)`, where `*` is the input shape and :math:`H=\text{embedding\_dim}`

    .. note::
        Keep in mind that only a limited number of optimizers support
        sparse gradients: currently it's :class:`optim.SGD` (`CUDA` and `CPU`),
        :class:`optim.SparseAdam` (`CUDA` and `CPU`) and :class:`optim.Adagrad` (`CPU`)

    .. note::
        With :attr:`padding_idx` set, the embedding vector at
        :attr:`padding_idx` is initialized to all zeros. However, note that this
        vector can be modified afterwards, e.g., using a customized
        initialization method, and thus changing the vector used to pad the
        output. The gradient for this vector from :class:`~torch.nn.Embedding`
        is always zero.

    Examples::

        >>> # an Embedding module containing 10 tensors of size 3
        >>> embedding = nn.Embedding(10, 3)
        >>> # a batch of 2 samples of 4 indices each
        >>> input = torch.LongTensor([[1,2,4,5],[4,3,2,9]])
        >>> embedding(input)
        tensor([[[-0.0251, -1.6902,  0.7172],
                 [-0.6431,  0.0748,  0.6969],
                 [ 1.4970,  1.3448, -0.9685],
                 [-0.3677, -2.7265, -0.1685]],

                [[ 1.4970,  1.3448, -0.9685],
                 [ 0.4362, -0.4004,  0.9400],
                 [-0.6431,  0.0748,  0.6969],
                 [ 0.9124, -2.3616,  1.1151]]])


        >>> # example with padding_idx
        >>> embedding = nn.Embedding(10, 3, padding_idx=0)
        >>> input = torch.LongTensor([[0,2,0,5]])
        >>> embedding(input)
        tensor([[[ 0.0000,  0.0000,  0.0000],
                 [ 0.1535, -2.0309,  0.9315],
                 [ 0.0000,  0.0000,  0.0000],
                 [-0.1655,  0.9897,  0.0635]]])
    )Únum_embeddingsÚembedding_dimÚpadding_idxÚmax_normÚ	norm_typeÚscale_grad_by_freqÚsparser   r   r   r   r   r   Úweightr   Nç       @F)	r   r   r   r   r   r   r   Ú_weightÚreturnc	           	         sÎ   t t| ƒ ¡  || _|| _|d urd|dkr>|| jk sdJ dƒ‚n&|dk rd|| j ksZJ dƒ‚| j| }|| _|| _|| _|| _|d u r t	t
 ||¡ƒ| _|  ¡  n$t|jƒ||gksºJ dƒ‚t	|ƒ| _|| _d S )Nr   z)Padding_idx must be within num_embeddingsú?Shape of weight does not match num_embeddings and embedding_dim)Úsuperr
   Ú__init__r   r   r   r   r   r   r   Útorchr   r   Úreset_parametersÚlistÚshaper   )	Úselfr   r   r   r   r   r   r   r   ©Ú	__class__© úW/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/nn/modules/sparse.pyr   \   s*    

ÿ
zEmbedding.__init__©r   c                 C   sT   t  | j¡ | jd urPt ¡ �" | j| j  d¡ W d   ƒ n1 sF0    Y  d S )Nr   )r	   Únormal_r   r   r   Zno_gradZfill_©r   r    r    r!   r   u   s    

zEmbedding.reset_parameters)Úinputr   c              	   C   s"   t  || j| j| j| j| j| j¡S ©N)ÚFÚ	embeddingr   r   r   r   r   r   )r   r%   r    r    r!   Úforward{   s    þzEmbedding.forwardc                 C   sp   d}| j d ur|d7 }| jd ur(|d7 }| jdkr:|d7 }| jdurL|d7 }| jdur^|d7 }|jf i | j¤ŽS )	Nú!{num_embeddings}, {embedding_dim}z, padding_idx={padding_idx}ú, max_norm={max_norm}r   ú, norm_type={norm_type}Fú), scale_grad_by_freq={scale_grad_by_freq}z, sparse=True)r   r   r   r   r   ÚformatÚ__dict__©r   Úsr    r    r!   Ú
extra_repr€   s    




zEmbedding.extra_reprTc              
   C   sD   |  ¡ dksJ dƒ‚|j\}}	| ||	||||||d�}
| |
j_|
S )a1  Creates Embedding instance from given 2-dimensional FloatTensor.

        Args:
            embeddings (Tensor): FloatTensor containing weights for the Embedding.
                First dimension is being passed to Embedding as ``num_embeddings``, second as ``embedding_dim``.
            freeze (boolean, optional): If ``True``, the tensor does not get updated in the learning process.
                Equivalent to ``embedding.weight.requires_grad = False``. Default: ``True``
            padding_idx (int, optional): See module initialization documentation.
            max_norm (float, optional): See module initialization documentation.
            norm_type (float, optional): See module initialization documentation. Default ``2``.
            scale_grad_by_freq (boolean, optional): See module initialization documentation. Default ``False``.
            sparse (bool, optional): See module initialization documentation.

        Examples::

            >>> # FloatTensor containing pretrained weights
            >>> weight = torch.FloatTensor([[1, 2.3, 3], [4, 5.1, 6.3]])
            >>> embedding = nn.Embedding.from_pretrained(weight)
            >>> # Get embeddings for index 1
            >>> input = torch.LongTensor([1])
            >>> embedding(input)
            tensor([[ 4.0000,  5.1000,  6.3000]])
        r   ú4Embeddings parameter is expected to be 2-dimensional)r   r   r   r   r   r   r   r   ©Zdimr   r   Zrequires_grad)ÚclsÚ
embeddingsÚfreezer   r   r   r   r   ÚrowsÚcolsr(   r    r    r!   Úfrom_pretrainedŽ   s     ÿ
ø	
zEmbedding.from_pretrained)NNr   FFN)TNNr   FF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__constants__ÚintÚ__annotations__ÚfloatÚboolr   r   r   r   r)   Ústrr2   Úclassmethodr:   Ú__classcell__r    r    r   r!   r
      s2   
C   þ

þ   þr
   c                       sö   e Zd ZU dZg d¢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
< eed< deeee eee
eee	 eddœ
‡ fdd„Zddœdd„Zd e	ee	 ee	 e	dœdd„Ze
dœdd„Zed!e	eee eee
eed dœ	dd„ƒZ‡  ZS )"ÚEmbeddingBagaf  Computes sums or means of 'bags' of embeddings, without instantiating the
    intermediate embeddings.

    For bags of constant length and no :attr:`per_sample_weights`, this class

        * with ``mode="sum"`` is equivalent to :class:`~torch.nn.Embedding` followed by ``torch.sum(dim=0)``,
        * with ``mode="mean"`` is equivalent to :class:`~torch.nn.Embedding` followed by ``torch.mean(dim=0)``,
        * with ``mode="max"`` is equivalent to :class:`~torch.nn.Embedding` followed by ``torch.max(dim=0)``.

    However, :class:`~torch.nn.EmbeddingBag` is much more time and memory efficient than using a chain of these
    operations.

    EmbeddingBag also supports per-sample weights as an argument to the forward
    pass. This scales the output of the Embedding before performing a weighted
    reduction as specified by ``mode``. If :attr:`per_sample_weights`` is passed, the
    only supported ``mode`` is ``"sum"``, which computes a weighted sum according to
    :attr:`per_sample_weights`.

    Args:
        num_embeddings (int): size of the dictionary of embeddings
        embedding_dim (int): the size of each embedding vector
        max_norm (float, optional): If given, each embedding vector with norm larger than :attr:`max_norm`
                                    is renormalized to have norm :attr:`max_norm`.
        norm_type (float, optional): The p of the p-norm to compute for the :attr:`max_norm` option. Default ``2``.
        scale_grad_by_freq (boolean, optional): if given, this will scale gradients by the inverse of frequency of
                                                the words in the mini-batch. Default ``False``.
                                                Note: this option is not supported when ``mode="max"``.
        mode (string, optional): ``"sum"``, ``"mean"`` or ``"max"``. Specifies the way to reduce the bag.
                                 ``"sum"`` computes the weighted sum, taking :attr:`per_sample_weights`
                                 into consideration. ``"mean"`` computes the average of the values
                                 in the bag, ``"max"`` computes the max value over each bag.
                                 Default: ``"mean"``
        sparse (bool, optional): if ``True``, gradient w.r.t. :attr:`weight` matrix will be a sparse tensor. See
                                 Notes for more details regarding sparse gradients. Note: this option is not
                                 supported when ``mode="max"``.
        include_last_offset (bool, optional): if ``True``, :attr:`offsets` has one additional element, where the last element
                                      is equivalent to the size of `indices`. This matches the CSR format.

    Attributes:
        weight (Tensor): the learnable weights of the module of shape `(num_embeddings, embedding_dim)`
                         initialized from :math:`\mathcal{N}(0, 1)`.

    Inputs: :attr:`input` (LongTensor), :attr:`offsets` (LongTensor, optional), and
        :attr:`per_index_weights` (Tensor, optional)

        - If :attr:`input` is 2D of shape `(B, N)`,

          it will be treated as ``B`` bags (sequences) each of fixed length ``N``, and
          this will return ``B`` values aggregated in a way depending on the :attr:`mode`.
          :attr:`offsets` is ignored and required to be ``None`` in this case.

        - If :attr:`input` is 1D of shape `(N)`,

          it will be treated as a concatenation of multiple bags (sequences).
          :attr:`offsets` is required to be a 1D tensor containing the
          starting index positions of each bag in :attr:`input`. Therefore,
          for :attr:`offsets` of shape `(B)`, :attr:`input` will be viewed as
          having ``B`` bags. Empty bags (i.e., having 0-length) will have
          returned vectors filled by zeros.

        per_sample_weights (Tensor, optional): a tensor of float / double weights, or None
            to indicate all weights should be taken to be ``1``. If specified, :attr:`per_sample_weights`
            must have exactly the same shape as input and is treated as having the same
            :attr:`offsets`, if those are not ``None``. Only supported for ``mode='sum'``.


    Output shape: `(B, embedding_dim)`

    Examples::

        >>> # an Embedding module containing 10 tensors of size 3
        >>> embedding_sum = nn.EmbeddingBag(10, 3, mode='sum')
        >>> # a batch of 2 samples of 4 indices each
        >>> input = torch.LongTensor([1,2,4,5,4,3,2,9])
        >>> offsets = torch.LongTensor([0,4])
        >>> embedding_sum(input, offsets)
        tensor([[-0.8861, -5.4350, -0.0523],
                [ 1.1306, -2.5798, -1.0044]])
    )r   r   r   r   r   Úmoder   Úinclude_last_offsetr   r   r   r   r   r   rH   r   rI   Nr   FÚmean)
r   r   r   r   r   rH   r   r   rI   r   c
           
         sŠ   t t| ƒ ¡  || _|| _|| _|| _|| _|d u rPtt	 
||¡ƒ| _|  ¡  n$t|jƒ||gksjJ dƒ‚t|ƒ| _|| _|| _|	| _d S )Nr   )r   rG   r   r   r   r   r   r   r   r   r   r   r   r   r   rH   r   rI   )
r   r   r   r   r   r   rH   r   r   rI   r   r    r!   r     s     
ÿ
zEmbeddingBag.__init__r"   c                 C   s   t  | j¡ d S r&   )r	   r#   r   r$   r    r    r!   r   +  s    zEmbeddingBag.reset_parameters)r%   ÚoffsetsÚper_sample_weightsr   c                 C   s*   t  || j|| j| j| j| j| j|| j¡
S r&   )	r'   Zembedding_bagr   r   r   r   rH   r   rI   )r   r%   rK   rL   r    r    r!   r)   .  s
    ýzEmbeddingBag.forwardc                 C   sT   d}| j d ur|d7 }| jdkr(|d7 }| jdur:|d7 }|d7 }|jf i | j¤ŽS )Nr*   r+   r   r,   Fr-   z, mode={mode})r   r   r   r.   r/   r0   r    r    r!   r2   4  s    


zEmbeddingBag.extra_reprT)	r6   r7   r   r   r   rH   r   rI   r   c	                 C   sF   |  ¡ dksJ dƒ‚|j\}	}
| |	|
|||||||d�	}| |j_|S )aì  Creates EmbeddingBag instance from given 2-dimensional FloatTensor.

        Args:
            embeddings (Tensor): FloatTensor containing weights for the EmbeddingBag.
                First dimension is being passed to EmbeddingBag as 'num_embeddings', second as 'embedding_dim'.
            freeze (boolean, optional): If ``True``, the tensor does not get updated in the learning process.
                Equivalent to ``embeddingbag.weight.requires_grad = False``. Default: ``True``
            max_norm (float, optional): See module initialization documentation. Default: ``None``
            norm_type (float, optional): See module initialization documentation. Default ``2``.
            scale_grad_by_freq (boolean, optional): See module initialization documentation. Default ``False``.
            mode (string, optional): See module initialization documentation. Default: ``"mean"``
            sparse (bool, optional): See module initialization documentation. Default: ``False``.
            include_last_offset (bool, optional): See module initialization documentation. Default: ``False``.

        Examples::

            >>> # FloatTensor containing pretrained weights
            >>> weight = torch.FloatTensor([[1, 2.3, 3], [4, 5.1, 6.3]])
            >>> embeddingbag = nn.EmbeddingBag.from_pretrained(weight)
            >>> # Get embeddings for index 1
            >>> input = torch.LongTensor([[1, 0]])
            >>> embeddingbag(input)
            tensor([[ 2.5000,  3.7000,  4.6500]])
        r   r3   )	r   r   r   r   r   r   rH   r   rI   r4   )r5   r6   r7   r   r   r   rH   r   rI   r8   r9   Zembeddingbagr    r    r!   r:   ?  s"    ÿ
÷

zEmbeddingBag.from_pretrained)Nr   FrJ   FNF)NN)TNr   FrJ   FF)r;   r<   r=   r>   r?   r@   rA   rB   rC   r   rD   r   r   r   r)   r2   rE   r:   rF   r    r    r   r!   rG   ¹   s<   
O   ý

ý   þþrG   )Útypingr   r   r   Ztorch.nn.parameterr   Úmoduler   Ú r   r'   r	   r
   rG   r    r    r    r!   Ú<module>   s    .