o
    hp\                     @   s  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 d dlm	Z	 d dl
mZ d dlmZ d dlmZ ejejeZejedgZd	d
 Ze  dd ZG dd deZdd ZddddddZddddddZdZdd Zdd Z G dd deZ!G d d! d!eZ"dS )"    N)Path)knobs)	GPUTarget)	GPUDriver)compile_module_from_src)TensorDescriptorincludec                    s   dd l }| dkrd S dd lddlm}m}m}mm m} G  fdddj	}
|||||||}zdj}W n
 tyL   Y d S w | g|_||_dd }	fd	d
}
|||
|	rut|	S d S )Nr   Linux)c_charc_intc_size_tc_void_pc_char_pPOINTERc                       s   e Zd Zdfd fgZdS )z8_find_already_mmapped_dylib_on_linux.<locals>.DlPhdrInfoZ	dlpi_addr	dlpi_nameN)__name__
__module____qualname__Z_fields_ )r   r   r   `/home/www/facesmatcher.com/frenv_anti/lib/python3.10/site-packages/triton/backends/amd/driver.py
DlPhdrInfo   s    r   z	libc.so.6i      c                    s@   | j j}tt|}|jv r ||tt| dS dS )Nr   r   )	contentsr   r   osfsdecodenameZmemmoveminlen)infosizedatar   p)ctypeslib_namemax_path_lengthr   r   callback2   s   
z6_find_already_mmapped_dylib_on_linux.<locals>.callback)platformsystemr"   r
   r   r   r   r   r   Z	StructureZ	CFUNCTYPECDLLdl_iterate_phdr	ExceptionargtypesrestypeZcreate_string_bufferr   r   Z	string_at)r#   r&   r
   r   r   r   r   Z
callback_tr)   pathr%   r   )r   r   r"   r#   r$   r   $_find_already_mmapped_dylib_on_linux   s(    
	r.   c                     s  d t jj } r|  rtj| r| S td|  d  t }|r7tj|r-|S td| d  g }tj	tj
td }tj|rM|S || dd l}| }| }|jrf|g| }|D ]}tj	|dd }tj|r}|  S || qhtd	}|r|d
D ]}	tj	|	 }
tj|
r|
  S ||
 qtddg } fdd| D }|D ]}tj|r|  S || qtj	d }tj|r|S || td  d| )Nzlibamdhip64.sozTRITON_LIBHIP_PATH 'z' does not point to a valid zmemory mapped 'z'' in process does not point to a valid libr   torchZLD_LIBRARY_PATH:z/sbin/ldconfigz-pc                    s&   g | ]}|   r| d  qS ))stripendswithsplit).0liner#   r   r   
<listcomp>u   s   & z2_get_path_to_hip_runtime_dylib.<locals>.<listcomp>z/opt/rocm/lib/zcannot locate z after attempted paths )r   Zamdlibhip_pathr4   r   r-   existsRuntimeErrorr.   joindirname__file__appendsitegetsitepackagesgetusersitepackagesENABLE_USER_SITEgetenvr5   
subprocesscheck_outputdecode
splitlines)Zenv_libhip_pathZmmapped_pathpathsZ	local_librA   site_packages	user_siter-   Zenv_ld_library_pathdfZlibsZlocslocZcommon_install_pathr   r8   r   _get_path_to_hip_runtime_dylib@   sV   



rP   c                       s$   e Zd Z fddZdd Z  ZS )HIPUtilsc                    s"   t | dstt| | | _| jS )Ninstance)hasattrsuperrQ   __new__rR   )cls	__class__r   r   rU      s   
zHIPUtils.__new__c                 C   sL   t  }ttjtd }|d|d}t|dt	d}|j
| _
|j| _d S )Nzdriver.cz/*py_libhip_search_path*/r   Z	hip_utilssrcr   include_dirs)rP   r   r   r-   r=   r>   	read_textreplacer   r[   Zload_binaryget_device_properties)selfr:   rZ   modr   r   r   __init__   s   zHIPUtils.__init__)r   r   r   rU   ra   __classcell__r   r   rW   r   rQ      s    rQ   c                 C   s8   | d dkrdS ddddddd	d
dddddddd|  S )Nr   *ZhipDeviceptr_tint32_tint8_tint16_tint64_tuint32_tuint8_tuint16_tuint64_tdouble)i1i8Zi16i32i64u1u8u16u32Zu64fp16bf16fp32f32fp64r   )tyr   r   r   	ty_to_cpp   s(   r{   rj   rh   rk   )ru   rv   rw   rx   ry   Z	pack_fp16Z	pack_bf16Z	pack_fp32Z	pack_fp64Z
piiiKKOOOOc                    s  dd }fdd fdd fddd	d
 t || D }dfdd| D }t| }dt| }ttt|d}dd
 t |D }t	|dkrfdddd |
 D  nd}g }|
 D ]&\}}	|	dkrwqn|	tv r|t|	  d|  qn|t|	 d|  qnd|}
g }|
 D ].\}}	|	d dkr|d| d q|	tv r|d| d q|	dkr|d|  qdd |
 D }t }ttt	|}dd |
 D }|d d| dt	|
dkrd|
 nd d d| d!| d"| d#d$ fd%d|
 D  d&| d'| d(d$| d)d*d+d |
 D  d,t	|dkrDdd| nd d-}|S ).Nc                 S   s   g }| D ]N}t |trM|drM|dd }td| }|d|  td| D ]}|d q,t|D ]}|d q8t|D ]}|d qDq|| q|S )	N
tensordesc,r   ztensordesc<([^[>]*)rc      rp   ro   )	
isinstancestr
startswithcountrematchgroupr@   range)	signatureoutputsigndimdtype_r   r   r   _expand_signature   s   z(make_launcher.<locals>._expand_signaturec                    s   t | trdt | S | S )Nr}   )r   tupler=   map)r   )_serialize_signaturer   r   r      s   
z+make_launcher.<locals>._serialize_signaturec                    sJ   t | trdt | }d| dS | d dkrdS | dkr!dS t| S )Nr}   []r   rc   z	PyObject*	constexprr   r   r=   r   r{   rz   val_extracted_typer   r   r      s   
z&make_launcher.<locals>._extracted_typec                    sd   t | trdt | }d| dS | d dkrdS | dkr!dS dd	d
dddddddd
t|  S )N ()r   rc   Or   rM   lbhiLBHIK)
rl   longre   rf   rd   rg   ri   rj   rh   rk   r   r   	format_ofr   r   r      s(   
z make_launcher.<locals>.format_ofc                 S      i | ]\}}||qS r   r   )r6   idxsr   r   r   
<dictcomp>       z!make_launcher.<locals>.<dictcomp>r   c                    s   g | ]} |qS r   r   )r6   rz   r   r   r   r9     s    z!make_launcher.<locals>.<listcomp>r}   c                 S   r   r   r   )r6   r   r   r   r   r   r     r   r   , c                 s   s    | ]
\}}d | V  qdS )z&_argNr   r6   r   rz   r   r   r   	<genexpr>  s    z make_launcher.<locals>.<genexpr>r   z argrc   Zptr_infoz.dev_ptrZ_argZ_storagec              
   S   s<   g | ]\}}|t v rt |  d | dt|  d| dqS ) _argz_storage = z(_argz);)FLOAT_STORAGE_TYPEFLOAT_PACK_FUNCTIONr   r   r   r   r9     s    "c                 S   s"   g | ]\}}|d krd| qS )r   z&argr   r   r   r   r   r9   &  s   " z&global_scratcha;  
#define __HIP_PLATFORM_AMD__
#include <hip/hip_runtime.h>
#include <Python.h>
#include <dlfcn.h>
#include <stdbool.h>
#include <dlfcn.h>

// The list of paths to search for the HIP runtime library. The caller Python
// code should substitute the search path placeholder.
static const char *hipLibSearchPaths[] = {"aj  "};

// The list of HIP dynamic library symbols and their signature we are interested
// in this file.
#define HIP_SYMBOL_LIST(FOR_EACH_ERR_FN, FOR_EACH_STR_FN)                     \
  FOR_EACH_STR_FN(hipGetErrorString, hipError_t hipError)                     \
  FOR_EACH_ERR_FN(hipModuleLaunchKernel, hipFunction_t f,                     \
                  unsigned int gridDimX, unsigned int gridDimY,               \
                  unsigned int gridDimZ, unsigned int blockDimX,              \
                  unsigned int blockDimY, unsigned int blockDimZ,             \
                  unsigned int sharedMemBytes, hipStream_t stream,            \
                  void **kernelParams, void **extra)                          \
  FOR_EACH_ERR_FN(hipModuleLaunchCooperativeKernel, hipFunction_t f,          \
                  unsigned int gridDimX, unsigned int gridDimY,               \
                  unsigned int gridDimZ, unsigned int blockDimX,              \
                  unsigned int blockDimY, unsigned int blockDimZ,             \
                  unsigned int sharedMemBytes, hipStream_t stream,            \
                  void **kernelParams, void **extra)                          \
  FOR_EACH_ERR_FN(hipPointerGetAttribute, void *data,                         \
                  hipPointer_attribute attribute, hipDeviceptr_t ptr)

// The HIP symbol table for holding resolved dynamic library symbols.
struct HIPSymbolTable {
#define DEFINE_EACH_ERR_FIELD(hipSymbolName, ...)                             \
  hipError_t (*hipSymbolName)(__VA_ARGS__);
#define DEFINE_EACH_STR_FIELD(hipSymbolName, ...)                             \
  const char *(*hipSymbolName)(__VA_ARGS__);

  HIP_SYMBOL_LIST(DEFINE_EACH_ERR_FIELD, DEFINE_EACH_STR_FIELD)
};

static struct HIPSymbolTable hipSymbolTable;

bool initSymbolTable() {
  // Use the HIP runtime library loaded into the existing process if it exits.
  void *lib = dlopen("libamdhip64.so", RTLD_NOLOAD);

  // Otherwise, go through the list of search paths to dlopen the first HIP
  // driver library.
  if (!lib) {
    int n = sizeof(hipLibSearchPaths) / sizeof(hipLibSearchPaths[0]);
    for (int i = 0; i < n; ++i) {
      void *handle = dlopen(hipLibSearchPaths[i], RTLD_LAZY | RTLD_LOCAL);
      if (handle) {
        lib = handle;
      }
    }
  }
  if (!lib) {
    PyErr_SetString(PyExc_RuntimeError, "cannot open libamdhip64.so");
    return false;
  }

  // Resolve all symbols we are interested in.
  dlerror(); // Clear existing errors
  const char *error = NULL;
#define QUERY_EACH_FN(hipSymbolName, ...)                                     \
  *(void **)&hipSymbolTable.hipSymbolName = dlsym(lib, #hipSymbolName);       \
  error = dlerror();                                                          \
  if (error) {                                                               \
    PyErr_SetString(PyExc_RuntimeError,                                       \
                    "cannot query " #hipSymbolName " from libamdhip64.so");   \
    dlclose(lib);                                                             \
    return false;                                                             \
  }

  HIP_SYMBOL_LIST(QUERY_EACH_FN, QUERY_EACH_FN)

  return true;
}

static inline void gpuAssert(hipError_t code, const char *file, int line)
{
   if (code != HIP_SUCCESS)
   {
      const char* prefix = "Triton Error [HIP]: ";
       const char* str = hipSymbolTable.hipGetErrorString(code);
      char err[1024] = {0};
      snprintf(err, 1024, "%s Code: %d, Messsage: %s", prefix, code, str );
      PyErr_SetString(PyExc_RuntimeError, err);
   }
}

#define HIP_CHECK(ans) { gpuAssert((ans), __FILE__, __LINE__); }

static void _launch(int gridX, int gridY, int gridZ, int num_warps, int num_ctas, int launch_cooperative_grid, int clusterDimX, int clusterDimY, int clusterDimZ, int shared_memory, hipStream_t stream, hipFunction_t functionz>) {
  hipDeviceptr_t global_scratch = 0;
  void *params[] = { z };
  if (gridX*gridY*gridZ > 0 && launch_cooperative_grid) {
    HIP_CHECK(hipSymbolTable.hipModuleLaunchCooperativeKernel(function, gridX, gridY, gridZ, z*num_warps, 1, 1, shared_memory, stream, params, 0));
    return;
  }
  if (gridX*gridY*gridZ > 0) {
    HIP_CHECK(hipSymbolTable.hipModuleLaunchKernel(function, gridX, gridY, gridZ, a	  *num_warps, 1, 1, shared_memory, stream, params, 0));
  }
}

typedef struct _DevicePtrInfo {
    hipDeviceptr_t dev_ptr;
    bool valid;
} DevicePtrInfo;

static inline DevicePtrInfo getPointer(PyObject *obj, int idx) {
  DevicePtrInfo ptr_info;
  ptr_info.dev_ptr = 0;
  ptr_info.valid = true;
  if (PyLong_Check(obj)) {
    ptr_info.dev_ptr = (hipDeviceptr_t)PyLong_AsUnsignedLongLong(obj);
    return ptr_info;
  }
  if (obj == Py_None) {
    // valid nullptr
    return ptr_info;
  }
  PyObject *ptr = PyObject_GetAttrString(obj, "data_ptr");
  if(ptr){
    PyObject *empty_tuple = PyTuple_New(0);
    PyObject *ret = PyObject_Call(ptr, empty_tuple, NULL);
    Py_DECREF(empty_tuple);
    Py_DECREF(ptr);
    if (!PyLong_Check(ret)) {
      PyErr_SetString(PyExc_TypeError, "data_ptr method of Pointer object must return 64-bit int");
      ptr_info.valid = false;
      return ptr_info;
    }
    ptr_info.dev_ptr = (hipDeviceptr_t)PyLong_AsUnsignedLongLong(ret);
    if(!ptr_info.dev_ptr)
      return ptr_info;
    uint64_t dev_ptr;
    hipError_t status = hipSymbolTable.hipPointerGetAttribute(&dev_ptr, HIP_POINTER_ATTRIBUTE_DEVICE_POINTER, ptr_info.dev_ptr);
    if (status == hipErrorInvalidValue) {
        PyErr_Format(PyExc_ValueError,
                     "Pointer argument (at %d) cannot be accessed from Triton (cpu tensor?)", idx);
        ptr_info.valid = false;
    }
    ptr_info.dev_ptr = (hipDeviceptr_t)dev_ptr;
    Py_DECREF(ret);
    return ptr_info;
  }
  PyErr_SetString(PyExc_TypeError, "Pointer argument must be either uint64 or have data_ptr method");
  return ptr_info;
}

static uint16_t pack_fp16(double f) {
    uint16_t result;
    // from https://github.com/python/pythoncapi-compat
#if 0x030600B1 <= PY_VERSION_HEX && PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION)
    _PyFloat_Pack2(f, (unsigned char*)&result, 1);
#else
    PyFloat_Pack2(f, (unsigned char*)&result, 1);
#endif
    return result;
}

static uint16_t pack_bf16(double f) {
    float f32 = (float)f;
    uint32_t u32 = *(uint32_t*)&f32;
    return (uint16_t)(u32 >> 16);
}

static uint32_t pack_fp32(double f) {
    float f32 = (float)f;
    return *(uint32_t*)&f32;
}

static uint64_t pack_fp64(double f) {
    return *(uint64_t*)&f;
}

static PyObject* launch(PyObject* self, PyObject* args) {
  int gridX, gridY, gridZ;
  uint64_t _stream;
  uint64_t _function;
  int launch_cooperative_grid;
  PyObject *launch_enter_hook = NULL;
  PyObject *launch_exit_hook = NULL;
  PyObject *kernel_metadata = NULL;
  PyObject *launch_metadata = NULL;
   c                    s$   g | ]\}} | d | dqS )r   ; r   r   r   r   r   r9     s   $ z
  if(!PyArg_ParseTuple(args, "a  ", &launch_cooperative_grid,
                                           &gridX, &gridY, &gridZ, &_stream, &_function,
                                           &kernel_metadata, &launch_metadata,
                                           &launch_enter_hook, &launch_exit_hook z)) {
    return NULL;
  }

  a8  

  // extract kernel metadata
  int num_warps, num_ctas, shared_memory, clusterDimX, clusterDimY, clusterDimZ;
  if (!PyArg_ParseTuple(kernel_metadata, "iiiiii", &num_warps, &num_ctas, &shared_memory, &clusterDimX, &clusterDimY, &clusterDimZ)) {
    return NULL;
  }
  // extract launch metadata
  if (launch_enter_hook != Py_None){
    PyObject* args = Py_BuildValue("(O)", launch_metadata);
    PyObject* ret = PyObject_CallObject(launch_enter_hook, args);
    Py_DECREF(args);
    if (!ret)
      return NULL;
    Py_DECREF(ret);
  }


  // raise exception asap
  r   c                 S   s>   g | ]\}}|d  dkrd| d| d| d| d	ndqS )r   rc   zDevicePtrInfo ptr_infoz = getPointer(_argr   z); if (!ptr_infoz.valid) return NULL;r   r   r   r   r   r   r9     s   > z;
  _launch(gridX, gridY, gridZ, num_warps, num_ctas, launch_cooperative_grid, clusterDimX, clusterDimY, clusterDimZ, shared_memory, (hipStream_t)_stream, (hipFunction_t)_functiona  );

  if(launch_exit_hook != Py_None){
    PyObject* args = Py_BuildValue("(O)", launch_metadata);
    PyObject* ret = PyObject_CallObject(launch_exit_hook, args);
    Py_DECREF(args);
    if (!ret)
      return NULL;
    Py_DECREF(ret);
  }

  if(PyErr_Occurred()) {
    return NULL;
  }
  // return None
  Py_INCREF(Py_None);
  return Py_None;
}

static PyMethodDef ModuleMethods[] = {
  {"launch", launch, METH_VARARGS, "Entry point for all kernels with this signature"},
  {NULL, NULL, 0, NULL} // sentinel
};

static struct PyModuleDef ModuleDef = {
  PyModuleDef_HEAD_INIT,
  "__triton_launcher",
  NULL, //documentation
  -1, //size
  ModuleMethods
};

PyMODINIT_FUNC PyInit___triton_launcher(void) {
  if (!initSymbolTable()) {
    return NULL;
  }
  PyObject *m = PyModule_Create(&ModuleDef);
  if(m == NULL) {
    return NULL;
  }
  PyModule_AddFunctions(m, ModuleMethods);
  return m;
}
)	enumeratevaluesr=   _BASE_ARGS_FORMATr   listfilterboolr5   r   itemsr   r@   r{   rP   r   )	constantsr   	warp_sizer   Zargs_formatformatZ	args_listZarg_decl_listr   rz   Z	arg_declsZinternal_args_listZfloat_storage_declsr:   paramsrZ   r   )r   r   r   r   make_launcher   s   
,


_acg =  >  A  E  X  Y   r   c                    s    fdd}|S )zN
    Replace all tensor descriptors with the base ptr, shape, and strides
    c                     s|   | d t t }| t td  }g }|D ] }t|tr/||jg|j|j|j|j q|| q g ||R  S N)	r   r   r   r   extendbaseshapestridesr@   )argsZ	meta_argsZraw_kernel_argsZ
final_argsarglauncherr   r   inner4  s   
(z,wrap_handle_tensor_descriptor.<locals>.innerr   )r   r   r   r   r   wrap_handle_tensor_descriptor/  s   r   c                   @   s   e Zd Zdd Zdd ZdS )HIPLauncherc                    s   t drjnt }fdd  fdd| D }dd j D }t|||jtdtd}t	d	d
 |
 D }|rFt|jn|j| _|j| _d S )Nr   c                    s   t | tr jj| fS | S r   )r   r   fn	arg_namesindex)x)rZ   r   r   <lambda>L  s    z&HIPLauncher.__init__.<locals>.<lambda>c                    s   i | ]	\}} ||qS r   r   r6   r   value)arg_idxr   r   r   M  s    z(HIPLauncher.__init__.<locals>.<dictcomp>c                 S   r   r   r   r   r   r   r   r   N  r   Z__triton_launcherrY   c                 s   s$    | ]}t |to|d V  qdS )r|   N)r   r   r   )r6   r   r   r   r   r   Q  s   " z'HIPLauncher.__init__.<locals>.<genexpr>)rS   r   dictr   r   r   r   r   r[   anyr   r   launchlaunch_cooperative_grid)r_   rZ   metadatar   r   r`   Zhas_tensor_desc_argr   )r   rZ   r   ra   J  s   zHIPLauncher.__init__c                 G   s   | j | jg|R   d S r   )r   r   )r_   r   r   r   r   __call__V  s   zHIPLauncher.__call__N)r   r   r   ra   r   r   r   r   r   r   H  s    r   c                       sX   e Zd Z fddZdd Zedd Zdd Zd	d
 Zdd Z	dd Z
dd Z  ZS )	HIPDriverc                    s   t    t | _t| _d S r   )rT   ra   rQ   utilsr   Zlauncher_cls)r_   rW   r   r   ra   \  s   

zHIPDriver.__init__c                 C   s   dd l }|jS )Nr   )r0   cudar_   r0   r   r   r   get_device_interfacea  s   zHIPDriver.get_device_interfacec                  C   s6   zdd l } | j o| jjd uW S  ty   Y dS w )Nr   F)r0   r   Zis_availableversionhipImportError)r0   r   r   r   	is_activee  s   zHIPDriver.is_activec                 C   sB   |   }| j|}tjjp|d }|d }td|dd |S )NarchZwarpSizer   r1   r   )get_current_devicer   r^   r   ZruntimeZoverride_archr   r5   )r_   deviceZdevice_propertiesr   r   r   r   r   get_current_targetm  s
   zHIPDriver.get_current_targetc                 C   s   dd l }|d|  S )Nr   r   )r0   r   r   r   r   r   r   get_active_torch_devicet  s   z!HIPDriver.get_active_torch_devicec                 C   s   ddl m} |S )Nr   )do_bench)Ztriton.testingr   )r_   r   r   r   r   get_benchmarkery  s   zHIPDriver.get_benchmarkerc                 C   s&   dd l }d}|jt|d |jddS )Nr   i      r   )r   r   )r0   emptyint)r_   r0   Z
cache_sizer   r   r   get_empty_cache_for_benchmark}  s   z'HIPDriver.get_empty_cache_for_benchmarkc                 C   s   |   d S r   )Zzero_)r_   cacher   r   r   clear_cache  s   zHIPDriver.clear_cache)r   r   r   ra   r   staticmethodr   r   r   r   r   r   rb   r   r   rW   r   r   Z  s    
r   )#	functoolsr   rF   r   pathlibr   Ztritonr   Ztriton.backends.compilerr   Ztriton.backends.driverr   Ztriton.runtime.buildr   Ztriton.tools.tensor_descriptorr   r-   r>   realpathr?   r=   r[   r.   	lru_cacherP   objectrQ   r{   r   r   r   r   r   r   r   r   r   r   r   <module>   sH    0
C  q