
    i                         d dl mZ d dlZd dlmZ dededdfdZddededee   deeef   fd	Zd
ededefdZddededee   defdZ	y)    )OptionalN)Tensorpredstargetreturnc                 V   t        | j                        dk7  r"t        dt        | j                         d      t        |j                        dk7  r"t        dt        |j                         d      | j                  dd |j                  k7  r)t        d| j                  dd  d|j                   d      | j                         st	        d	| j
                   d      |j
                  t        j                  k7  r*t	        d
t        j                   d|j
                   d      y)a3  Check shape and type consistency of input vectors.

    Args:
        preds:
            Logits or a unnormalized score assigned to each token in a sequence with shape [batch_size, seq_len,
            vocab_size]. Scores will be normalized internally using softmax.
        target:
            Ground truth values with a shape [batch_size, seq_len].

    Raises:
        ValueError:
            If ``preds`` tensor has no 3 dimensions.
        ValueError:
            If ``target`` tensor has no 2 dimensions.
        ValueError:
            If the first two dimensions of ``preds`` and ``target`` do not equal.
        TypeError:
            If ``preds`` dtype is not one of ``(torch.float16, torch.float32, torch.float64)``
        TypeError:
            If ``target`` is not of a type LongTensor (torch.int64)

       zbInput tensor `preds` is expected to have 3 dimensions, [batch_size, seq_len, vocab_size], but got .   zWInput tensor `target` is expected to have 2 dimensions, [batch_size, seq_len], but got NzvInput tensors `preds` and `target` are expected to have equaling first two dimensions, [batch_size, seq_len], but got z and zFInput tensor `preds` is expected to be of floating point type but got z2Input tensor `target` is expected to be of a type z	 but got )lenshape
ValueErroris_floating_point	TypeErrordtypetorchint64)r   r   s     |/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/functional/text/perplexity.py!_check_shape_and_type_consistencyr      s/   . 5;;1EKK(),
 	
 6<<AFLL)*!-
 	
 {{2A&,,&//4{{2A.?uV\\NRSU
 	
 ""$`afalal`mmnopp||u{{"LU[[MYbcicocobppqrss #    ignore_indexc                 b   t        | |       t        j                  j                  j	                  | j                  d| j                  d         d      }|j                  d      }|F|j                  |      }|j                  ||k7  t        j                  d|j                              }n%t        j                  |t        j                        }|t        j                  |j                               |f   |   }|j                         j!                          }|j!                         }||fS )a]  Compute intermediate statistics for Perplexity.

    Args:
        preds:
            Logits or a unnormalized score assigned to each token in a sequence with shape [batch_size, seq_len,
            vocab_size]. Scores will be normalized internally using softmax.
        target:
            Ground truth values with a shape [batch_size, seq_len].
        ignore_index:
            Integer specifying a target class to ignore. If given, this class index does not contribute
            to the returned score.

    Returns:
        Log probabilities, summed over all samples
        Number of samples

       )dimr   )device)r   )r   r   nn
functionalsoftmaxreshaper   newheretensorr   	ones_likeboolarangenumellogsum)r   r   r   probsmasktotal_log_probscounts          r   _perplexity_updater.   A   s    $ &eV4HH''b%++b/(JPQ'RE^^BFyy&f4ell1V]]6[\vUZZ8%,,v||~.67=Eyy{((OHHJEE!!r   totalr-   c                 2    t        j                  | |z        S )zCompute the Perplexity.

    Args:
        total: Log probabilities, summed over all samples
        count: Number of samples
    Returns:
        Perplexity

    )r   exp)r/   r-   s     r   _perplexity_computer2   e   s     99UU]##r   c                 :    t        | ||      \  }}t        ||      S )a  Perplexity measures how well a language model predicts a text sample.

    This metric is calculated as the average number of bits per word a model needs to represent the sample.

    Args:
        preds:
            Logits or a unnormalized score assigned to each token in a sequence with shape [batch_size, seq_len,
            vocab_size], which is the output of a language model. Scores will be normalized internally using softmax.
        target:
            Ground truth values with a shape [batch_size, seq_len].
        ignore_index:
            Integer specifying a target class to ignore. If given, this class index does not contribute
            to the returned score.

    Returns:
        Perplexity value

    Examples:
        >>> from torch import rand, randint
        >>> preds = rand(2, 8, 5)
        >>> target = randint(5, (2, 8))
        >>> target[0, 6:] = -100
        >>> perplexity(preds, target, ignore_index=-100)
        tensor(5.8540)

    )r.   r2   )r   r   r   r/   r-   s        r   
perplexityr4   r   s#    6 &eV\BLE5ue,,r   )N)
typingr   r   r   r   inttupler.   r2   r4    r   r   <module>r9      s      )tV )tV )t )tX!"f !"f !"HSM !"]bcikqcq]r !"H
$v 
$f 
$ 
$-f -f -HSM -U[ -r   