o
    yi                     @   s  d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZm	Z	m
Z
mZ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mZ d dlmZ 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dedede dee dee! ddfddZ"dededeee!f fddZ#de!dee ddfddZ$dedede!dee de!ddfddZ%de!dee de!ddfd d!Z&d"e!d#e'de!dee d$eddfd%d&Z(	dQdedede dee! dee d"ee! dee! defd'd(Z)dededeeef fd)d*Z*	+				dRdedede d"ee! dee! dee dee! deeeef fd,d-Z+	+	.dSde!dedede d/edeeef fd0d1Z,	.dTdeded2edeeef fd3d4Z-	.	dUd5ededed2edee! deeeef fd6d7Z.	.dTdeded2edeeef fd8d9Z/dVd;ed<ed=e defd>d?Z0ei i g d@dAfdBe
e'ef dCe
e'ef dDee! dEe!def
dFdGZ1dHe'dIe2dJe2defdKdLZ3efdMe	dNe!defdOdPZ4dS )W    N)partial)perf_counter)AnyCallableDictMappingOptionalSequenceTupleno_type_check)Mock)Tensor)select_topk	to_onehot)DataTypeDOCTEST_DOWNLOAD_TIMEOUTx   SKIP_SLOW_DOCTESTpredstargetreturnc                 C   s(   |   |    krdkrdS  dS dS )Nr   TF)numelr   r    r   Q/home/ubuntu/.local/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   	threshold
multiclassignore_indexc                 C   s   t | |rdS | rtd|du r| dk rtd|dur/|dkr/| dk r/td|  }|s?|  dk r?td| jd |jd ksMtd|du r[| dkr[td	|du rk|sm|  dkrotd
dS dS dS )zhPerform basic validation of inputs that does not require deducing any information of the type of inputs.Nz)The `target` has to be an integer tensor.r   z-The `target` has to be a non-negative tensor.z6If `preds` are integers, they have to be non-negative.z>The `preds` and `target` should have the same first dimension.F   zAIf you set `multiclass=False`, then `target` should not exceed 1.zYIf you set `multiclass=False` and `preds` are integers, then `preds` should not exceed 1.)r   is_floating_point
ValueErrorminr   max)r   r   r    r!   r"   preds_floatr   r   r   _basic_input_validation.   s$   
r)   c                 C   sT  |   }| j|jkrf| j|jkrtdd| j d|j d|r0| dkr0| dkr0td| jdkr;|r;tj}n| jdkrF|sFtj}n| jdkrQ|rQtj	}ntj
}|  dkr`| d  nd}||fS | j|jd kr|sttd| jd	d
 |jdd
 krtd|  dkr| jd nd}| jd	krtj}||fS tj
}||fS td)a  This checks that the shape and type of inputs are consistent with each other and fall into one of the
    allowed input types (see the documentation of docstring of ``_input_format_classification``). It does not check
    for consistency of number of classes, other functions take care of that.

    It returns the name of the case in which the inputs fall, and the implied number of classes (from the ``C`` dim for
    multi-class data, or extra dim(s) for multi-label data).
    z4The `preds` and `target` should have the same shape,z got `preds` with shape=z and `target` with shape=r   r   r#   z`If `preds` and `target` are of shape (N, ...) and `preds` are floats, `target` should be binary.zSIf `preds` have one dimension more than `target`, `preds` should be a float tensor.   NzIf `preds` have one dimension more than `target`, the shape of `preds` should be (N, C, ...), and the shape of `target` should be (N, ...).zEither `preds` and `target` both should have the (same) shape (N, ...), or `target` should be (N, ...) and `preds` should be (N, C, ...).)r$   ndimr   r%   r   r'   r   BINARY
MULTICLASS
MULTILABELMULTIDIM_MULTICLASS)r   r   r(   caseimplied_classesr   r   r   !_check_shape_and_type_consistencyL   sH   	
	r2   num_classesc                 C   s@   | dkrt d| dkr|st d| dkr|rt ddS dS )zgThis checks that the consistency of `num_classes` with the data and `multiclass` param for binary data.r*   z8Your data is binary, but `num_classes` is larger than 2.zYour data is binary and `num_classes=2`, but `multiclass` is not True. Set it to True if you want to transform binary data to multi-class format.r#   zYou have binary data and have set `multiclass=True`, but `num_classes` is 1. Either set `multiclass=None`(default) or set `num_classes=2` to transform binary data to multi-class format.Nr%   )r3   r!   r   r   r   _check_num_classes_binary   s   r5   r1   c                 C   s   |dkr|durt d|dkr:|du r||krt d| dkr,|| kr,t d| j|jkr<||kr>t ddS dS dS )	zThis checks that the consistency of `num_classes` with the data and `multiclass` param for (multi-
    dimensional) multi-class data.r#   FzYou have set `num_classes=1`, but predictions are integers. If you want to convert (multi-dimensional) multi-class data with 2 classes to binary/multi-label, set `multiclass=False`.aU  You have set `multiclass=False`, but the implied number of classes  (from shape of inputs) does not match `num_classes`. If you are trying to transform multi-dim multi-class data with 2 classes to multi-label, `num_classes` should be either None or the product of the size of extra dimensions (...). See Input Types in Metrics documentation.r   zCThe highest label in `target` should be smaller than `num_classes`.z@The size of C dimension of `preds` does not match `num_classes`.N)r%   r   r'   r   )r   r   r3   r!   r1   r   r   r   _check_num_classes_mc   s   
r6   c                 C   s0   |r
| dkr
t d|s| |krt ddS dS )ztThis checks that the consistency of ``num_classes`` with the data and ``multiclass`` param for multi-label
    data.r*   zYour have set `multiclass=True`, but `num_classes` is not equal to 2. If you are trying to transform multi-label data to 2 class multi-dimensional multi-class, you should set `num_classes` to either 2 or None.zPThe implied number of classes (from shape of inputs) does not match num_classes.Nr4   )r3   r!   r1   r   r   r   _check_num_classes_ml   s   r7   top_kr0   r(   c                 C   sr   |t jkr	tdt| tr| dkrtd|std|du r$td|t jkr/|r/td| |kr7tdd S )	Nz3You can not use `top_k` parameter with binary data.r   z/The `top_k` has to be an integer larger than 0.zBYou have set `top_k`, but you do not have probability predictions.Fz7If you set `multiclass=False`, you can not set `top_k`.zIf you want to transform multi-label data to 2 class multi-dimensionalmulti-class data using `multiclass=True`, you can not use `top_k`.zIThe `top_k` has to be strictly smaller than the `C` dimension of `preds`.)r   r,   r%   
isinstanceintr.   )r8   r0   r1   r!   r(   r   r   r   _check_top_k   s   
r;   c           	      C   s   t | |||| t| |\}}| j|jkr+|du r!|dkr!td| |kr+td|rR|tjkr8t|| n|tjtj	fv rIt
| |||| n	|jrRt||| |dur`t|||||   |S )a'  Performs error checking on inputs for classification.

    This ensures that preds and target take one of the shape/type combinations that are
    specified in ``_input_format_classification`` docstring. It also checks the cases of
    over-rides with ``multiclass`` by checking (for multi-class and multi-dim multi-class
    cases) that there are only up to 2 distinct labels.

    In case where preds are floats (probabilities), it is checked whether they are in ``[0,1]`` interval.

    When ``num_classes`` is given, it is checked that it is consistent with input cases (binary,
    multi-label, ...), and that, if available, the implied number of classes in the ``C``
    dimension is consistent with it (as well as that max label in target is smaller than it).

    When ``num_classes`` is not specified in these cases, consistency of the highest target
    value against ``C`` dimension is checked for (multi-dimensional) multi-class cases.

    If ``top_k`` is set (not None) for inputs that do not have probability predictions (and
    are not binary), an error is raised. Similarly, if ``top_k`` is set to a number that
    is higher than or equal to the ``C`` dimension of ``preds``, an error is raised.

    Preds and target tensors are expected to be squeezed already - all dimensions should be
    greater than 1, except perhaps the first one (``N``).

    Args:
        preds: Tensor with predictions (labels or probabilities)
        target: Tensor with ground truth labels, always integers (labels)
        threshold:
            Threshold value for transforming probability/logit predictions to binary
            (0,1) predictions, in the case of binary or multi-label inputs.
        num_classes:
            Number of classes. If not explicitly set, the number of classes will be inferred
            either from the shape of inputs, or the maximum label in the ``target`` and ``preds``
            tensor, where applicable.
        top_k:
            Number of the highest probability entries for each sample to convert to 1s - relevant
            only for inputs with probability predictions. The default value (``None``) will be
            interpreted as 1 for these inputs. If this parameter is set for multi-label inputs,
            it will take precedence over threshold.

            Should be left unset (``None``) for inputs with label predictions.
        multiclass:
            Used only in certain special cases, where you want to treat inputs as a different type
            than what they appear to be. See the parameter's
            :ref:`documentation section <pages/overview:using the multiclass parameter>`
            for a more detailed explanation and examples.


    Return:
        case: The case the inputs fall in, one of 'binary', 'multi-class', 'multi-label' or
            'multi-dim multi-class'
    Fr*   zpYou have set `multiclass=False`, but have more than 2 classes in your data, based on the C dimension of `preds`.z^The highest label in `target` should be smaller than the size of the `C` dimension of `preds`.N)r)   r2   r   r%   r'   r   r,   r5   r-   r/   r6   r.   r7   r;   r$   )	r   r   r    r3   r!   r8   r"   r0   r1   r   r   r   _check_classification_inputs   s*   >
r<   c                 C   sN   | j d dkr|  d| d} }| |fS |  | } }| |fS )zRemove excess dimensions.r   r#   )r   squeeze	unsqueezer   r   r   r   _input_squeeze5  s
   r?         ?c              	   C   s  t | |\} }| jtjkr|  } t| ||||||d}|tjtjfv r2|s2| |k	 } |s0|nd}|tjkr>|r>t
| |} |tjtjfv sH|r|  rY| jd }t
| |pVd} n|r]|n
t|  | d }t| td|} t|td|}|du r| ddddf |ddddf } }t| |s|tjtjfv r|dus|r||jd |jd d}| | jd | jd d} n||jd d}| | jd d} | jdkr| d|d} }| 	 |	 |fS )	aU  Convert preds and target tensors into common format.

    Preds and targets are supposed to fall into one of these categories (and are
    validated to make sure this is the case):

    * Both preds and target are of shape ``(N,)``, and both are integers (multi-class)
    * Both preds and target are of shape ``(N,)``, and target is binary, while preds
      are a float (binary)
    * preds are of shape ``(N, C)`` and are floats, and target is of shape ``(N,)`` and
      is integer (multi-class)
    * preds and target are of shape ``(N, ...)``, target is binary and preds is a float
      (multi-label)
    * preds are of shape ``(N, C, ...)`` and are floats, target is of shape ``(N, ...)``
      and is integer (multi-dimensional multi-class)
    * preds and target are of shape ``(N, ...)`` both are integers (multi-dimensional
      multi-class)

    To avoid ambiguities, all dimensions of size 1, except the first one, are squeezed out.

    The returned output tensors will be binary tensors of the same shape, either ``(N, C)``
    of ``(N, C, X)``, the details for each case are described below. The function also returns
    a ``case`` string, which describes which of the above cases the inputs belonged to - regardless
    of whether this was "overridden" by other settings (like ``multiclass``).

    In binary case, targets are normally returned as ``(N,1)`` tensor, while preds are transformed
    into a binary tensor (elements become 1 if the probability is greater than or equal to
    ``threshold`` or 0 otherwise). If ``multiclass=True``, then both targets are preds
    become ``(N, 2)`` tensors by a one-hot transformation; with the thresholding being applied to
    preds first.

    In multi-class case, normally both preds and targets become ``(N, C)`` binary tensors; targets
    by a one-hot transformation and preds by selecting ``top_k`` largest entries (if their original
    shape was ``(N,C)``). However, if ``multiclass=False``, then targets and preds will be
    returned as ``(N,1)`` tensor.

    In multi-label case, normally targets and preds are returned as ``(N, C)`` binary tensors, with
    preds being binarized as in the binary case. Here the ``C`` dimension is obtained by flattening
    all dimensions after the first one. However, if ``multiclass=True``, then both are returned as
    ``(N, 2, C)``, by an equivalent transformation as in the binary case.

    In multi-dimensional multi-class case, normally both target and preds are returned as
    ``(N, C, X)`` tensors, with ``X`` resulting from flattening of all dimensions except ``N`` and
    ``C``. The transformations performed here are equivalent to the multi-class case. However, if
    ``multiclass=False`` (and there are up to two classes), then the data is returned as
    ``(N, X)`` binary tensors (multi-label).

    Note:
        Where a one-hot transformation needs to be performed and the number of classes
        is not implicitly given by a ``C`` dimension, the new ``C`` dimension will either be
        equal to ``num_classes``, if it is given, or the maximum label value in preds and
        target.

    Args:
        preds: Tensor with predictions (labels or probabilities)
        target: Tensor with ground truth labels, always integers (labels)
        threshold:
            Threshold value for transforming probability/logit predictions to binary
            (0 or 1) predictions, in the case of binary or multi-label inputs.
        num_classes:
            Number of classes. If not explicitly set, the number of classes will be inferred
            either from the shape of inputs, or the maximum label in the ``target`` and ``preds``
            tensor, where applicable.
        top_k:
            Number of the highest probability entries for each sample to convert to 1s - relevant
            only for (multi-dimensional) multi-class inputs with probability predictions. The
            default value (``None``) will be interpreted as 1 for these inputs.

            Should be left unset (``None``) for all other types of inputs.
        multiclass:
            Used only in certain special cases, where you want to treat inputs as a different type
            than what they appear to be. See the parameter's
            :ref:`documentation section <pages/overview:using the multiclass parameter>`
            for a more detailed explanation and examples.

    Returns:
        preds: binary tensor of shape ``(N, C)`` or ``(N, C, X)``
        target: binary tensor of shape ``(N, C)`` or ``(N, C, X)``
        case: The case the inputs fall in, one of ``'binary'``, ``'multi-class'``, ``'multi-label'`` or
            ``'multi-dim multi-class'``
    )r    r3   r!   r8   r"   r*   r#   FN.r   )r?   dtypetorchfloat16floatr<   r   r,   r.   r:   r   r-   r/   r$   r   r'   r   r   reshaper+   r=   )r   r   r    r8   r3   r!   r"   r0   r   r   r   _input_format_classificationA  sF   Z


&

rG   F
multilabelc                 C   s   |j |j |j d fvrtd|j |j d krtj|dd}|j |j kr@|jtjtjfv r@| dkr@|s@t|| d}t|| d}n|j |j krP| rP||k }|j dkra|	dd}|	dd}|
| d|
| dfS )a  Convert preds and target tensors into one hot spare label tensors.

    Args:
        num_classes: number of classes
        preds: either tensor with labels, tensor with probabilities/logits or multilabel tensor
        target: tensor with ground-true labels
        threshold: float used for thresholding multilabel input
        multilabel: boolean flag indicating if input is multilabel

    Raises:
        ValueError:
            If ``preds`` and ``target`` don't have the same number of dimensions
            or one additional dimension for ``preds``.

    Returns:
        preds: one hot tensor of shape [num_classes, -1] with predicted labels
        target: one hot tensors of shape [num_classes, -1] with true labels
    r#   z[preds and target must have same number of dimensions, or one additional dimension for preds)dim)r3   r   rA   )r+   r%   rC   argmaxrB   longr:   r   r$   	transposerF   )r3   r   r   r    rH   r   r   r   $_input_format_classification_one_hot  s   *
rM   allow_non_binary_targetc                 C   s:   | j |j kr
td|  r|  stdt| ||dS )a8  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rN   )r   r%   r   size,_check_retrieval_target_and_prediction_typesr   r   rN   r   r   r   "_check_retrieval_functional_inputs   s
   rS   indexesc                 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
        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 tensorsrO   )	r   r%   rB   rC   rK   r   rP   rQ   flatten)rT   r   r   rN   r"   valid_positionsr   r   r   _check_retrieval_inputs  s   
rW   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 floatsr#   r   z%`target` must contain `binary` values)rB   rC   boolrK   r:   r$   r%   r'   r&   rE   rU   rR   r   r   r   rQ   M  s    rQ   ư>res1res2atolc                    s|   t  trtj |dS t  tr kS t  tr'tdd t D S t  tr:t fdd 	 D S  kS )z[Utility function for recursively asserting that two results are within a certain tolerance.)r\   c                 s   s    | ]
\}}t ||V  qd S N_allclose_recursive).0r1r2r   r   r   	<genexpr>t  s    z&_allclose_recursive.<locals>.<genexpr>c                 3   s"    | ]}t  | | V  qd S r]   r^   )r`   krZ   r[   r   r   rc   v  s     )
r9   r   rC   allclosestrr	   allzipr   keys)rZ   r[   r\   r   re   r   r_   l  s   



r_   )
   d   i     	init_args
input_argsnum_update_to_comparerepsc              
   C   s$  G dd d| }G dd d| }|di |}|di |}d}	t |d D ]&}
|di |}z	|di |}W n tyD   d}	Y  n	w |	t||@ }	q&| }z| }W n tyb   d}	Y nw |	t||@ }	|	srtd d	S td
t||}t||gD ]5\}}t|D ],\}}t |D ]#}t	 }t |D ]	}
|di |}
qt	 }|| ||||f< |
  qqqt|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  Utility function for checking if the new ``full_state_update`` 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 detech 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: +ELLIPSIS
        ...     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 dependend 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__full_state_updater   r   r   r   	FullState      rx   c                   @   rr   )z4check_forward_full_state_property.<locals>.PartStateFNrs   r   r   r   r   	PartState  ry   rz   Tr   Fz,Recommended setting `full_state_update=True`Nr*   rA   zFull state for z steps took: z+-z0.3fzPartial state for r#   )r#   rA   )r   rA   z'Recommended setting `full_state_update=`r   )ranger   r_   computeprintrC   zeroslen	enumerater   resetmeanstditem)metric_classrn   ro   rp   rq   rx   rz   	fullstate	partstateequal_out1out2rZ   r[   resimetricjtrstartendr   r   fasterr   r   r   !check_forward_full_state_propertyz  sV   3
	04r   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hasattrr   r9   r   _mock_wrapsr   funcr%   __code__)r   r   r   instance_attrparent_attrr   r   r   is_overridden  s   


r   fntimeoutc                 C   sR   t j| d}|  || | sdS td| j d |  |  dS )ag  Function for checking 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
    )r   Tz	running `z`... let's kill it...F)	multiprocessingProcessr   joinis_aliveloggingwarningrt   	terminate)r   r   procr   r   r   _try_proceed_with_timeout  s   
r   r]   )r@   NNNN)r@   F)F)FN)rY   )5r   r   os	functoolsr   timer   typingr   r   r   r   r   r	   r
   r   unittest.mockr   rC   r   torchmetrics.utilities.datar   r   torchmetrics.utilities.enumsr   environget_DOCTEST_DOWNLOAD_TIMEOUTrX   _SKIP_SLOW_DOCTESTr   r   rE   r:   r)   r2   r5   r6   r7   rg   r;   r<   r?   rG   rM   rS   rW   rQ   r_   r   objectr   r   r   r   r   r   <module>   sD  (
9
&
_


 

4

"
2



g