
    wi|,                         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 d dlm	Z	 d dl
mZmZmZmZ d dlmZ i Zd Ze G d d                      Z e	d	
           G d de                      Z G d de          ZdS )    N)ABCMetaabstractmethodabstractclassmethod)	dataclass)DictListTupleUnion)
ModuleTypec                 $    | t           | j        <   | S )z9
    Register a descriptor into the descriptor table
    )_descriptor_table__name__)clss    h/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/triton/backends/compiler.pyregister_descriptorr      s     '*cl#J    c                       e Zd ZdZdZddZd ZddZd Zde	fd	Z
de	fd
Zd Zd Zd Zed             Zedeeeef                  fd            Zed             Zed             Zed             Zd ZdS )AttrsDescriptoraG  
    This class handles compile-time properties for specific function parameters.

    Different backends can add more properties to the common ones. The class
    contains two fields:

    `arg_properties`: a dictionary containing the different compile-time properties for different
        parameters. I.e., the dictionary is a map from property names to parameter indices
        {
        "prop0": (0, 2, 3)
        "prop1": (0, 4, 5)
        }
        Different backends might need different properties on those paraemters to enable
        specific optimizations. The common compile time properties contained in this class
        are :
        - "tt.divisibility", i.e., is the given parameter divisible by 16
        - "tt.equal_to_1", i.e., is the given parameter an integer constant 1

    `property_values`: a dictionary containing the value of the different compile-time properties, like:
        {
            "prop0": val0
            "prop1": val1
        }

    `constant_properties`: a set containing the properties that can be used to determine if a parameter is constant

    )divisibility_16
equal_to_1arg_propertiesproperty_valuesconstant_propertiesNc                     i | _         i | _        t                      | _        |                     ||           |                     ||           |                                  dS )a  
        Initialize the compile-time properties

        We can initialize the AttrsDescriptor class by passing the list of params
        of the function and their `values`. The function will try to apply the properties
        to the values and save the parameters in the `arg_properties` list. If we don't pass
        either the `params` or the `values` we should initialize the class via an alternative method
        (see `from_dict` or `from_hints`)
        N)r   r   setr   _add_common_properties_add_backend_properties_init_slotsselfparamsvaluess      r   __init__zAttrsDescriptor.__init__8   sd     !!#&55 ##FF333$$VV444r   c                 :   d| j         d<   d| j         d<   | j                            d           ||dS t          |          t          |          k    sJ d t	          ||          D             | j        d<   d t	          ||          D             | j        d<   dS )z$ Add common compile-time properties    ztt.divisibility   ztt.equal_toNc                 r    g | ]4\  }}t                               |          |j        &|j        -|j        5S  )r   is_divisible_by_16do_not_specializedo_not_specialize_on_alignmentnum.0paramargs      r   
<listcomp>z:AttrsDescriptor._add_common_properties.<locals>.<listcomp>X   sX     2
 2
 2
$%?a?abe?f?f2
+2
494X2
I2
 2
 2
r   c                 d    g | ]-\  }}t                               |          |j        &|j        .S r(   )r   is_equal_to_1r*   r,   r-   s      r   r1   z:AttrsDescriptor._add_common_properties.<locals>.<listcomp>^   sP     .
 .
 .
s,,S11.
 ;@:Q.
I.
 .
 .
r   )r   r   addlenzipr   r   s      r   r   z&AttrsDescriptor._add_common_propertiesK   s    24././]+ $$]333NF Fs6{{****2
 2
(+FF(;(;2
 2
 2
-..
 .
!&&11.
 .
 .
M***r   c                     dS )zX This method is for different subclasses to implement their own compile-time properties Nr(   r   s      r   r   z'AttrsDescriptor._add_backend_propertiesd   s    r   c           	          | j                                         D ]G\  }}t          | |                    d          dz   t	          | j        |                   z   |           HdS )z$ Initialize the slots of this class ztt._N)r   itemssetattrremoveprefixstrr   )r    namevals      r   r   zAttrsDescriptor._init_slotsh   sq    ,2244 	a 	aID#D$++E22S83t?STX?Y;Z;ZZ\_````	a 	ar   returnc                     i }| j                                         D ]6\  }}| j        |         }|D ]!}|                    |g           ||fgz   ||<   "7|S )a  
        Get the function attributes as a dictionary.

        The returned dictionary will look like :
            {
            "arg0" : [(prop_name00, val00), (prop_name01, val01), ...)]}
            "arg1" : [(prop_name10, val10), (prop_name11, val11), ...)]}
            }
        )r   r:   r   get)r    attrs	prop_namearg_setprop_valr0   s         r   get_fn_attrszAttrsDescriptor.get_fn_attrsm   s}     "&"5";";"="= 	J 	JIw+I6H J J"YYsB//Ix3H2IIc

Jr   c                 z    i }| j         D ]0}| j                            |g           D ]}| j        |         ||<   1|S )z9 Return a mapping of constant parameters to their values )r   r   rB   r   )r    	constantsrD   ps       r   get_constantszAttrsDescriptor.get_constants~   sY    	1 	? 	?I(,,Y;; ? ?#3I>	!?r   c                     ddl }|                    |           }|j        D ]8}|j                            |d           |j                            |d           9i |_        |S )z? Return the same object, without properties marked as constantsr   N)copydeepcopyr   r   popr   )r    rM   crD   s       r   filter_out_constantsz$AttrsDescriptor.filter_out_constants   sp    MM$. 	3 	3I  D111!!)T2222 "r   c                 d   t          | j                                                  g}|t          | j                                                  gz  }|t          | j                  gz  }t          |          }t          j        |                    d                    	                                S )Nutf-8)
sortedr   r"   r   r   r=   hashlibsha256encode	hexdigest)r    r"   keys      r   hashzAttrsDescriptor.hash   s    ,33556676$.557788996$23344&kk~cjj1122<<>>>r   c                 :    | j         t          |           j        dS )zM
        Store the fields of this class in a serializable dictionary
        )r   r   )r   typer   r    s    r   to_dictzAttrsDescriptor.to_dict   s     #'"5d4jj>QRRRr   c                     t          | d                              }| d                                         D ]\  }}||j        |<   |                                 |S )zB
        Create the object from a serializable dictionary
        r   r   )r   r:   r   r   )dataattrs_descriptorrD   	param_idss       r   	from_dictzAttrsDescriptor.from_dict   sj    
 -T%[9;;$()9$:$@$@$B$B 	C 	C Iy9B+I66$$&&&r   hintsc                      |             }|j                                         D ]-\  }fd|                                D             |j        |<   .|                                 |S )a  
        Create the class from a set of hints that are passed in.

        Instead of deducing the properties from a list of paramaters and values,
        the user can pass in a list of `hints=[(param_index, val)]` and if `val`
        matches one of the values of the properties (e.g., `prop_val[prop0]`),
        then we insert `param_index` into the correct list (e.g., in
        `arg_properties[prop0]`)
        c                 &    g | ]\  }}|k    |S r(   r(   )r.   ihrF   s      r   r1   z.AttrsDescriptor.from_hints.<locals>.<listcomp>   s)    9g9g9g1YZ^fYfYf!YfYfYfr   )r   r:   r   r   )r   rd   ra   rD   rF   s       @r   
from_hintszAttrsDescriptor.from_hints   s{     355#3#C#I#I#K#K 	h 	hIx9g9g9g9g9g9g9g+I66$$&&&r   c                     t          | d          r|                                 dz  dk    S t          | t                    r	| dz  dk    S | dS dS )z+ Return if the argument is a multiple of 16data_ptrr%   r   NTF)hasattrrk   
isinstanceintxs    r   r)   z"AttrsDescriptor.is_divisible_by_16   s]     1j!! 	::<<"$))3 	r6Q;94ur   c                 j    t          | t                    rt          | t                    s| dk    rdndS )z' Return if the argument is a constant 1r&   TF)rm   rn   boolro   s    r   r3   zAttrsDescriptor.is_equal_to_1   s5     "!S))[*Q2E2E[!q&&ttV[[r   c                 z    |rt                               |           rdS t                               |           rdS dS )ND1N)r   r)   r3   )r?   aligns     r   get_property_keyz AttrsDescriptor.get_property_key   sD     	_77<< 	3((-- 	3sr   c                 2    d|                                  dS )NzAttrsDescriptor.from_dict())r^   r]   s    r   __repr__zAttrsDescriptor.__repr__   s    ?DLLNN????r   )NN)r   
__module____qualname____doc__	__slots__r#   r   r   r   r   rG   rK   rQ   rZ   r^   staticmethodrc   classmethodr   r	   rn   ri   r)   r3   rx   r{   r(   r   r   r   r      s        6 nI   &
 
 
2   a a a
d    "t      ? ? ?S S S     \   tE#s(O4       [     \ \ \ \\   \@ @ @ @ @r   r   T)frozenc                   >    e Zd ZU eed<   eeef         ed<   eed<   dS )	GPUTargetbackendarch	warp_sizeN)r   r|   r}   r=   __annotations__r
   rn   r(   r   r   r   r      s8          LLL
S/NNNNNr   r   c                      e Zd ZdeddfdZedefd            Zedefd            Z	e
defd            Ze
d	edefd
            Ze
ded	eddfd            Ze
d             Ze
deeef         fd            Zd Zd ZdS )BaseBackendtargetr@   Nc                 B    || _         |                     |          sJ d S N)r   supports_target)r    r   s     r   r#   zBaseBackend.__init__   s)    ##F+++++++r   binaryc                    t           j                            t           j                            t                    t           j                  }t           j                            d|                                  dd          t           j                            |ddd|           g}|D ]}|	                    d          d         }t           j        
                    |          rt           j                            |          rst          j        |d	gt          j        
          }|Ot          j        d|                    d          t          j                  }|||                    d          fc S t)          d|            )NTRITON__PATH third_partycudabin r   z	--version)stderrz.*release (\d+\.\d+).*rS   )flagsr&   zCannot find )ospathjoindirname__file__pardirenvironrB   uppersplitexistsisfile
subprocesscheck_outputSTDOUTresearchdecode	MULTILINEgroupRuntimeError)r   base_dirpathsrJ   r   resultversions          r   _path_to_binaryzBaseBackend._path_to_binary   sC   7<< 9 929EEJNN:V\\^^:::B??GLL=&%HH
  	3 	3A''#,,q/Cw~~c"" 3rw~~c':': 3#0#{1CJL]^^^% i(A6==QXCYCYacamnnnG* '--"2"222222&22333r   c                     t           r   NotImplementedError)r   s    r   r   zBaseBackend.supports_target   s    !!r   c                     t           )z,Returns a unique identifier for this backendr   r]   s    r   rZ   zBaseBackend.hash   s
     "!r   optionsc                     t           )z
        Converts an `options` dictionary into an arbitrary object and returns it.
        This function may contain target-specific heuristics and check the legality of the provided options
        r   )r    r   s     r   parse_optionszBaseBackend.parse_options  s
     "!r   stagesc                     t           )a  
        Populates `stages` dictionary with entries of the form:
        ir_name [str] => Function[(src: str, metadata: dict) -> str|bytes]
        The value of each entry may populate a `metadata` dictionary.
        Stages will be run sequentially (in inseriton order) and can communicate using `metadata`.
        All stages are expected to return a `str` object, except for the last stage which returns
        a `bytes` object for execution by the launcher.
        r   )r    r   r   s      r   
add_stageszBaseBackend.add_stages
  s
     "!r   c                     t           )zK
        Load additional MLIR dialects into the provided `context`
        r   )r    contexts     r   load_dialectszBaseBackend.load_dialects  
    
 "!r   c                     t           )z\
        Return a map of interface modules to their device-specific implementations
        r   r]   s    r   get_module_mapzBaseBackend.get_module_map  r   r   c                 "    t          ||          S )z
        Return an attribute descriptor: given a set of parameters and arguments
        the descriptor stores a set of compile time properties that can improve code
        generation. Different backends might benefit from different properties
        )r   )r    r!   argss      r   get_attrs_descriptorz BaseBackend.get_attrs_descriptor$  s     vt,,,r   c                 8    t                               ||          S )zZ
        Return the ascii key for a given argument with a given set of properties
        )r   rx   )r    r0   rw   s      r   compute_spec_keyzBaseBackend.compute_spec_key,  s     //U;;;r   )r   r|   r}   r   r#   r   r=   r   r   r   r   rZ   dictobjectr   r   r   r   r   r   r   r   r(   r   r   r   r      sx       ,y ,T , , , , 4 4 4 4 \4  "	 " " " " "c " " " ^" "T "f " " " ^" 	" 	" 	"4 	" 	" 	" ^	" " " ^" "S*_ 5 " " " ^"- - -< < < < <r   r   )	metaclass)r   r   rU   r   abcr   r   r   dataclassesr   typingr   r   r	   r
   typesr   r   r   r   r   r   r   r(   r   r   <module>r      sw   				 				      < < < < < < < < < < ! ! ! ! ! ! + + + + + + + + + + + +      
     |@ |@ |@ |@ |@ |@ |@ |@~ $       N< N< N< N< N<G N< N< N< N< N< N<r   