U
    d@/                     @   s~   d dl mZ d dlZd dlmZ d dlmZmZ ddlmZm	Z	m
Z
 ddlmZ dd	lmZ ed
ddgZG dd deZdS )    )
namedtupleN)Tensor)ListSequence   )
Sequential
ModuleListLinear)Module   )log_softmax
_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eeee eedd fddZddddZeeedddZdd ZeedddZeedddZ  ZS )AdaptiveLogSoftmaxWithLossu  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)r   r   r   r   r   returnc                    sj  ||d}t t|   t|}|t|ksnt|dksnt||d ksntt|t|ksnt	dd |D rvt
d|| _|| _||g | _|| _|| _| jd | _t| jd | _| j| j | _t| j| jfd| ji|| _t | _t| jD ]p}	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   r   c                 S   s   g | ]}t ||kqS  )int).0cr   r   =/tmp/pip-unpacked-wheel-ua33x9lu/torch/nn/modules/adaptive.py
<listcomp>   s     z7AdaptiveLogSoftmaxWithLoss.__init__.<locals>.<listcomp>zcutoffs should be a sequence of unique, positive integers sorted in an increasing order, where each value is between 1 and n_classes-1ZbiasF)superr   __init__listsortedminmaxlensetany
ValueErrorr   r   r   r   r   shortlist_sizeZ
n_clustersZ	head_sizer	   r   r   r   ranger   r   append)selfr   r   r   r   r   r   r   Zfactory_kwargsiZhszZoszZ
projection	__class__r   r    r#   p   sB    


z#AdaptiveLogSoftmaxWithLoss.__init__)r   c                 C   s.   | j   | jD ]\}}|  |  qd S )N)r   reset_parametersr   )r/   Zi2hZh2or   r   r    r3      s    
z+AdaptiveLogSoftmaxWithLoss.reset_parameters)input_target_r   c                 C   sL  |  }|dkrH|d|dkr,td|  dkrttd| n,|dkrl|  dkrttd| ntd|dk}|r|n|d}|r|n|d}d}|d}||}	||}
dg| j }tt|d D ]}|| }||d  }||k||k @ }|	 
 }| dkr"q|dkr@|
d|||  nx|| | }|d|}| j|d  |}| j| d }|
d|| t|dd}|d|d}|	d||
d || 7 }q||krtd	| jd |  |  | |}t|dd}|	|d|
d
 7 }	|	  }|sB|	
d}	t|	|S )
Nr   r   zBInput and target should have the same size in the batch dimension.r   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dimzMTarget values should be in [0, {}], but values in range [{}, {}] were found. )r7   sizeRuntimeError	unsqueezeZ	new_zeros	new_emptyr   r-   r(   ZnonzeroZsqueezeZnumelZindex_copy_Zindex_selectr   r,   Zindex_fill_r   Zgatherformatr   r&   itemr'   r   Zmeanr   )r/   r4   r5   Ztarg_dimZ
is_batchedinputtargetZ	used_rowsZ
batch_sizer   Zgather_indsZcutoff_valuesr0   Zlow_idxZhigh_idxZtarget_maskZrow_indicesZrelative_targetZinput_subsetcluster_outputZcluster_indexcluster_logprobZlocal_logprobhead_outputhead_logprobr   r   r   r    forward   sj    









z"AdaptiveLogSoftmaxWithLoss.forwardc                 C   s   | |d| jf}t|dd}|ddd| jf |ddd| jf< tt| j| jdd D ]Z\}\}}| j| |}t|dd}	|	|dd| j| f 	d }
|
|dd||f< qd|S )za Given input tensor, and output of `self.head`,
        compute the log of the full distribution r   r   r6   N)
r;   r8   r   r   r,   	enumeratezipr   r   r:   )r/   r>   rB   outrC   r0   Z	start_idxZstop_idxr@   rA   Zoutput_logprobr   r   r    _get_full_log_prob   s    (& z-AdaptiveLogSoftmaxWithLoss._get_full_log_prob)r>   r   c                 C   s   |  |}| ||S )a   Computes 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   rH   )r/   r>   rB   r   r   r    log_prob  s    
z#AdaptiveLogSoftmaxWithLoss.log_probc                 C   s   |  |}tj|dd}|| jk}|  }|r4|S | rV| ||}tj|ddS | || || }tj|dd||< |S dS )a   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   r6   N)r   torchZargmaxr,   r*   allrH   )r/   r>   rB   r   Znot_in_shortlistZall_in_shortlistrI   r   r   r    predict  s    



z"AdaptiveLogSoftmaxWithLoss.predict)r   FNN)__name__
__module____qualname____doc__r   __annotations__r   floatboolr	   r   r   r#   r3   r   r   rD   rH   rI   rL   __classcell__r   r   r1   r    r      s2   
U    3Jr   )collectionsr   rJ   r   typingr   r    r   r   r	   moduler
   Z
functionalr   r   r   r   r   r   r    <module>   s   