o
    }oi                     @   s.   d dl Z d dlmZ dgZG dd deZdS )    N)MetricSequencePerplexityc                       sB   e Zd ZdZd fdd	Zddejdejfdd	Zd
d Z  Z	S )r   a  
    This class computes mean perplexity across the batches of sequences.

    You have to provide ``log_probs`` (float tensor of shape [batch_size x seq_length x vocab_size]) and
    ``labels`` (int tensor of shape [batch_size x seq_length] with values from the range [0, vocab_size-1])
    to the :meth:`update` method. If some of the sequences are shorter than seq_length, you can also provide
    an optional argument ``mask`` (bool tensor of shape [batch_size x seq_length]) which masks out tokens
    not participating in perplexity computation.

    See :doc:`PyTorch Lightning Metrics<pytorch-lightning:metrics>` for the metric usage instructions.

    Args:
        dist_sync_on_step:
            Synchronize metric state across processes at each ``forward()`` before returning the value at the step.
        process_group:
            Specify the process group on which synchronization is called. default: ``None`` (which selects the entire
                world)
        dist_sync_fn:
            Callback that performs the allgather operation on the metric state. When ``None``, DDP will be used
                to perform the allgather.
    FNc                    sN   t  j|||d | jdtjdtjddd | jdtjdtjddd d S )	N)dist_sync_on_stepprocess_groupdist_sync_fnperplexities_sumg        )dtypesum)defaultdist_reduce_fxnum_sequencesr   )super__init__	add_statetorchtensorfloat64int64)selfr   r   r   	__class__ d/home/ubuntu/.local/lib/python3.10/site-packages/nemo/collections/nlp/metrics/sequence_perplexity.pyr   ,   s
    zSequencePerplexity.__init__	log_probslabelsc                 C   s   |d u r	t |}|j|jur||j}|d|dd}|| jdd |jdd }| }|  j	|
 7  _	|  j| 7  _d S )N   )dim)r   	ones_liker   togather	unsqueezesqueezer	   expr   numelr   )r   r   r   masktarget_log_probs
avg_neg_llpplr   r   r   update6   s   
zSequencePerplexity.updatec                 C   s   | j drdS | j| j  S )z{
        Returns perplexity across all workers and resets to 0 :attr:`perplexities_sum` and :attr:`num_sequences`.
        r   N)r   eqr   )r   r   r   r   computeC   s   zSequencePerplexity.compute)FNN)N)
__name__
__module____qualname____doc__r   r   Tensorr)   r+   __classcell__r   r   r   r   r      s
    
)r   torchmetricsr   __all__r   r   r   r   r   <module>   s   