o
    °ôjk  ã                	   @   s¾   d dl mZmZ d dlmZmZmZmZmZ d dl	Z	d dl	m
Z
mZ d dlmZ d dlmZ d dlmZ d dlmZmZ 			dd
e
deed ef dee de
fdd„ZG dd„ deeƒZdS )é    )ÚABCÚabstractmethod)ÚAnyÚCallableÚListÚOptionalÚUnionN)ÚTensorÚtensor)ÚLiteral)ÚMetric)Ú_check_retrieval_inputs)Ú_flexible_bincountÚdim_zero_catÚmeanÚvaluesÚaggregation©r   ÚmedianÚminÚmaxÚdimÚreturnc                 C   s¢   |dkr|du r|   ¡ S | j |d�S |dkr%|du r|  ¡ S | j|d�jS |dkr8|du r1|  ¡ S | j|d�jS |dkrK|du rD|  ¡ S | j|d�jS || |d�S )z9Aggregate the final retrieval values into a single value.r   N©r   r   r   r   )r   r   r   r   r   )r   r   r   © r   ún/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/retrieval/base.pyÚ_retrieval_aggregate   s   r   c                       sÚ   e Zd ZU dZdZeed< dZeed< dZeed< e	e
 ed< e	e
 ed< e	e
 ed	< 	
		ddedee deed ef deddf
‡ fdd„Zde
d	e
de
ddfdd„Zde
fdd„Zede
d	e
de
fdd„ƒZ‡  ZS )ÚRetrievalMetricaQ	  Works with binary target data. Accepts float predictions from a model output.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
    - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)``
    - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a
      prediction belongs

    .. hint::
        The ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flattened
        to single dimension once provided.

    .. attention::
        Predictions will be first grouped by ``indexes`` and then the real metric, defined by overriding
        the `_metric` method, will be computed as the mean of the scores over each query.

    As output to ``forward`` and ``compute`` the metric returns the following output:

    - ``metric`` (:class:`~torch.Tensor`): A tensor as computed by ``_metric`` if the number of positive targets is
      at least 1, otherwise behave as specified by ``self.empty_target_action``.

    Args:
        empty_target_action:
            Specify what to do with queries that do not have at least a positive
            or negative (depend on metric) target. Choose from:

            - ``'neg'``: those queries count as ``0.0`` (default)
            - ``'pos'``: those queries count as ``1.0``
            - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned
            - ``'error'``: raise a ``ValueError``

        ignore_index:
            Ignore predictions where the target is equal to this number.
        aggregation:
            Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor
            and returns a scalar value or one of the following strings:

            - ``'mean'``: average value is returned
            - ``'median'``: median value is returned
            - ``'max'``: max value is returned
            - ``'min'``: min value is returned

        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ValueError:
            If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``.
        ValueError:
            If ``ignore_index`` is not `None` or an integer.

    FÚis_differentiableTÚhigher_is_betterÚfull_state_updateÚindexesÚpredsÚtargetÚnegNr   Úempty_target_actionÚignore_indexr   r   Úkwargsr   c                    s´   t ƒ jdi |¤Ž d| _d}||vrtd|› d�ƒ‚|| _|d ur*t|tƒs*tdƒ‚|| _|dv s=t|ƒs=td|› d�ƒ‚|| _	| j
d	g d d
� | j
dg d d
� | j
dg d d
� d S )NF)ÚerrorÚskipr$   Úposz7Argument `empty_target_action` received a wrong value `z`.z3Argument `ignore_index` must be an integer or None.r   zˆArgument `aggregation` must be one of `mean`, `median`, `min`, `max` or a custom callable functionwhich takes tensor of values, but got Ú.r!   )ÚdefaultÚdist_reduce_fxr"   r#   r   )ÚsuperÚ__init__Úallow_non_binary_targetÚ
ValueErrorr%   Ú
isinstanceÚintr&   Úcallabler   Ú	add_state)Úselfr%   r&   r   r'   Zempty_target_action_options©Ú	__class__r   r   r/   i   s&   ÿÿzRetrievalMetric.__init__c                 C   sT   |du rt dƒ‚t|||| j| jd�\}}}| j |¡ | j |¡ | j |¡ dS )zGCheck shape, check and convert dtypes, flatten and add to accumulators.Nz!Argument `indexes` cannot be None)r0   r&   )r1   r   r0   r&   r!   Úappendr"   r#   )r6   r"   r#   r!   r   r   r   Úupdate‡   s   ÿzRetrievalMetric.updatec                    s  t | jƒ}t | jƒ‰ t | jƒ}t |¡\}}ˆ | ‰ || }t|ƒ ¡  ¡  	¡ }g }t
tjˆ |dd�tj||dd�ƒD ]4\}}| ¡ sf| jdkrLtdƒ‚| jdkrY| tdƒ¡ q;| jdkre| tdƒ¡ q;| |  ||¡¡ q;|r‚tt ‡ fd	d
„|D ƒ¡| jƒS tdƒ ˆ ¡S )a„  First concat state ``indexes``, ``preds`` and ``target`` since they were stored as lists.

        After that, compute list of groups that will help in keeping together predictions about the same query. Finally,
        for each group compute the ``_metric`` if the number of positive targets is at least 1, otherwise behave as
        specified by ``self.empty_target_action``.

        r   r   r(   zC`compute` method was provided with a query with no positive target.r*   g      ð?r$   g        c                    s   g | ]}|  ˆ ¡‘qS r   )Úto)Ú.0Úx©r"   r   r   Ú
<listcomp>¶   s    z+RetrievalMetric.compute.<locals>.<listcomp>)r   r!   r"   r#   ÚtorchÚsortr   ÚdetachÚcpuÚtolistÚzipÚsplitÚsumr%   r1   r9   r
   Ú_metricr   Ústackr   r;   )r6   r!   r#   ÚindicesÚsplit_sizesÚresZ
mini_predsZmini_targetr   r>   r   Úcompute”   s.   


ÿ


€ zRetrievalMetric.computec                 C   s   dS )z„Compute a metric over a predictions and target of a single group.

        This method should be overridden by subclasses.

        Nr   )r6   r"   r#   r   r   r   rH   ¹   s    zRetrievalMetric._metric)r$   Nr   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r    r   r	   Ústrr   r3   r   r   r   r   r/   r:   rM   r   rH   Ú__classcell__r   r   r7   r   r   +   s4   
 5üþýüûú% r   )r   N)Úabcr   r   Útypingr   r   r   r   r   r@   r	   r
   Útyping_extensionsr   Útorchmetricsr   Útorchmetrics.utilities.checksr   Útorchmetrics.utilities.datar   r   r3   r   r   r   r   r   r   Ú<module>   s(   ýÿþý
ü