o
    }oiW                     @   s  d dl Z d dlZd dlZd dlmZ d dlmZmZ 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 d dlmZ d dlmZmZ d	Zd
ZdZdZdZdZdd Zi dddfdededej dej dedede!de"de!de!de#fddZ$i dfdej dej d edede"de#fd!d"Z%G d#d$ d$Z&d%d& Z'i dddfdeded'eej  d(eej  de!de"de!de!de#fd)d*Z(G d+d, d,e&Z)d-ej d.ej d/e!fd0d1Z*			d6deded-eej  d.eej  de!d/e!de!de!de#fd2d3Z+G d4d5 d5e&Z,dS )7    N)partial)CallableOptional)entropy)logits_to_probs)Poolset_start_method)Metric)GlobalAverageLossMetric
Perplexity   
            g      ?c                 C   sF   dt jd< dt jd< tj rtjdvr!tjjd| |d dS dS dS )	z Setup ddp enviroment 	localhostMASTER_ADDR8088MASTER_PORT)win32cygwingloorank
world_sizeN)osenvirontorchdistributedis_availablesysplatforminit_process_groupr    r#   U/home/ubuntu/.local/lib/python3.10/site-packages/tests/collections/common/pl_utils.py	setup_ddp5   s
   

r%   T:0yE>r   	worldsizepredstargetmetric_class	sk_metricdist_sync_on_stepmetric_argscheck_dist_sync_on_stepcheck_batchatolc                    s`  |d
d|i|}t |}t |}t| t|D ][ |    }|jr]| dkr\t fddt|D }t fddt|D }|||}|r\tj	|
 ||
ds\J q|    }|	rttj	|
 ||
dstJ q| }t|tjsJ tfddttD }tfddttD }|||}tj	|
 ||
dsJ d	S )a   Utility function doing the actual comparison between lightning class metric
        and reference metric.
        Args:
            rank: rank of current process
            worldsize: number of processes
            preds: torch tensor with predictions
            target: torch tensor with targets
            metric_class: lightning metric class that should be tested
            sk_metric: callable function that is used for comparison
            dist_sync_on_step: bool, if true will synchronize metric state across
                processes at each ``forward()``
            metric_args: dict with additional arguments used for class initialization
            check_dist_sync_on_step: bool, if true will check if the metric is also correctly
                calculated per batch per device (and not just at the end)
            check_batch: bool, if true will check if the metric is also correctly
                calculated across devices for each batch (and not just at the end)
    r,   r   c                       g | ]} |  qS r#   r#   .0r)ir(   r#   r$   
<listcomp>h       z_class_test.<locals>.<listcomp>c                    r1   r#   r#   r2   )r5   r)   r#   r$   r6   i   r7   r0   c                       g | ]} | qS r#   r#   r3   r5   )r(   r#   r$   r6   x       c                    r9   r#   r#   r:   )r)   r#   r$   r6   y   r;   Nr#   )pickledumpsloadsrangeNUM_BATCHESr,   r   stacknpallclosenumpycompute
isinstanceTensor)r   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   metricpickled_metricbatch_result	ddp_preds
ddp_targetsk_batch_resultresulttotal_predstotal_target	sk_resultr#   )r5   r(   r)   r$   _class_test>   s.   



rR   metric_functionalc           
      C   s^   t |fi |}ttD ] }|| | || }|| | || }	tj| |	|ds,J qdS )a   Utility function doing the actual comparison between lightning functional metric
        and reference metric.
        Args:
            preds: torch tensor with predictions
            target: torch tensor with targets
            metric_functional: lightning metric functional that should be tested
            sk_metric: callable function that is used for comparison
            metric_args: dict with additional arguments used for class initialization
    r8   N)r   r?   r@   rB   rC   rD   )
r(   r)   rS   r+   r-   r0   rH   r5   lightning_resultrQ   r#   r#   r$   _functional_test   s   rU   c                   @   s   e Zd ZdZdZdd Zdd Zi fdejdejd	e	d
e	de
f
ddZi ddfdedejdejded
e	dede
dedefddZdS )MetricTesterae   Class used for efficiently run alot of parametrized tests in ddp mode.
        Makes sure that ddp is only setup once and that pool of processes are
        used for all tests.
        All tests should subclass from this and implement a new method called
            `test_metric_name`
        where the method `self.run_metric_test` is called inside.
    r&   c                    sZ   zt d W n	 ty   Y nw t _t jd _ jt fddt jD  dS )z Setup the metric class. This will spawn the pool of workers that are
            used for metric testing and setup_ddp
        spawn)	processesc                       g | ]}| j fqS r#   poolSizer3   r   selfr#   r$   r6          z,MetricTester.setup_class.<locals>.<listcomp>N)	r   RuntimeErrorNUM_PROCESSESr[   r   poolstarmapr%   r?   r]   r#   r]   r$   setup_class   s   &zMetricTester.setup_classc                 C   s   | j   | j   dS )z Close pool of workers N)rb   closejoinr]   r#   r#   r$   teardown_class   s   
zMetricTester.teardown_classr(   r)   rS   r+   r-   c                 C   s   t |||||| jd dS )a   Main method that should be used for testing functions. Call this inside
            testing method
            Args:
                preds: torch tensor with predictions
                target: torch tensor with targets
                metric_functional: lightning metric class that should be tested
                sk_metric: callable function that is used for comparison
                metric_args: dict with additional arguments used for class initialization
        )r(   r)   rS   r+   r-   r0   N)rU   r0   )r^   r(   r)   rS   r+   r-   r#   r#   r$   run_functional_metric_test   s   
z'MetricTester.run_functional_metric_testTddpr*   r,   r.   r/   c
           
         s|   |r,t jdkrtd  jtt||||||||	 jd
 fddt	 j
D  dS tdd||||||||	 jd dS )	a   Main method that should be used for testing class. Call this inside testing
            methods.
            Args:
                ddp: bool, if running in ddp mode or not
                preds: torch tensor with predictions
                target: torch tensor with targets
                metric_class: lightning metric class that should be tested
                sk_metric: callable function that is used for comparison
                dist_sync_on_step: bool, if true will synchronize metric state across
                    processes at each ``forward()``
                metric_args: dict with additional arguments used for class initialization
                check_dist_sync_on_step: bool, if true will check if the metric is also correctly
                    calculated per batch per device (and not just at the end)
                check_batch: bool, if true will check if the metric is also correctly
                    calculated across devices for each batch (and not just at the end)
        r   DDP not supported on windows)	r(   r)   r*   r+   r,   r-   r.   r/   r0   c                    rY   r#   rZ   r\   r]   r#   r$   r6      r_   z6MetricTester.run_class_metric_test.<locals>.<listcomp>r      N)r    r!   pytestskiprb   rc   r   rR   r0   r?   r[   )
r^   ri   r(   r)   r*   r+   r,   r-   r.   r/   r#   r]   r$   run_class_metric_test   s>   


z"MetricTester.run_class_metric_testN)__name__
__module____qualname____doc__r0   rd   rg   r   rG   r   dictrh   boolr	   rn   r#   r#   r#   r$   rV      sN    
"	
rV   c                 C   s   t | dd}t|}| S )N)axis)r   rB   expmean)probsentpplr#   r#   r$   reference_perplexity_func  s   
r|   ry   logitsc	                    s  t d
d|i|}	du du kr.tt |	 W d   dS 1 s'w   Y  dS t|	}
t|
}	t| t|D ]} |	du rGdn  du rPdn  }|	j	r| dkrdurpt
 fddt|D }nt
 fddt|D }t|dd}t|}|rtj| ||d	sJ q>du rt  dd}n  }t|}|rtj| ||d	sJ q>du du ksJ |	 }t|t
jsJ du rtddt}tj| ||d	sJ dS )a   Utility function doing the actual comparison between lightning class metric
        and reference metric.
        Args:
            rank: rank of current process
            worldsize: number of processes
            probs: torch tensor with probabilities
            logits: torch tensor with logits. The function checks ``probs`` and ``logits are mutually exclusive for
                ``Perplexity`` metric.
            dist_sync_on_step: bool, if true will synchronize metric state across
                processes at each ``forward()``
            metric_args: dict with additional arguments used for class initialization
            check_dist_sync_on_step: bool, if true will check if the metric is also correctly
                calculated per batch per device (and not just at the end)
            check_batch: bool, if true will check if the metric is also correctly
                calculated across devices for each batch (and not just at the end)
    r,   Nr   c                    r1   r#   r#   r2   )r5   ry   r#   r$   r6   B  r7   z*_perplexity_class_test.<locals>.<listcomp>c                    r1   r#   r#   r2   )r5   r}   r#   r$   r6   D  r7   F)	is_binaryr8   r#   )r   rl   raises
ValueErrorr<   r=   r>   r?   r@   r,   r   rA   r   r|   rB   rC   rD   rE   rF   rG   )r   r'   ry   r}   r,   r-   r.   r/   r0   
perplexityrI   rJ   	ddp_probs
ddp_logitsrM   prN   rQ   r#   )r5   r}   ry   r$   _perplexity_class_test  sH   


* r   c                   @   sF   e Zd Zi ddfdedeej deej dedededefd	d
ZdS )PerplexityTesterTri   ry   r}   r,   r-   r.   r/   c                    st   |r*t jdkrtd  jtt|||||| jd fddt	 j
D  dS tdd|||||| jd	 dS )	a   Main method that should be used for testing class. Call this inside testing
            methods.
            Args:
                ddp: bool, if running in ddp mode or not
                probs: torch tensor with probabilities.
                logits: torch tensor with logits. This test checks that probs and logits are mutually exclusive for
                    ``Perplexity`` metric.
                dist_sync_on_step: bool, if true will synchronize metric state across
                    processes at each ``forward()``
                metric_args: dict with additional arguments used for class initialization
                check_dist_sync_on_step: bool, if true will check if the metric is also correctly
                    calculated per batch per device (and not just at the end)
                check_batch: bool, if true will check if the metric is also correctly
                    calculated across devices for each batch (and not just at the end)
        r   rj   )ry   r}   r,   r-   r.   r/   r0   c                    rY   r#   rZ   r\   r]   r#   r$   r6     r_   z>PerplexityTester.run_class_perplexity_test.<locals>.<listcomp>r   rk   N)r    r!   rl   rm   rb   rc   r   r   r0   r?   r[   )r^   ri   ry   r}   r,   r-   r.   r/   r#   r]   r$   run_class_perplexity_testb  s6   



z*PerplexityTester.run_class_perplexity_testN)	ro   rp   rq   rt   r   r   rG   rs   r   r#   r#   r#   r$   r   a  s&    r   loss_sum_or_avgnum_measurementstake_avg_lossc                 C   sD   |    } |r| |9 } | }|drttdS |  | S )a%  
    Returns average loss for data from``loss_sum_or_avg``. This function sums all losses from ``loss_sum_or_avg`` and
    divides the sum by the sum of ``num_measurements`` elements.

    If ``take_avg_loss`` is ``True`` then ``loss_sum_or_avg[i]`` elements are mean values of ``num_measurements[i]``
    losses. In that case before computing sum of losses each element of ``loss_sum_or_avg`` is multiplied by
    corresponding element of ``num_measurements``.

    If ``num_measurements`` sum is zero then the function returns NaN tensor.

    The function is used for testing ``nemo.collections.common.metrics.GlobalAverageLossMetric`` class.

    Args:
        loss_sum_or_avg: a one dimensional float ``torch.Tensor``. Sums or mean values of loss.
        num_measurements: a one dimensional integer ``torch.Tensor``. Number of values on which sums of means in
            ``loss_sum_or_avg`` are calculated.
        take_avg_loss: if ``True`` then ``loss_sum_or_avg`` contains mean losses else ``loss_sum_or_avg`` contains
            sums of losses.
    r   nan)clonedetachsumeqr   tensorfloat)r   r   r   nm_sumr#   r#   r$   reference_loss_func  s   
r   c	                    s  t ||d}	t|	}
t|
}	t| t|D ] |	    }|	jrs| dkrrt fddt|D }t fddt|D }t	|||}|rr|
 rY|
 sXJ qtj| ||dsrJ d|  d| d	  q  d
  }  d
  }t	|||}|r|
 r|
 sJ qtj| ||dsJ d|  d| d	  q|	 }t|tjsJ t	|}|
 r|
 sJ dS tj| ||dsJ d|  d| dS )a   Utility function doing the actual comparison between lightning class metric
        and reference metric.
        Args:
            rank: rank of current process
            worldsize: number of processes
            loss_sum_or_avg: a one dimensional float torch tensor with loss sums or means.
            num_measurements: a one dimensional integer torch tensor with number of values on which sums or means from
                ``loss_sum_or_avg`` were computed.
            dist_sync_on_step: bool, if true will synchronize metric state across processes at each call of the
                method :meth:`forward()`
            take_avg_loss: dict with additional arguments used for class initialization
            check_dist_sync_on_step: bool, if true will check if the metric is also correctly
                calculated per batch per device (and not just at the end)
            check_batch: bool, if true will check if the metric is also correctly
                calculated across devices for each batch (and not just at the end)
    )r,   r   r   c                    r1   r#   r#   r2   )r5   r   r#   r$   r6     r7   z$_loss_class_test.<locals>.<listcomp>c                    r1   r#   r#   r2   )r5   r   r#   r$   r6     r7   r8   zbatch_result = z, sk_batch_result = z, i = rk   z	result = z, sk_result = N)r
   r<   r=   r>   r?   r@   r,   r   rA   r   isnanrB   rC   rD   rE   rF   rG   )r   r'   r   r   r,   r   r.   r/   r0   loss_metricrI   rJ   ddp_loss_sum_or_avgddp_num_measurementsrM   lsnmrN   rQ   r#   )r5   r   r   r$   _loss_class_test  sJ   



0r   c                   @   s<   e Zd Z		ddedejdejdedededefd	d
ZdS )
LossTesterTri   r   r   r,   r   r.   r/   c                    st   |r*t jdkrtd  jtt|||||| jd fddt	 j
D  d S tdd|||||| jd	 d S )Nr   rj   )r   r   r,   r   r.   r/   r0   c                    rY   r#   rZ   r\   r]   r#   r$   r6     r_   z2LossTester.run_class_loss_test.<locals>.<listcomp>r   rk   )r    r!   rl   rm   rb   rc   r   r   r0   r?   r[   )r^   ri   r   r   r,   r   r.   r/   r#   r]   r$   run_class_loss_test   s6   




zLossTester.run_class_loss_testN)TT)ro   rp   rq   rt   r   rG   r   r#   r#   r#   r$   r     s$    r   )TTr&   )-r   r<   r    	functoolsr   typingr   r   rD   rB   rl   r   scipy.statsr   torch.distributions.utilsr   torch.multiprocessingr   r   torchmetricsr	   nemo.collections.common.metricsr
   r   ra   r@   
BATCH_SIZENUM_CLASSES	EXTRA_DIM	THRESHOLDr%   intrG   rt   rs   r   rR   rU   rV   r|   r   r   r   r   r   r#   r#   r#   r$   <module>   s   	

G
u	
K9$	
H