o
    }oim                     @   s:   d dl Z d dlmZ d dlmZ dgZG dd deZdS )    N)Categorical)Metric
Perplexityc                       s8   e Zd ZdZdZd fdd	ZdddZd	d
 Z  ZS )r   a  
    This class computes mean perplexity of distributions in the last dimension of inputs. It is a wrapper around
    :doc:`torch.distributions.Categorical.perplexity<pytorch:distributions>` method. You have to provide either
    ``probs`` or ``logits`` to the :meth:`update` method. The class computes perplexities for distributions passed to
    :meth:`update` method in ``probs`` or ``logits`` arguments and averages the perplexities. Reducing results between
    all workers is done via SUM operations.
    See the `TorchMetrics in PyTorch Lightning guide
    <https://lightning.ai/docs/torchmetrics/stable/pages/lightning.html>`_
    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)
        validate_args:
            If ``True`` values of :meth:`update` method parameters are checked. ``logits`` has to not contain NaNs and
            ``probs`` last dim has to be valid probability distribution.
    TFNc                    sR   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perplexities_sumg        )dtypesum)dist_reduce_fxnum_distributionsr   )super__init__validate_args	add_statetorchtensorfloat64int64)selfr   r   r   	__class__ ^/home/ubuntu/.local/lib/python3.10/site-packages/nemo/collections/common/metrics/perplexity.pyr   /   s    zPerplexity.__init__c                 C   s`   t |du rdn| |du rdn| | jd}| }|  j| 7  _|  j| 7  _dS )z
        Updates :attr:`perplexities_sum` and :attr:`num_distributions`.
        Args:
            probs: A ``torch.Tensor`` which innermost dimension is valid probability distribution.
            logits: A ``torch.Tensor`` without NaNs.
        N)r   )r   detachr   
perplexityr   numelr   r	   )r   probslogitsdpplr   r   r   update6   s   zPerplexity.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_distributions`.
        r   N)r   eqr   )r   r   r   r   computeF   s   zPerplexity.compute)FNT)NN)	__name__
__module____qualname____doc__full_state_updater   r    r"   __classcell__r   r   r   r   r      s    
)r   torch.distributions.categoricalr   torchmetricsr   __all__r   r   r   r   r   <module>   s
   