o
    yi                     @   s  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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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e&fddZ'G dd deeZ(dedefddZ)G dd de(Z*dS )    N)ABCabstractmethod)contextmanagerdeepcopy)	AnyCallableDict	GeneratorListOptionalSequenceTupleUnion)Tensor)Module)apply_to_collectionrank_zero_warn)_flatten_squeeze_if_scalardim_zero_catdim_zero_maxdim_zero_meandim_zero_mindim_zero_sum)gather_all_tensors)TorchMetricsUserErrorreturnc                   C   s   t j o	t j S N)torchdistributedis_availableis_initialized r#   r#   G/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/metric.pyjit_distributed_available'      r%   c                       s  e Zd ZU dZdgZdgZ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		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f ddfddZedfdedee ddfd d!Zd"edefd#d$Z dd%d&Z!			'	ddee dee d(ed)ee ddf
d*d+Z"dd,eddfd-d.Z#e$			'	'	ddee dee d(ed,ed)ee de%fd/d0Z&d1edefd2d3Z'e(d4ed5eddfd6d7Z)e(defd8d9Z*dd:d;Z+dd<d=Z,deeef fd>d?Z-d@eeef ddfdAdBZ.dedCeddf fdDdEZ/eddGdHZ0dIeeej1f dd fdJdKZ2ddLdMZ3ddNdOZ4ddPdQZ5dIeeej1f dd f fdRdSZ6dTede7f fdUdVZ8ddWeddfdXdYZ9		Z	dd[eeef d\ed]edeeeef  f fd^d_Z:d`e;d\edae;dbedce<e dde<e dee<e ddf fdfdgZ=dedeeef fdhdiZ>de?fdjdkZ@ddmdnZAddodpZBddqdrZCddsdtZDddudvZEddwdxZFddydzZGdd{d|ZHdd}d~ZIdddZJdddZKdddZLdddZMdddZNdddZOdddZPdddZQdddZRdddZSdddZTdddZUdddZVdddZWdddZXdddZYdddZZdddZ[dddZ\dddZ]dddZ^dddZ_dddZ`dddZade?dd fddZbdecfddZddd Ze  ZfS )Metrica  Base class for all metrics present in the Metrics API.

    Implements ``add_state()``, ``forward()``, ``reset()`` and a few other things to
    handle distributed synchronization and per-step metric computation.

    Override ``update()`` and ``compute()`` functions to implement your own metric. Use
    ``add_state()`` to register metric state variables which keep track of state on each
    call of ``update()`` and are synchronized across processes when ``compute()`` is called.

    Note:
        Metric state variables can either be :class:`~torch.Tensor` or an empty list which can we used
        to store :class:`~torch.Tensor`.

    Note:
        Different metrics only override ``update()`` and not ``forward()``. A call to ``update()``
        is valid, but it won't return the metric value at the current step. A call to ``forward()``
        automatically calls ``update()`` and also returns the metric value at the current step.

    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 an
                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``-
    deviceis_differentiableNhigher_is_betterfull_state_updatekwargsr   c                    sp  t    tjd| jj  td| _|	dd| _
t| j
ts+td| j
 |	dd| _t| jts@td| j |	dd | _|	d	d | _| jd ur`t| js`td
| j |	dt| _|	dd| _t| jts|td| j 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 r   )(super__init__r   _C_log_api_usage_once	__class____name__r(   _devicepopr.   
isinstancebool
ValueErrorr/   r0   r1   callabler%   r2   r3   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)selfr,   r8   r#   r$   r5   R   sP   





zMetric.__init__c                 C   s
   | j dkS )Nr   )rI   rS   r#   r#   r$   _update_called   s   
zMetric._update_calledF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 )	a  Adds metric state variable. Only used by subclasses.

        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.

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

        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"``, ``None``.
        zPstate variable must be a tensor or any empty list (where you can append tensors)summeanmaxmincatNzH`dist_reduce_fx` must be callable or one of ['mean', 'sum', 'cat', None])r<   r   listr>   r   r   r   r   r   r?   
contiguoussetattrr   rN   rO   rP   )rS   rW   rX   rY   rZ   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 )aZ  ``forward`` serves the dual purpose of both computing the metric on the current batch of inputs but also
        add the batch statistics to the overall accumululating metric state.

        Input arguments are the exact same as corresponding ``update`` method. The returned output is the exact same as
        the output of ``compute``.
        zfThe Metric shouldn't be synced when performing ``forward``. HINT: Did you forget to call ``unsync`` ?.N)rQ   r   r+   r/   _forward_full_state_updaterH   _forward_reduce_state_updaterS   rd   r,   r#   r#   r$   forward   s   	zMetric.forwardc           	         s    j |i |  j} j _d _ j}d _ fdd jD }d _    j |i |  	 }|
 D ]
\}}t || q9| _d _d _ j _d _d _| _ jra   |S )a  forward computation using two calls to `update` to calculate the metric value on the current batch and
        accumulate global state.

        Doing this secures that metrics that need access to the full metric state during `update` works as expected.
        Fc                       i | ]}|t  |qS r#   getattr.0attrrU   r#   r$   
<dictcomp>      z5Metric._forward_full_state_update.<locals>.<dictcomp>TN)rB   rI   r/   rJ   rK   r.   rN   rL   resetrF   itemsrb   rQ   r3   rG   _move_list_states_to_cpu)	rS   rd   r,   rI   _temp_compute_on_cpucache	batch_valrn   valr#   rU   r$   re      s.   z!Metric._forward_full_state_updatec                    s    fdd j  D } j}    j _d _ j}d _d _ j	|i |  
 }|d  _t   | W d   n1 sHw   Y  d _d _ j _d _d _| _ jrg   |S )zforward computation using single call to `update` to calculate the metric value on the current batch and
        accumulate global state.

        This can be done when the global metric state is a sinple reduction of batch states.
        c                    ri   r#   rj   rl   rU   r#   r$   ro   "  rp   z7Metric._forward_reduce_state_update.<locals>.<dictcomp>FT   N)rN   keysrI   rq   r/   rJ   rK   r.   rL   rB   rF   r   no_grad_reduce_statesrQ   r3   rG   rs   )rS   rd   r,   global_staterI   rt   rv   r#   rU   r$   rf     s.   

z#Metric._forward_reduce_state_updateincoming_statec                 C   s  | j  D ]{}t| |}|| }| j| }|tkr|| }n\|tkr1| jd | |  | j }nI|tkr<t	
||}n>|tkrGt	||}n3|tkrP|| }n*|du rat|trat	||g}n|du rqt|trqt||g}n	|t	||g}t| || qdS )zAdds an incoming metric state to the current state of the metric.

        Args:
            incoming_state: a dict containing a metric state similar metric itself
        rx   N)rN   ry   rk   rP   r   r   rI   floatr   r   r]   r   r^   r   r<   r   stackr`   r   rb   )rS   r}   rn   local_stater|   	reduce_fnreducedr#   r#   r$   r{   B  s*   



zMetric._reduce_statesr1   r0   c                    sB   fdd j D } j  D ] \}}|tkr/t|| tr/t|| dkr/t|| g||< qt|t||p8 jd} j  D ]^\}}t|| trZt|| dkrZt	 |g  q@t|| d trmt
|| ||< nt|| d tr~t|| ||< t|s|d u std|d ur||| n|| }t	 || q@d S )Nc                    ri   r#   rj   rl   rU   r#   r$   ro   `  rp   z%Metric._sync_dist.<locals>.<dictcomp>rx   )groupr   z%reduction_fn must be callable or None)rP   rr   r   r<   r`   lenr   r   r0   rb   r   r   r   r?   	TypeError)rS   r1   r0   
input_dictrn   reduction_fnoutput_dictr   r#   rU   r$   
_sync_dist_  s0   &zMetric._sync_distrB   c                    s*   t dtdtdd f fdd}|S )Nrd   r,   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 )Nrx   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.)rG   rI   r   set_grad_enabledrL   RuntimeErrorstrr8   r9   r.   rs   )rd   r,   errrS   rB   r#   r$   wrapped_func  s0   z)Metric._wrap_update.<locals>.wrapped_func	functoolswrapsr   )rS   rB   r   r#   r   r$   rD     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 )r-   )torm   cur_vr#   r#   r$   
<listcomp>  s    z3Metric._move_list_states_to_cpu.<locals>.<listcomp>N)rN   ry   rk   r<   r   rb   )rS   keycurrent_valr#   r#   r$   rs     s   

zMetric._move_list_states_to_cpuTshould_syncdistributed_availablec                    s    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} fdd jD  _ j||d d _ dS )ap  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
        z#The Metric has already been synced.Nc                    ri   r#   rj   rl   rU   r#   r$   ro     rp   zMetric.sync.<locals>.<dictcomp>)r0   T)rQ   r   r2   r?   r   rN   rR   r   )rS   r1   r0   r   r   is_distributedr#   rU   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)rQ   r   rR   rr   rb   )rS   r   rn   rw   r#   r#   r$   unsync  s   

zMetric.unsyncc                 c   s0    | j ||||d dV  | j| jo|d dS )a1  Context manager to synchronize the states between processes when running in a distributed setting and
        restore the local cache states after yielding.

        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
        )r1   r0   r   r   N)r   )r   r   rQ   )rS   r1   r0   r   r   r   r#   r#   r$   sync_context  s   zMetric.sync_contextrF   c                    s*   t  dtdtdtf fdd}|S )Nrd   r,   r   c                     s   j dkrtdjj dt jd urjS jjjj	d  | i |}t
|_W d    jS 1 s<w   Y  jS )Nr   z!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.)r1   r   r   )rI   r   r8   r9   UserWarningrG   r   r1   rJ   rK   r   )rd   r,   valuerF   rS   r#   r$   r     s$   


z*Metric._wrap_compute.<locals>.wrapped_funcr   )rS   rF   r   r#   r   r$   rE     s   zMetric._wrap_compute___c                 O      dS )zHOverride this method to update the state variables of your metric class.Nr#   )rS   r   r   r#   r#   r$   rB         zMetric.updatec                 C   r   )zOverride this method to compute the final metric value from state variables synchronized across the
        distributed backend.Nr#   rU   r#   r#   r$   rF     r   zMetric.computec                 C   st   d| _ d| _d| _| j D ]#\}}t| |}t|tr+t| ||	 
 |j qt| |g  qd| _d| _dS )zSThis method automatically resets the metric state variables to their default value.r   NF)rI   rH   rG   rN   rr   rk   r<   r   rb   detachcloner   r(   rR   rQ   )rS   rn   rX   r   r#   r#   r$   rq   $  s   


zMetric.resetc                 C   s   t | S )zMake a copy of the metric.r   rU   r#   r#   r$   r   5  s   zMetric.clonec                 C   s   dd | j  D S )Nc                 S   s   i | ]\}}|d vr||qS ))rB   rF   rC   r#   rm   kvr#   r#   r$   ro   ;  s    z'Metric.__getstate__.<locals>.<dictcomp>)__dict__rr   rU   r#   r#   r$   __getstate__9  s   zMetric.__getstate__statec                 C   s:   | j | t| j| _| | j| _| | j| _d S r   )r   rB   r@   rA   rC   rD   rE   rF   )rS   r   r#   r#   r$   __setstate__=  s   zMetric.__setstate__r   c                    s*   |dv rt d| dt || d S )N)r*   r)   r+   zCan't change const `z`.)r   r4   __setattr__)rS   rW   r   rT   r#   r$   r   D  s   zMetric.__setattr__torch.devicec                 C   s   | j S )z Return the device of the metric.)r:   rU   r#   r#   r$   r(   I  s   zMetric.devicedst_typec                 C      | S zrMethod override default and prevent dtype casting.

        Please use `metric.set_dtype(dtype)` instead.
        r#   )rS   r   r#   r#   r$   typeN     zMetric.typec                 C   r   r   r#   rU   r#   r#   r$   r~   U  r   zMetric.floatc                 C   r   r   r#   rU   r#   r#   r$   double\  r   zMetric.doublec                 C   r   r   r#   rU   r#   r#   r$   halfc  r   zMetric.halfc                    s   d| _ t |}d|_ |S )zSpecial version of `type` for transferring all metric states to specific dtype
        Arguments:
            dst_type (type or string): the desired type
        TF)rM   r4   r   )rS   r   outrT   r#   r$   	set_dtypej  s   zMetric.set_dtypefnc                    s0  t   }t tfdddD }| js|r|S |j D ]N\}}t|tr2 ||j|< nt|t	rC fdd|D |j|< t
||}t|trVt|| | q!t|t	rit|| fdd|D  q!td|  tjd| jd	j| _|jd
urt|jt |_|jd
urt|jt |_|S )aE  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 garded and will only happen through the special `set_dtype` method.
        c                 3   s    | ]}| v V  qd S r   r#   )rm   f)fsr#   r$   	<genexpr>|  s    z Metric._apply.<locals>.<genexpr>)zModule.typezModule.halfzModule.floatzModule.doublezModule.bfloat16c                       g | ]} |qS r#   r#   rm   r   r   r#   r$   r         z!Metric._apply.<locals>.<listcomp>c                    r   r#   r#   r   r   r#   r$   r     r   zPExpected metric state to be either a Tensoror a list of Tensor, but encountered rx   )r(   N)r4   _applyr   anyrM   rN   rr   r<   r   r   rk   rb   r   r   zerosr(   r:   rG   r   rH   )rS   r   thiscondr   r   r   rT   )r   r   r$   r   t  s0   







zMetric._applymodec                 C   s   | j D ]}|| j |< qdS )zRMethod for post-init to change if metric states should be saved to its state_dict.N)rO   )rS   r   r   r#   r#   r$   rZ     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 )N)r   r   r   c                 S   s"   g | ]}t |tr| n|qS r#   )r<   r   r   r   r#   r#   r$   r     s   " z%Metric.state_dict.<locals>.<listcomp>)
r4   
state_dictrN   rO   rk   r<   r   r   r`   r   )rS   r   r   r   r   r   rT   r#   r$   r     s   





zMetric.state_dictr   local_metadatastrictmissing_keysunexpected_keys
error_msgsc           
   	      sJ   | j D ]}|| }	|	|v rt| |||	 qt |||d||| dS )z$Loads metric states from state_dict.TN)rN   rb   r;   r4   _load_from_state_dict)
rS   r   r   r   r   r   r   r   r   rW   rT   r#   r$   r     s   
zMetric._load_from_state_dictc                    sb   t jjt jjf | jj fdd| D }tdd  D }|s+|s+i }|S |r/|}|S )zFfilter kwargs such that they match the update signature of the metric.c                    s0   i | ]\}}|  v r| j vr||qS r#   )ry   kindr   _params_sign_paramsr#   r$   ro     s    *z)Metric._filter_kwargs.<locals>.<dictcomp>c                 s   s    | ]
}|j tjjkV  qd S r   )r   r@   	ParameterVAR_KEYWORDr   r#   r#   r$   r     s    z(Metric._filter_kwargs.<locals>.<genexpr>)	r@   r   VAR_POSITIONALr   rC   
parametersrr   r   values)rS   r,   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 )N__iter__)r8   r9   idrN   rk   hasattrr<   r   extendappendhashtuple)rS   	hash_valsr   rw   r#   r#   r$   __hash__  s   

zMetric.__hash__otherc                 C      t tj| |S r   CompositionalMetricr   addrS   r   r#   r#   r$   __add__     zMetric.__add__c                 C   r   r   r   r   bitwise_andr   r#   r#   r$   __and__  r   zMetric.__and__c                 C   r   r   )r   r   eqr   r#   r#   r$   __eq__  r   zMetric.__eq__c                 C   r   r   r   r   floor_divider   r#   r#   r$   __floordiv__  r   zMetric.__floordiv__c                 C   r   r   )r   r   ger   r#   r#   r$   __ge__   r   zMetric.__ge__c                 C   r   r   )r   r   gtr   r#   r#   r$   __gt__  r   zMetric.__gt__c                 C   r   r   )r   r   ler   r#   r#   r$   __le__  r   zMetric.__le__c                 C   r   r   )r   r   ltr   r#   r#   r$   __lt__	  r   zMetric.__lt__c                 C   r   r   r   r   matmulr   r#   r#   r$   
__matmul__  r   zMetric.__matmul__c                 C   r   r   r   r   fmodr   r#   r#   r$   __mod__  r   zMetric.__mod__c                 C   r   r   r   r   mulr   r#   r#   r$   __mul__  r   zMetric.__mul__c                 C   r   r   )r   r   ner   r#   r#   r$   __ne__  r   zMetric.__ne__c                 C   r   r   r   r   
bitwise_orr   r#   r#   r$   __or__  r   zMetric.__or__c                 C   r   r   r   r   powr   r#   r#   r$   __pow__  r   zMetric.__pow__c                 C      t tj|| S r   r   r   r#   r#   r$   __radd__  r   zMetric.__radd__c                 C   r   r   r   r   r#   r#   r$   __rand__"  s   zMetric.__rand__c                 C   r  r   r   r   r#   r#   r$   __rfloordiv__&  r   zMetric.__rfloordiv__c                 C   r  r   r  r   r#   r#   r$   __rmatmul__)  r   zMetric.__rmatmul__c                 C   r  r   r  r   r#   r#   r$   __rmod__,  r   zMetric.__rmod__c                 C   r  r   r  r   r#   r#   r$   __rmul__/  r   zMetric.__rmul__c                 C   r  r   r  r   r#   r#   r$   __ror__2  r   zMetric.__ror__c                 C   r  r   r  r   r#   r#   r$   __rpow__5  r   zMetric.__rpow__c                 C   r  r   r   r   subr   r#   r#   r$   __rsub__8  r   zMetric.__rsub__c                 C   r  r   r   r   true_divider   r#   r#   r$   __rtruediv__;  r   zMetric.__rtruediv__c                 C   r  r   r   r   bitwise_xorr   r#   r#   r$   __rxor__>  r   zMetric.__rxor__c                 C   r   r   r  r   r#   r#   r$   __sub__A  r   zMetric.__sub__c                 C   r   r   r  r   r#   r#   r$   __truediv__D  r   zMetric.__truediv__c                 C   r   r   r!  r   r#   r#   r$   __xor__G  r   zMetric.__xor__c                 C      t tj| d S r   r   r   absrU   r#   r#   r$   __abs__J  r   zMetric.__abs__c                 C   r'  r   )r   r   bitwise_notrU   r#   r#   r$   __inv__M  r   zMetric.__inv__c                 C   s   |   S r   )r,  rU   r#   r#   r$   
__invert__P     zMetric.__invert__c                 C   s   t t| d S r   )r   _negrU   r#   r#   r$   __neg__S     zMetric.__neg__c                 C   r'  r   r(  rU   r#   r#   r$   __pos__V  r   zMetric.__pos__idxc                    s   t  fdd| d S )Nc                    s   |   S r   r#   xr3  r#   r$   <lambda>Z  s    z$Metric.__getitem__.<locals>.<lambda>)r   )rS   r3  r#   r6  r$   __getitem__Y  r&   zMetric.__getitem__c                 C   s   t | fS r   )r'   __str__rU   r#   r#   r$   __getnewargs__\  r1  zMetric.__getnewargs__c                 C   s   t d)Nz#Metrics does not support iteration.)NotImplementedErrorrU   r#   r#   r$   r   _  r.  zMetric.__iter__)NFr   N)NNTN)T)NNTTN)r   r'   )r   r   F)Nr   F)r   r'   r   r'   )gr9   
__module____qualname____doc____jit_ignored_attributes____jit_unused_properties__r)   r   r=   __annotations__r*   r+   r   r5   propertyrV   r   r   r`   r   r   rc   r   jitunusedrh   re   rf   r	   r{   r   r   rD   rs   r   r   r   r
   r   rE   r   rB   rF   rq   r   r   r   r   r(   dtyper   r~   r   r   r   r   r   rZ   r   dictr   r   r   intr   r   r   r   r   r   r   r   r   r  r  r	  r  r  r  r  r  r  r  r  r  r  r  r  r   r#  r$  r%  r&  r*  r,  r-  r0  r2  r8  r   r:  r   __classcell__r#   r#   rT   r$   r'   +   s8  
  =

F+'  
	
'!




 
)
	
































r'   r5  c                 C   s   t |  S r   )r   r)  r4  r#   r#   r$   r/  c  r1  r/  c                       s   e Zd ZdZdedeeeee	f de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                    sR   t    || _t|tr| d| n|| _t|tr$| d| dS || _dS )a  
        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
        rL  rM  N)r4   r5   opr<   r   register_bufferrL  rM  )rS   rK  rL  rM  rT   r#   r$   r5   j  s   



zCompositionalMetric.__init__r1   r0   c                 C   s   d S r   r#   )rS   r1   r0   r#   r#   r$   r     s   zCompositionalMetric._sync_distrd   r,   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 Nr#   )r<   rL  r'   rB   r   rM  rg   r#   r#   r$   rB     s
    $zCompositionalMetric.updatec                 C   sZ   t | jtr| j }n| j}t | jtr| j }n| j}|d u r'| |S | ||S r   )r<   rL  r'   rF   rM  rN  )rS   val_aval_br#   r#   r$   rF     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 r6d S |d u rGt | jtrBd S | |S | ||S rP  )r<   rL  r'   r   rM  rN  )rS   rd   r,   rQ  rR  r#   r#   r$   rh     s   
 
 
zCompositionalMetric.forwardc                 C   s4   t | jtr| j  t | jtr| j  d S d S r   )r<   rL  r'   rq   rM  rU   r#   r#   r$   rq     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 )N)r   )r<   rL  r'   rZ   rM  )rS   r   r#   r#   r$   rZ     s
   zCompositionalMetric.persistentc                 C   s8   d| j j dt| j dt| j d}| jj| }|S )Nz(
  z(
    z,
    z
  )
))rN  r9   reprrL  rM  r8   )rS   _op_metricsrepr_strr#   r#   r$   __repr__  s   (zCompositionalMetric.__repr__rF   c                 C   s   |S r   r#   )rS   rF   r#   r#   r$   rE     s   z!CompositionalMetric._wrap_compute)NNr<  r=  )r9   r>  r?  r@  r   r   r'   rI  r~   r   r5   r   r   r   rB   rF   r   rE  rF  rh   rq   r=   rZ   r   rV  rE   rJ  r#   r#   rT   r$   r   g  s(     
r   )+r   r@   abcr   r   
contextlibr   copyr   typingr   r   r	   r
   r   r   r   r   r   r   r   torch.nnr   torchmetrics.utilitiesr   r   torchmetrics.utilities.datar   r   r   r   r   r   r   "torchmetrics.utilities.distributedr   !torchmetrics.utilities.exceptionsr   r=   r%   r'   r/  r   r#   r#   r#   r$   <module>   s.   ,$	      >