o
    ²ôjU2  ã                   @   sú  d dl Z d dl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mZmZmZ d dlmZ d dlZd dlmZ d dlmZ eej d	d
¡ƒZeej dd ¡ƒZdededefdd„Zdededdfdd„Z	d5dedededeeef fdd„Z		d6dededededee deeeef fdd„Z	d5dedededeeef fdd„Z d7deded e!defd!d"„Z"eddg d#¢d$fd%ed&ee#e$ef  d'ee#e$ef  d(ee d)eddfd*d+„ƒZ%d,e$d-e&d.e&defd/d0„Z'efd1ed2edefd3d4„Z(dS )8é    N)ÚMappingÚSequence)Úpartial)Úperf_counter)ÚAnyÚCallableÚOptionalÚno_type_check)ÚMock)ÚTensor)ÚMetricZDOCTEST_DOWNLOAD_TIMEOUTéx   ZSKIP_SLOW_DOCTESTÚpredsÚtargetÚreturnc                 C   s    |   ¡ |  ¡   kodkS   S )Nr   )Únumel©r   r   © r   úp/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/utilities/checks.pyÚ_check_for_empty_tensors    s    r   c                 C   s*   | j |j krtd| j › d|j › d�ƒ‚dS )zHCheck that predictions and target have the same shape, else raise error.zEPredictions and targets are expected to have the same shape, but got z and Ú.N)ÚshapeÚRuntimeErrorr   r   r   r   Ú_check_same_shape$   s
   ÿÿr   FÚallow_non_binary_targetc                 C   s:   | j |j kr
tdƒ‚|  ¡ r|  ¡ stdƒ‚t| ||d�S )a9  Check ``preds`` and ``target`` tensors are of the same shape and of the correct data type.

    Args:
        preds: either tensor with scores/logits
        target: tensor with ground true labels
        allow_non_binary_target: whether to allow target to contain non-binary values

    Raises:
        ValueError:
            If ``preds`` and ``target`` don't have the same shape, if they are empty
            or not of the correct ``dtypes``.

    Returns:
        preds: as torch.float32
        target: as torch.long if not floating point else torch.float32

    z.`preds` and `target` must be of the same shapez=`preds` and `target` must be non-empty and non-scalar tensors©r   )r   Ú
ValueErrorr   ÚsizeÚ,_check_retrieval_target_and_prediction_types©r   r   r   r   r   r   Ú"_check_retrieval_functional_inputs,   s
   r    ÚindexesÚignore_indexc                 C   sœ   | j |j ks|j |j krtdƒ‚| jtjurtdƒ‚|dur0||k}| | || || } }}|  ¡ r8|  ¡ s<tdƒ‚t|||d�\}}|  ¡  ¡ ||fS )a²  Check ``indexes``, ``preds`` and ``target`` tensors are of the same shape and of the correct data type.

    Args:
        indexes: tensor with queries indexes
        preds: tensor with scores/logits
        target: tensor with ground true labels
        allow_non_binary_target: whether to allow target to contain non-binary values
        ignore_index: ignore predictions where targets are equal to this number

    Raises:
        ValueError:
            If ``preds`` and ``target`` don't have the same shape, if they are empty or not of the correct ``dtypes``.

    Returns:
        indexes: as ``torch.long``
        preds: as ``torch.float32``
        target: as ``torch.long``

    z9`indexes`, `preds` and `target` must be of the same shapez+`indexes` must be a tensor of long integersNzH`indexes`, `preds` and `target` must be non-empty and non-scalar tensorsr   )	r   r   ÚdtypeÚtorchÚlongr   r   r   Úflatten)r!   r   r   r   r"   Úvalid_positionsr   r   r   Ú_check_retrieval_inputsK   s   ÿ
ÿr(   c                 C   sŒ   |j tjtjtjfvrt |¡stdƒ‚|  ¡ stdƒ‚|s.| ¡ dks*| ¡ dk r.tdƒ‚| ¡ r6| 	¡ n| ¡ }|  	¡ } |  
¡ | 
¡ fS )a¸  Check ``preds`` and ``target`` tensors are of the same shape and of the correct data type.

    Args:
        preds: either tensor with scores/logits
        target: tensor with ground true labels
        allow_non_binary_target: whether to allow target to contain non-binary values

    Raises:
        ValueError:
            If ``preds`` and ``target`` don't have the same shape, if they are empty or not of the correct ``dtypes``.

    z9`target` must be a tensor of booleans, integers or floatsz"`preds` must be a tensor of floatsé   r   z%`target` must contain `binary` values)r#   r$   Úboolr%   ÚintÚis_floating_pointr   ÚmaxÚminÚfloatr&   r   r   r   r   r   |   s    r   ç�íµ ÷Æ°>Úres1Úres2Úatolc                    sx   t ˆ tƒrtjˆ ˆ|d�S t ˆ tƒrˆ ˆkS t ˆ tƒr'tdd„ tˆ ˆƒD ƒƒS t ˆ tƒr8t‡ ‡fdd„ˆ D ƒƒS ˆ ˆkS )zFRecursively asserting that two results are within a certain tolerance.)r3   c                 s   s   � | ]
\}}t ||ƒV  qd S ©N©Ú_allclose_recursive)Ú.0Úr1Úr2r   r   r   Ú	<genexpr>¤   s   € z&_allclose_recursive.<locals>.<genexpr>c                 3   s"   � | ]}t ˆ | ˆ| ƒV  qd S r4   r5   )r7   Úk©r1   r2   r   r   r:   ¦   s   €  )	Ú
isinstancer   r$   ÚallcloseÚstrr   ÚallÚzipr   )r1   r2   r3   r   r<   r   r6   œ   s   



r6   )é
   éd   iè  é   Úmetric_classÚ	init_argsÚ
input_argsÚnum_update_to_compareÚrepsc              
   C   s*  |pi }|pi }G dd„ d| ƒ}G dd„ d| ƒ}|di |¤Ž}|di |¤Ž}d}	zt |d ƒD ]}
|	t|di |¤Ž|di |¤Žƒ@ }	q/W n tyO   d}	Y nw | ¡ }z| ¡ }W n tye   d}	Y nw |	t||ƒ@ }	|	sutdƒ d	S t d
t|ƒ|¡}t||gƒD ]5\}}t|ƒD ],\}}t |ƒD ]#}t	ƒ }t |ƒD ]	}
|di |¤Ž}
q�t	ƒ }|| ||||f< | 
¡  q”qŒq„t |d¡}t |d¡}t t|ƒƒD ]3}td|| › d|d|f › d|d|f d›�ƒ td|| › d|d|f d›d|d|f d›�ƒ qÌ|d |d k  ¡ }td| › d�ƒ d	S )aÝ  Check if the new ``full_state_update`` property works as intended.

    This function checks if the property can safely be set to ``False`` which will for most metrics results in a
    speedup when using ``forward``.

    Args:
        metric_class: metric class object that should be checked
        init_args: dict containing arguments for initializing the metric class
        input_args: dict containing arguments to pass to ``forward``
        num_update_to_compare: if we successfully detect that the flag is safe to set to ``False``
            we will run some speedup test. This arg should be a list of integers for how many
            steps to compare over.
        reps: number of repetitions of speedup test

    Example (states in ``update`` are independent, save to set ``full_state_update=False``)
        >>> from torchmetrics.classification import MulticlassConfusionMatrix
        >>> check_forward_full_state_property(  # doctest: +SKIP
        ...     MulticlassConfusionMatrix,
        ...     init_args = {'num_classes': 3},
        ...     input_args = {'preds': torch.randint(3, (100,)), 'target': torch.randint(3, (100,))},
        ... )
        Full state for 10 steps took: ...
        Partial state for 10 steps took: ...
        Full state for 100 steps took: ...
        Partial state for 100 steps took: ...
        Full state for 1000 steps took: ...
        Partial state for 1000 steps took: ...
        Recommended setting `full_state_update=False`

    Example (states in ``update`` are dependent meaning that ``full_state_update=True``):
        >>> from torchmetrics.classification import MulticlassConfusionMatrix
        >>> class MyMetric(MulticlassConfusionMatrix):
        ...     def update(self, preds, target):
        ...         super().update(preds, target)
        ...         # by construction make future states dependent on prior states
        ...         if self.confmat.sum() > 20:
        ...             self.reset()
        >>> check_forward_full_state_property(
        ...     MyMetric,
        ...     init_args = {'num_classes': 3},
        ...     input_args = {'preds': torch.randint(3, (10,)), 'target': torch.randint(3, (10,))},
        ... )
        Recommended setting `full_state_update=True`

    c                   @   ó   e Zd ZdZdS )z4check_forward_full_state_property.<locals>.FullStateTN©Ú__name__Ú
__module__Ú__qualname__Zfull_state_updater   r   r   r   Ú	FullStateâ   ó    rO   c                   @   rJ   )z4check_forward_full_state_property.<locals>.PartStateFNrK   r   r   r   r   Ú	PartStateå   rP   rQ   Tr   Fz,Recommended setting `full_state_update=True`Né   éÿÿÿÿzFull state for z steps took: z+-z0.3fzPartial state for r)   )r)   rS   )r   rS   z'Recommended setting `full_state_update=ú`r   )Úranger6   r   ÚcomputeÚprintr$   ÚzerosÚlenÚ	enumerater   ÚresetÚmeanÚstdÚitem)rE   rF   rG   rH   rI   rO   rQ   Z	fullstateZ	partstateÚequalÚ_r1   r2   ÚresÚiÚmetricÚjÚtÚrÚstartÚendr\   r]   Zfasterr   r   r   Ú!check_forward_full_state_propertyª   sX   5$ÿÿÿ
úÿ	04ri   Úmethod_nameÚinstanceÚparentc                 C   s~   t || dƒ}|du rdS t|dƒr|j}t|tƒr|j}nt|tƒr%|j}|du r+dS t || dƒ}|du r9tdƒ‚|j	|j	kS )zRCheck if a method has been overridden by an instance compared to its parent class.NFÚ__wrapped__z#The parent should define the method)
ÚgetattrÚhasattrrm   r=   r
   Ú_mock_wrapsr   Úfuncr   Ú__code__)rj   rk   rl   Úinstance_attrÚparent_attrr   r   r   Úis_overridden  s   


ru   ÚfnÚtimeoutc                 C   s€   t  ¡ jrdS t j| d�}td| j› d|› d�tjd� | ¡  | 	|¡ | 
¡ s+dS td| j› d|› d	�tjd� | ¡  d
S )aY  Check if a certain function is taking too long to execute.

    Function will only be executed if running inside a doctest context. Currently, does not support Windows.

    Args:
        fn: function to check
        timeout: timeout for function

    Returns:
        Bool indicating if the function finished within the specified timeout

    T)r   zTrying to run `z` for zs...)ÚfilerT   z` did not complete with z%, killing process and returning FalseF)ÚmultiprocessingÚcurrent_processÚdaemonÚProcessrW   rL   ÚsysÚstderrrg   ÚjoinÚis_aliveÚkill)rv   rw   Úprocr   r   r   Ú_try_proceed_with_timeout-  s   

rƒ   )F)FN)r0   ))ry   Úosr}   Úcollections.abcr   r   Ú	functoolsr   Útimer   Útypingr   r   r   r	   Úunittest.mockr
   r$   r   Útorchmetrics.metricr   r+   ÚenvironÚgetZ_DOCTEST_DOWNLOAD_TIMEOUTr*   Z_SKIP_SLOW_DOCTESTr   r   Útupler    r(   r   r/   r6   Údictr?   ri   Úobjectru   rƒ   r   r   r   r   Ú<module>   sŽ   ýÿþý

ü#ûÿþýüû
ú4ýÿþý

ü ûÿþýüûúi