o
    ohE                     @  s   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mZm	Z	m
Z
 ddlmZ ddlmZmZ ddlmZ G dd	 d	eZG d
d dZ		dddZG dd deZdd ZdS )    )annotationsN)DictTupleListOptional   )KernelInterface)OutOfResources
PTXASError)driverc                   @  sH   e Zd Z							ddddZdd Zd	d
 ZdddZdd ZdS )	AutotunerNFprune_configs_byOptional[Dict]c              
     s  |st i ddddddddg_n|_|_i _|_g _|dur)t|_g _|dur5t|_ddd	_d
d	 _	d_
d_|rO|_d_
ntjdks]tjdkrgdfdd	}|_|rp|_	d_ntjdkrfdd}|_	d_d_d_|	r|	dj_|	dj_|	dj_|_|_tjsjj_tjr__|_dus͈dus|rddl}|jdtdd |rddlm   fdd	_dS ddlfdd	_dS |du rtj ! _dS |_dS )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_ctasnum_buffers_warp_specnum_consumer_groupsreg_dec_producerreg_inc_consumerNFc                 S     dS Nr    )kwargs
reset_onlyr   r   l/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/triton/runtime/autotuner.py<lambda>:       z$Autotuner.__init__.<locals>.<lambda>c                 S  r   r   r   )r   	exceptionr   r   r   r   ;   r   Tc                   s:   j D ]} |   q|s fddjD _d S d S )Nc                   s   i | ]	}| |   qS r   )clone).0namer   r   r   
<dictcomp>G   s    z9Autotuner.__init__.<locals>._pre_hook.<locals>.<dictcomp>)reset_to_zerozero_restore_valuerestore_copies)r   r   r#   selfr$   r   	_pre_hookC   s
   
z%Autotuner.__init__.<locals>._pre_hookc                   s*    j D ]}| |  j|  qi  _d S N)r(   copy_r)   )r   r    r#   r*   r   r   
_post_hookP   s   

z&Autotuner.__init__.<locals>._post_hook      ?
perf_modeltop_kearly_config_prunez{warmup, rep, and use_cuda_graph parameters are deprecated. See https://github.com/triton-lang/triton/pull/4496 for details.)
stacklevel   )do_bench_cudagraphc                   s     | d ur|dS d|dS )Nd   )rep	quantilesr   kernel_callr9   )r6   r8   r   r   r   q   s    
c                   s2   j j| d ur
nd d ur |dS d|dS )N   r7   )warmupr8   r9   )testingdo_benchr:   )r8   tritonr=   r   r   r   y   s    
)F)"Configconfigskeyscache	arg_namesr&   listr(   pre_hook	post_hookuser_defined_pre_hookuser_defined_post_hooklenr1   configs_top_kr3   getfnbase_fninspect
isfunctionnum_warmupsnum_repsuse_cuda_graphwarningswarnDeprecationWarningr>   r6   r?   triton.testingr   activeget_benchmarker)r+   rN   rE   rB   keyr&   r(   rG   rH   r   r=   r8   rT   r?   r,   r/   rU   r   )r6   r8   r+   r@   r=   r   __init__   s|   





zAutotuner.__init__c          	   
     s   ddl m} tjdd dk}|rtdjj d  | j	 @ }|r3t
dd| d	t|fi  i j fd
d}zj|ddW S  t|tfy } z|rjtd|  tdtdtdgW  Y d }~S d }~ww )Nr5   )CompileTimeAssertionFailureTRITON_PRINT_AUTOTUNING1zAutotuning kernel z with config zConflicting meta-parameters: , z8. Make sure that you don't re-define auto-tuned symbols.c               
     sr   j r    zjj i  W n ty/ }  zz	j| d W   d } ~ ww jd d d S )N)r    )rG   rN   run	ExceptionrH   )eargsconfigcurrent
full_nargsr+   r   r   r;      s    


z%Autotuner._bench.<locals>.kernel_call)g      ?g?g?)r9   zAutotuning failed with inf)compiler.errorsr]   osenvironrM   printrO   __name__rC   r   
ValueErrorjoindict
all_kwargsnargsr?   r	   r
   float)	r+   rf   re   metar]   verbose	conflictsr;   rc   r   rd   r   _bench   s$   "zAutotuner._benchc                   s  t tj_d}tjdkri j}fdd| D   fddjD }  D ]\}}t|drC|	t
|j q2t|}|jvrd}}t }	fd	d|D }
t }||	 _tj|
|
jd
j|< i jj|  }j|dd |
_j| }njd }|_tdd dkr|stdjj djddj d |jd uri j| }|| jji | }d _|S )NTr   c                   s    i | ]\}}| j v r||qS r   )rE   r"   kvr*   r   r   r%      s     z!Autotuner.run.<locals>.<dictcomp>c                   s   g | ]
}| v r | qS r   r   )r"   r[   )_argsr   r   
<listcomp>   s    z!Autotuner.run.<locals>.<listcomp>dtypeFc                   s"   i | ]}|j  d |iqS )rf   )rx   r"   rf   )re   r   r+   r   r   r%      s   " r[   )r   r   r^   r_   zTriton autotuning for function z finished after z.2fzs; best config selected: ;)rq   ziprE   rs   rK   rB   itemsrC   hasattrappendstrr~   tuplerD   prune_configstime
bench_timebuiltinsminrM   rr   rG   configs_timingsbest_configrk   getenvrm   rO   rn   rN   ra   )r+   re   r   used_cached_resultall_argsr[   _argpruned_configsbench_starttimings	bench_endrh   rf   retr   )r|   re   r   r+   r   ra      sV   







zAutotuner.runr   r   returnList[Config]c                   s   j }jrjj jfi }jrTj}t|tr+|dkr+ttj | }n	t|ts4t	dt||krTfdd|D  t
   fdddd | }|S )Nr0   zPError while pruning configs, top_k must be either 1) a float <= 1.0 or 2) an intc                   s,   i | ]}|j d i j | qS )r   )r1   rs   rr   r   )r   r+   r   r   r%      s    
z+Autotuner.prune_configs.<locals>.<dictcomp>c                   s    |  S r-   r   )x)
est_timingr   r   r      s    z)Autotuner.prune_configs.<locals>.<lambda>r   )rB   r3   rs   r1   rL   
isinstancert   intrK   	TypeErrorsortedrC   )r+   r   r   r2   r   )r   r   r+   r   r      s   
 zAutotuner.prune_configsc                 O  sP   t t| j|| _g }| |D ]}|| jj|i ||  qd | _|S r-   )	rq   r   rE   rs   r   r   rN   r=   rr   )r+   re   r   r   rf   r   r   r   r=      s   

zAutotuner.warmup)NNNNNFN)r   r   )r   r   r   r   )rn   
__module____qualname__r\   rx   ra   r   r=   r   r   r   r   r      s    
v*
)r   c                   @  s.   e Zd ZdZ		dddZd	d
 Zdd ZdS )rA   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.
    r   r   r   r   Nc                 C  s@   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	d S r-   )
r   r   r   r   r   r   r   r   maxnregrG   )r+   r   r   r   r   r   r   r   r   r   rG   r   r   r   r\     s   
zConfig.__init__c                 C  sX   i | j dd d| jfd| jfd| jfd| jfd| jfd| jfd	| jfd
| jffD S )Nc                 S  s   i | ]\}}|d ur||qS r-   r   ry   r   r   r   r%   "  s
    	
z%Config.all_kwargs.<locals>.<dictcomp>r   r   r   r   r   r   r   r   )	r   r   r   r   r   r   r   r   r   r*   r   r   r   rr      s   zConfig.all_kwargsc                 C  s   g }| j  D ]\}}|| d|  q|d| j  |d| j  |d| j  |d| j  |d| j  |d| j  |d| j	  |d	| j
  d
|S )Nz: znum_warps: z
num_ctas: znum_stages: znum_buffers_warp_spec: znum_consumer_groups: zreg_dec_producer: zreg_inc_consumer: z	maxnreg: r`   )r   r   r   r   r   r   r   r   r   r   r   rp   )r+   resrz   r{   r   r   r   __str__1  s   
zConfig.__str__)	r   r   r   r   r   r   r   NN)rn   r   r   __doc__r\   rr   r   r   r   r   r   rA      s    
rA   Fc                   s$    	
fdd}|S )ak  
    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, BLOCK_SIZE: tl.constexpr):
            ...
    :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'.
        'kwargs': a dict of all 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'.
        'kwargs': a dict of all 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 (deprecated).
    :type warmup: int
    :param rep: repetition time (in ms) to pass to benchmarking (deprecated).
    :type rep: int
    :param do_bench: a benchmark function to measure the time of each run.
    :type do_bench: lambda fn, quantiles
    c                   s$   t | | j 
	dS )N)rG   rH   r   r=   r8   rT   r?   )r   rE   rN   rB   r?   r[   rH   rG   r   r8   r&   r(   rT   r=   r   r   	decoratory  s   zautotune.<locals>.decoratorr   )rB   r[   r   r&   r(   rG   rH   r=   r8   rT   r?   r   r   r   r   autotune@  s    9r   c                   @  s   e Zd ZdddZdd ZdS )	
Heuristicsr   Nonec                 C  s   || _ || _|| _d S r-   )rN   valuesrE   )r+   rN   rE   r   r   r   r   r\     s   
zHeuristics.__init__c                 O  sF   | j  D ]\}}|i tt| j||||< q| jj|i |S r-   )r   r   rq   r   rE   rN   ra   )r+   re   r   r{   heurr   r   r   ra     s   "zHeuristics.runN)r   r   )rn   r   r   r\   ra   r   r   r   r   r     s    
r   c                   s    fd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 prohibitively expensive, or just not applicable.

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

        # smallest power-of-two >= x_size
        @triton.heuristics(values={'BLOCK_SIZE': lambda args: triton.next_power_of_2(args['x_size'])})
        @triton.jit
        def kernel(x_ptr, x_size, BLOCK_SIZE: tl.constexpr):
            ...
    :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[[dict[str, Any]], Any]]
    c                   s   t | | j S r-   )r   rE   r   r   r   r   r     s   zheuristics.<locals>.decoratorr   )r   r   r   r   r   
heuristics  s   r   )	NNNNNNNFN)
__future__r   r   rk   r   rP   typingr   r   r   r   jitr   errorsr	   r
   r   r   rA   r   r   r   r   r   r   r   <module>   s"     qB
A