
    wg~:                        d dl m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mZ  G d	 d
e      Z G d d      Z	 	 ddZ G d de      Zd Zy)    )annotationsN)Dict   )do_benchdo_bench_cudagraph   )KernelInterface)OutOfResourcesc                  <    e Zd Z	 	 	 	 	 	 d	 ddZd Zd Zd Zd Zy)		AutotunerNc                    |st        i ddd      g _        n| _        |D cg c]  }|j                  |       c} _        i  _        | _        g  _        |$|D cg c]  }|j                  |       c} _        g  _        |$|D cg c]  }|j                  |       c} _        dd _        d  _	        |r| _        n=t         j                        dkD  st         j                        dkD  rd fd		}| _        |r| _	        n$t         j                        dkD  r fd
}| _	        d _        d _        d _        |	rc|	j                  d j                         _        |	j                  d j                         _        |	j                  d j                         _        | _        | _        t#        j$                   j                         s; j                   j                   _        t#        j$                   j                         s;|
 _        | _        ddl}|xr |j,                  j/                          _        yc c}w c c}w c c}w )a  
        :param prune_configs_by: a dict of functions that are used to prune configs, fields:
            'perf_model': performance model used to predicate running time with different configs, returns running time
            'top_k': number of configs to bench
            'prune_num_stages_by'(optional): a function used to prune num_stages. It takes configs:List[Config] as its input, and returns pruned configs.
           r   r   )	num_warps
num_stagesnum_ctasNc                     yNr    )args
reset_onlys     ]/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/triton/runtime/autotuner.py<lambda>z$Autotuner.__init__.<locals>.<lambda>6           c                     yr   r   )r   	exceptions     r   r   z$Autotuner.__init__.<locals>.<lambda>7   r   r   r   c                    j                   D ]  }| |   j                           |s1j                  D cg c]  }| |   j                          c}_        y y c c}w N)	reset_idxzero_restore_idxclonerestore_copies)r   r   iselfs      r   	_pre_hookz%Autotuner.__init__.<locals>._pre_hook<   sQ     $AGMMO$!DHDTDT*Uq47==?*UD' "*Us   Ac                    t        j                        D ]&  \  }}| |   j                  j                  |          ( g _        y r   )	enumerater!   copy_r#   )r   r   r$   jr%   s       r   
_post_hookz&Autotuner.__init__.<locals>._post_hookH   sD    %d&6&67 :DAqGMM$"5"5a"89:&(#r         ?
perf_modeltop_kearly_config_prune)F)Configconfigsindexkey_idxcache	arg_namesr   r!   pre_hook	post_hooklenr-   configs_top_kr/   getfnbase_fninspect
isfunctionnum_warmupsnum_repstorchcudais_availableuse_cuda_graph)r%   r;   r5   r1   keyreset_to_zerorestore_valuer6   r7   prune_configs_bywarmupreprD   kr&   r+   rA   s   `                r   __init__zAutotuner.__init__   s   * "2q1MNDL"DL478q	*8
" $:GHQiooa0HDN$<IJq	 2JD 92$DM$..!A%T-=-=)>)BV &DM&DN!!"Q&)
 (DN "&.22<QDO!1!5!5gt?Q?Q!RD&6&:&:;OQUQhQh&iD#$$T\\2<<??DL $$T\\2!,J1H1H1Jk 9 I  Ks   I IIc                  	
 ddl m} |j                         j                  j                         z  }|rt	        ddj                  |       d      t        |fi j                         	i  j                  	
	
 fd}	  j                  rZdd l
}|j                  j                  |j                  j                               5  t        | j                  d	      }d d d        |S t!        | j"                   j                  d
      S # 1 sw Y   S xY w# t$        |f$ r<  j                  rt'        d      cY S t'        d      t'        d      t'        d      gcY S w xY w)Nr   )CompileTimeAssertionFailurezConflicting meta-parameters: , z8. Make sure that you don't re-define auto-tuned symbols.c                    j                   rj                         j                         	  j                  j                  i  j	                  d        y # t        $ r} 	 j	                  |         #  xY wd } ~ ww xY w)N)r   )r6   r;   run	Exceptionr7   )er   configcurrent
full_nargsr%   s    r   kernel_callz%Autotuner._bench.<locals>.kernel_callm   s    
+MM$
 NN44N0  NN41N5 Es)   A! !	B	+A?>B?BBB	r   median)rJ   return_mode)g      ?g?g?)rI   rJ   	quantilesinf)compiler.errorsrN   keyskwargs
ValueErrorjoindict
all_kwargsnargsrD   rA   rB   streamStreamr   r@   r   r?   r
   float)r%   rT   r   metarN   	conflictsrW   rA   	bench_resrU   rV   s   ```      @@r   _benchzAutotuner._bench`   sO   A IIK&--"4"4"66	<TYYy=Q<R SW W X X t3v0023.

.g.
	1 	1$	g""ZZ&&uzz'8'8':; i 2;DMM_g hIi  K0@0@dmm_nooi   ;< 	g#'#6#65<fU5\5QV<Y^_dYe<ff	gs=   AD! D'	D! 1"D! DD! D! !"E( E('E(c           	     "   t        t        | j                  |            | _        d}t	        | j
                        dkD  rhi | j                  |}g }| j                  D ]  }||v s|j                  ||           | j                  D cg c]  }||   	 }}|D ]3  }	t        |	d      s|j                  t        |	j                               5 t        |      }|| j                  vrd}| j                  |      }
t        j                         }|
D ci c]  }| | j                  |d|i| }}t        j                         }||z
  | _        t#        j$                  ||j&                        | j                  |<   | j)                  |d       || _        | j                  |   }n| j
                  d   }|| _        t/        j0                  d	d       d
k(  r@|s>t3        d| j4                  j6                   d| j                   dd| j,                   d       |j(                  /|j)                  i | j                  ||j9                                 | j:                  j<                  |i ||j9                         }d | _        |S c c}w c c}w )NTr   dtypeFrT   rE   )r   r   TRITON_PRINT_AUTOTUNING1zTriton autotuning for function z finished after z.2fzs; best config selected: ;)ra   zipr5   rc   r8   r1   appendr3   hasattrstrrl   tupler4   prune_configstimerj   
bench_timebuiltinsminr:   r6   configs_timingsbest_configosgetenvprintr<   __name__rb   r;   rQ   )r%   r   r^   used_cached_resultall_args_argsnamer$   rE   argpruned_configsbench_startrT   timings	bench_endrets                   r   rQ   zAutotuner.run   sf   #dnnd34
!t||q /$**//HE 18#LL$01 &*\\2582C2 /3(JJs399~./ *C$**$%*"!%!3!3F!;"iik]klSY6;4;;#NV#Nv#NNll IIK	"+k"9"*,,wGKK"H

3dt4'.$ZZ_F\\!_F!99.5<EW3DLL4I4I3JJZ__S))B4CSCSBTTUW X??&OOKtzzKVKv7H7H7JKLdggkk

 !

 

? 3 ms   
JJc           
        | j                   }| j                  r( | j                  | j                   | j                  fi |}| j                  r| j                  }t        |t              r&|dk  r!t        t        | j                         |z        }t        |      |kD  r^|D ci c]1  }| | j                  di | j                  ||j                         3 c}t        j                         fd      d | }|S c c}w )Nr,   c                    |    S r   r   )x
est_timings    r   r   z)Autotuner.prune_configs.<locals>.<lambda>   s    TU r   rm   r   )r1   r/   rc   r-   r9   
isinstancerf   intr8   rb   sortedr]   )r%   r^   r   r.   rT   r   s        @r   rv   zAutotuner.prune_configs   s    ""4T44T\\4::XQWXN??&&E%'ESLC-56>"U* #1  ODOO **  !++- 
 "(
(9?V!WX^Y^!_s   "6C>c           	        t        t        | j                  |            | _        g }| j	                  |      D ]=  }|j                   | j                  j                  |i ||j                                ? d | _        |S r   )	ra   rq   r5   rc   rv   rr   r;   rI   rb   )r%   r   r^   r   rT   s        r   rI   zAutotuner.warmup   s    #dnnd34
((0 	FJJ~tww~~ ##% 	 

r   )NNN   d   F)rH   r   )r   
__module____qualname__rL   rj   rQ   rv   rI   r   r   r   r   r      sA     !%NK NK`'gR(T(
r   r   c                  $    e Zd ZdZddZd Zd Zy)r0   ax  
    An object that represents a possible kernel configuration for the auto-tuner to try.

    :ivar kwargs: a dictionary of meta-parameters to pass to the kernel as keyword arguments.
    :type kwargs: dict[Str, Any]
    :ivar num_warps: the number of warps to use for the kernel when compiled for GPUs. For example, if
                      `num_warps=8`, then each kernel instance will be automatically parallelized to
                      cooperatively execute using `8 * 32 = 256` threads.
    :type num_warps: int
    :ivar num_stages: the number of stages that the compiler should use when software-pipelining loops.
                       Mostly useful for matrix multiplication workloads on SM80+ GPUs.
    :type num_ctas: int
    :ivar num_ctas: number of blocks in a block cluster. SM90+ only.
    :type maxnreg: Optional[int]
    :ivar maxnreg: maximum number of registers one thread can use.  Corresponds
                       to ptx .maxnreg directive.  Not supported on all platforms.
    :ivar pre_hook: a function that will be called before the kernel is called. Parameters of this
                    function are args.
    Nc                X    || _         || _        || _        || _        || _        || _        y r   )r^   r   r   r   maxnregr6   )r%   r^   r   r   r   r   r6   s          r   rL   zConfig.__init__   s,    " $ r   c                    i | j                   d| j                  fd| j                  fd| j                  fd| j                  ffD ci c]
  \  }}||| c}}S c c}}w )Nr   r   r   r   )r^   r   r   r   r   )r%   rK   vs      r   rb   zConfig.all_kwargs   s{    

kk

 !$..1/!4??3-	Q
 ] 1

 
	
s   Ac                   g }| j                   j                         D ]  \  }}|j                  | d|         |j                  d| j                          |j                  d| j                          |j                  d| j
                          |j                  d| j                          dj                  |      S )Nz: znum_warps: z
num_ctas: znum_stages: z	maxnreg: rO   )r^   itemsrr   r   r   r   r   r`   )r%   resrK   r   s       r   __str__zConfig.__str__   s    KK%%' 	$DAqJJ!Bqc{#	$

[ 012

Z/0

\$//!234

Yt||n-.yy~r   )r   r   r   NN)r   r   r   __doc__rL   rb   r   r   r   r   r0   r0      s    (!
r   r0   c
           
     6    	  	f
d}
|
S )a  
    Decorator for auto-tuning a :code:`triton.jit`'d function.

    .. highlight:: python
    .. code-block:: python

        @triton.autotune(configs=[
            triton.Config(kwargs={'BLOCK_SIZE': 128}, num_warps=4),
            triton.Config(kwargs={'BLOCK_SIZE': 1024}, num_warps=8),
          ],
          key=['x_size'] # the two above configs will be evaluated anytime
                         # the value of x_size changes
        )
        @triton.jit
        def kernel(x_ptr, x_size, **META):
            BLOCK_SIZE = META['BLOCK_SIZE']
    :note: When all the configurations are evaluated, the kernel will run multiple times.
           This means that whatever value the kernel updates will be updated multiple times.
           To avoid this undesired behavior, you can use the `reset_to_zero` argument, which
           resets the value of the provided tensor to `zero` before running any configuration.

    If the environment variable :code:`TRITON_PRINT_AUTOTUNING` is set to
    :code:`"1"`, Triton will print a message to stdout after autotuning each
    kernel, including the time spent autotuning and the best configuration.

    :param configs: a list of :code:`triton.Config` objects
    :type configs: list[triton.Config]
    :param key: a list of argument names whose change in value will trigger the evaluation of all provided configs.
    :type key: list[str]
    :param prune_configs_by: a dict of functions that are used to prune configs, fields:
        'perf_model': performance model used to predicate running time with different configs, returns running time
        'top_k': number of configs to bench
        'early_config_prune'(optional): a function used to do early prune (eg, num_stages). It takes configs:List[Config] as its input, and returns pruned configs.
    :param reset_to_zero: a list of argument names whose value will be reset to zero before evaluating any configs.
    :type reset_to_zero: list[str]
    :param restore_value: a list of argument names whose value will be restored after evaluating any configs.
    :type restore_value: list[str]
    :param pre_hook: a function that will be called before the kernel is called.
        This overrides the default pre_hook used for 'reset_to_zero' and 'restore_value'.
        'args': a list of arguments passed to the kernel.
        'reset_only': a boolean indicating whether the pre_hook is called to reset the values only, without a corresponding post_hook.
    :type pre_hook: lambda args, reset_only
    :param post_hook: a function that will be called after the kernel is called.
        This overrides the default post_hook used for 'restore_value'.
        'args': a list of arguments passed to the kernel.
        'exception': the exception raised by the kernel in case of a compilation or runtime error.
    :type post_hook: lambda args, exception
    :param warmup: Warmup time (in ms) to pass to benchmarking, defaults to 25.
    :type warmup: int
    :param rep: Repetition time (in ms) to pass to benchmarking, defaults to 100.
    :type rep: int
    c                F   
 t        | | j                  
	      S )N)r6   r7   rH   rI   rJ   rD   )r   r5   )r;   r1   rE   r7   r6   rH   rJ   rF   rG   rD   rI   s    r   	decoratorzautotune.<locals>.decorator@  s2    R\\7C`h#,?OX^dg(68 	8r   r   )r1   rE   rH   rF   rG   r6   r7   rI   rJ   rD   r   s   `````````` r   autotuner   	  s    n8 8
 r   c                      e Zd ZddZd Zy)
Heuristicsc                .    || _         || _        || _        y r   )r;   valuesr5   )r%   r;   r5   r   s       r   rL   zHeuristics.__init__J  s    "r   c           
         | j                   j                         D ]1  \  }} |i t        t        | j                  |            |      ||<   3  | j
                  j                  |i |S r   )r   r   ra   rq   r5   r;   rQ   )r%   r   r^   r   heurs        r   rQ   zHeuristics.runO  sg    {{((* 	LGAtJS%> ?J6JKF1I	Ltww{{D+F++r   N)returnNone)r   r   r   rL   rQ   r   r   r   r   r   H  s    #
,r   r   c                      fd}|S )a  
    Decorator for specifying how the values of certain meta-parameters may be computed.
    This is useful for cases where auto-tuning is prohibitevely expensive, or just not applicable.

    .. highlight:: python
    .. code-block:: python

        @triton.heuristics(values={'BLOCK_SIZE': lambda args: 2 ** int(math.ceil(math.log2(args[1])))})
        @triton.jit
        def kernel(x_ptr, x_size, **META):
            BLOCK_SIZE = META['BLOCK_SIZE'] # smallest power-of-two >= x_size
    :param values: a dictionary of meta-parameter names and functions that compute the value of the meta-parameter.
                   each such function takes a list of positional arguments as input.
    :type values: dict[str, Callable[[list[Any]], Any]]
    c                2    t        | | j                        S r   )r   r5   )r;   r   s    r   r   zheuristics.<locals>.decoratorf  s    "bllF33r   r   )r   r   s   ` r   
heuristicsr   U  s    "4 r   )NNNNNr   r   F)
__future__r   ry   r}   rw   r=   typingr   testingr   r   jitr	   errorsr
   r   r0   r   r   r   r   r   r   <module>r      s[    "  	    2   "C CL2 2j tx05<~
, 
,r   