o
    hH0                     @   s   d dl mZ d dlmZ d dlZd dlm  mZ d dlm	Z	 ddl
mZmZ ddlmZ ddlmZ d	gZed
ddgZG dd	 d	eZdS )    )
namedtuple)SequenceN)Tensor   )
ModuleList
Sequential)Linear)ModuleAdaptiveLogSoftmaxWithLoss
_ASMoutputoutputlossc                       s   e Zd ZU dZeed< eed< ee ed< eed< eed< e	ed< e
ed< 			
		ddededee dededdf fddZdddZdededefddZdd ZdedefddZdedefddZ  ZS )r
   u  Efficient softmax approximation.

    As described in
    `Efficient softmax approximation for GPUs by Edouard Grave, Armand Joulin,
    Moustapha Cissé, David Grangier, and Hervé Jégou
    <https://arxiv.org/abs/1609.04309>`__.

    Adaptive softmax is an approximate strategy for training models with large
    output spaces. It is most effective when the label distribution is highly
    imbalanced, for example in natural language modelling, where the word
    frequency distribution approximately follows the `Zipf's law`_.

    Adaptive softmax partitions the labels into several clusters, according to
    their frequency. These clusters may contain different number of targets
    each.
    Additionally, clusters containing less frequent labels assign lower
    dimensional embeddings to those labels, which speeds up the computation.
    For each minibatch, only clusters for which at least one target is
    present are evaluated.

    The idea is that the clusters which are accessed frequently
    (like the first one, containing most frequent labels), should also be cheap
    to compute -- that is, contain a small number of assigned labels.

    We highly recommend taking a look at the original paper for more details.

    * :attr:`cutoffs` should be an ordered Sequence of integers sorted
      in the increasing order.
      It controls number of clusters and the partitioning of targets into
      clusters. For example setting ``cutoffs = [10, 100, 1000]``
      means that first `10` targets will be assigned
      to the 'head' of the adaptive softmax, targets `11, 12, ..., 100` will be
      assigned to the first cluster, and targets `101, 102, ..., 1000` will be
      assigned to the second cluster, while targets
      `1001, 1002, ..., n_classes - 1` will be assigned
      to the last, third cluster.

    * :attr:`div_value` is used to compute the size of each additional cluster,
      which is given as
      :math:`\left\lfloor\frac{\texttt{in\_features}}{\texttt{div\_value}^{idx}}\right\rfloor`,
      where :math:`idx` is the cluster index (with clusters
      for less frequent words having larger indices,
      and indices starting from :math:`1`).

    * :attr:`head_bias` if set to True, adds a bias term to the 'head' of the
      adaptive softmax. See paper for details. Set to False in the official
      implementation.

    .. warning::
        Labels passed as inputs to this module should be sorted according to
        their frequency. This means that the most frequent label should be
        represented by the index `0`, and the least frequent
        label should be represented by the index `n_classes - 1`.

    .. note::
        This module returns a ``NamedTuple`` with ``output``
        and ``loss`` fields. See further documentation for details.

    .. note::
        To compute log-probabilities for all classes, the ``log_prob``
        method can be used.

    Args:
        in_features (int): Number of features in the input tensor
        n_classes (int): Number of classes in the dataset
        cutoffs (Sequence): Cutoffs used to assign targets to their buckets
        div_value (float, optional): value used as an exponent to compute sizes
            of the clusters. Default: 4.0
        head_bias (bool, optional): If ``True``, adds a bias term to the 'head' of the
            adaptive softmax. Default: ``False``

    Returns:
        ``NamedTuple`` with ``output`` and ``loss`` fields:
            * **output** is a Tensor of size ``N`` containing computed target
              log probabilities for each example
            * **loss** is a Scalar representing the computed negative
              log likelihood loss

    Shape:
        - input: :math:`(N, \texttt{in\_features})` or :math:`(\texttt{in\_features})`
        - target: :math:`(N)` or :math:`()` where each value satisfies :math:`0 <= \texttt{target[i]} <= \texttt{n\_classes}`
        - output1: :math:`(N)` or :math:`()`
        - output2: ``Scalar``

    .. _Zipf's law: https://en.wikipedia.org/wiki/Zipf%27s_law
    in_features	n_classescutoffs	div_value	head_biasheadtail      @FNreturnc                    sz  ||d}t    t|}t|dkrtd|t|ks?t|dks?t||d ks?tt|t|ks?t	dd |D rCtd|| _
|| _||g | _|| _|| _| jd | _t| jd | _| j| j | _t| j
| jfd| ji|| _t | _t| jD ]8}	t| j
| j|	d   }
| j|	d  | j|	  }tt| j
|
fdd	i|t|
|fdd	i|}| j| qd S )
N)devicedtyper   z4cutoffs should be a sequence of length larger than 0r   c                 s   s    | ]	}t ||kV  qd S N)int).0c r   m/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/nn/modules/adaptive.py	<genexpr>   s    z6AdaptiveLogSoftmaxWithLoss.__init__.<locals>.<genexpr>zcutoffs should be a sequence of unique, positive integers sorted in an increasing order, where each value is between 1 and n_classes-1biasF)super__init__listlen
ValueErrorsortedminmaxsetanyr   r   r   r   r   shortlist_size
n_clusters	head_sizer   r   r   r   ranger   r   append)selfr   r   r   r   r   r   r   factory_kwargsihszosz
projection	__class__r   r   r"   t   sN   


z#AdaptiveLogSoftmaxWithLoss.__init__c                 C   s.   | j   | jD ]\}}|  |  qd S r   )r   reset_parametersr   )r0   i2hh2or   r   r   r8      s
   

z+AdaptiveLogSoftmaxWithLoss.reset_parametersinput_target_c                 C   sT  |  }|dkr$|d|dkrtd|  dkr#td| n|dkr6|  dkr5td| ntd|dk}|rB|n|d}|rK|n|d}d}|d}||}	||}
dg| j }tt|d D ]r}|| }||d  }||k||k @ }|	 
 }| dkrqo|dkr|
d|||  n=|| | }|d|}| j|d  |}| j| d }|
d|| tj|dd}|d|d}|	d||
d || 7 }qo||krtd	| jd  d
|   d|   d| |}tj|dd}|	|d|
d
 7 }	|	  }|s%|	
d}	t|	|S )Nr   r   zBInput and target should have the same size in the batch dimension.   zE1D target tensor expects 2D input tensors, but found inputs with sizezE0D target tensor expects 1D input tensors, but found inputs with sizez;0D or 1D target tensor expected, multi-target not supporteddimzTarget values should be in [0, z], but values in range [z, z] were found. )r?   sizeRuntimeError	unsqueeze	new_zeros	new_emptyr   r.   r$   nonzerosqueezenumelindex_copy_index_selectr   r+   index_fill_Flog_softmaxgatherr   r'   itemr(   r   meanr   )r0   r;   r<   targ_dim
is_batchedinputtarget	used_rows
batch_sizer   gather_indscutoff_valuesr2   low_idxhigh_idxtarget_maskrow_indicesrelative_targetinput_subsetcluster_outputcluster_indexcluster_logproblocal_logprobhead_outputhead_logprobr   r   r   r   forward   s~   








z"AdaptiveLogSoftmaxWithLoss.forwardc                 C   s   | |d| jf}tj|dd}|ddd| jf |ddd| jf< tt| j| jdd D ].\}\}}| j	| |}tj|dd}	|	|dd| j| f 
d }
|
|dd||f< q3|S )zZGiven input tensor, and output of ``self.head``, compute the log of the full distribution.r   r   r>   N)rD   r@   r   rK   rL   r+   	enumeratezipr   r   rB   )r0   rR   rb   outrc   r2   	start_idxstop_idxr^   r`   output_logprobr   r   r   _get_full_log_prob  s   (&z-AdaptiveLogSoftmaxWithLoss._get_full_log_probrR   c                 C   s   |  |}| ||S )a  Compute log probabilities for all :math:`\texttt{n\_classes}`.

        Args:
            input (Tensor): a minibatch of examples

        Returns:
            log-probabilities of for each class :math:`c`
            in range :math:`0 <= c <= \texttt{n\_classes}`, where :math:`\texttt{n\_classes}` is a
            parameter passed to ``AdaptiveLogSoftmaxWithLoss`` constructor.

        Shape:
            - Input: :math:`(N, \texttt{in\_features})`
            - Output: :math:`(N, \texttt{n\_classes})`

        )r   rk   )r0   rR   rb   r   r   r   log_prob  s   
z#AdaptiveLogSoftmaxWithLoss.log_probc                 C   s   |  |}tj|dd}|| jk}|  }|r|S | r+| ||}tj|ddS | || || }tj|dd||< |S )a  Return the class with the highest probability for each example in the input minibatch.

        This is equivalent to ``self.log_prob(input).argmax(dim=1)``, but is more efficient in some cases.

        Args:
            input (Tensor): a minibatch of examples

        Returns:
            output (Tensor): a class with the highest probability for each example

        Shape:
            - Input: :math:`(N, \texttt{in\_features})`
            - Output: :math:`(N)`
        r   r>   )r   torchargmaxr+   r*   allrk   )r0   rR   rb   r   not_in_shortlistall_in_shortlistrl   r   r   r   predict*  s   


z"AdaptiveLogSoftmaxWithLoss.predict)r   FNN)r   N)__name__
__module____qualname____doc__r   __annotations__r#   floatboolr   r   r   r"   r8   r   r   rd   rk   rl   rr   __classcell__r   r   r6   r   r
      s>   
 W	
9R)collectionsr   collections.abcr   rm   torch.nn.functionalnn
functionalrK   r   	containerr   r   linearr   moduler	   __all__r   r
   r   r   r   r   <module>   s   