o
    ^i_9                     @   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 d dl	m
Z
 d dlmZ er2d dlmZ dd	 d
fdefddZe jedd	 ddZe jedd	 d
dZeG dd dZeG dd dZG dd dZG dd dZd$ddZdd	 d dfddZdd  Zd%d"d#ZdS )&    N)deque)	dataclass)TYPE_CHECKINGprofile)
DeviceType)_KinetoEventc                 C      | j S N)childrenx r   P/var/www/html/RAG/RAG_venv/lib/python3.10/site-packages/torch/profiler/_utils.py<lambda>       r   Freversec                 c   sX    |rt ndd }t|| }|r*||}|V  |||D ]}|| q|sd S d S )Nc                 S      | S r
   r   r   r   r   r   r          z_traverse.<locals>.<lambda>)reversedr   append)treenext_fnchildren_fnr   order	remaining
curr_eventchild_eventr   r   r   	_traverse   s   r   c                 C      |   S r
   )popr   r   r   r   r          T)r   r   c                 C   r   r
   )popleftr   r   r   r   r      r!   c                   @   sJ   e Zd ZU dZeed< dZeed< dZeed< dZeed< e	dd Z
dS )	EventMetricsr   duration_time_nsself_time_nsidle_time_nsqueue_depthc                 C   s   | j dkrdS | j| j  S )Nr   g        )r$   r&   selfr   r   r   fraction_idle_time(   s   
zEventMetrics.fraction_idle_timeN)__name__
__module____qualname__r$   int__annotations__r%   r&   r'   propertyr*   r   r   r   r   r#   !   s   
 r#   c                   @   s*   e Zd ZU eed< eed< dZeed< dS )Intervalstartendr   r'   N)r+   r,   r-   r.   r/   r'   r   r   r   r   r1   /   s   
 r1   c                   @   sF   e Zd ZdddZdd Zdd Zdefd	d
Zdee	 fddZ
dS )EventKeyreturnNc                 C   s
   || _ d S r
   event)r)   r7   r   r   r   __init__7      
zEventKey.__init__c                 C   s   t | jjS r
   )hashr7   idr(   r   r   r   __hash__:   s   zEventKey.__hash__c                 C   s   | j j|j jkS r
   )r7   r;   )r)   otherr   r   r   __eq__=   s   zEventKey.__eq__c                 C   s
   | j j S r
   )r7   namer(   r   r   r   __repr__@   r9   zEventKey.__repr__	intervalsc           	      C   s   d}t |dd d}|r*t| jj|d j}t| jj|d j}||k r*||| 7 }d\}}|t|k rw|| }|| }|d7 }|j|jkrW|j|jkrQ|d7 }q.|j|_|}t| jj|j}t| jj|j}||k rq||| 7 }|t|k s4|S )Nr   c                 S   r	   r
   r2   r   r   r   r   r   E   r   z,EventKey.intervals_overlap.<locals>.<lambda>key)r      rE   )	sortedmaxr7   start_time_nsr2   minend_time_nsr3   len)	r)   rA   overlap_timeoverlap_startoverlap_endijprev_intervalcurr_intervalr   r   r   intervals_overlapC   s0   zEventKey.intervals_overlapr5   N)r+   r,   r-   r8   r<   r>   strr@   listr1   rS   r   r   r   r   r4   6   s    
r4   c                   @   sV   e Zd ZdeddfddZdddZdd	 Zdd
dZdd Zdde	de
fddZdS )BasicEvaluationprofr5   Nc                 C   sd   || _ i | _|   tdd | j D dd d| _dd | jD | _g | _|  | _	| 
  d S )Nc                 s   s    | ]}|V  qd S r
   r   .0er   r   r   	<genexpr>j   s    z+BasicEvaluation.__init__.<locals>.<genexpr>c                 S   s   | j jS r
   )r7   rH   r   r   r   r   r   j   r!   z*BasicEvaluation.__init__.<locals>.<lambda>rC   c                 S      g | ]}|j qS r   r6   rY   r   r   r   
<listcomp>l       z,BasicEvaluation.__init__.<locals>.<listcomp>)r   metricscompute_self_timerF   keys
event_keyseventscuda_eventscompute_queue_depthqueue_depth_listcompute_idle_time)r)   rX   r   r   r   r8   e   s   
zBasicEvaluation.__init__c                 C   s   | j jdusJ t| j j }|rS| }|j}|jD ]}||j8 }|| qt|| j	vs<J d|j
 d|j t|d| j	t|< |j| j	t| _|sdS dS )zM
        Computes event's self time(total time - time in child ops).
        NzDuplicate id: z, )r%   )r   kineto_resultsr   experimental_event_treer    r$   r   r   r4   r`   r;   r?   r#   )r)   stackr   	self_timer   r   r   r   ra   q   s$   

z!BasicEvaluation.compute_self_timec                    s2  | j jdusJ | j j }dd dd tfdd|D dd	 d
}tfdd|D dd	 d
}t|| dd	 d
| _i }d}|D ] t| fdd	|d}|| < |dur\|n|}qEd}d}|| | j }	dd }
g }|	j|
d
 |	D ]}t|dr| d }| |	  d }||v r|| dur|| }t|dr|
 }|
 |  }||v r|| dur|| }nt|dr|j}|j}|t|k r|| 
 |kr|d7 }|t|k r|| 
 |ks|| d }t|d}t|dst|dr|t||| qxt|dr|| jt| _qx|S )z
        Computes queue_depth at each event. This will calculate the queue depth data for
        All the events in the tree.
        This will return a list of Interval of queue depth data of cuda launch and kernels.
        Nc                    s.   h d}t t| d|  t fdd|D S )z+Check if the event is a CUDA launch kernel.>   cudaLaunchKernel__cudaLaunchKernelcudaLaunchKernelExCcudaLaunchCooperativeKernel&cudaLaunchCooperativeKernelMultiDevicer?   c                 3   s    | ]}  |V  qd S r
   )
startswithrZ   patternr?   r   r   r\      s    zUBasicEvaluation.compute_queue_depth.<locals>.is_cuda_launch_kernel.<locals>.<genexpr>)rU   getattrany)r[   launch_patternsr   ru   r   is_cuda_launch_kernel   s   zBBasicEvaluation.compute_queue_depth.<locals>.is_cuda_launch_kernelc                    sF   |   tjkr	dS tt| d|   h d}t fdd|D  S )z,Check if the event is a CUDA runtime kernel.Fr?   >   cpymemfreeallocc                 3   s    | ]}| v V  qd S r
   r   rs   ru   r   r   r\      s    zNBasicEvaluation.compute_queue_depth.<locals>.is_cuda_kernel.<locals>.<genexpr>)device_typer   CUDArU   rv   lowerrw   )r[   exclude_patternsr   ru   r   is_cuda_kernel   s
   z;BasicEvaluation.compute_queue_depth.<locals>.is_cuda_kernelc                 3       | ]	} |r|V  qd S r
   r   rY   )ry   r   r   r\          z6BasicEvaluation.compute_queue_depth.<locals>.<genexpr>c                 S   r   r
   start_nsr   r   r   r   r      r!   z5BasicEvaluation.compute_queue_depth.<locals>.<lambda>rC   c                 3   r   r
   r   rY   )r   r   r   r\      r   c                 S   r   r
   r   r   r   r   r   r      r!   c                 S   r   r
   r   r   r   r   r   r      r!   r   c                    s   |      kS r
   )linked_correlation_idr   )cuda_launch_eventr   r   r      s    rB   c                 S   s@   t | dr|  d S t | dr|  S t | dr| jS td)Nstart_us  r   rH   zUnknown Event Type)hasattrr   r   rH   	Exceptionr6   r   r   r   new_old_event_comparator   s   


zEBasicEvaluation.compute_queue_depth.<locals>.new_old_event_comparatorr   r   r   rH   rE   )r   ri   rd   rF   re   index_of_first_matchsortr   r   duration_usr   duration_nsrH   rJ   rK   rG   r   r1   r`   r4   r'   )r)   cuda_event_listcuda_launch_eventscuda_kernel_eventskernel_mappinglast_mapped_kernelindexcurrent_kernel_indexspawned_kernel_index
all_eventsr   rg   r7   
start_timeend_timecurrent_queue_depthr   )r   r   ry   r   rf      sz   
	




z#BasicEvaluation.compute_queue_depthc                 C   s   d}d}g }| j r(| jr(|t| jd j| j d jt| j d j| jd jg7 }| j D ] }|jdkr9|s9|j}d}|jdkrK|rK|t||j d}q+dd | j	
 D }|D ]}t||| j	t| _qXdS )z4
        Computes idle time of the profile.
        Fr   r   Tc                 S   r]   r   r6   rY   r   r   r   r^     r_   z5BasicEvaluation.compute_idle_time.<locals>.<listcomp>N)rg   rd   r1   rH   r2   r3   rJ   r'   r   r`   rb   r4   rS   r&   )r)   idle
idle_startidle_intervals
data_point
event_listr7   r   r   r   rh      s0   
z!BasicEvaluation.compute_idle_timec                    s  ddl }ttj}dd |D }d d}g d}|t|k ru||  kr+|d7 }qt|d t|D ]6}t| fdd|d	}t|||d
}	|	durj||	 |krjt	||	 j
|| j
 |durf|n|} nq4|d7 }|t|k s fddj D }
|
r|jfdd|
D |jd}|jfdd|
D |jd}||| || }||| || }|d|  }dd tt||
tdddD }
|
d| }
|
S )a  
        Filter and Rank the events based on some heuristics:
        1) Events that are in the falling phase of the queue depth.
        2) Events that have a high idle_time, self_time difference.

        Parameters:
            length: The number of events to return.
        r   Nc                 S   r]   r   )r'   rY   r   r   r   r^     r_   z/BasicEvaluation.rank_events.<locals>.<listcomp>   rE   c                    s   |  kS r
   r   r   )bottom_threasholdr   r   r   -  r!   z-BasicEvaluation.rank_events.<locals>.<lambda>rB   )r2   r3   c                    s   g | ]	}|  r|qS r   )rS   rZ   r7   )decrease_intervalr   r   r^   <  s    c                       g | ]} j | jqS r   )r`   r%   r   r(   r   r   r^   C      )dtypec                    r   r   )r`   r*   r   r(   r   r   r^   G  r   g333333?c                 S   s   g | ]\}}|qS r   r   )rZ   _r7   r   r   r   r^   O  s    T)rD   r   )torchrV   r   rg   rK   ranger   argmaxr   r1   r2   r`   rb   tensorfloat32meanstdrF   zipoperator
itemgetter)r)   lengthr   rg   	qd_valuestop_threasholdrO   rP   next_minimum_idxpeak_idxr   rl   	idle_timenormalized_gainnormalized_selfheuristic_score_listr   )r   r   r)   r   rank_events  sf   
zBasicEvaluation.rank_eventsrE   Tr   print_enablec                    sJ     |}|s	|S |rdnd}|d fdd|D 7 }|r#t| |S )NzOptimizable events:
zNo events to optimize

c                    s@   g | ]}d  d| dt |j d j| jd ddd  	qS )zP--------------------------------------------------------------------------------z
Event:                z
Source code location: z
Percentage idle time: d   z.2fz%
)source_code_locationr7   r`   r*   r   r(   r   r   r^   a  s    z:BasicEvaluation.get_optimizable_events.<locals>.<listcomp>)r   joinprint)r)   r   r   r   outputr   r(   r   get_optimizable_eventsZ  s   


z&BasicEvaluation.get_optimizable_eventsrT   )rE   T)r+   r,   r-   r   r8   ra   rf   rh   r   r.   boolr   r   r   r   r   rW   d   s    

nIrW   c                 C   sD   |d u s
|t | krt | }t||D ]}|| | r|  S qd S r
   )rK   r   )seq	predicater2   r3   rO   r   r   r   r   o  s   r   c                 C   r   r
   r   r   r   r   r   r   x  r   c                 C   s2   | || } t | dkrd S | t| |d| S )Nr   rC   )rK   r   rG   )r   rD   r2   r3   r   r   r   r   x  s   r   c                 C   s0   | d urt d| j}|d u r| j} q | jS dS )Nz
\.py\(.*\)zNo source code location found)researchr?   parent)r7   matchr   r   r   r     s   r   r5   c                  C   s8   ddl m}  |  	 W d    d S 1 sw   Y  d S )Nr   r   )torch.autograd.profilerr   r   r   r   r   _init_for_cuda_graphs  s   "r   )r   NrT   )	functoolsr   r   collectionsr   dataclassesr   typingr   r   r   torch.profilerr   torch.autogradr   r   r   partialtraverse_dfstraverse_bfsr#   r1   r4   rW   r   r   r   r   r   r   r   r   <module>   s6   

.  
	