Ë
    ÃÓ^jÿ  ã                  óF  — U d dl m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 d dlm	Z	m
Z
 d dlmZ d dlZd dlmZmZ e
rd dlmZmZ  ed«      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<   dd„Z	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dd„Zy)é    )ÚannotationsN)ÚAbstractContextManager)ÚAnyÚTYPE_CHECKING)ÚTypeVar)ÚprofileÚProfilerActivity)ÚCallableÚSequenceÚ_Rc                  ó   — y )N© r   ó    úk/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/_functorch/benchmark_utils.pyÚsynchronizer      s   € Ør   c	                ó  — |€dg}|dgk7  r8t         j                  j                  «       rt         j                  j                  a|€i }|€i }|5  t        j                  d«       t        d«      D ]  }	 | |fi |¤Ž t        «        Œ t        j                  d«       t        j                  «       }
t        |«      D ]  }	 | |fi |¤Ž t        «        Œ t        j                  «       }ddd«       
z
  }t        dd|i|¤Ž5 }|5  t        «        t        j                  d«       t        |«      D ]  }	 | |fi |¤Ž t        «        Œ 	 ddd«       ddd«       j                  |«       |S # 1 sw Y   Œ…xY w# 1 sw Y   Œ0xY w# 1 sw Y   Œ4xY w)a1  
    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   )
ÚtorchÚacceleratorÚ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Úprofs                 r   Údump_chrome_tracer,      s‹  € ð* €Ø�(ˆð �5�'Òœe×/Ñ/×<Ñ<Ô>Ü×'Ñ'×3Ñ3ˆàÐØˆØÐ"Ø Ðà	ñ 
!Ü×Ñ˜$ÔÜ�q“ò 	ˆAÙˆfÑ%˜Ò%Ü�Mð	ô 	×Ñ˜$ÔÜ×ÑÓ ˆÜ�x“ò 	ˆAÙˆfÑ%˜Ò%Ü�Mð	ô ×ÑÓ ˆ÷
!ð �"‰W€Fä	Ñ	>˜JÐ	>Ð*=Ñ	>ð À$Øñ 	ÜŒMÜ×Ñ˜dÔ#Ü˜8“_ò �Ù�&Ñ)˜LÒ)Ü•ñ÷	÷ð 	×Ñ˜^Ô,à€M÷-
!ð 
!ú÷	ð 	ú÷ð ús2   ÁBE+ÄFÄAE7ÅFÅ+E4Å7F 	Å<FÆFc                óz   — t        | «      5 }t        j                  |«      }d d d «       d   }|S # 1 sw Y   ŒxY w)NÚtraceEvents)ÚopenÚjsonÚload)Úfilenamer   ÚdataÚeventss       r   Úget_chrome_trace_eventsr5   U   s<   € Ü	ˆh‹ð ˜1Ü�y‰y˜‹|ˆ÷à�-Ñ €FØ€M÷ð ús   Œ1±:c                óD   — d| v xr | d   t         v xr d| v xr | d   dk(  S )NÚpidÚphÚX)Úgpu_pids©Úevents    r   Úis_gpu_compute_eventr=   \   s@   € ð 	�ˆò 	Ø�%‰LœHÐ$ò	à�EˆMò	ð �$‰K˜3Ñð	r   c                óŽ   — g }| D ]  }t        |«      sŒ|j                  |«       Œ! t        |t        j                  d«      ¬«      S )NÚts)Úkey)r=   ÚappendÚsortedÚoperatorÚ
itemgetter)r4   Úsorted_gpu_eventsr<   s      r   Úget_sorted_gpu_eventsrF   f   sK   € Ø.0ÐØò (ˆÜ# EÔ*ØØ× Ñ  Õ'ð(ô Ð#¬×)<Ñ)<¸TÓ)BÔCÐCr   c                óÒ   — t        | «      dk(  ry| d   }|d   |d   z   }|d   }| dd  D ]:  }t        |d   |«      }|d   |d   z   }|t        ||z
  d«      z   }t        ||«      }Œ< |S )Nr   r?   Úduré   )ÚlenÚmax)rE   r<   Úcurrent_end_timeÚtotal_durationÚ
start_timeÚend_times         r   Úget_durationrP   o   sž   € Ü
ÐÓ Ò"ØØ˜aÑ €EØ˜T‘{ U¨5¡\Ñ1ÐØ˜5‘\€NØ" 1 2Ð&ò ;ˆÜ˜˜t™Ð&6Ó7ˆ
Ø˜‘;  u¡Ñ-ˆØ'¬#¨h¸Ñ.CÀQÓ*GÑGˆÜÐ/°Ó:Ñð	;ð
 Ðr   c                ój   — dd„}t        | «      }g }|D ]  } ||«      sŒ|j                  |«       Œ |S )Nc                óR   — d| v xr" d| d   v xs d| d   v xs d| d   v xs d| d   v S )NÚnameÚgemmÚconvÚcutlassÚwgradr   r;   s    r   Úis_mm_conv_eventz7get_sorted_gpu_mm_conv_events.<locals>.is_mm_conv_event~   sT   € Ø˜ˆò 
Ø�e˜F‘mÐ#ò (Ø˜˜v™Ð&ò(à˜E &™MÐ)ò(ð ˜% ™-Ð'ð		
r   ©r<   zdict[str, Any]ÚreturnÚbool)rF   rA   )r4   rX   Ú
gpu_eventsÚsorted_eventsr<   s        r   Úget_sorted_gpu_mm_conv_eventsr^   }   sH   € ó
ô ' vÓ.€JØ*,€MØò $ˆÙ Ô&ØØ×Ñ˜UÕ#ð$ð Ðr   z	list[Any]r:   c                ó  — t        | «      }g a|D ]3  }d|vrŒ|d   dk(  sŒd|d   d   v sŒt        j                  |d   «       Œ5 |dz  }t        |«      }t	        |«      |z  }t        |«      }t	        |«      |z  }||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)
    rS   Úprocess_labelsÚGPUÚargsÚlabelsr7   g    €„.A)r5   r:   rA   rF   rP   r^   )r2   Útotal_lengthr4   r<   rE   ÚutilizationÚsorted_gpu_mm_conv_eventsÚmm_conv_utilizations           r   Úcompute_utilizationrh   ’   s«   € ô % XÓ.€Fð €HØò *ˆØ˜ÑØØ�‰=Ð,Ó,°¸%À¹-ÈÑ:QÒ1QÜ�O‰O˜E %™LÕ)ð	*ð   #Ñ%€LÜ-¨fÓ5ÐÜÐ0Ó1°LÑ@€Kä =¸fÓ EÐÜ&Ð'@ÓAÀLÑPÐàÐ+Ð+Ð+r   c           	     óf  — t         j                  j                  |«      }|s#t        j                  |«       t	        d|z   «       |€t        j                  «       }t         j                  j                  ||dz   «      }t        | |||t        j                  g|dg¬«      }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 z.jsonr   )r#   r$   )ÚosÚpathÚexistsÚmakedirsÚprintÚ
contextlibÚnullcontextÚjoinr,   r	   ÚCUDArh   )r   r    Útrace_folderr"   Útrace_file_namer#   ÚisExistÚchrome_trace_file_namerd   re   rg   s              r   Úbenchmark_utilizationrw   ´   s±   € ôV �g‰g�n‰n˜\Ó*€GÙÜ
�‰�LÔ!ÜÐ Ñ-Ô.àÐÜ!×-Ñ-Ó/ˆäŸW™WŸ\™\¨,¸È'Ñ8QÓRÐÜ$Ø	ØØØÜ	×	Ñ	ÐØØ�ô€Lô (;Ø ó(Ñ$€KÐ$ð Ð+Ð+Ð+r   )rZ   ÚNone)rI   NNN)r   úCallable[[tuple[Any, ...]], _R]r    útuple[Any, ...]r!   Ústrr"   zAbstractContextManager[Any]r   zSequence[ProfilerActivity]r#   Úintr$   zlist[str] | Noner%   údict[str, Any] | Noner&   r}   rZ   Úfloat)r2   r{   rZ   úlist[dict[str, Any]]rY   )r4   r   rZ   r   )rE   r   rZ   r|   )r2   r{   rd   r~   rZ   útuple[float, float])NÚtmp_chrome_tracerI   )r   ry   r    rz   rs   r{   r"   z"AbstractContextManager[Any] | Nonert   r{   r#   r|   rZ   r€   ) Ú
__future__r   ro   r0   rC   rj   r   r   Útypingr   r   Útyping_extensionsr   r   Útorch.profilerr   r	   Úcollections.abcr
   r   r   r   r,   r5   r=   rF   rP   r^   r:   Ú__annotations__rh   rw   r   r   r   ú<module>rˆ      s8  ðÞ "ã Û Û Û 	Û Ý -ß %Ý %ã ß 4ñ ß2ñ ˆTƒ]€ó	ð Ø $Ø*.Ø15ð7Ø&ð7àð7ð ð7ð .ð	7ð
 +ð7ð ð7ð ð7ð (ð7ð /ð7ð ó7ótóóDóóð$ €ˆ)Ó ó,ðL 8<Ø-ØðA,Ø&ðA,àðA,ð ðA,ð 5ð	A,ð
 ðA,ð ðA,ð ôA,r   