Ë
    [^(hH0  ã                   óœ   — d dl mZ d dlmZ d dlZd dlmc 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	e«      Zy)é    )Ú
namedtuple)ÚSequenceN)ÚTensoré   )Ú
ModuleListÚ
Sequential)ÚLinear)ÚModuleÚAdaptiveLogSoftmaxWithLossÚ
_ASMoutputÚoutputÚlossc                   óÜ   ‡ — 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„Zdd„Zdeded
efd„Zd„ Zded
efd„Zded
efd„Zˆ x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ÚtailNÚreturnc           	      ó  •— ||dœ}t         ‰| �  «        t        |«      }t        |«      dk(  rt	        d«      ‚|t        |«      k7  sQt        |«      dk  sCt        |«      |dz
  kD  s2t        t        |«      «      t        |«      k7  st        d„ |D «       «      rt	        d«      ‚|| _
        || _        ||gz   | _        || _        || _        | j                  d   | _        t        | j                  «      dz
  | _        | j                  | j                   z   | _        t%        | j                  | j"                  fd| j                  i|¤Ž| _        t)        «       | _        t-        | j                   «      D ]—  }	t/        | j                  | j                  |	dz   z  z  «      }
| j                  |	dz      | j                  |	   z
  }t1        t%        | j                  |
fddi|¤Žt%        |
|fddi|¤Ž«      }| j*                  j3                  |«       Œ™ y )	N)ÚdeviceÚdtyper   z4cutoffs should be a sequence of length larger than 0r   c              3   ó8   K  — | ]  }t        |«      |k7  –— Œ y ­w©N)Úint)Ú.0Úcs     úW/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/torch/nn/modules/adaptive.pyú	<genexpr>z6AdaptiveLogSoftmaxWithLoss.__init__.<locals>.<genexpr>‹   s   è ø€ Ò0 1”3�q“6˜Q•;Ñ0ùs   ‚z†cutoffs 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__s                €r    r$   z#AdaptiveLogSoftmaxWithLoss.__init__t   sá  ø€ ð %+°UÑ;ˆÜ‰ÑÔä�w“-ˆäˆw‹<˜1ÒÜÐSÓTÐTð œ˜w›Ò'Ü�G“ Ò!Ü�G“ 	¨A¡Ò.Ü”C˜“LÓ!¤S¨£\Ò1ÜÑ0¨Ô0Ô0äð:óð ð 'ˆÔØ"ˆŒØ ) Ñ,ˆŒØ"ˆŒØ"ˆŒà"Ÿl™l¨1™oˆÔÜ˜dŸl™lÓ+¨aÑ/ˆŒØ×,Ñ,¨t¯©Ñ>ˆŒäØ×Ñ˜dŸn™nñ
Ø37·>±>ð
ØESñ
ˆŒ	ô “LˆŒ	ä�t—‘Ó'ò 		)ˆAÜ�d×&Ñ&¨4¯>©>¸aÀ!¹eÑ+DÑEÓFˆCØ—,‘,˜q 1™uÑ%¨¯©°Q©Ñ7ˆCä#Ü�t×'Ñ'¨ÑK°5ÐK¸NÑKÜ�s˜CÑ> eÐ>¨~Ñ>óˆJð
 �I‰I×Ñ˜ZÕ(ñ		)ó    c                 ó    — | j                   j                  «        | j                  D ]%  \  }}|j                  «        |j                  «        Œ' y r   )r   Úreset_parametersr   )r2   Úi2hÚh2os      r    r;   z+AdaptiveLogSoftmaxWithLoss.reset_parameters­   sA   € Ø�	‰	×"Ñ"Ô$ØŸ	™	ò 	#‰HˆC�Ø× Ñ Ô"Ø× Ñ Õ"ñ	#r9   Úinput_Útarget_c           	      ó¦  — |j                  «       }|dk(  r[|j                  d«      |j                  d«      k7  rt        d«      ‚|j                  «       dk7  rWt        d|j                  «       «      ‚|dk(  r-|j                  «       dk7  r%t        d|j                  «       «      ‚t        d«      ‚|dkD  }|r|n|j                  d«      }|r|n|j                  d«      }d}|j                  d«      }|j	                  |«      }	|j                  |«      }
dg| j                  z   }t        t        |«      dz
  «      D �]-  }||   }||dz      }||k\  ||k  z  }|j                  «       j                  «       }|j                  «       dk(  rŒN|dk(  r|
j                  d|||   «       n±||   |z
  }|j                  d|«      } | j                  |dz
     |«      }| j                  |z   dz
  }|
j!                  d||«       t#        j$                  |d¬«      }|j'                  d|j                  d«      «      }|	j                  d||j                  d«      «       ||j                  «       z  }�Œ0 ||k7  rZt        d	| j(                  dz
  › d
|j+                  «       j-                  «       › d|j/                  «       j-                  «       › d�«      ‚| j1                  |«      }t#        j$                  |d¬«      }|	|j'                  d|
j                  d«      «      j                  «       z  }	|	 j3                  «       }|s|	j                  d«      }	t5        |	|«      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. )rC   ÚsizeÚRuntimeErrorÚ	unsqueezeÚ	new_zerosÚ	new_emptyr   r0   r&   ÚnonzeroÚsqueezeÚnumelÚindex_copy_Úindex_selectr   r-   Úindex_fill_ÚFÚlog_softmaxÚgatherr   r)   Úitemr*   r   Úmeanr   )r2   r>   r?   Útarg_dimÚ
is_batchedÚinputÚtargetÚ	used_rowsÚ
batch_sizer   Úgather_indsÚcutoff_valuesr4   Úlow_idxÚhigh_idxÚtarget_maskÚrow_indicesÚrelative_targetÚinput_subsetÚcluster_outputÚcluster_indexÚcluster_logprobÚlocal_logprobÚhead_outputÚhead_logprobr   s                             r    Úforwardz"AdaptiveLogSoftmaxWithLoss.forward³   sO  € Ø—;‘;“=ˆà�qŠ=Ø�{‰{˜1‹~ §¡¨a£Ò0Ü"ð.óð ð �z‰z‹|˜qÒ Ü"ð1à—K‘K“Móð ð
 ˜Š]Ø�z‰z‹|˜qÒ Ü"ð1à—K‘K“Móð ô ØMóð ð  ‘\ˆ
Ù$‘¨&×*:Ñ*:¸1Ó*=ˆÙ&‘¨G×,=Ñ,=¸aÓ,@ˆàˆ	Ø—[‘[ “^ˆ
à—‘ Ó,ˆØ×&Ñ& zÓ2ˆà˜˜dŸl™lÑ*ˆÜ”s˜=Ó)¨AÑ-Ó.ó 	-ˆAØ# AÑ&ˆGØ$ Q¨¡UÑ+ˆHà! WÑ,°¸(Ñ1BÑCˆKØ%×-Ñ-Ó/×7Ñ7Ó9ˆKà× Ñ Ó" aÒ'Øà�AŠvØ×'Ñ'¨¨;¸¸{Ñ8KÕLð #)¨Ñ"5¸Ñ"?�Ø$×1Ñ1°!°[ÓA�à!1 §¡¨1¨q©5Ñ!1°,Ó!?�Ø $× 3Ñ 3°aÑ 7¸!Ñ ;�à×'Ñ'¨¨;¸ÔFÜ"#§-¡-°ÀAÔ"F�Ø /× 6Ñ 6°q¸/×:SÑ:SÐTUÓ:VÓ W�Ø×"Ñ" 1 k°=×3HÑ3HÈÓ3KÔLà˜×*Ñ*Ó,Ñ,ŠIð3	-ð6 ˜
Ò"ÜØ1°$·.±.À1Ñ2DÐ1Eð F(Ø(.¯
©
«×(9Ñ(9Ó(;Ð'<¸B¸v¿z¹z»|×?PÑ?PÓ?RÐ>Sð Tðóð ð —i‘i Ó&ˆÜ—}‘} [°aÔ8ˆØ�,×%Ñ% a¨×)>Ñ)>¸qÓ)AÓB×JÑJÓLÑLˆØ��~‰~ÓˆáØ—^‘^ AÓ&ˆFä˜& $Ó'Ð'r9   c                 ó  — |j                  |j                  d«      | j                  f«      }t        j                  |d¬«      }|dd…d| j
                  …f   |dd…d| j
                  …f<   t        t        | j                  | j                  dd «      «      D ]g  \  }\  }} | j                  |   |«      }t        j                  |d¬«      }	|	|dd…| j
                  |z   f   j                  d«      z   }
|
|dd…||…f<   Œi |S )zZGiven input tensor, and output of ``self.head``, compute the log of the full distribution.r   r   rB   N)rH   rD   r   rO   rP   r-   Ú	enumerateÚzipr   r   rF   )r2   rV   rf   Úoutrg   r4   Ú	start_idxÚstop_idxrb   rd   Úoutput_logprobs              r    Ú_get_full_log_probz-AdaptiveLogSoftmaxWithLoss._get_full_log_prob  s	  € à�o‰o˜{×/Ñ/°Ó2°D·N±NÐCÓDˆÜ—}‘} [°aÔ8ˆà(4²QÐ8M¸$×:MÑ:MÐ8MÐ5MÑ(NˆŠAÐ$�×$Ñ$Ð$Ð$Ñ%ä(1´#°d·l±lÀDÇLÁLÐQRÐQSÐDTÓ2UÓ(Vò 	8Ñ$ˆAÑ$�	˜8Ø)˜TŸY™Y q™\¨%Ó0ˆNÜŸm™m¨NÀÔBˆOØ,¨|Ú�4×&Ñ&¨Ñ*Ð*ñ0ç‰i˜‹lñˆNð *8ˆC’�9˜XÐ%Ð%Ò&ð	8ð ˆ
r9   rV   c                 óH   — | j                  |«      }| j                  ||«      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   rp   )r2   rV   rf   s      r    Úlog_probz#AdaptiveLogSoftmaxWithLoss.log_prob  s%   € ð  —i‘i Ó&ˆØ×&Ñ& u¨kÓ:Ð:r9   c                 ót  — | j                  |«      }t        j                  |d¬«      }|| j                  k\  }|j	                  «        }|r|S |j                  «       r)| j                  ||«      }t        j                  |d¬«      S | j                  ||   ||   «      }t        j                  |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   rB   )r   ÚtorchÚargmaxr-   r,   Úallrp   )r2   rV   rf   r   Únot_in_shortlistÚall_in_shortlistrr   s          r    Úpredictz"AdaptiveLogSoftmaxWithLoss.predict*  s¼   € ð —i‘i Ó&ˆÜ—‘˜k¨qÔ1ˆØ! T×%8Ñ%8Ñ8ÐØ 0× 4Ñ 4Ó 6Ð7ÐáØˆMà×!Ñ!Ô#Ø×.Ñ.¨u°kÓBˆHÜ—<‘< ¨aÔ0Ð0ð ×.Ñ.ØÐ&Ñ'¨Ð5EÑ)FóˆHô (-§|¡|°HÀ!Ô'DˆFÐ#Ñ$ØˆMr9   )g      @FNN)r   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__annotations__r%   ÚfloatÚboolr	   r   r   r$   r;   r   r   rh   rp   rr   ry   Ú__classcell__)r8   s   @r    r   r      sØ   ø… ñUðn ÓØƒNØ�#‰YÓØÓØƒOØ
ƒLØ
Óð ØØØñ7)àð7)ð ð7)ð ˜#‘ð	7)ð
 ð7)ð ð7)ð 
õ7)ór#ðP(˜fð P(¨vð P(¸*ó P(òdð$;˜fð ;¨ó ;ð& ˜Vð  ¨÷  r9   )Úcollectionsr   Úcollections.abcr   rt   Útorch.nn.functionalÚnnÚ
functionalrO   r   Ú	containerr   r   Úlinearr	   Úmoduler
   Ú__all__r   r   © r9   r    ú<module>rŒ      sK   ðõ #Ý $ã ß Ð Ý ç -Ý Ý ð (Ð
(€á˜ x°Ð&8Ó9€
ôv õ vr9   