
    ^j              
          U 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lmZm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 d dlZd dlmc mZ d dlmc mZ d dlmZ d d	lm Z  d d
l!m"Z" d dl#m$Z$ ejJ                  jM                  e'd      Z(dZ)dZ*dZ+ ed      Z, ed      Z-de.fdZ/de.ej`                  z  dz  de.fdZ1eg e jd                  d   f   Z3da4e3dz  e5d<   de3dz  de3dz  fdZ6e jn                  ded   fd       Z8dee,e-f   dee,e-f   fdZ9i Z:e;e.edef   f   e5d<   ddde.dedef   d e<ddfd!Z=dedef   dedef   fd"Z>d:d#Z?deeee,f   e-f   deeee,f   e-f   fd$Z@ G d% d&      ZAd' ZBd( ZCd) ZD e=d*eBd+        e=d,eCd+        e=d-eDd+       d.ed/ed0eEd1edeFf
d2ZG G d3 d4eA      ZH G d5 d6eH      ZI G d7 d8eI      ZJdeAfd9ZK eK       ZLy);    N)CallableIterator)cached_propertywraps)chain)median)AnyConcatenate)	ParamSpecSelfTypeVar)get_interface_for_device)counters)	DebugMode)
OrderedSetbenchmarking)cudaxpumtia	_CALLABLEi  PTreturnc                      t         D  cg c]"  } t        t        |       j                         r| $ }} t	        |      dk  sJ t	        |      dk(  rdS |j                         S c c} w )N   r   r   )GPU_BENCHMARK_DEVICE_TYPESgetattrtorchis_availablelenpop)device_type
avail_gpuss     o/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/_inductor/runtime/benchmarking.py_get_default_gpu_device_typer%       sj     65+&335 	J 
 z?a_)6?z~~/??s   'A"r"   c                     | 
t               S t        | t        j                        r| j                  S t        j                  |       j                  S N)r%   
isinstancer   devicetyper"   s    r$   _normalize_gpu_device_typer,   *   s@    +--+u||,<<$)))    _gpu_benchmark_lock_contextcontext_factoryc                     t         }| a |S )ag  Override the process-local GPU benchmark lock context.

    This lets benchmark harnesses provide the context used by Inductor GPU
    benchmark calls. Some benchmark helpers delegate to other benchmark
    methods, so harness contexts should support nested entry from the same
    thread. Returning the previous context lets callers restore it in tests.
    r.   )r/   previouss     r$   set_gpu_benchmark_lock_contextr3   6   s     +H"1Or-   c               #   f   K   t         } | d y |        5  d ddd       y# 1 sw Y   yxY ww)z;Optionally enter the registered GPU benchmark lock context.Nr1   )r/   s    r$   maybe_gpu_benchmark_lockr5   F   s6      2O		   s   1%	1.1fnc                 |     t               dt        j                  dt        j                  dt        f fd       }|S )Nargskwargsr   c                  T    t               5   | i |cd d d        S # 1 sw Y   y xY wr'   )r5   )r8   r9   r6   s     r$   wrapperz#gpu_benchmark_lock.<locals>.wrapperR   s+    %' 	't&v&	' 	' 	's   ')r   r   r8   r9   r   r6   r;   s   ` r$   gpu_benchmark_lockr=   Q   s=    
2Y'qvv ' 'a ' ' Nr-   ._BENCHMARK_DISPATCHF)overrider?   c                    t        | t              r| st        d      t        |      st	        d      |s| t
        v rt        d|  d      |t
        | <   y)a  
    Register a device-type specific benchmarker.

    Args:
        device_type: torch.device.type string (e.g., "cuda", "cpu", "mps", "xpu").
        fn: callable(self, _callable, *, warmup, rep, **kwargs) -> Any
        override: allow overriding an existing registration.
    zAdevice_type must be a non-empty string matching torch.device.typezfn must be callablezBenchmarker for device_type 'z' already registeredN)r(   str
ValueErrorcallable	TypeErrorr>   )r"   r6   r?   s      r$   register_benchmarkerrE   a   sg     k3'{O
 	
 B<-..'::+K=8LM
 	
 (*$r-   c           
          ddl m j                  j                  dk(  r S dt        t
           t        t
        df   z  t
        z  dt        t
           t        t
        df   z  t
        z  ffdt        j                         dt        t           d	t        t        t        f   dt        t
           t        t
        df   z  t
        z  f fd
       }|S )Nr   )config ms.r   c                    t        | t        t        f      r t        |       fd| D              S j                  j
                  }t        | t              sJ |dk(  r	| rd| z  S dS |dk(  rdd l}|j                         S t        d|       )Nc              3   .   K   | ]  } |        y wr'    ).0valdistorts     r$   	<genexpr>zCmay_distort_benchmarking_result.<locals>.distort.<locals>.<genexpr>   s     7SGCL7s   inverseg      ?        randomr   zUnrecognized distort method )	r(   listtupler*   test_configsdistort_benchmarking_resultfloatrS   RuntimeError)rI   distort_methodrS   rG   rO   s      r$   rO   z0may_distort_benchmarking_result.<locals>.distort   s     b4-(487B777,,HH"e$$$Y&!38*s*x'==?"!=n=MNOOr-   r8   r9   c                  $     | i |} |      S r'   rL   )r8   r9   rI   rO   r6   s      r$   r;   z0may_distort_benchmarking_result.<locals>.wrapper   s       r{r-   )torch._inductorrG   rV   rW   rT   rX   rU   	functoolsr   r	   dictrA   )r6   r;   rG   rO   s   ` @@r$   may_distort_benchmarking_resultr_   |   s    &66"<	PK%s
++e3P	euUCZ(	(5	0P" __RCy$(cN	euUCZ(	(5	0  Nr-   c                  b    t         j                  j                  j                  rt	        d      y )Na  In the deterministic mode of Inductor, we will avoid those
        benchmarkings that would cause non-deterministic results. Only benchmarkings in the vetted
        scenarios are allowed. Examples include autotuning for triton configs of pointwise kernels.

        When you see this exception, you can do one of the following two things:
        1. if the benchmarking you are doing does not introduce any non-determinism, you can just
        add is_vetted_benchmarking=True to your benchmark_gpu call. That would solve the issue.

        2. if the benchmarking you are doing indeed introduces non-determinism, you'll need to disable
        such feature in deterministic mode or find an alternative implementation that is deterministic.
        )r   	_inductorrG   deterministicrY   rL   r-   r$   may_ban_benchmarkingrc      s,    ++ 
 
 
	 ,r-   c           	           t               dt        dt        j                  dt        j                  dt
        f fd       }|S )am  
    Wraps `fn` to increment the appropriate dynamo counters. It is expected that `fn`
    is a method of `Benchmarker` or one of its subclasses; typing limitations prevent
    us from declaring this directly.

    NOTE: If you're tempted to add a dynamo_timed call here, this function can be
    called enough that the dynamo_timed overhead is not negligible.
    selfr8   r9   r   c                     | j                   j                   dj                   }t        d   d| xx   dz  cc<    | g|i |S )N.inductorzbenchmarking.r   )	__class____name__r   )re   r8   r9   fn_qual_namer6   s       r$   r;   ztime_and_count.<locals>.wrapper   sS    ..112!BKK=A}\N;<A<$((((r-   )r   r	   r   r8   r9   r   r<   s   ` r$   time_and_countrl      sF     2Y)c )!&& )AHH ) ) )
 Nr-   c                   T   e Zd ZdZdeddfdZdededej                  fdZ	e
	 	 	 dded	ed
ef   deed
f   dz  deeef   dz  deej                  z  dz  dedefd       Ze
	 ddedeg ef   dededef
d       Ze
dedededefd       Ze
ededeg ef   dedefd              Zy)Benchmarkerzo
    A device-agnostic benchmarking utility for measuring the runtime of
    inductor generated callables.
    re   r   Nc                      y r'   rL   re   s    r$   __init__zBenchmarker.__init__   s    r-   fn_args	fn_kwargsc                    d }t        ||j                               D ]`  }t        j                  |      D ]F  }t	        |t
        j                        s||j                  }-|j                  |k7  s=t        d       b |t        d      |S )NzcCan't safely infer the device type of `fn` with multiple device types in `fn_args` and `fn_kwargs`!zCan't safely infer the device type of `fn` with no device types in `fn_args` or `fn_kwargs`. Use a direct benchmarking method instead e.g. `Benchmarker.benchmark_cpu` or `Benchmarker.benchmark_gpu`.)	r   valuespytreetree_leavesr(   r   Tensorr)   rB   )re   rr   rs   inferred_devicearg_or_kwargarg_or_kwarg_leafs         r$   infer_devicezBenchmarker.infer_device   s    /3!'9+;+;+=> 	L &,%7%7%E !!"3U\\B"*&7&>&>O&--@$} 	 "N  r-   r6   .r)   r9   c                 |   d}|(t        |t              rt        j                  |      n|}n5||t	        d      |xs
 t               }|xs i } | j                  |i |}t        |t        j                        sJ |xs
 t               }|xs i }t        |      dk(  rt        |      dk(  rdt        ffd}n||dt        ffd}|j                  dt        j                        }|j                  dt        j                        }	t        j                         5  t        j!                  |j"                        }
|
 |
| |f||	d	|cddd       S |t        j                  d
      k(  r | j$                  |f||	d	|cddd       S  | j&                  |f||	d	|cddd       S # 1 sw Y   yxY w)a7  Benchmark `fn(*fn_args, *fn_kwargs)` and return the runtime, in milliseconds (the
        actual runtime calculation is dictated by the benchmarking implementation, but may be
        one of [mean, median, minimum, etc.]). Functions as a convenience wrapper around
        device-specific implementations, like `benchmark_cpu` and `benchmark_gpu`. Raises
        `ValueError(...)` if we can't safely infer the device type of `fn`; for example,
        if multiple device types are found in `fn_args` and `fn_kwargs`, or if no device
        types are found. To bypass device inference, provide the device to the `device`
        parameter.

        WARNING: if `fn` mutates `fn_args` or `fn_kwargs`, benchmarking may fail unexpectedly.
        For example, if `fn` clears a mutable object, subsequent invocations of `fn` during
        benchmarking will fail. In such cases, `fn` should handle cloning its arguments internally.
        If device inference is required, `Benchmarker.infer_device` can be used prior to calling
        this method without any arguments for `fn_args` and `fn_kwargs`.

        Arguments:
        - fn: The function to benchmark.
        - fn_args: The function's arguments.
        - fn_kwargs: The function's kwargs.

        Keyword Arguments:
        - device: Which device to use for benchmarking. If not provided the device will be attempted
        to be inferred from `fn_args` and `fn_kwargs`.
        - **kwargs: The benchmarking implementation's kwargs.

        Returns:
        - The runtime of `fn(*fn_args, **fn_kwargs)`, in milliseconds.
        NzJ`fn_args` and `fn_kwargs` cannot both be None if `device` is not provided.r   r   c                               S r'   rL   )r6   s   r$   	_callablez(Benchmarker.benchmark.<locals>._callable  s
    tr-   c                        i S r'   rL   )_args_kwargsr6   s   r$   r   z(Benchmarker.benchmark.<locals>._callable%  s    5,G,,r-   warmuprepr   r   cpu)r(   rA   r   r)   rB   rU   r|   r    r	   r!   inductor_config inductor_default_autotune_warmupinductor_default_autotune_repr   _benchmarking_inductorr>   getr*   benchmark_cpubenchmark_gpu)re   r6   rr   rs   r)   r9   ry   r   r   r   benchmark_fnr   r   s    `         @@r$   	benchmarkzBenchmarker.benchmark   s   J 04(263(?V$V  9#4 `  (G!RI/d//FIFO/5<<888$UWO	 w<1Y1!4s  EG-s - Ho&V&VWjj M MN --/ 	S6I6M6M$$7L '#D)VFVvV	S 	S %,,u"55)t)))VFVvV	S 	S &4%%iRCR6R	S 	S 	Ss   $.F2-F2F22F;r   r   r   c                 h    dt         dt        t           ffd} ||       t         ||            S )a  Benchmark the CPU callable, `_callable`, and return the median runtime,
        in milliseconds.

        Arguments:
        - _callable: The CPU callable to benchmark.

        Keyword Arguments:
        - warmup: Optionally, the duration, in milliseconds, to run `_callable`
        before benchmarking starts.
        - rep: Optionally, the duration, in milliseconds, to run `_callable`
        during benchmarking.

        Returns:
        - The median runtime of `_callable`, in milliseconds.
        rI   r   c                     g }t        j                         }	 t        j                         }         t        j                         }|j                  ||z
  t        z         ||z
  t        z  | kD  r	 |S ]r'   )timeperf_counterappendMILLISECONDS_PER_SECOND)rI   timingsrun_start_tstart_tend_tr   s        r$   run_forz*Benchmarker.benchmark_cpu.<locals>.run_forO  sp    G++-K++-))+3JJK[(,CCrIN r-   )intrT   rX   r   )re   r   r   r   r   s    `   r$   r   zBenchmarker.benchmark_cpu;  s2    (
	 
	U 
	 	gcl##r-   r8   c                     t         r'   )NotImplementedError)re   r8   r9   s      r$   r   zBenchmarker.benchmark_gpu^  s    !!r-   c                 x    |        t         j                  j                          t         j                  j                         }t         j                  j	                  |d      5   |        ddd       t         j                  j                           | j
                  |j                  fi |S # 1 sw Y   DxY w)a  Benchmark a GPU callable using CUDA graph capture and replay.

        This captures the callable into a CUDA graph and benchmarks the graph replay,
        which eliminates kernel launch overhead for fair comparison between different
        implementations.
        thread_local)capture_error_modeN)r   r   synchronize	CUDAGraphgraphr   replay)re   r   r9   
cuda_graphs       r$   benchmark_gpu_with_cuda_graphz)Benchmarker.benchmark_gpu_with_cuda_graphb  s     	

  ZZ))+
ZZj^L 	K	

 !t!!*"3"3>v>>		 	s   %B00B9)NNN)   d   )rj   
__module____qualname____doc__r   rq   r	   r   r)   r|   rl   r   rU   r^   rA   rX   r   r   r   r   r=   r   rL   r-   r$   rn   rn      s   
t  S s u|| 0  +/+/,0USUSS#XUS sCx4'US S>D(	US
 ell"T)US US 
US USn OR $ $'C0 $:= $IL $	 $  $D "D " " " " " ??BG$? ? 
	?  ?r-   rn   c                .     | j                   |f||d|S )Nr   )r   re   fr   r   kws        r$   _default_cpu_benchr   }  s!    4a>C>2>>r-   c                R    |j                  dd        | j                  |f||d|S )Nr"   r   r   
setdefaultr   r   s        r$   _default_cuda_benchr     s/    MM-(4a>C>2>>r-   c                R    |j                  dd        | j                  |f||d|S )Nr"   r   r   r   r   s        r$   _default_xpu_benchr     s/    MM-'4a>C>2>>r-   r   Tr   r   kineto_eventsprofiler_eventsr   profiler_device_typec           
      Z   ddl m t               dt        dd ffd|D cg c]0  }|j                  t
        k(  r|j                  j                  k(  r|2 }}t        |      |k7  r"t        d| dt
         dt        |       d	      |D ]
  } |        g }| D ]g  }|j	                         t
        k(  s|j                         j                  k(  s9|j                  |j                         |j                         f       i |r{| D ]v  }|j                         j                  k7  r!|j                         }|j                         }	|D ]1  \  }
}||
k\  s|	|k  sj                  |j                                 v x d
}| D ]  }|j                         }|j                         }|j!                         }|j                         |k(  sG|dk7  sM|v s|dk(  sW|v s\|j	                         dk7  sp||j                         |j                         z
  dz  z  } |S c c}w )Nr   
DeviceTypeeventr   c                     | j                   j                  k7  ry j                  | j                         | j                  D ]
  } |        y r'   )r"   CPUaddidcpu_children)r   childr   benchmark_event_idscollect_cpu_event_idss     r$   r   zB_get_callable_device_kernel_time_us.<locals>.collect_cpu_event_ids  sG    
.)'' 	)E!%(	)r-   z	Expected  z profiling events. Found z events.rR   gpu_user_annotationzContext Sync     @@)torch.autogradr   r   r	   name_CALLABLE_PROFILE_EVENT_NAMEr"   r   r    rY   r   start_nsend_nsr   correlation_idlinked_correlation_idactivity_type)r   r   r   r   r   benchmark_eventscallable_kineto_windowsevev_startev_end	win_startwin_enddevice_time_usr   r   r   r   r   r   s                   @@@r$   #_get_callable_device_kernel_time_usr     sL    *+5<)S )T ) %::55/ 	  #uA:; <)*+85
 	

 " %e$% 68 IGGI55 JNN2#**BKKM299;+GHI  	B~~:>>1{{}HYY[F&= "	7y(Vw->'++B,=,=,?@	 N K % ; ; =--/++-#77!66%)<<)Q.>EX3X 

.u||~0@@FJJNK" ss   5H(c                   x    e Zd Zedededef   fd       Zee	e
	 d
dedeg ef   dededef
d                     Zy	)TritonBenchmarkerre   r   .c                 N    	 ddl m} |S # t        $ r}t        d      |d}~ww xY w)z"Lazily import Triton's `do_bench`.r   )do_benchzrequires TritonN)triton.testingr   ImportErrorr   )re   r   es      r$   triton_do_benchz!TritonBenchmarker.triton_do_bench  s4    	@/   	@%&78a?	@s   
 	$$r   is_vetted_benchmarkingr9   c                    |s
t                t        j                  | j                        j                  }t        |j                               D ]
  }||vs||=  	 d|v r | j                  |fi |d   S d|v r | j                  |fi |S  | j                  |fi |ddiS # t        $ rI}t        |      j                         }d|v r&t        j                  d|       t        d      cY d}~S  d}~ww xY w)	a  Benchmark the GPU callable, `_callable`, and return the runtime, in milliseconds.

        Arguments:
        - _callable: The GPU callable to benchmark.

        Keyword Arguments:
        - quantiles: Optionally, a tuple of floats denoting the requested quantiles.
        - return_mode: Optionally, the requested return mode. Currently, Triton's
        `do_bench` supports min, max, mean, and median return modes.
        - **kwargs: Additional kwargs passed to Triton's `do_bench`.

        Returns:
        - The runtime of `callable`, in milliseconds. If `kwargs["quantiles"]` is specified,
        this is the first requested quantile. Else, if `kwargs["return_mode"]` is specified,
        this is the requested return mode. Otherwise, this is the median.
        	quantilesr   return_moder   zinvalid configurationz9Skipping benchmark due to invalid configuration error: %sinfN)rc   inspect	signaturer   
parametersrT   keys	ExceptionrA   lowerloggerwarningrX   )re   r   r   r9   do_bench_paramskwargr   	error_strs           r$   r   zTritonBenchmarker.benchmark_gpu  s   4 & "!++D,@,@ALL&++-( 	"EO+5M	"	f$+t++I@@CC&(+t++I@@@'4''	RVRRR 
	 AI&)3O U|#
	s0   B% 7B% B% %	C7.=C2+C71C22C7N)F)rj   r   r   r   r   r   r	   r   r_   rl   r=   boolrX   r   rL   r-   r$   r   r     s    d xS'9   %
 (---BG$- !%- 	-
 
-   %-r-   r   c                      e Zd Zededefd       Z	 ddedeej                  z  dz  defdZ
	 ddededeej                  z  dz  deeeef      fdZded	eeeef      defd
Zeee	 	 	 	 	 	 	 	 ddedeg ef   dedededededeej*                     dz  dedeej                  z  dz  dedeee   z  fd                     Zy)InductorBenchmarkerre   r   c                 "    | j                         S )z7Get the L2 cache size, in bytes, of the current device.)get_device_cache_sizerp   s    r$   L2_cache_sizez!InductorBenchmarker.L2_cache_size  s     ))++r-   Nr"   c                     d| j                   v r| j                   d   S t        |      }t        |      }|j                         }|j	                  |      }dD ]  }t        ||d      }|s|c S  y)z>Get the L2/global cache size, in bytes, of the current device.r   )r   last_level_cache_sizeN   )__dict__r,   r   current_deviceget_device_propertiesr   )re   r"   device_interfacer)   propsattr
cache_sizes          r$   r   z)InductorBenchmarker.get_device_cache_size"  s}     dmm+==110=3K@!002 66v>> 	"D d3J!!	" !r-   itersc                     t        t        |            }t        |      D cg c]&  }|j                  d      |j                  d      f( c}S c c}w )z#Get `iters` pairs of device events.T)enable_timing)r   r,   rangeEvent)re   r  r"   r   _s        r$   get_event_pairsz#InductorBenchmarker.get_event_pairs3  sc     4&{3
 5\

  !&&T&: &&T&:
 	
 
s   +Aevent_pairsc           	      h    t        |D cg c]  \  }}|j                  |       c}}      S c c}}w )zDGet the minimum timing, in milliseconds, for a group of event pairs.)minelapsed_time)re   r	  start_event	end_events       r$   get_event_pairs_min_timingz.InductorBenchmarker.get_event_pairs_min_timingB  s=      /:*K ((3
 	
s   .
r   estimation_itersmemory_warmup_itersbenchmark_itersmax_benchmark_durationr   grad_to_noner   r9   c
           	      h   |s
t                t        |	      }	t        |	      }|j                           |        |j                          t	        j
                  | j                  |	      dz  t        j                  |	      }|j                          | j                  ||	      }|D ]L  \  }}||D ]	  }d|_
         |j                          |j                           |        |j                          N |j                          | j                  |      }|dkD  r"t        t        |t        ||z              d      }t        |      D ]  }|j                           | j                  ||	      }|D ]L  \  }}||D ]	  }d|_
         |j                          |j                           |        |j                          N |j                          ~|dk(  r%|D cg c]  \  }}|j!                  |       }}}|S |dk(  r| j                  |      }t        ||      S t#        d	| d
      c c}}w )a  Benchmark a GPU callable using a custom benchmarking implementation.

        Arguments:
        - _callable: The callable to benchmark.

        Keyword Arguments:
        - estimation_iters: Optionally, the number of iterations to run `_callable`
        during runtime estimation.
        - memory_warmup_iters: Optionally, the number of iterations to flush the L2
        cache before starting benchmarking.
        - benchmark_iters: Optionally, the number of iterations to run `_callable`
        during the benchmarking.
        - max_benchmark_duration: Optionally, the maximum duration of the benchmarking,
        in milliseconds. An estimated duration is calculated based on the values
        of `memory_warmup_iters` and `benchmark_iters`, along with the estimated
        runtime of `_callable` and various other factors, and we then shrink
        `benchmark_iters` to fit in the allotted maximum duration.
        - return_mode: Return mode for benchmark results. Options are "min" (default),
        "all" (returns all measurements).
        - grad_to_none: Optionally, a list of tensors whose gradients should be cleared
        before each benchmark iteration.
        - is_vetted_benchmarking: in deterministic mode, we only allow
        benchmarking in vetted cases.
        - **kwargs: Additional kwargs that may be passed to the fallback.

        Returns:
        - If return_mode="min": The minimum runtime of `_callable`, in milliseconds.
        - If return_mode="all": List of all runtime measurements, in milliseconds.
           dtyper)   r+   Nr   r   allr  Unsupported return_mode: z. Use 'min' or 'all'.)rc   r,   r   r   r   emptyr   r   zero_r  gradrecordr  maxr  r  r  rB   )re   r   r  r  r  r  r   r  r   r"   r9   r   bufferr	  r  r  xestimated_timingr  all_timingsbenchmarked_timings                        r$   r   z!InductorBenchmarker.benchmark_gpuM  s_   \ & "0=3K@ 	$$& 	$$& &&{3q8))

 	 **+;*U&1 	"K'% "A!AF"LLN K	 	$$&::;G a!OS)?CS)S%TUWXO
 *+ 	ALLN	 **?*T&1 	"K'% "A!AF"LLN K	 	$$&  % /:*K ((3K  E!!%!@!@!M ');<<+K=8MN s   H.r'   )   r   r      r  NFN)rj   r   r   r   r   r   r   rA   r   r)   r   rT   rU   r	   r  rX   r  r_   rl   r=   r   rx   r   r   rL   r-   r$   r   r     s   ,D ,S , ,
 >B!!!$u||!3d!:!	!$ JN


-05<<-?$-F
	eCHo	
	
	
!%eCHo!6	
		
 % !"#&"&( 26',15yyBG$y y !	y
 y !$y y 5<<(4/y !%y 5<<'$.y y 
e	y   %yr-   r   c                       e Zd ZdZee	 	 	 	 	 	 	 	 ddedeg ef   de	de	de	de	d	e	d
e
deej                     dz  de
ej                  z  dz  dedefd              Zy)TorchProfilerBenchmarkerzABenchmarker that uses torch.profiler for GPU kernel benchmarking.Nre   r   r   r   r  r  r  r   r  r"   r9   r   c
           	         t        |	      }	t        |	      }|j                           |        |j                          t        j                  j
                  rd}n| j                  |	      }t        j                  |dz  t        j                  |	      }|j                          | j                  ||	      }|D ]L  \  }}||D ]	  }d|_         |j                          |j                           |        |j                          N |j                          | j                  |      }|dkD  r"t        t        |t        ||z              d      }t!        |      D ]  }|j                           |	j#                         }t%        t        j&                  j(                  |      }t        j&                  j+                  t        j&                  j(                  j,                  |gd	      5 }t!        |      D ]Q  }||D ]	  }d|_         |j                          t        j&                  j/                  d
      5   |        ddd       S 	 ddd       |j                          ddlm} t%        ||      }d}j&                  j4                  j7                         D ]U  }|j9                         t:        k(  s|j=                         |k(  s/||j?                         |jA                         z
  dz  z  }W |dk  r>tC        |j&                  j4                  j7                         |j7                         ||      }|dk  rtE        d| d      |}||z  dz  }~|dv r|S tG        d| d      # 1 sw Y   ~xY w# 1 sw Y   .xY w)a  Benchmark a GPU callable using torch.profiler.

        Arguments:
        - _callable: The callable to benchmark.

        Keyword Arguments:
        - warmup: Ignored (kept for API compat). Warmup is handled by the
        estimation phase which runs estimation_iters with cache flushing.
        - rep: Optionally, the maximum number of iterations to run during benchmarking.
        - estimation_iters: Optionally, the number of iterations used to estimate
        the runtime of `_callable` for dynamic rep adjustment. These iterations
        also serve as warmup for the callable.
        - memory_warmup_iters: Optionally, the number of buffer.zero_() iterations
        to run after estimation to bring the cache into a steady state before
        the profiled benchmark phase.
        - max_benchmark_duration: Optionally, the maximum duration of the profiled
        benchmark phase, in milliseconds. The rep count is reduced if the
        estimated total would exceed this budget.
        - return_mode: Return mode for benchmark results. Options are "min", "mean" (default),
        or "max".
        - grad_to_none: Optionally, a list of tensors whose gradients should be cleared
        before each benchmark iteration.
        - **kwargs: Additional kwargs that may be passed to the fallback.

        Returns:
        - The runtime of `_callable` in milliseconds, computed according to return_mode.
        r   r  r  r+   Nr   r   F)
activitiesrecord_shapesr   r   rR   r   z&TorchProfilerBenchmarker: '_CALLABLE' zS event not found in raw kineto results, and no correlated device events were found.)r  meanr  r  z. Use 'min', 'mean', or 'max'.)$r,   r   r   r   versionhipr   r  r   r  r  r  r  r  r  r  r  upperr   profilerProfilerActivityprofiler   record_functionr   r   kineto_resultseventsr   r   r"   r   r   r   AssertionErrorrB   )re   r   r   r   r  r  r  r   r  r"   r9   r   buffer_size_bytesr   r	  r  r  r!  estimated_msr  device_type_upperprofile_activityprof_DeviceTyper   callable_gpu_time_uskineto_eventtotal_time_usavg_time_mss                                r$   r   z&TorchProfilerBenchmarker.benchmark_gpu  s   T 1=3K@ 	$$& 	$$&
 == 1 $ : :; G"%))K
 	
 **+;*U&1 	"K'% "A!AF"LLN K	 	$$&66{C!c#s#9L#HIJANC *+ 	ALLN	 (--/"5>>#B#BDUV^^##//33    $ 
 	  3Z  +) &!%&^^33K@  K    	   	$$& 	=&{4EF" MM88??A 	L!!#'CC ,,.2FF$ '')L,A,A,CC) $	  1$#F,,335$	$   1$ 89J8K LR R  -$s*f4 
 00+K=8VW e   	  	 s%   *AM78M* 
M7*M4/M77N)r&  r   r%  
   r&  r,  NN)rj   r   r   r   rl   r=   r   r   r	   r   rA   rT   r   rx   r)   rX   r   rL   r-   r$   r(  r(    s    K  !#%&(!2615ZZBG$Z Z 	Z
 Z !Z !$Z Z 5<<(4/Z 5<<'$.Z Z 
Z  Zr-   r(  c                  ~    t         j                  r
t               S t         j                  r
t	               S t               S r'   )r   use_torch_profiler_benchmarkerr(  use_experimental_benchmarkerr   r   rL   r-   r$   _make_default_benchmarkerrE  n  s/    55'))33"$$r-   )r   N)M
contextlibr]   r   r   collections.abcr   r   r   r   	itertoolsr   
statisticsr   typingr	   r
   typing_extensionsr   r   r   r   torch._inductor.configra   rG   r   torch.utils._pytreeutils_pytreerv   torch._dynamo.device_interfacer   torch._dynamo.utilsr   torch.utils._debug_moder   torch.utils._ordered_setr   _logginggetArtifactLoggerrj   r   r   r   r   r   r   rA   r%   r)   r,   AbstractContextManager_GpuBenchmarkLockContextr.   __annotations__r3   contextmanagerr5   r=   r>   r^   r   rE   r_   rc   rl   rn   r   r   r   r   rX   r   r   r   r(  rE  benchmarkerrL   r-   r$   <module>r[     s       . ,   # 6 6  0 0 $ $ C ( - / 
	)	)(N	C4 *   cNCL@c @*C%,,,>,E *# * $B
(I(I$(O$OP ?C 5< C-4$  (4.  8AqD> hq!tn  68 T#xS112 7 	**c* 	*
 
*6c(: xS?Q DS!V$a'(k#q&!1$%*w? w?v??
?
 U. > V04 @ U. >KKK 
K 	K
 K\; ;|m+ m`_2 _D;  ()r-   