triton-windows 3.2.0.post11__cp311-cp311-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of triton-windows might be problematic. Click here for more details.

Files changed (154) hide show
  1. triton/_C/libtriton.pyd +0 -0
  2. triton/__init__.py +85 -0
  3. triton/_internal_testing.py +123 -0
  4. triton/backends/__init__.py +50 -0
  5. triton/backends/amd/compiler.py +368 -0
  6. triton/backends/amd/driver.c +211 -0
  7. triton/backends/amd/driver.py +512 -0
  8. triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h +358 -0
  9. triton/backends/amd/include/hip/amd_detail/amd_device_functions.h +1031 -0
  10. triton/backends/amd/include/hip/amd_detail/amd_hip_atomic.h +1612 -0
  11. triton/backends/amd/include/hip/amd_detail/amd_hip_bf16.h +1337 -0
  12. triton/backends/amd/include/hip/amd_detail/amd_hip_bfloat16.h +293 -0
  13. triton/backends/amd/include/hip/amd_detail/amd_hip_common.h +32 -0
  14. triton/backends/amd/include/hip/amd_detail/amd_hip_complex.h +174 -0
  15. triton/backends/amd/include/hip/amd_detail/amd_hip_cooperative_groups.h +829 -0
  16. triton/backends/amd/include/hip/amd_detail/amd_hip_fp16.h +1809 -0
  17. triton/backends/amd/include/hip/amd_detail/amd_hip_gl_interop.h +108 -0
  18. triton/backends/amd/include/hip/amd_detail/amd_hip_math_constants.h +124 -0
  19. triton/backends/amd/include/hip/amd_detail/amd_hip_runtime.h +405 -0
  20. triton/backends/amd/include/hip/amd_detail/amd_hip_runtime_pt_api.h +196 -0
  21. triton/backends/amd/include/hip/amd_detail/amd_hip_unsafe_atomics.h +565 -0
  22. triton/backends/amd/include/hip/amd_detail/amd_hip_vector_types.h +2226 -0
  23. triton/backends/amd/include/hip/amd_detail/amd_math_functions.h +104 -0
  24. triton/backends/amd/include/hip/amd_detail/amd_surface_functions.h +244 -0
  25. triton/backends/amd/include/hip/amd_detail/amd_warp_functions.h +494 -0
  26. triton/backends/amd/include/hip/amd_detail/concepts.hpp +30 -0
  27. triton/backends/amd/include/hip/amd_detail/device_library_decls.h +133 -0
  28. triton/backends/amd/include/hip/amd_detail/functional_grid_launch.hpp +218 -0
  29. triton/backends/amd/include/hip/amd_detail/grid_launch.h +67 -0
  30. triton/backends/amd/include/hip/amd_detail/grid_launch.hpp +50 -0
  31. triton/backends/amd/include/hip/amd_detail/grid_launch_GGL.hpp +26 -0
  32. triton/backends/amd/include/hip/amd_detail/helpers.hpp +137 -0
  33. triton/backends/amd/include/hip/amd_detail/hip_api_trace.hpp +1350 -0
  34. triton/backends/amd/include/hip/amd_detail/hip_assert.h +101 -0
  35. triton/backends/amd/include/hip/amd_detail/hip_cooperative_groups_helper.h +242 -0
  36. triton/backends/amd/include/hip/amd_detail/hip_fp16_gcc.h +254 -0
  37. triton/backends/amd/include/hip/amd_detail/hip_fp16_math_fwd.h +96 -0
  38. triton/backends/amd/include/hip/amd_detail/hip_ldg.h +100 -0
  39. triton/backends/amd/include/hip/amd_detail/hip_prof_str.h +10169 -0
  40. triton/backends/amd/include/hip/amd_detail/hip_runtime_prof.h +77 -0
  41. triton/backends/amd/include/hip/amd_detail/host_defines.h +180 -0
  42. triton/backends/amd/include/hip/amd_detail/hsa_helpers.hpp +102 -0
  43. triton/backends/amd/include/hip/amd_detail/macro_based_grid_launch.hpp +798 -0
  44. triton/backends/amd/include/hip/amd_detail/math_fwd.h +698 -0
  45. triton/backends/amd/include/hip/amd_detail/ockl_image.h +177 -0
  46. triton/backends/amd/include/hip/amd_detail/program_state.hpp +107 -0
  47. triton/backends/amd/include/hip/amd_detail/texture_fetch_functions.h +491 -0
  48. triton/backends/amd/include/hip/amd_detail/texture_indirect_functions.h +478 -0
  49. triton/backends/amd/include/hip/channel_descriptor.h +39 -0
  50. triton/backends/amd/include/hip/device_functions.h +38 -0
  51. triton/backends/amd/include/hip/driver_types.h +468 -0
  52. triton/backends/amd/include/hip/hip_bf16.h +36 -0
  53. triton/backends/amd/include/hip/hip_bfloat16.h +44 -0
  54. triton/backends/amd/include/hip/hip_common.h +100 -0
  55. triton/backends/amd/include/hip/hip_complex.h +38 -0
  56. triton/backends/amd/include/hip/hip_cooperative_groups.h +46 -0
  57. triton/backends/amd/include/hip/hip_deprecated.h +95 -0
  58. triton/backends/amd/include/hip/hip_ext.h +159 -0
  59. triton/backends/amd/include/hip/hip_fp16.h +36 -0
  60. triton/backends/amd/include/hip/hip_gl_interop.h +32 -0
  61. triton/backends/amd/include/hip/hip_hcc.h +24 -0
  62. triton/backends/amd/include/hip/hip_math_constants.h +36 -0
  63. triton/backends/amd/include/hip/hip_profile.h +27 -0
  64. triton/backends/amd/include/hip/hip_runtime.h +75 -0
  65. triton/backends/amd/include/hip/hip_runtime_api.h +8919 -0
  66. triton/backends/amd/include/hip/hip_texture_types.h +29 -0
  67. triton/backends/amd/include/hip/hip_vector_types.h +41 -0
  68. triton/backends/amd/include/hip/hip_version.h +17 -0
  69. triton/backends/amd/include/hip/hiprtc.h +421 -0
  70. triton/backends/amd/include/hip/library_types.h +78 -0
  71. triton/backends/amd/include/hip/math_functions.h +42 -0
  72. triton/backends/amd/include/hip/surface_types.h +63 -0
  73. triton/backends/amd/include/hip/texture_types.h +194 -0
  74. triton/backends/amd/include/hsa/Brig.h +1131 -0
  75. triton/backends/amd/include/hsa/amd_hsa_common.h +91 -0
  76. triton/backends/amd/include/hsa/amd_hsa_elf.h +436 -0
  77. triton/backends/amd/include/hsa/amd_hsa_kernel_code.h +269 -0
  78. triton/backends/amd/include/hsa/amd_hsa_queue.h +109 -0
  79. triton/backends/amd/include/hsa/amd_hsa_signal.h +80 -0
  80. triton/backends/amd/include/hsa/hsa.h +5729 -0
  81. triton/backends/amd/include/hsa/hsa_amd_tool.h +91 -0
  82. triton/backends/amd/include/hsa/hsa_api_trace.h +566 -0
  83. triton/backends/amd/include/hsa/hsa_ext_amd.h +3090 -0
  84. triton/backends/amd/include/hsa/hsa_ext_finalize.h +531 -0
  85. triton/backends/amd/include/hsa/hsa_ext_image.h +1454 -0
  86. triton/backends/amd/include/hsa/hsa_ven_amd_aqlprofile.h +488 -0
  87. triton/backends/amd/include/hsa/hsa_ven_amd_loader.h +667 -0
  88. triton/backends/amd/include/roctracer/ext/prof_protocol.h +107 -0
  89. triton/backends/amd/include/roctracer/hip_ostream_ops.h +4435 -0
  90. triton/backends/amd/include/roctracer/hsa_ostream_ops.h +1467 -0
  91. triton/backends/amd/include/roctracer/hsa_prof_str.h +3027 -0
  92. triton/backends/amd/include/roctracer/roctracer.h +779 -0
  93. triton/backends/amd/include/roctracer/roctracer_ext.h +81 -0
  94. triton/backends/amd/include/roctracer/roctracer_hcc.h +24 -0
  95. triton/backends/amd/include/roctracer/roctracer_hip.h +37 -0
  96. triton/backends/amd/include/roctracer/roctracer_hsa.h +112 -0
  97. triton/backends/amd/include/roctracer/roctracer_plugin.h +137 -0
  98. triton/backends/amd/include/roctracer/roctracer_roctx.h +67 -0
  99. triton/backends/amd/include/roctracer/roctx.h +229 -0
  100. triton/backends/amd/lib/ockl.bc +0 -0
  101. triton/backends/amd/lib/ocml.bc +0 -0
  102. triton/backends/compiler.py +304 -0
  103. triton/backends/driver.py +48 -0
  104. triton/backends/nvidia/__init__.py +0 -0
  105. triton/backends/nvidia/bin/ptxas.exe +0 -0
  106. triton/backends/nvidia/compiler.py +410 -0
  107. triton/backends/nvidia/driver.c +451 -0
  108. triton/backends/nvidia/driver.py +524 -0
  109. triton/backends/nvidia/include/cuda.h +24359 -0
  110. triton/backends/nvidia/lib/libdevice.10.bc +0 -0
  111. triton/backends/nvidia/lib/x64/cuda.lib +0 -0
  112. triton/compiler/__init__.py +4 -0
  113. triton/compiler/code_generator.py +1303 -0
  114. triton/compiler/compiler.py +430 -0
  115. triton/compiler/errors.py +51 -0
  116. triton/compiler/make_launcher.py +0 -0
  117. triton/errors.py +5 -0
  118. triton/language/__init__.py +294 -0
  119. triton/language/_utils.py +21 -0
  120. triton/language/core.py +2694 -0
  121. triton/language/extra/__init__.py +26 -0
  122. triton/language/extra/cuda/__init__.py +13 -0
  123. triton/language/extra/cuda/_experimental_tma.py +108 -0
  124. triton/language/extra/cuda/libdevice.py +1629 -0
  125. triton/language/extra/cuda/utils.py +109 -0
  126. triton/language/extra/hip/__init__.py +3 -0
  127. triton/language/extra/hip/libdevice.py +475 -0
  128. triton/language/extra/libdevice.py +786 -0
  129. triton/language/math.py +250 -0
  130. triton/language/random.py +207 -0
  131. triton/language/semantic.py +1796 -0
  132. triton/language/standard.py +452 -0
  133. triton/runtime/__init__.py +23 -0
  134. triton/runtime/autotuner.py +408 -0
  135. triton/runtime/build.py +111 -0
  136. triton/runtime/cache.py +295 -0
  137. triton/runtime/driver.py +60 -0
  138. triton/runtime/errors.py +26 -0
  139. triton/runtime/interpreter.py +1235 -0
  140. triton/runtime/jit.py +951 -0
  141. triton/testing.py +511 -0
  142. triton/tools/__init__.py +0 -0
  143. triton/tools/build_extern.py +365 -0
  144. triton/tools/compile.c +67 -0
  145. triton/tools/compile.h +14 -0
  146. triton/tools/compile.py +155 -0
  147. triton/tools/disasm.py +144 -0
  148. triton/tools/experimental_descriptor.py +32 -0
  149. triton/tools/link.py +322 -0
  150. triton/windows_utils.py +375 -0
  151. triton_windows-3.2.0.post11.dist-info/METADATA +39 -0
  152. triton_windows-3.2.0.post11.dist-info/RECORD +154 -0
  153. triton_windows-3.2.0.post11.dist-info/WHEEL +5 -0
  154. triton_windows-3.2.0.post11.dist-info/top_level.txt +12 -0
@@ -0,0 +1,512 @@
1
+ import functools
2
+ import os
3
+ import hashlib
4
+ import subprocess
5
+ import tempfile
6
+ from pathlib import Path
7
+ from triton.runtime.build import _build
8
+ from triton.runtime.cache import get_cache_manager
9
+ from triton.backends.compiler import GPUTarget
10
+ from triton.backends.driver import GPUDriver
11
+
12
+ dirname = os.path.dirname(os.path.realpath(__file__))
13
+ include_dir = [os.path.join(dirname, "include")]
14
+
15
+
16
+ def _find_already_mmapped_dylib_on_linux(lib_name):
17
+ import platform
18
+ if platform.system() != 'Linux':
19
+ return None
20
+
21
+ # Use dl_iterate_phdr to walk through the list of shared libraries at runtime.
22
+ # See https://www.man7.org/linux/man-pages/man3/dl_iterate_phdr.3.html for details.
23
+
24
+ import ctypes
25
+ from ctypes import c_char, c_int, c_size_t, c_void_p, c_char_p, POINTER
26
+
27
+ class DlPhdrInfo(ctypes.Structure):
28
+ _fields_ = [
29
+ ('dlpi_addr', c_void_p),
30
+ ('dlpi_name', c_char_p),
31
+ # We don't care about the remaining fields.
32
+ ]
33
+
34
+ # callback_t must use POINTER(c_char) to avoid copying.
35
+ callback_t = ctypes.CFUNCTYPE(c_int, POINTER(DlPhdrInfo), POINTER(c_size_t), POINTER(c_char))
36
+
37
+ # Load libc and get the dl_iterate_phdr symbol.
38
+ try:
39
+ dl_iterate_phdr = ctypes.CDLL('libc.so.6').dl_iterate_phdr
40
+ except:
41
+ return None
42
+ # argtypes must use c_char_p to accept create_string_buffer.
43
+ dl_iterate_phdr.argtypes = [callback_t, c_char_p]
44
+ dl_iterate_phdr.restype = c_int
45
+
46
+ max_path_length = 4096
47
+ path = ctypes.create_string_buffer(max_path_length + 1)
48
+
49
+ # Define callback to get the loaded dylib path.
50
+ def callback(info, size, data):
51
+ dlpi_name = info.contents.dlpi_name
52
+ p = Path(os.fsdecode(dlpi_name))
53
+ if lib_name in p.name:
54
+ # Found the dylib; get its path.
55
+ ctypes.memmove(data, dlpi_name, min(max_path_length, len(dlpi_name)))
56
+ return 1
57
+ return 0
58
+
59
+ if dl_iterate_phdr(callback_t(callback), path):
60
+ return os.fsdecode(ctypes.string_at(path))
61
+ return None
62
+
63
+
64
+ @functools.lru_cache()
65
+ def _get_path_to_hip_runtime_dylib():
66
+ lib_name = "libamdhip64.so"
67
+
68
+ # If we are told explicitly what HIP runtime dynamic library to use, obey that.
69
+ env_libhip_path = os.getenv("TRITON_LIBHIP_PATH")
70
+ if env_libhip_path:
71
+ if env_libhip_path.endswith(lib_name) and os.path.exists(env_libhip_path):
72
+ return env_libhip_path
73
+ raise RuntimeError(f"TRITON_LIBHIP_PATH '{env_libhip_path}' does not point to a valid {lib_name}")
74
+
75
+ # If the shared object is already mmapped to address space, use it.
76
+ mmapped_path = _find_already_mmapped_dylib_on_linux(lib_name)
77
+ if mmapped_path:
78
+ if os.path.exists(mmapped_path):
79
+ return mmapped_path
80
+ raise RuntimeError(f"memory mapped '{mmapped_path}' in process does not point to a valid {lib_name}")
81
+
82
+ paths = []
83
+
84
+ import site
85
+ # First search the HIP runtime dynamic library packaged with PyTorch. It's very likely
86
+ # that we run Triton together with PyTorch. This makes sure we use the same dynamic
87
+ # library to avoid version mismatch.
88
+ site_packages = site.getsitepackages()
89
+ user_site = site.getusersitepackages()
90
+ if site.ENABLE_USER_SITE: # ENABLE_USER_SITE is initialized in getusersitepackages()
91
+ site_packages = [user_site] + site_packages
92
+ for path in site_packages:
93
+ path = os.path.join(path, "torch", "lib", lib_name)
94
+ if os.path.exists(path):
95
+ return path
96
+ paths.append(path)
97
+
98
+ # Then try to see if developer provides a HIP runtime dynamic library using LD_LIBARAY_PATH.
99
+ env_ld_library_path = os.getenv("LD_LIBRARY_PATH")
100
+ if env_ld_library_path:
101
+ for d in env_ld_library_path.split(":"):
102
+ f = os.path.join(d, lib_name)
103
+ if os.path.exists(f):
104
+ return f
105
+ paths.append(f)
106
+
107
+ # Afterwards try to search the loader dynamic library resolution paths.
108
+ libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode()
109
+ # each line looks like the following:
110
+ # libamdhip64.so.6 (libc6,x86-64) => /opt/rocm-6.0.2/lib/libamdhip64.so.6
111
+ # libamdhip64.so (libc6,x86-64) => /opt/rocm-6.0.2/lib/libamdhip64.so
112
+ locs = [line.split()[-1] for line in libs.splitlines() if line.strip().endswith(lib_name)]
113
+ for loc in locs:
114
+ if os.path.exists(loc):
115
+ return loc
116
+ paths.append(loc)
117
+
118
+ # As a last resort, guess if we have it in some common installation path.
119
+ common_install_path = os.path.join('/opt/rocm/lib/', lib_name)
120
+ if os.path.exists(common_install_path):
121
+ return common_install_path
122
+ paths.append(common_install_path)
123
+
124
+ raise RuntimeError(f"cannot locate {lib_name} after attempted paths {paths}")
125
+
126
+
127
+ def compile_module_from_src(src, name):
128
+ key = hashlib.sha256(src.encode("utf-8")).hexdigest()
129
+ cache = get_cache_manager(key)
130
+ cache_path = cache.get_file(f"{name}.so")
131
+ if cache_path is None:
132
+ with tempfile.TemporaryDirectory() as tmpdir:
133
+ src_path = os.path.join(tmpdir, f"{name}.c")
134
+ with open(src_path, "w") as f:
135
+ f.write(src)
136
+ so = _build(name, src_path, tmpdir, [], include_dir, [])
137
+ with open(so, "rb") as f:
138
+ cache_path = cache.put(f.read(), f"{name}.so", binary=True)
139
+ import importlib.util
140
+ spec = importlib.util.spec_from_file_location(name, cache_path)
141
+ mod = importlib.util.module_from_spec(spec)
142
+ spec.loader.exec_module(mod)
143
+ return mod
144
+
145
+
146
+ class HIPUtils(object):
147
+
148
+ def __new__(cls):
149
+ if not hasattr(cls, "instance"):
150
+ cls.instance = super(HIPUtils, cls).__new__(cls)
151
+ return cls.instance
152
+
153
+ def __init__(self):
154
+ libhip_path = _get_path_to_hip_runtime_dylib()
155
+ src = Path(os.path.join(dirname, "driver.c")).read_text()
156
+ # Just do a simple search and replace here instead of templates or format strings.
157
+ # This way we don't need to escape-quote C code curly brackets and we can replace
158
+ # exactly once.
159
+ src = src.replace('/*py_libhip_search_path*/', libhip_path, 1)
160
+ mod = compile_module_from_src(src, "hip_utils")
161
+ self.load_binary = mod.load_binary
162
+ self.get_device_properties = mod.get_device_properties
163
+
164
+
165
+ # -------------------- Launcher ----------------------------
166
+ def ty_to_cpp(ty):
167
+ if ty[0] == '*':
168
+ return "hipDeviceptr_t"
169
+ return {
170
+ "i1": "int32_t",
171
+ "i8": "int8_t",
172
+ "i16": "int16_t",
173
+ "i32": "int32_t",
174
+ "i64": "int64_t",
175
+ "u1": "uint32_t",
176
+ "u8": "uint8_t",
177
+ "u16": "uint16_t",
178
+ "u32": "uint32_t",
179
+ "u64": "uint64_t",
180
+ "fp16": "float",
181
+ "bf16": "float",
182
+ "fp32": "float",
183
+ "f32": "float",
184
+ "fp64": "double",
185
+ }[ty]
186
+
187
+
188
+ def make_launcher(constants, signature, ids, warp_size):
189
+ start_desc = len(signature)
190
+ #signature = generate_cu_signature(constants, signature, ids)
191
+ arg_decls = ', '.join(f"{ty_to_cpp(ty)} arg{i}" for i, ty in signature.items())
192
+
193
+ def _extracted_type(ty):
194
+ if ty[0] == '*':
195
+ return "PyObject*"
196
+ return {
197
+ 'i1': 'int32_t',
198
+ 'i8': 'int8_t',
199
+ 'i16': 'int16_t',
200
+ 'i32': 'int32_t',
201
+ 'i64': 'int64_t',
202
+ 'u1': 'uint32_t',
203
+ 'u8': 'uint8_t',
204
+ 'u16': 'uint16_t',
205
+ 'u32': 'uint32_t',
206
+ 'u64': 'uint64_t',
207
+ 'fp16': 'float',
208
+ 'bf16': 'float',
209
+ 'fp32': 'float',
210
+ 'f32': 'float',
211
+ 'fp64': 'double',
212
+ }[ty]
213
+
214
+ def format_of(ty):
215
+ return {
216
+ "PyObject*": "O",
217
+ "float": "f",
218
+ "double": "d",
219
+ "long": "l",
220
+ "int8_t": "b",
221
+ "int16_t": "h",
222
+ "int32_t": "i",
223
+ "int64_t": "L",
224
+ "uint8_t": "B",
225
+ "uint16_t": "H",
226
+ "uint32_t": "I",
227
+ "uint64_t": "K",
228
+ }[ty]
229
+
230
+ args_format = ''.join([format_of(_extracted_type(ty)) for ty in signature.values()])
231
+ format = "iiiKKOOOO" + args_format
232
+ args_list = ', ' + ', '.join(f"&_arg{i}" for i, ty in signature.items()) if len(signature) > 0 else ''
233
+
234
+ libhip_path = _get_path_to_hip_runtime_dylib()
235
+
236
+ # generate glue code
237
+ params = [i for i in signature.keys() if i not in constants]
238
+ src = f"""
239
+ #define __HIP_PLATFORM_AMD__
240
+ #include <hip/hip_runtime.h>
241
+ #include <Python.h>
242
+ #include <dlfcn.h>
243
+ #include <stdbool.h>
244
+ #include <dlfcn.h>
245
+
246
+ // The list of paths to search for the HIP runtime library. The caller Python
247
+ // code should substitute the search path placeholder.
248
+ static const char *hipLibSearchPaths[] = {{"{libhip_path}"}};
249
+
250
+ // The list of HIP dynamic library symbols and their signature we are interested
251
+ // in this file.
252
+ #define HIP_SYMBOL_LIST(FOR_EACH_ERR_FN, FOR_EACH_STR_FN) \\
253
+ FOR_EACH_STR_FN(hipGetErrorString, hipError_t hipError) \\
254
+ FOR_EACH_ERR_FN(hipModuleLaunchKernel, hipFunction_t f, \\
255
+ unsigned int gridDimX, unsigned int gridDimY, \\
256
+ unsigned int gridDimZ, unsigned int blockDimX, \\
257
+ unsigned int blockDimY, unsigned int blockDimZ, \\
258
+ unsigned int sharedMemBytes, hipStream_t stream, \\
259
+ void **kernelParams, void **extra) \\
260
+ FOR_EACH_ERR_FN(hipPointerGetAttribute, void *data, \\
261
+ hipPointer_attribute attribute, hipDeviceptr_t ptr)
262
+
263
+ // The HIP symbol table for holding resolved dynamic library symbols.
264
+ struct HIPSymbolTable {{
265
+ #define DEFINE_EACH_ERR_FIELD(hipSymbolName, ...) \\
266
+ hipError_t (*hipSymbolName)(__VA_ARGS__);
267
+ #define DEFINE_EACH_STR_FIELD(hipSymbolName, ...) \\
268
+ const char *(*hipSymbolName)(__VA_ARGS__);
269
+
270
+ HIP_SYMBOL_LIST(DEFINE_EACH_ERR_FIELD, DEFINE_EACH_STR_FIELD)
271
+ }};
272
+
273
+ static struct HIPSymbolTable hipSymbolTable;
274
+
275
+ bool initSymbolTable() {{
276
+ // Use the HIP runtime library loaded into the existing process if it exits.
277
+ void *lib = dlopen("libamdhip64.so", RTLD_NOLOAD);
278
+ if (lib) {{
279
+ // printf("[triton] chosen loaded libamdhip64.so in the process\\n");
280
+ }}
281
+
282
+ // Otherwise, go through the list of search paths to dlopen the first HIP
283
+ // driver library.
284
+ if (!lib) {{
285
+ int n = sizeof(hipLibSearchPaths) / sizeof(hipLibSearchPaths[0]);
286
+ for (int i = 0; i < n; ++i) {{
287
+ void *handle = dlopen(hipLibSearchPaths[i], RTLD_LAZY | RTLD_LOCAL);
288
+ if (handle) {{
289
+ lib = handle;
290
+ // printf("[triton] chosen %s\\n", hipLibSearchPaths[i]);
291
+ }}
292
+ }}
293
+ }}
294
+ if (!lib) {{
295
+ PyErr_SetString(PyExc_RuntimeError, "cannot open libamdhip64.so");
296
+ return false;
297
+ }}
298
+
299
+ // Resolve all symbols we are interested in.
300
+ dlerror(); // Clear existing errors
301
+ const char *error = NULL;
302
+ #define QUERY_EACH_FN(hipSymbolName, ...) \\
303
+ *(void **)&hipSymbolTable.hipSymbolName = dlsym(lib, #hipSymbolName); \\
304
+ error = dlerror(); \\
305
+ if (error) {{ \\
306
+ PyErr_SetString(PyExc_RuntimeError, \\
307
+ "cannot query " #hipSymbolName " from libamdhip64.so"); \\
308
+ dlclose(lib); \\
309
+ return false; \\
310
+ }}
311
+
312
+ HIP_SYMBOL_LIST(QUERY_EACH_FN, QUERY_EACH_FN)
313
+
314
+ return true;
315
+ }}
316
+
317
+ static inline void gpuAssert(hipError_t code, const char *file, int line)
318
+ {{
319
+ if (code != HIP_SUCCESS)
320
+ {{
321
+ const char* prefix = "Triton Error [HIP]: ";
322
+ const char* str = hipSymbolTable.hipGetErrorString(code);
323
+ char err[1024] = {{0}};
324
+ snprintf(err, 1024, "%s Code: %d, Messsage: %s", prefix, code, str );
325
+ PyErr_SetString(PyExc_RuntimeError, err);
326
+ }}
327
+ }}
328
+
329
+ #define HIP_CHECK(ans) {{ gpuAssert((ans), __FILE__, __LINE__); }}
330
+
331
+ static void _launch(int gridX, int gridY, int gridZ, int num_warps, int num_ctas, int clusterDimX, int clusterDimY, int clusterDimZ, int shared_memory, hipStream_t stream, hipFunction_t function{', ' + arg_decls if len(arg_decls) > 0 else ''}) {{
332
+ // printf("_launch hip kernel\\n");
333
+ void *params[] = {{ {', '.join(f"&arg{i}" for i in params)} }};
334
+ if (gridX*gridY*gridZ > 0) {{
335
+ HIP_CHECK(hipSymbolTable.hipModuleLaunchKernel(function, gridX, gridY, gridZ, {warp_size}*num_warps, 1, 1, shared_memory, stream, params, 0));
336
+ }}
337
+ }}
338
+
339
+ typedef struct _DevicePtrInfo {{
340
+ hipDeviceptr_t dev_ptr;
341
+ bool valid;
342
+ }} DevicePtrInfo;
343
+
344
+ static inline DevicePtrInfo getPointer(PyObject *obj, int idx) {{
345
+ DevicePtrInfo ptr_info;
346
+ ptr_info.dev_ptr = 0;
347
+ ptr_info.valid = true;
348
+ if (PyLong_Check(obj)) {{
349
+ ptr_info.dev_ptr = (hipDeviceptr_t)PyLong_AsUnsignedLongLong(obj);
350
+ return ptr_info;
351
+ }}
352
+ if (obj == Py_None) {{
353
+ // valid nullptr
354
+ return ptr_info;
355
+ }}
356
+ PyObject *ptr = PyObject_GetAttrString(obj, "data_ptr");
357
+ if(ptr){{
358
+ PyObject *empty_tuple = PyTuple_New(0);
359
+ PyObject *ret = PyObject_Call(ptr, empty_tuple, NULL);
360
+ Py_DECREF(empty_tuple);
361
+ Py_DECREF(ptr);
362
+ if (!PyLong_Check(ret)) {{
363
+ PyErr_SetString(PyExc_TypeError, "data_ptr method of Pointer object must return 64-bit int");
364
+ ptr_info.valid = false;
365
+ return ptr_info;
366
+ }}
367
+ ptr_info.dev_ptr = (hipDeviceptr_t)PyLong_AsUnsignedLongLong(ret);
368
+ if(!ptr_info.dev_ptr)
369
+ return ptr_info;
370
+ uint64_t dev_ptr;
371
+ hipError_t status = hipSymbolTable.hipPointerGetAttribute(&dev_ptr, HIP_POINTER_ATTRIBUTE_DEVICE_POINTER, ptr_info.dev_ptr);
372
+ if (status == hipErrorInvalidValue) {{
373
+ PyErr_Format(PyExc_ValueError,
374
+ "Pointer argument (at %d) cannot be accessed from Triton (cpu tensor?)", idx);
375
+ ptr_info.valid = false;
376
+ }}
377
+ ptr_info.dev_ptr = (hipDeviceptr_t)dev_ptr;
378
+ Py_DECREF(ret);
379
+ return ptr_info;
380
+ }}
381
+ PyErr_SetString(PyExc_TypeError, "Pointer argument must be either uint64 or have data_ptr method");
382
+ return ptr_info;
383
+ }}
384
+
385
+ static PyObject* launch(PyObject* self, PyObject* args) {{
386
+ // printf("launch\\n");
387
+ int gridX, gridY, gridZ;
388
+ uint64_t _stream;
389
+ uint64_t _function;
390
+ PyObject *launch_enter_hook = NULL;
391
+ PyObject *launch_exit_hook = NULL;
392
+ PyObject *kernel_metadata = NULL;
393
+ PyObject *launch_metadata = NULL;
394
+ {' '.join([f"{_extracted_type(ty)} _arg{i}; " for i, ty in signature.items()])}
395
+ if(!PyArg_ParseTuple(args, \"{format}\", &gridX, &gridY, &gridZ, &_stream, &_function,
396
+ &kernel_metadata, &launch_metadata,
397
+ &launch_enter_hook, &launch_exit_hook {args_list})) {{
398
+ return NULL;
399
+ }}
400
+
401
+ // extract kernel metadata
402
+ int num_warps, num_ctas, shared_memory, clusterDimX, clusterDimY, clusterDimZ;
403
+ if (!PyArg_ParseTuple(kernel_metadata, \"iiiiii\", &num_warps, &num_ctas, &shared_memory, &clusterDimX, &clusterDimY, &clusterDimZ)) {{
404
+ return NULL;
405
+ }}
406
+ // extract launch metadata
407
+ if (launch_enter_hook != Py_None){{
408
+ PyObject* args = Py_BuildValue("(O)", launch_metadata);
409
+ PyObject* ret = PyObject_CallObject(launch_enter_hook, args);
410
+ Py_DECREF(args);
411
+ if (!ret)
412
+ return NULL;
413
+ }}
414
+
415
+
416
+ // raise exception asap
417
+ {"; ".join([f"DevicePtrInfo ptr_info{i} = getPointer(_arg{i}, {i}); if (!ptr_info{i}.valid) return NULL;" if ty[0] == "*" else "" for i, ty in signature.items()])};
418
+ _launch(gridX, gridY, gridZ, num_warps, num_ctas, clusterDimX, clusterDimY, clusterDimZ, shared_memory, (hipStream_t)_stream, (hipFunction_t)_function{', ' + ', '.join(f"ptr_info{i}.dev_ptr" if ty[0]=="*" else f"_arg{i}"for i, ty in signature.items()) if len(signature) > 0 else ''});
419
+
420
+ if(launch_exit_hook != Py_None){{
421
+ PyObject* args = Py_BuildValue("(O)", launch_metadata);
422
+ PyObject* ret = PyObject_CallObject(launch_exit_hook, args);
423
+ Py_DECREF(args);
424
+ if (!ret)
425
+ return NULL;
426
+ }}
427
+
428
+ if(PyErr_Occurred()) {{
429
+ return NULL;
430
+ }}
431
+ // return None
432
+ Py_INCREF(Py_None);
433
+ return Py_None;
434
+ }}
435
+
436
+ static PyMethodDef ModuleMethods[] = {{
437
+ {{"launch", launch, METH_VARARGS, "Entry point for all kernels with this signature"}},
438
+ {{NULL, NULL, 0, NULL}} // sentinel
439
+ }};
440
+
441
+ static struct PyModuleDef ModuleDef = {{
442
+ PyModuleDef_HEAD_INIT,
443
+ \"__triton_launcher\",
444
+ NULL, //documentation
445
+ -1, //size
446
+ ModuleMethods
447
+ }};
448
+
449
+ PyMODINIT_FUNC PyInit___triton_launcher(void) {{
450
+ if (!initSymbolTable()) {{
451
+ return NULL;
452
+ }}
453
+ PyObject *m = PyModule_Create(&ModuleDef);
454
+ if(m == NULL) {{
455
+ return NULL;
456
+ }}
457
+ PyModule_AddFunctions(m, ModuleMethods);
458
+ return m;
459
+ }}
460
+ """
461
+ return src
462
+
463
+
464
+ class HIPLauncher(object):
465
+
466
+ def __init__(self, src, metadata):
467
+ ids = {"ids_of_const_exprs": src.fn.constexprs if hasattr(src, "fn") else tuple()}
468
+ constants = src.constants if hasattr(src, "constants") else dict()
469
+ cst_key = lambda i: src.fn.arg_names.index(i) if isinstance(i, str) else i
470
+ constants = {cst_key(key): value for key, value in constants.items()}
471
+ signature = {cst_key(key): value for key, value in src.signature.items()}
472
+ src = make_launcher(constants, signature, ids, metadata.warp_size)
473
+ mod = compile_module_from_src(src, "__triton_launcher")
474
+ self.launch = mod.launch
475
+
476
+ def __call__(self, *args, **kwargs):
477
+ self.launch(*args, **kwargs)
478
+
479
+
480
+ class HIPDriver(GPUDriver):
481
+
482
+ def __init__(self):
483
+ super().__init__()
484
+ self.utils = HIPUtils()
485
+ self.launcher_cls = HIPLauncher
486
+
487
+ def get_device_interface(self):
488
+ import torch
489
+ return torch.cuda
490
+
491
+ @staticmethod
492
+ def is_active():
493
+ import torch
494
+ return torch.version.hip is not None
495
+
496
+ def get_current_target(self):
497
+ device = self.get_current_device()
498
+ device_properties = self.utils.get_device_properties(device)
499
+ arch = device_properties['arch']
500
+ warp_size = device_properties['warpSize']
501
+ return GPUTarget("hip", arch.split(':')[0], warp_size)
502
+
503
+ def get_benchmarker(self):
504
+ from triton.testing import do_bench
505
+ return do_bench
506
+
507
+ def get_empty_cache_for_benchmark(self):
508
+ import torch
509
+
510
+ # It's the same as the Nvidia backend.
511
+ cache_size = 256 * 1024 * 1024
512
+ return torch.empty(int(cache_size // 4), dtype=torch.int, device='cuda')