o
    .wi                     @   sJ  d dl Z d dlZd dlZd dlmZm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mZmZ d dlZd dlm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! d dl"m#Z# d dl$m%Z% d dl&m'Z' d dl(m)Z)m*Z*m+Z+ d dl,m-Z- de.fddZ/G dd deeZ0dedefddZ1G dd de0Z2dS )    N)ABCabstractmethod)	GeneratorSequence)contextmanagerdeepcopy)AnyCallableClassVarListOptionalUnion)apply_to_collection)Tensor)Module)_flatten_squeeze_if_scalardim_zero_catdim_zero_maxdim_zero_meandim_zero_mindim_zero_sum)gather_all_tensors)TorchMetricsUserError)_TORCH_GREATER_EQUAL_2_1)_AX_TYPE_PLOT_OUT_TYPEplot_single_or_multi_val)rank_zero_warnreturnc                   C   s   t j o	t j S )z-Determine if distributed mode is initialized.)torchdistributedis_availableis_initialized r%   r%   P/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/metric.pyjit_distributed_available/      r'   c                       s  e Zd ZU dZdgZeee  ed< g dZ	eee  ed< dZ
ee ed< dZee ed< dZee ed	< dZee ed
< dZee ed< dZee ed< deddf fddZedefddZedefddZedefddZedeeeee ef f fddZ		ddedeeef deeeef  deddf
ddZ e!j"j#d ededefd!d"Z$d ededefd#d$Z%d ededefd%d&Z&d'eeeef d f ddfd(d)Z'd'eeef ddfd*d+Z(e)dfd,ed-ee ddfd.d/Z*d0edefd1d2Z+dd3d4Z,			5	dd,ee d-ee d6ed7ee ddf
d8d9Z-dd:eddfd;d<Z.e/			5	5	dd,ee d-ee d6ed:ed7ee de0fd=d>Z1d?edefd@dAZ2e3dBedCeddfdDdEZ4e3defdFdGZ5dBedCedefdHdIZ6		ddJeeee7e eeef e7eeef  f  dKee8 de9fdLdMZ:ddNdOZ;ddPdQZ<deeef fdRdSZ=dTeeef ddfdUdVZ>dedWeddf fdXdYZ?edd[d\Z@edd^d_ZAd`eee!jAf dd fdadbZBddcddZddedfZCddgdhZDd`eee!jAf dd f fdidjZEddledme7e deFf fdndoZGddpeddfdqdrZH		k	ddseeeef  dteduedeeef f fdvdwZIdeeeeee f f fdxdyZJdzedted{ed|ed}ee d~ee dee ddf fddZKdedeeef fddZLdefddZMded eNjef ddfddZOded eNjef ddfddZPded eNjef ddfddZQded eNjef ddfddZRded eNjef ddfddZSded eNjef ddfddZTded eNjef ddfddZUded eNjef ddfddZVded eNjef ddfddZWded eNjef ddfddZXded eNjef ddfddZYded eNjef ddfddZZded eNjef ddfddZ[ded eNjef ddfddZ\ded eNjef ddfddZ]ded eNjef ddfddZ^dddZ_ded eNjef ddfddZ`ded eNjef ddfddZaded eNjef ddfddZbded eNjef ddfddZcded eNjef ddfddZdded eNjef ddfddZeded eNjef ddfddZfded eNjef ddfddZgded eNjef ddfddZhded eNjef ddfddZided eNjef ddfddZjdddZkdddÄZldddńZmdddǄZndddɄZodeddfdd̄Zpdeqfdd΄ZrdZs  ZtS )MetricaF  Base class for all metrics present in the Metrics API.

    This class is inherited by all metrics and implements the following functionality:

        1. Handles the transfer of metric states to the correct device.
        2. Handles the synchronization of metric states across processes.
        3. Provides properties and methods to control the overall behavior of the metric and its states.

    The three core methods of the base class are: ``add_state()``, ``forward()`` and ``reset()`` which should almost
    never be overwritten by child classes. Instead, the following methods should be overwritten ``update()`` and
    ``compute()``.

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

            - **compute_on_cpu**:
                If metric state should be stored on CPU during computations. Only works for list states.
            - **dist_sync_on_step**:
                If metric state should synchronize on ``forward()``. Default is ``False``.
            - **process_group**:
                The process group on which the synchronization is called. Default is the world.
            - **dist_sync_fn**:
                Function that performs the allgather option on the metric state. Default is a custom
                implementation that calls ``torch.distributed.all_gather`` internally.
            - **distributed_available_fn**:
                Function that checks if the distributed backend is available. Defaults to a
                check of ``torch.distributed.is_available()`` and ``torch.distributed.is_initialized()``.
            - **sync_on_compute**:
                If metric state should synchronize when ``compute`` is called. Default is ``True``.
            - **compute_with_cache**:
                If results from ``compute`` should be cached. Default is ``True``.

    device__jit_ignored_attributes__)is_differentiablehigher_is_betterplot_lower_boundplot_upper_boundplot_legend_namemetric_state_update_called__jit_unused_properties__Nr,   r-   full_state_updater.   r/   r0   kwargsr    c                    s  t    tjd| jj  tt| _t	d| _
t | _|dd| _t| jts5td| j |dd| _t| jtsJtd| j |dd | _|d	d | _| jd urjt| jsjtd
| j |dd pqt| _|dd| _t| jtstd| j |dd| _t| jtstd| j |rdd t|D }tdd| t| j| _| | j| _|  | j!| _!d | _"d | _#d| _$| j| _%d| _&d| _'d| _(i | _)i | _*i | _+d| _,d | _-d S )Nztorchmetrics.metric.cpucompute_on_cpuFzCExpected keyword argument `compute_on_cpu` to be an `bool` but got dist_sync_on_stepzFExpected keyword argument `dist_sync_on_step` to be an `bool` but got process_groupdist_sync_fnzLExpected keyword argument `dist_sync_fn` to be an callable function but got distributed_available_fnsync_on_computeTzCExpected keyword argument `sync_on_compute` to be a `bool` but got compute_with_cachezFExpected keyword argument `compute_with_cache` to be a `bool` but got c                 S   s   g | ]}d | d qS )`r%   ).0ar%   r%   r&   
<listcomp>       z#Metric.__init__.<locals>.<listcomp>zUnexpected keyword arguments: z, r   ).super__init__r!   _C_log_api_usage_once	__class____name__boolr   r*   _deviceget_default_dtype_dtypepopr7   
isinstance
ValueErrorr8   r9   r:   callabler'   r;   r<   r=   sortedjoininspect	signatureupdate_update_signature_wrap_update_wrap_computecompute	_computed_forward_cache_update_count_to_sync_should_unsync_enable_grad_dtype_convert	_defaults_persistent_reductions
_is_synced_cache)selfr5   kwargs_rG   r%   r&   rD   i   sd   








zMetric.__init__c                 C   s   t dtdd | jS )NzLThis property will be removed in 2.0.0. Use `Metric.updated_called` instead.   )
stacklevel)r   DeprecationWarningupdate_calledrf   r%   r%   r&   r2      s   zMetric._update_calledc                 C   s
   | j dkS )zWReturns `True` if `update` or `forward` has been called initialization or last `reset`.r   r\   rm   r%   r%   r&   rl      s   
zMetric.update_calledc                 C      | j S )zgGet the number of times `update` and/or `forward` has been called since initialization or last `reset`.rn   rm   r%   r%   r&   update_count      zMetric.update_countc                    s    fdd j D S )z$Get the current state of the metric.c                       i | ]}|t  |qS r%   getattrr?   attrrm   r%   r&   
<dictcomp>   rB   z'Metric.metric_state.<locals>.<dictcomp>)ra   rm   r%   rm   r&   r1      s   zMetric.metric_stateFnamedefaultdist_reduce_fx
persistentc                 C   s   t |ttfrt |tr|rtd|dkrt}n(|dkr t}n!|dkr't}n|dkr.t}n|dkr5t}n|durAt	|sAtdt |trJ|
 }t| || t|| j|< || j|< || j|< dS )	aL  Add metric state variable. Only used by subclasses.

        Metric state variables are either `:class:`~torch.Tensor` or an empty list, which can be appended to by the
        metric. Each state variable must have a unique name associated with it. State variables are accessible as
        attributes of the metric i.e, if ``name`` is ``"my_state"`` then its value can be accessed from an instance
        ``metric`` as ``metric.my_state``. Metric states behave like buffers and parameters of :class:`~torch.nn.Module`
        as they are also updated when ``.to()`` is called. Unlike parameters and buffers, metric states are not by
        default saved in the modules :attr:`~torch.nn.Module.state_dict`.

        Args:
            name: The name of the state variable. The variable will then be accessible at ``self.name``.
            default: Default value of the state; can either be a :class:`~torch.Tensor` or an empty list.
                The state will be reset to this value when ``self.reset()`` is called.
            dist_reduce_fx (Optional): Function to reduce state across multiple processes in distributed mode.
                If value is ``"sum"``, ``"mean"``, ``"cat"``, ``"min"`` or ``"max"`` we will use ``torch.sum``,
                ``torch.mean``, ``torch.cat``, ``torch.min`` and ``torch.max``` respectively, each with argument
                ``dim=0``. Note that the ``"cat"`` reduction only makes sense if the state is a list, and not
                a tensor. The user can also pass a custom function in this parameter.
            persistent (Optional): whether the state will be saved as part of the modules ``state_dict``.
                Default is ``False``.

        .. note::
            Setting ``dist_reduce_fx`` to None will return the metric state synchronized across different processes.
            However, there won't be any reduction function applied to the synchronized metric state.

            The metric states would be synced as follows

            - If the metric state is :class:`~torch.Tensor`, the synced value will be a stacked :class:`~torch.Tensor`
              across the process dimension if the metric state was a :class:`~torch.Tensor`. The original
              :class:`~torch.Tensor` metric state retains dimension and hence the synchronized output will be of shape
              ``(num_process, ...)``.

            - If the metric state is a ``list``, the synced value will be a ``list`` containing the
              combined elements from all processes.

        .. important::
            When passing a custom function to ``dist_reduce_fx``, expect the synchronized metric state to follow
            the format discussed in the above note.

        .. caution::
            The values inserted into a list state are deleted whenever :meth:`~Metric.reset` is called. This allows
            device memory to be automatically reallocated, but may produce unexpected effects when referencing list
            states. To retain such values after :meth:`~Metric.reset` is called, you must first copy them to another
            object.

        Raises:
            ValueError:
                If ``default`` is not a ``tensor`` or an ``empty list``.
            ValueError:
                If ``dist_reduce_fx`` is not callable or one of ``"mean"``, ``"sum"``, ``"cat"``, ``"min"``,
                ``"max"`` or ``None``.

        zPstate variable must be a tensor or any empty list (where you can append tensors)summeanmaxmincatNzV`dist_reduce_fx` must be callable or one of ['mean', 'sum', 'cat', 'min', 'max', None])rN   r   listrO   r   r   r   r   r   rP   
contiguoussetattrr   ra   rb   rc   )rf   rx   ry   rz   r{   r%   r%   r&   	add_state   s(   <

zMetric.add_stateargsc                 O   sT   | j rtd| js| jdu s| jr| j|i || _| jS | j|i || _| jS )a  Aggregate and evaluate batch input directly.

        Serves the dual purpose of both computing the metric on the current batch of inputs but also add the batch
        statistics to the overall accumulating metric state. Input arguments are the exact same as corresponding
        ``update`` method. The returned output is the exact same as the output of ``compute``.

        Args:
            args: Any arguments as required by the metric ``update`` method.
            kwargs: Any keyword arguments as required by the metric ``update`` method.

        Returns:
            The output of the ``compute`` method evaluated on the current batch.

        Raises:
            TorchMetricsUserError:
                If the metric is already synced and ``forward`` is called again.

        zfThe Metric shouldn't be synced when performing ``forward``. HINT: Did you forget to call ``unsync`` ?.N)rd   r   r4   r8   _forward_full_state_updater[   _forward_reduce_state_updaterf   r   r5   r%   r%   r&   forward  s   zMetric.forwardc           	      O   s   | j |i | | j}| j| _d| _| j}d| _|  }d| _|   | j |i | | 	 }|
 D ]
\}}t| || q3|| _d| _d| _| j| _d| _d| _|| _| jr[|   |S )a3  Forward computation using two calls to `update`.

        Doing this secures that metrics that need access to the full metric state during `update` works as expected.
        This is the most safe method to use for any metric but also the slower version of the two forward
        implementations.

        FTN)rU   r\   r8   r]   r^   r7   _copy_state_dictr_   resetrY   itemsr   rd   r<   rZ   _move_list_states_to_cpu)	rf   r   r5   r\   _temp_compute_on_cpucache	batch_valrv   valr%   r%   r&   r   ?  s.   	z!Metric._forward_full_state_updatec                 O   s   |   }| j}|   | j| _d| _| j}d| _d| _| j|i | | 	 }|d | _t
  | | W d   n1 s@w   Y  d| _d| _| j| _d| _d| _|| _| jr_|   |S )a  Forward computation using single call to `update`.

        This can be done when the global metric state is a simple reduction of batch states. This can be unsafe for
        certain metric cases but is also the fastest way to both accumulate globally and compute locally.

        FT   N)r   r\   r   r8   r]   r^   r7   r_   rU   rY   r!   no_grad_reduce_statesrd   r<   rZ   r   )rf   r   r5   global_stater\   r   r   r%   r%   r&   r   l  s.   

z#Metric._forward_reduce_state_updateincoming_statec                 C   s   t |ttfstdt| | js| jdu s| jrtdt |tr<| j}t ||s9td|j	 dt| |j
}| | dS )a  Merge incoming metric state to the current state of the metric.

        Args:
            incoming_state:
                either a dict containing a metric state similar to the metric itself or an instance of the
                metric class.

        Raises:
            ValueError:
                If the incoming state is neither a dict nor an instance of the metric class.
            RuntimeError:
                If the metric has ``full_state_update=True`` or ``dist_sync_on_step=True``. In these cases, the metric
                cannot be merged with another metric state in a simple way. The user should overwrite the method in the
                metric class to handle the merge operation.
            ValueError:
                If the incoming state is a metric instance but the class is different from the current metric class.

        Example with a metric instance:

            >>> from torchmetrics.aggregation import SumMetric
            >>> metric1 = SumMetric()
            >>> metric2 = SumMetric()
            >>> metric1.update(1)
            >>> metric2.update(2)
            >>> metric1.merge_state(metric2)
            >>> metric1.compute()
            tensor(3.)

        Example with a dict:

            >>> from torchmetrics.aggregation import SumMetric
            >>> metric = SumMetric()
            >>> metric.update(1)
            >>> # SumMetric has one state variable called `sum_value`
            >>> metric.merge_state({"sum_value": torch.tensor(2)})
            >>> metric.compute()
            tensor(3.)

        zFExpected incoming state to be a dict or an instance of Metric but got Nz``merge_state`` is not supported for metrics with ``full_state_update=True`` or ``dist_sync_on_step=True``. Please overwrite the merge_state method in the metric class.z-Expected incoming state to be an instance of z	 but got )rN   dictr)   rO   typer4   r8   RuntimeErrorrG   rH   r1   r   )rf   r   
this_classr%   r%   r&   merge_state  s    (

zMetric.merge_statec                 C   sT  | j D ]}t| |}||vrtd| d| || }| j| }|tkr*|| }nw|tkr=| jd | |  | j }nd|tkrHt	
||}nY|tkrSt	||}nN|tkrit|trdt	||g}n=|| }n8|du rzt|trzt	||g}n'|du rt|trt||g}n|rt|r|t	||g}ntd| t| || qdS )zAdd an incoming metric state to the current state of the metric.

        Args:
            incoming_state: a dict containing a metric state similar metric itself

        zExpected state variable z! to be present in incoming state r   NzUnsupported reduce_fn: )ra   rt   rO   rc   r   r   r\   floatr   r!   r~   r   r   r   rN   r   r   stackr   r   rP   	TypeErrorr   )rf   r   rv   local_stater   	reduce_fnreducedr%   r%   r&   r     s6   





zMetric._reduce_statesr:   r9   c                    s   fdd j D } j  D ]C\}}|tkr/t|| tr/t|| dkr/t|| g||<  jrR|tkrRt|| trRt|| dkrRtjg  j	 j
dg||< qt|t||p[ jd} j  D ]^\}}t|| tr}t|| dkr}t |g  qct|| d trt|| ||< nt|| d trt|| ||< t|s|d u std|d ur||| n|| }t || qcd S )Nc                    rr   r%   rs   ru   rm   r%   r&   rw     rB   z%Metric._sync_dist.<locals>.<dictcomp>r   r   )r*   dtype)groupz%reduction_fn must be callable or None)rc   r   r   rN   r   lenr   r!   tensorr*   r   r   r   r9   r   r   r   rP   r   )rf   r:   r9   
input_dictrv   reduction_fnoutput_dictr   r%   rm   r&   
_sync_dist  s>   &zMetric._sync_distrU   c                    s*   t dtdtdd f fdd}|S )Nr   r5   r    c                     s   d  _   jd7  _t j6 z	| i | W n$ ty> } zdt|v r8td jj d jj d||d }~ww W d    n1 sIw   Y   j	rW 
  d S d S )Nr   zExpected all tensors to be onzEncountered different devices in metric calculation (see stacktrace for details). This could be due to the metric class not being on the same device as input. Instead of `metric=z(...)` try to do `metric=zF(...).to(device)` where device corresponds to the device of the input.)rZ   r\   r!   set_grad_enabledr_   r   strrG   rH   r7   r   )r   r5   errrf   rU   r%   r&   wrapped_func  s0   z)Metric._wrap_update.<locals>.wrapped_func	functoolswrapsr	   )rf   rU   r   r%   r   r&   rW     s   zMetric._wrap_updatec                 C   s:   | j D ]}t| |}t|trt| |dd |D  qdS )z+Move list states to cpu to save GPU memory.c                 S   s   g | ]}| d qS )r6   )tor?   cur_vr%   r%   r&   rA   ;  s    z3Metric._move_list_states_to_cpu.<locals>.<listcomp>N)ra   rt   rN   r   r   )rf   keycurrent_valr%   r%   r&   r   6  s   


zMetric._move_list_states_to_cpuTshould_syncdistributed_availablec                 C   sv   | j r	|r	td|du r| jdur| j}t|r| nd}|r"|s$dS |du r*t}|  | _| j||d d| _ dS )a  Sync function for manually controlling when metrics states should be synced across processes.

        Args:
            dist_sync_fn: Function to be used to perform states synchronization
            process_group:
                Specify the process group on which synchronization is called.
                default: `None` (which selects the entire world)
            should_sync: Whether to apply to state synchronization. This will have an impact
                only when running in a distributed setting.
            distributed_available: Function to determine if we are running inside a distributed setting

        Raises:
            TorchMetricsUserError:
                If the metric is already synced and ``sync`` is called again.

        z#The Metric has already been synced.N)r9   T)rd   r   r;   rP   r   r   re   r   )rf   r:   r9   r   r   is_distributedr%   r%   r&   sync=  s   


zMetric.syncshould_unsyncc                 C   sX   |sdS | j std| jdu rtd| j D ]
\}}t| || qd| _ d| _dS )zUnsync function for manually controlling when metrics states should be reverted back to their local states.

        Args:
            should_unsync: Whether to perform unsync

        Nz&The Metric has already been un-synced.z5The internal cache should exist to unsync the Metric.F)rd   r   re   r   r   )rf   r   rv   r   r%   r%   r&   unsynci  s   

zMetric.unsyncc                 c   s0    | j ||||d dV  | j| jo|d dS )a`  Context manager to synchronize states.

        This context manager is used in distributed setting and makes sure that the local cache states are restored
        after yielding the synchronized state.

        Args:
            dist_sync_fn: Function to be used to perform states synchronization
            process_group:
                Specify the process group on which synchronization is called.
                default: `None` (which selects the entire world)
            should_sync: Whether to apply to state synchronization. This will have an impact
                only when running in a distributed setting.
            should_unsync: Whether to restore the cache state so that the metrics can
                continue to be accumulated.
            distributed_available: Function to determine if we are running inside a distributed setting

        )r:   r9   r   r   N)r   )r   r   rd   )rf   r:   r9   r   r   r   r%   r%   r&   sync_context  s   zMetric.sync_contextrY   c                    s*   t  dtdtdtf fdd}|S )Nr   r5   r    c                     s   j stdjj dt jd urjS jjjj	d t
 | i |}t|tdd }W d    n1 s=w   Y  jrH|_|S )Nz!The ``compute`` method of metric zn was called before the ``update`` method which may lead to errors, as metric states have not yet been updated.)r:   r   r   c                 S      |   S N)clonexr%   r%   r&   <lambda>      z<Metric._wrap_compute.<locals>.wrapped_func.<locals>.<lambda>)rl   r   rG   rH   UserWarningrZ   r   r:   r]   r^   r   r   r   r=   )r   r5   valuerY   rf   r%   r&   r     s$   
	z*Metric._wrap_compute.<locals>.wrapped_funcr   )rf   rY   r   r%   r   r&   rX     s   zMetric._wrap_compute___c                 O      dS )zHOverride this method to update the state variables of your metric class.Nr%   rf   r   r   r%   r%   r&   rU         zMetric.updatec                 C   r   )zOverride this method to compute the final metric value.

        This method will automatically synchronize state variables when running in distributed backend.

        Nr%   rm   r%   r%   r&   rY     r   zMetric.computec                 O   s   t )z+Override this method plot the metric value.)NotImplementedErrorr   r%   r%   r&   plot     zMetric.plotr   axc              	   C   sB   |dur|n|   }t||| j| jj| j| j| jd\}}||fS )a  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        N)r   r-   rx   lower_boundupper_boundlegend_name)rY   r   r-   rG   rH   r.   r/   r0   )rf   r   r   figr%   r%   r&   _plot  s   
	zMetric._plotc                 C   sv   d| _ d| _d| _| j D ]$\}}t| |}t|tr+t| ||	 
 |j qt| |  qd| _d| _dS )z4Reset metric state variables to their default value.r   NF)r\   r[   rZ   ra   r   rt   rN   r   r   detachr   r   r*   clearre   rd   )rf   rv   ry   r   r%   r%   r&   r     s   


zMetric.resetc                 C   s   t | S )zMake a copy of the metric.r   rm   r%   r%   r&   r        zMetric.clonec                 C   s   dd | j  D S )z|Get the current state, including all metric states, for the metric.

        Used for loading and saving a metric.

        c                 S   s   i | ]\}}|d vr||qS ))rU   rY   rV   r%   r?   kvr%   r%   r&   rw     s    z'Metric.__getstate__.<locals>.<dictcomp>)__dict__r   rm   r%   r%   r&   __getstate__  s   zMetric.__getstate__statec                 C   s:   | j | t| j| _| | j| _| | j| _dS )zmSet the state of the metric, based on a input state.

        Used for loading and saving a metric.

        N)r   rU   rS   rT   rV   rW   rX   rY   )rf   r   r%   r%   r&   __setstate__  s   zMetric.__setstate__r   c                    s*   |dv rt d| dt || dS )zOOverwrite default method to prevent specific attributes from being set by user.)r-   r,   r4   r.   r/   r0   zCan't change const `z`.N)r   rC   __setattr__)rf   rx   r   rh   r%   r&   r      s   zMetric.__setattr__torch.devicec                 C   ro   )z Return the device of the metric.)rJ   rm   r%   r%   r&   r*   -  rq   zMetric.devicetorch.dtypec                 C   ro   )z'Return the default dtype of the metric.)rL   rm   r%   r%   r&   r   2  rq   zMetric.dtypedst_typec                 C      | S zkOverride default and prevent dtype casting.

        Please use :meth:`Metric.set_dtype` instead.

        r%   )rf   r   r%   r%   r&   r   7     zMetric.typec                 C   r   r   r%   rm   r%   r%   r&   r   ?  r   zMetric.floatc                 C   r   r   r%   rm   r%   r%   r&   doubleG  r   zMetric.doublec                 C   r   r   r%   rm   r%   r%   r&   halfO  r   zMetric.halfc                    s   d| _ t |}d|_ |S )zTransfer all metric state to specific dtype. Special version of standard `type` method.

        Arguments:
            dst_type: the desired type as string or dtype object

        TF)r`   rC   r   )rf   r   outrh   r%   r&   	set_dtypeW  s   zMetric.set_dtype fnexclude_statec           	         sF  t   }t tfdddD }| js|r|S |j D ]S\}}||v r*q!t|tr7 ||j|< nt|t	rH fdd|D |j|< t
||}t|tr[t|| | q!t|t	rnt|| fdd|D  q!td|  tjd| jd	}|j| _|j| _|jd
urt|jt |_|jd
urt|jt |_|S )a"  Overwrite `_apply` function such that we can also move metric states to the correct device.

        This method is called by the base ``nn.Module`` class whenever `.to`, `.cuda`, `.float`, `.half` etc. methods
        are called. Dtype conversion is guarded and will only happen through the special `set_dtype` method.

        Args:
            fn: the function to apply
            exclude_state: list of state variables to exclude from applying the function, that then needs to be handled
                by the metric class itself.

        c                 3   s    | ]}| v V  qd S r   r%   )r?   f)fsr%   r&   	<genexpr>q  s    z Metric._apply.<locals>.<genexpr>)zModule.typezModule.halfzModule.floatzModule.doublezModule.bfloat16c                       g | ]} |qS r%   r%   r?   r   r   r%   r&   rA   }      z!Metric._apply.<locals>.<listcomp>c                    r   r%   r%   r   r   r%   r&   rA     r   zQExpected metric state to be either a Tensor or a list of Tensor, but encountered r   )r*   N)rC   _applyr   anyr`   ra   r   rN   r   r   rt   r   r   r!   zerosr*   rJ   r   rL   rZ   r   r[   )	rf   r   r   thiscondr   r   r   _dummy_tensorrh   )r   r   r&   r   c  s8   







zMetric._applymodec                 C   s   | j D ]}|| j |< qdS )zDChange post-init if metric states should be saved to its state_dict.N)rb   )rf   r   r   r%   r%   r&   r{     s   
zMetric.persistentdestinationprefix	keep_varsc                    sx   t  j|||d}| jD ]-}| j| sqt| |}|s1t|tr%| }nt|tr1dd |D }t	|||| < q|S )aW  Get the current state of metric as an dictionary.

        Args:
            destination: Optional dictionary, that if provided, the state of module will be updated into the dict and
                the same object is returned. Otherwise, an ``OrderedDict`` will be created and returned.
            prefix: optional string, a prefix added to parameter and buffer names to compose the keys in state_dict.
            keep_vars: by default the :class:`~torch.Tensor` returned in the state dict are detached from autograd.
                If set to ``True``, detaching will not be performed.

        )r   r   r   c                 S   s"   g | ]}t |tr| n|qS r%   )rN   r   r   r   r%   r%   r&   rA     s   " z%Metric.state_dict.<locals>.<listcomp>)
rC   
state_dictra   rb   rt   rN   r   r   r   r   )rf   r   r   r   r   r   rh   r%   r&   r     s    





zMetric.state_dictc                 C   sT   i }| j D ]"}t| |}t|tr|  |j||< qdd |D ||< q|S )zCopy the current state values.c                 S   s2   g | ]}t |tr|  |jnt|qS r%   )rN   r   r   r   r   r*   r   )r?   r   r%   r%   r&   rA     s    &z+Metric._copy_state_dict.<locals>.<listcomp>)ra   rt   rN   r   r   r   r   r*   )rf   r   rv   current_valuer%   r%   r&   r     s   


zMetric._copy_state_dictr   local_metadatastrictmissing_keysunexpected_keys
error_msgsc           
   	      sJ   | j D ]}|| }	|	|v rt| |||	 qt |||d||| dS )z#Load metric states from state_dict.TN)ra   r   rM   rC   _load_from_state_dict)
rf   r   r   r  r  r  r  r  r   rx   rh   r%   r&   r    s   
zMetric._load_from_state_dictc                    s^   t jjt jjf | jj fdd| D }tdd  D }|s)|s)i S |r-|S |S )zFFilter kwargs such that they match the update signature of the metric.c                    s,   i | ]\}}|v r| j  vr||qS r%   )kindr   _params_sign_paramsr%   r&   rw     s    &z)Metric._filter_kwargs.<locals>.<dictcomp>c                 s   s    | ]
}|j tjjkV  qd S r   )r  rS   	ParameterVAR_KEYWORDr   r%   r%   r&   r     s    z(Metric._filter_kwargs.<locals>.<genexpr>)	rS   r  VAR_POSITIONALr  rV   
parametersr   r   values)rf   r5   filtered_kwargsexists_var_keywordr%   r  r&   _filter_kwargs  s   zMetric._filter_kwargsc                 C   s\   | j jt| g}| jD ]}t| |}t|dr"t|ts"|| q|	| qt
t|S )a  Return an unique hash of the metric.

        The hash depends on both the class itself but also the current metric state, which therefore enforces that two
        instances of the same metrics never have the same hash even if they have been updated on the same data.

        __iter__)rG   rH   idra   rt   hasattrrN   r   extendappendhashtuple)rf   	hash_valsr   r   r%   r%   r&   __hash__  s   

zMetric.__hash__otherCompositionalMetricc                 C      t tj| |S z;Construct compositional metric using the addition operator.r  r!   addrf   r  r%   r%   r&   __add__     zMetric.__add__c                 C   r  z>Construct compositional metric using the logical and operator.r  r!   bitwise_andr"  r%   r%   r&   __and__  r$  zMetric.__and__c                 C   r  )z8Construct compositional metric using the equal operator.)r  r!   eqr"  r%   r%   r&   __eq__  r$  zMetric.__eq__c                 C   r  zAConstruct compositional metric using the floor division operator.r  r!   floor_divider"  r%   r%   r&   __floordiv__  r$  zMetric.__floordiv__c                 C   r  )zHConstruct compositional metric using the greater than or equal operator.)r  r!   ger"  r%   r%   r&   __ge__  r$  zMetric.__ge__c                 C   r  )z?Construct compositional metric using the greater than operator.)r  r!   gtr"  r%   r%   r&   __gt__"  r$  zMetric.__gt__c                 C   r  )zEConstruct compositional metric using the less than or equal operator.)r  r!   ler"  r%   r%   r&   __le__&  r$  zMetric.__le__c                 C   r  )z<Construct compositional metric using the less than operator.)r  r!   ltr"  r%   r%   r&   __lt__*  r$  zMetric.__lt__c                 C   r  zHConstruct compositional metric using the matrix multiplication operator.r  r!   matmulr"  r%   r%   r&   
__matmul__.  r$  zMetric.__matmul__c                 C   r  z<Construct compositional metric using the remainder operator.r  r!   fmodr"  r%   r%   r&   __mod__2  r$  zMetric.__mod__c                 C   r  zAConstruct compositional metric using the multiplication operator.r  r!   mulr"  r%   r%   r&   __mul__6  r$  zMetric.__mul__c                 C   r  )z<Construct compositional metric using the not equal operator.)r  r!   ner"  r%   r%   r&   __ne__:  r$  zMetric.__ne__c                 C   r  z=Construct compositional metric using the logical or operator.r  r!   
bitwise_orr"  r%   r%   r&   __or__>  r$  zMetric.__or__c                 C   r  zDConstruct compositional metric using the exponential/power operator.r  r!   powr"  r%   r%   r&   __pow__B  r$  zMetric.__pow__c                 C      t tj|| S r  r   r"  r%   r%   r&   __radd__F  r$  zMetric.__radd__c                 C   r  r%  r&  r"  r%   r%   r&   __rand__J  s   zMetric.__rand__c                 C   rM  r+  r,  r"  r%   r%   r&   __rfloordiv__O  r$  zMetric.__rfloordiv__c                 C   rM  r7  r8  r"  r%   r%   r&   __rmatmul__S  r$  zMetric.__rmatmul__c                 C   rM  r;  r<  r"  r%   r%   r&   __rmod__W  r$  zMetric.__rmod__c                 C   rM  r?  r@  r"  r%   r%   r&   __rmul__[  r$  zMetric.__rmul__c                 C   rM  rE  rF  r"  r%   r%   r&   __ror___  r$  zMetric.__ror__c                 C   rM  rI  rJ  r"  r%   r%   r&   __rpow__c  r$  zMetric.__rpow__c                 C   rM  z>Construct compositional metric using the subtraction operator.r  r!   subr"  r%   r%   r&   __rsub__g  r$  zMetric.__rsub__c                 C   rM  z>Construct compositional metric using the true divide operator.r  r!   true_divider"  r%   r%   r&   __rtruediv__k  r$  zMetric.__rtruediv__c                 C   rM  z>Construct compositional metric using the logical xor operator.r  r!   bitwise_xorr"  r%   r%   r&   __rxor__o  r$  zMetric.__rxor__c                 C   r  rV  rW  r"  r%   r%   r&   __sub__s  r$  zMetric.__sub__c                 C   r  rZ  r[  r"  r%   r%   r&   __truediv__w  r$  zMetric.__truediv__c                 C   r  r^  r_  r"  r%   r%   r&   __xor__{  r$  zMetric.__xor__c                 C      t tj| dS )z;Construct compositional metric using the absolute operator.Nr  r!   absrm   r%   r%   r&   __abs__  r$  zMetric.__abs__c                 C   re  )6Construct compositional metric using the not operator.N)r  r!   bitwise_notrm   r%   r%   r&   __inv__  r$  zMetric.__inv__c                 C   r   )ri  )rk  rm   r%   r%   r&   
__invert__  r   zMetric.__invert__c                 C   s   t t| dS )z@Construct compositional metric using absolute negative operator.N)r  _negrm   r%   r%   r&   __neg__  s   zMetric.__neg__c                 C   re  )z7Construct compositional metric using absolute operator.Nrf  rm   r%   r%   r&   __pos__  r$  zMetric.__pos__idxc                    s   t  fdd| dS )z;Construct compositional metric using the get item operator.c                    s   |   S r   r%   r   rp  r%   r&   r     r   z$Metric.__getitem__.<locals>.<lambda>N)r  )rf   rp  r%   rq  r&   __getitem__  r(   zMetric.__getitem__c                 C   s   t t| S )z=Needed method for construction of new metrics __new__ method.)r  r)   __str__rm   r%   r%   r&   __getnewargs__  s   zMetric.__getnewargs__)NFr    N)NNTN)T)NNTTNNN)r    r)   )r    r   )r    r   )r   F)Nr   F)r  r  r    r)   )r    r  )urH   
__module____qualname____doc__r+   r   r   r   __annotations__r3   r,   r   rI   r-   r4   r.   r   r/   r0   r	   rD   propertyr2   rl   intrp   r   r   r   r   r1   r
   r   r!   jitunusedr   r   r   r   r   r   r   rW   r   r   r   r   r   r   rX   r   rU   rY   r   r   r   r   r   r   r   r   r   r   r*   r   r   r   r   r   r   r   r{   r   r   r  r  r  builtinsr#  r(  r*  r.  r0  r2  r4  r6  r:  r>  rB  rD  rH  rL  rN  rO  rP  rQ  rR  rS  rT  rU  rY  r]  ra  rb  rc  rd  rh  rk  rl  rn  ro  rr  r  rt  r  __classcell__r%   r%   rh   r&   r)   4   sf  
 "	H$

U -"(= $)
	
,$"*

 
	


  4
""	





r)   r   c                 C   s   t |  S r   )r!   rg  r   r%   r%   r&   rm    s   rm  c                
       s   e Zd ZdZdedeeeef deeeedf ddf fddZ	d d	e
e d
e
e ddfddZdededdfddZdefddZejjdededefddZd!ddZd"deddfddZdefddZdedefddZ  ZS )#r  z`Composition of two metrics with a specific operator which will be executed upon metrics compute.operatormetric_ametric_bNr    c                    sZ   t    || _t|tr| jd|dd n|| _t|tr(| jd|dd dS || _dS )aQ  Class for creating compositions of metrics.

        This metric class is the output of adding, multiplying etc. any other metric. The metric re-implements the
        standard ``update``, ``forward``, ``reset`` and ``compute`` methods to redirect the arguments to the metrics
        that formed this composition.

        Args:
            operator:
                The operator taking in one (if metric_b is None) or two arguments. Will be applied to outputs of
                metric_a.compute() and (optionally if metric_b is not None) metric_b.compute()
            metric_a:
                First metric whose compute() result is the first argument of operator
            metric_b: second metric whose compute() result is the second argument of operator.
                For operators taking in only one input, this should be None.

        r  F)r{   r  N)rC   rD   oprN   r   register_bufferr  r  )rf   r  r  r  rh   r%   r&   rD     s   



zCompositionalMetric.__init__r:   r9   c                 C   r   )z[No syncing required here.

        syncing will be done in metric_a and metric_b.

        Nr%   )rf   r:   r9   r%   r%   r&   r     r   zCompositionalMetric._sync_distr   r5   c                 O   s`   t | jtr| jj|i | jjdi | t | jtr.| jj|i | jjdi | dS dS )ERedirect the call to the input which the composition was formed from.Nr%   )rN   r  r)   rU   r  r  r   r%   r%   r&   rU     s
    $zCompositionalMetric.updatec                 C   sV   t | jtr| j n| j}t | jtr| j n| j}|du r%| |S | ||S r  N)rN   r  r)   rY   r  r  )rf   val_aval_br%   r%   r&   rY     s
   
zCompositionalMetric.computec                 O   s   t | jtr| j|i | jjdi |n| j}t | jtr-| j|i | jjdi |n| j}|du r:d| _| jS |du rSt | jtrJd| _| jS | || _| jS | ||| _| jS )zACalculate metric on current batch and accumulate to global state.Nr%   )rN   r  r)   r  r  r[   r  )rf   r   r5   r  r  r%   r%   r&   r     s&   
 
 zCompositionalMetric.forwardc                 C   s4   t | jtr| j  t | jtr| j  dS dS r  )rN   r  r)   r   r  rm   r%   r%   r&   r     s
   
zCompositionalMetric.resetFr   c                 C   s<   t | jtr| jj|d t | jtr| jj|d dS dS )zChange if metric state is persistent (save as part of state_dict) or not.

        Args:
            mode: bool indicating if all states should be persistent or not

        )r   N)rN   r  r)   r{   r  )rf   r   r%   r%   r&   r{     s
   zCompositionalMetric.persistentc                 C   s,   d| j j d| jd| jd}| jj| S )zaReturn a representation of the compositional metric, including the two inputs it was formed from.z(
  z(
    z,
    z
  )
))r  rH   r  r  rG   )rf   _op_metricsr%   r%   r&   __repr__  s    zCompositionalMetric.__repr__rY   c                 C   s   |S )z0No wrapping necessary for compositional metrics.r%   )rf   rY   r%   r%   r&   rX     r   z!CompositionalMetric._wrap_computerv  ru  rw  )rH   rx  ry  rz  r
   r   r)   r   r   rD   r   r	   r   rU   rY   r!   r~  r  r   r   rI   r{   r   r  rX   r  r%   r%   rh   r&   r    s(     $
r  )3r  r   rS   abcr   r   collections.abcr   r   
contextlibr   copyr   typingr	   r
   r   r   r   r   r!   lightning_utilitiesr   r   torch.nnr   torchmetrics.utilities.datar   r   r   r   r   r   r   "torchmetrics.utilities.distributedr   !torchmetrics.utilities.exceptionsr   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   r   torchmetrics.utilities.printsr   rI   r'   r)   rm  r  r%   r%   r%   r&   <module>   s<    $	        t