o
    Ih                     @   s   d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZmZ dd a					dddZ
dd	 Zd
d Zdd Zdd Zdd Zg adedefddZ			dddZdS )    N)profileProfilerActivityc                   C   s   d S )N r   r   r   T/var/www/vscode/kcb/lib/python3.10/site-packages/torch/_functorch/benchmark_utils.pysynchronize   s   r      c	              	   C   sr  |du rdg}|dgkrt j rt jja|du ri }|du r!i }|> t d tdD ]}	| |fi | t  q-t d t }
t|D ]}	| |fi | t  qHt }W d   n1 sdw   Y  ||
 }tdd|i|4}|" t  t d t|D ]}	| |fi | t  qW d   n1 sw   Y  W d   n1 sw   Y  |	| |S )a0  
    Output the chrome trace of running f(input, **kwargs_for_f) with [optimize_ctx]
    [num_runs] times to [trace_filename].

    [activities] are the activities that the profiler will record, e.g. ProfilerActivity.CUDA.
    Return total runtime without the profiler

    Outputs to trace_filename
    Ncudacpui9     
activitiesr   )
torchr   is_availabler   manual_seedrangetimeperf_counterr   export_chrome_trace)finputtrace_filenameoptimize_ctxr   num_runsdeviceskwargs_for_fkwargs_for_profiler_t0t1timingprofr   r   r   dump_chrome_trace   sD   




r    c                 C   s   t | }t|}|d }|S )NtraceEvents)openjsonload)filenamer   dataeventsr   r   r   get_chrome_trace_eventsK   s   
r(   c                 C   s(   d| v o| d t v od| v o| d dkS )NpidphX)gpu_pidseventr   r   r   is_gpu_compute_eventR   s   

r/   c                 C   s4   g }| D ]}t |sq|| qt|tddS )Nts)key)r/   appendsortedoperator
itemgetter)r'   sorted_gpu_eventsr.   r   r   r   get_sorted_gpu_events\   s   r7   c                 C   s   t | dkrdS | d }|d |d  }|d }| dd  D ]}t|d |}|d |d  }|t|| d }t||}q|S )Nr   r0   durr   )lenmax)r6   r.   current_end_timetotal_duration
start_timeend_timer   r   r   get_duratione   s   r?   c                 C   s6   dd }t | }g }|D ]}||sq|| q|S )Nc                 S   s8   d| v od| d v pd| d v pd| d v pd| d v S )Nnamegemmconvcutlasswgradr   r-   r   r   r   is_mm_conv_eventt   s   


z7get_sorted_gpu_mm_conv_events.<locals>.is_mm_conv_event)r7   r2   )r'   rE   
gpu_eventssorted_eventsr.   r   r   r   get_sorted_gpu_mm_conv_eventss   s   rH   r%   total_lengthc                 C   s   t | }g a|D ]}d|vrq|d dkr$d|d d v r$t|d  q|d }t|}t|| }t|}t|| }||fS )a  
    Process the chrome traces outputs by the pytorch profiler to compute GPU Utilization
    and percent of times spent on matmul and convolution

    Args:
        filename(str): Name of chrome traces file produced by pytorch profiler

        total_length(float): total length of the process without profiler in second

    Return:
        tuple: (GPU Utilization, percent of time spent on matmul and convolution)
    r@   process_labelsGPUargslabelsr)   g    .A)r(   r,   r2   r7   r?   rH   )r%   rI   r'   r.   r6   utilizationsorted_gpu_mm_conv_eventsmm_conv_utilizationr   r   r   compute_utilization   s   rQ   tmp_chrome_tracec              	   C   sz   t j|}|st | td|  |du rt }t j||d }t| |||t	j
g|dgd}t||\}	}
|	|
fS )a  
    Benchmark the GPU Utilization and percent of time spent on matmul and convolution operations of
    running f(input, **kwargs_for_f) with [optimize_ctx] [num_runs] times.
    It will produce a chrome trace file in trace_folder/trace_file_name.json

    Example:

    ```
    def f(a):
        return a.sum()
    a = torch.rand(2**20, device="cuda")
    utilization, mm_conv_utilization = benchmark_utilization(f, a, "tmp", trace_file_name = "tmp_chrome_trace")
    ```

    Args:
        f: function to benchmark

        input: input to :attr:`f`

        trace_folder: name of the folder to store the chrome trace

        optimize_ctx: the context in which f will run

        trace_file_name: name of the dumped chrome trace file, default to "tmp_chrome_trace"

        num_runs: number of times to run f, excluding the warm-up runs, default to 1.

    Return:
        tuple: (GPU Utilization, percent of time spent on matmul and convolution)

    zcreate folder Nz.jsonr   )r   r   )ospathexistsmakedirsprint
contextlibnullcontextjoinr    r   CUDArQ   )r   r   trace_folderr   trace_file_namer   isExistchrome_trace_file_namerI   rN   rP   r   r   r   benchmark_utilization   s(   '
	r`   )r   NNN)NrR   r   )rX   r#   r4   rS   r   r   torch.profilerr   r   r   r    r(   r/   r7   r?   rH   r,   strfloatrQ   r`   r   r   r   r   <module>   s0   

:
	&