U
    9%e*                     @  s   d dl mZ d dlZd dlZd dlmZ ddlmZ ddlm	Z	 G dd	 d	e
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   )do_bench   )KernelInterfacec                      s$   e Zd Z fddZdd Z  ZS )OutOfResourcesc                   sJ   d| d| d| | _ |  j d7  _ || _|| _|| _t | j  d S )Nzout of resource: z, Required: z, Hardware limit: z0. Reducing block sizes or `num_stages` may help.)messagerequiredlimitnamesuper__init__)selfr
   r   r   	__class__ W/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/triton/runtime/autotuner.pyr      s    zOutOfResources.__init__c                 C  s   t | | j| j| jffS N)typer
   r   r   r   r   r   r   
__reduce__   s    zOutOfResources.__reduce__)__name__
__module____qualname__r   r   __classcell__r   r   r   r   r      s   
r   c                   @  s<   e Zd ZdddddZdd	 Zd
d Zdd Zdd ZdS )	AutotunerN   d   r   )prune_configs_byc	                   s   |st i dddg_n|_ fdd|D _i _dd _|dk	rp fd	d|D _fd
d}	|	_ _|r|d |d  }
}d|kr|d }n
d\}
}}|
| __|_	|_
|_|_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   	num_warps
num_stagesc                   s   g | ]}  |qS r   index.0k	arg_namesr   r   
<listcomp>'   s     z&Autotuner.__init__.<locals>.<listcomp>c                 S  s   dS )Nr   r   )argsr   r   r   <lambda>*       z$Autotuner.__init__.<locals>.<lambda>Nc                   s   g | ]}  |qS r   r$   r&   r)   r   r   r+   ,   s     c                   s    j D ]}| |   qd S r   )	reset_idxZzero_)r,   ir   r   r   _hook.   s    
z!Autotuner.__init__.<locals>._hook
perf_modeltop_kearly_config_prune)NNN)Configconfigskey_idxcachehookr/   r*   r2   configs_top_kr4   fnwarmuprep)r   r;   r*   r6   keyreset_to_zeror   r<   r=   r1   r2   r3   r4   r   )r*   r   r   r      s*    


zAutotuner.__init__c                  s   |  j  @ }|r,tdd| dt|fjj fdd}zt|jjddW S  t	k
r   t
dt
dt
dg Y S X d S )	NzConflicting meta-parameters: , z8. Make sure that you don't re-define auto-tuned symbols.c                     s:   j r    jj jjd d S Nr!   )pre_hookr9   r;   runr"   r#   r   r,   configcurrent
full_nargsr   r   r   kernel_callM   s    

z%Autotuner._bench.<locals>.kernel_call)g      ?g?g?)r<   r=   Z	quantilesinf)keyskwargs
ValueErrorjoindictnargsr   r<   r=   r   float)r   rE   r,   meta	conflictsrH   r   rD   r   _bench@   s    
zAutotuner._benchc                   s>  t tj_tjdkrވj}g  jD ]}||kr4 ||  q4t fddjD }|j	kr҈
}t }fdd|D }t }	|	| _tj||jdj	|<  |_j	| }
n
jd }
|
_|
jd k	rjjj}|
| jj|
j|
jd|
j}d _|S )	Nr   c                 3  s   | ]} | V  qd S r   r   )r'   r0   )_argsr   r   	<genexpr>_   s     z Autotuner.run.<locals>.<genexpr>c                   s"   i | ]}|j  d |iqS )rE   )rS   r'   rE   )r,   rK   r   r   r   
<dictcomp>d   s    z!Autotuner.run.<locals>.<dictcomp>r>   r   r!   )rN   zipr*   rO   lenr6   appendtupler7   r8   prune_configstimeZ
bench_timebuiltinsmingetr9   Zconfigs_timingsZbest_configrB   rK   r;   rC   r"   r#   )r   r,   rK   Zall_argsr   r>   pruned_configsZbench_startZtimingsZ	bench_endrE   rG   retr   )rT   r,   rK   r   r   rC   W   s8    







 zAutotuner.runc                   s   j }jrj j}jrj}t|trL|dkrLttj | }t||krfdd|D  t	 
  fdddd | }|S )Ng      ?c                   s0   i | ](}|j f j |j|j|jd qS ))r#   r"   )r2   rO   rK   r#   r"   rV   )rK   r   r   r   rW      s
    z+Autotuner.prune_configs.<locals>.<dictcomp>c                   s    |  S r   r   )x)
est_timingr   r   r-      r.   z)Autotuner.prune_configs.<locals>.<lambda>rX   )r6   r4   rO   r2   r:   
isinstancerP   intrZ   sortedrJ   )r   rK   rb   r3   r   )re   rK   r   r   r]   v   s     zAutotuner.prune_configsc                 O  sL   t t| j|| _| |D ]$}| jj||j|jd||j	 qd | _d S rA   )
rN   rY   r*   rO   r]   r;   r<   r"   r#   rK   )r   r,   rK   rE   r   r   r   r<      s    zAutotuner.warmup)Nr   r   )r   r   r   r   rS   rC   r]   r<   r   r   r   r   r      s
   $r   c                   @  s"   e Zd ZdZd	ddZdd ZdS )
r5   am  
    An object that represents a possible kernel configuration for the auto-tuner to try.

    :ivar meta: a dictionary of meta-parameters to pass to the kernel as keyword arguments.
    :type meta: 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_stages: int
    :ivar pre_hook: a function that will be called before the kernel is called. Parameters of this
                    function are args.
    r    r   Nc                 C  s   || _ || _|| _|| _d S r   )rK   r"   r#   rB   )r   rK   r"   r#   rB   r   r   r   r      s    zConfig.__init__c                 C  sZ   g }| j  D ]\}}|| d|  q|d| j  |d| j  d|S )Nz: znum_warps: znum_stages: r@   )rK   itemsr[   r"   r#   rM   )r   resr(   vr   r   r   __str__   s    zConfig.__str__)r    r   N)r   r   r   __doc__r   rl   r   r   r   r   r5      s   
r5   r   r   c                   s    fdd}|S )a  
    Decorator for auto-tuning a :code:`triton.jit`'d function.

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

        @triton.autotune(configs=[
            triton.Config(meta={'BLOCK_SIZE': 128}, num_warps=4),
            triton.Config(meta={'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.
    :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 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              	     s   t | | j S r   )r   r*   r;   r6   r>   r   r=   r?   r<   r   r   	decorator   s    zautotune.<locals>.decoratorr   )r6   r>   r   r?   r<   r=   rp   r   ro   r   autotune   s    $rq   c                   @  s"   e Zd ZddddZdd ZdS )
HeuristicsNone)returnc                 C  s   || _ || _|| _d S r   )r;   valuesr*   )r   r;   r*   ru   r   r   r   r      s    zHeuristics.__init__c                 O  s>   | j  D ]$\}}|tt| j||||< q
| jj||S r   )ru   ri   rN   rY   r*   r;   rC   )r   r,   rK   rk   Zheurr   r   r   rC      s    zHeuristics.runN)r   r   r   r   rC   r   r   r   r   rr      s   rr   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 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                   s   t | | j S r   )rr   r*   rn   ru   r   r   rp      s    zheuristics.<locals>.decoratorr   )ru   rp   r   rv   r   
heuristics   s    rw   )NNr   r   )
__future__r   r_   r^   typingr   testingr   Zjitr   	Exceptionr   r   r5   rq   rr   rw   r   r   r   r   <module>   s   y 
*