triton-windows 3.1.0.post17__cp39-cp39-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 (248) hide show
  1. triton/_C/libtriton.pyd +0 -0
  2. triton/__init__.py +73 -0
  3. triton/backends/__init__.py +50 -0
  4. triton/backends/amd/compiler.py +262 -0
  5. triton/backends/amd/driver.c +211 -0
  6. triton/backends/amd/driver.py +497 -0
  7. triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h +358 -0
  8. triton/backends/amd/include/hip/amd_detail/amd_device_functions.h +1031 -0
  9. triton/backends/amd/include/hip/amd_detail/amd_hip_atomic.h +1612 -0
  10. triton/backends/amd/include/hip/amd_detail/amd_hip_bf16.h +1337 -0
  11. triton/backends/amd/include/hip/amd_detail/amd_hip_bfloat16.h +293 -0
  12. triton/backends/amd/include/hip/amd_detail/amd_hip_common.h +32 -0
  13. triton/backends/amd/include/hip/amd_detail/amd_hip_complex.h +174 -0
  14. triton/backends/amd/include/hip/amd_detail/amd_hip_cooperative_groups.h +829 -0
  15. triton/backends/amd/include/hip/amd_detail/amd_hip_fp16.h +1809 -0
  16. triton/backends/amd/include/hip/amd_detail/amd_hip_gl_interop.h +108 -0
  17. triton/backends/amd/include/hip/amd_detail/amd_hip_math_constants.h +124 -0
  18. triton/backends/amd/include/hip/amd_detail/amd_hip_runtime.h +405 -0
  19. triton/backends/amd/include/hip/amd_detail/amd_hip_runtime_pt_api.h +196 -0
  20. triton/backends/amd/include/hip/amd_detail/amd_hip_unsafe_atomics.h +565 -0
  21. triton/backends/amd/include/hip/amd_detail/amd_hip_vector_types.h +2226 -0
  22. triton/backends/amd/include/hip/amd_detail/amd_math_functions.h +104 -0
  23. triton/backends/amd/include/hip/amd_detail/amd_surface_functions.h +244 -0
  24. triton/backends/amd/include/hip/amd_detail/amd_warp_functions.h +494 -0
  25. triton/backends/amd/include/hip/amd_detail/concepts.hpp +30 -0
  26. triton/backends/amd/include/hip/amd_detail/device_library_decls.h +133 -0
  27. triton/backends/amd/include/hip/amd_detail/functional_grid_launch.hpp +218 -0
  28. triton/backends/amd/include/hip/amd_detail/grid_launch.h +67 -0
  29. triton/backends/amd/include/hip/amd_detail/grid_launch.hpp +50 -0
  30. triton/backends/amd/include/hip/amd_detail/grid_launch_GGL.hpp +26 -0
  31. triton/backends/amd/include/hip/amd_detail/helpers.hpp +137 -0
  32. triton/backends/amd/include/hip/amd_detail/hip_api_trace.hpp +1350 -0
  33. triton/backends/amd/include/hip/amd_detail/hip_assert.h +101 -0
  34. triton/backends/amd/include/hip/amd_detail/hip_cooperative_groups_helper.h +242 -0
  35. triton/backends/amd/include/hip/amd_detail/hip_fp16_gcc.h +254 -0
  36. triton/backends/amd/include/hip/amd_detail/hip_fp16_math_fwd.h +96 -0
  37. triton/backends/amd/include/hip/amd_detail/hip_ldg.h +100 -0
  38. triton/backends/amd/include/hip/amd_detail/hip_prof_str.h +10169 -0
  39. triton/backends/amd/include/hip/amd_detail/hip_runtime_prof.h +77 -0
  40. triton/backends/amd/include/hip/amd_detail/host_defines.h +180 -0
  41. triton/backends/amd/include/hip/amd_detail/hsa_helpers.hpp +102 -0
  42. triton/backends/amd/include/hip/amd_detail/macro_based_grid_launch.hpp +798 -0
  43. triton/backends/amd/include/hip/amd_detail/math_fwd.h +698 -0
  44. triton/backends/amd/include/hip/amd_detail/ockl_image.h +177 -0
  45. triton/backends/amd/include/hip/amd_detail/program_state.hpp +107 -0
  46. triton/backends/amd/include/hip/amd_detail/texture_fetch_functions.h +491 -0
  47. triton/backends/amd/include/hip/amd_detail/texture_indirect_functions.h +478 -0
  48. triton/backends/amd/include/hip/channel_descriptor.h +39 -0
  49. triton/backends/amd/include/hip/device_functions.h +38 -0
  50. triton/backends/amd/include/hip/driver_types.h +468 -0
  51. triton/backends/amd/include/hip/hip_bf16.h +36 -0
  52. triton/backends/amd/include/hip/hip_bfloat16.h +44 -0
  53. triton/backends/amd/include/hip/hip_common.h +100 -0
  54. triton/backends/amd/include/hip/hip_complex.h +38 -0
  55. triton/backends/amd/include/hip/hip_cooperative_groups.h +46 -0
  56. triton/backends/amd/include/hip/hip_deprecated.h +95 -0
  57. triton/backends/amd/include/hip/hip_ext.h +159 -0
  58. triton/backends/amd/include/hip/hip_fp16.h +36 -0
  59. triton/backends/amd/include/hip/hip_gl_interop.h +32 -0
  60. triton/backends/amd/include/hip/hip_hcc.h +24 -0
  61. triton/backends/amd/include/hip/hip_math_constants.h +36 -0
  62. triton/backends/amd/include/hip/hip_profile.h +27 -0
  63. triton/backends/amd/include/hip/hip_runtime.h +75 -0
  64. triton/backends/amd/include/hip/hip_runtime_api.h +8919 -0
  65. triton/backends/amd/include/hip/hip_texture_types.h +29 -0
  66. triton/backends/amd/include/hip/hip_vector_types.h +41 -0
  67. triton/backends/amd/include/hip/hip_version.h +17 -0
  68. triton/backends/amd/include/hip/hiprtc.h +421 -0
  69. triton/backends/amd/include/hip/library_types.h +78 -0
  70. triton/backends/amd/include/hip/math_functions.h +42 -0
  71. triton/backends/amd/include/hip/surface_types.h +63 -0
  72. triton/backends/amd/include/hip/texture_types.h +194 -0
  73. triton/backends/amd/include/hsa/Brig.h +1131 -0
  74. triton/backends/amd/include/hsa/amd_hsa_common.h +91 -0
  75. triton/backends/amd/include/hsa/amd_hsa_elf.h +435 -0
  76. triton/backends/amd/include/hsa/amd_hsa_kernel_code.h +269 -0
  77. triton/backends/amd/include/hsa/amd_hsa_queue.h +109 -0
  78. triton/backends/amd/include/hsa/amd_hsa_signal.h +80 -0
  79. triton/backends/amd/include/hsa/hsa.h +5729 -0
  80. triton/backends/amd/include/hsa/hsa_amd_tool.h +91 -0
  81. triton/backends/amd/include/hsa/hsa_api_trace.h +566 -0
  82. triton/backends/amd/include/hsa/hsa_ext_amd.h +3090 -0
  83. triton/backends/amd/include/hsa/hsa_ext_finalize.h +531 -0
  84. triton/backends/amd/include/hsa/hsa_ext_image.h +1454 -0
  85. triton/backends/amd/include/hsa/hsa_ven_amd_aqlprofile.h +488 -0
  86. triton/backends/amd/include/hsa/hsa_ven_amd_loader.h +667 -0
  87. triton/backends/amd/include/roctracer/ext/prof_protocol.h +107 -0
  88. triton/backends/amd/include/roctracer/hip_ostream_ops.h +4435 -0
  89. triton/backends/amd/include/roctracer/hsa_ostream_ops.h +1467 -0
  90. triton/backends/amd/include/roctracer/hsa_prof_str.h +3027 -0
  91. triton/backends/amd/include/roctracer/roctracer.h +779 -0
  92. triton/backends/amd/include/roctracer/roctracer_ext.h +81 -0
  93. triton/backends/amd/include/roctracer/roctracer_hcc.h +24 -0
  94. triton/backends/amd/include/roctracer/roctracer_hip.h +37 -0
  95. triton/backends/amd/include/roctracer/roctracer_hsa.h +112 -0
  96. triton/backends/amd/include/roctracer/roctracer_plugin.h +137 -0
  97. triton/backends/amd/include/roctracer/roctracer_roctx.h +67 -0
  98. triton/backends/amd/include/roctracer/roctx.h +229 -0
  99. triton/backends/amd/lib/ockl.bc +0 -0
  100. triton/backends/amd/lib/ocml.bc +0 -0
  101. triton/backends/compiler.py +76 -0
  102. triton/backends/driver.py +34 -0
  103. triton/backends/nvidia/__init__.py +0 -0
  104. triton/backends/nvidia/bin/ptxas.exe +0 -0
  105. triton/backends/nvidia/compiler.py +347 -0
  106. triton/backends/nvidia/driver.c +451 -0
  107. triton/backends/nvidia/driver.py +430 -0
  108. triton/backends/nvidia/include/cuda.h +24359 -0
  109. triton/backends/nvidia/lib/libdevice.10.bc +0 -0
  110. triton/backends/nvidia/lib/x64/cuda.lib +0 -0
  111. triton/compiler/__init__.py +4 -0
  112. triton/compiler/code_generator.py +1302 -0
  113. triton/compiler/compiler.py +416 -0
  114. triton/compiler/errors.py +51 -0
  115. triton/compiler/make_launcher.py +0 -0
  116. triton/errors.py +5 -0
  117. triton/language/__init__.py +284 -0
  118. triton/language/core.py +2621 -0
  119. triton/language/extra/__init__.py +4 -0
  120. triton/language/extra/cuda/__init__.py +8 -0
  121. triton/language/extra/cuda/libdevice.py +1629 -0
  122. triton/language/extra/cuda/utils.py +109 -0
  123. triton/language/extra/hip/__init__.py +3 -0
  124. triton/language/extra/hip/libdevice.py +468 -0
  125. triton/language/extra/libdevice.py +1213 -0
  126. triton/language/math.py +250 -0
  127. triton/language/random.py +207 -0
  128. triton/language/semantic.py +1621 -0
  129. triton/language/standard.py +441 -0
  130. triton/ops/__init__.py +7 -0
  131. triton/ops/blocksparse/__init__.py +7 -0
  132. triton/ops/blocksparse/matmul.py +432 -0
  133. triton/ops/blocksparse/softmax.py +228 -0
  134. triton/ops/cross_entropy.py +96 -0
  135. triton/ops/flash_attention.py +466 -0
  136. triton/ops/matmul.py +219 -0
  137. triton/ops/matmul_perf_model.py +171 -0
  138. triton/runtime/__init__.py +23 -0
  139. triton/runtime/autotuner.py +361 -0
  140. triton/runtime/build.py +129 -0
  141. triton/runtime/cache.py +289 -0
  142. triton/runtime/driver.py +60 -0
  143. triton/runtime/errors.py +26 -0
  144. triton/runtime/interpreter.py +1127 -0
  145. triton/runtime/jit.py +956 -0
  146. triton/runtime/tcc/include/_mingw.h +170 -0
  147. triton/runtime/tcc/include/assert.h +57 -0
  148. triton/runtime/tcc/include/conio.h +409 -0
  149. triton/runtime/tcc/include/ctype.h +281 -0
  150. triton/runtime/tcc/include/dir.h +31 -0
  151. triton/runtime/tcc/include/direct.h +68 -0
  152. triton/runtime/tcc/include/dirent.h +135 -0
  153. triton/runtime/tcc/include/dos.h +55 -0
  154. triton/runtime/tcc/include/errno.h +75 -0
  155. triton/runtime/tcc/include/excpt.h +123 -0
  156. triton/runtime/tcc/include/fcntl.h +52 -0
  157. triton/runtime/tcc/include/fenv.h +108 -0
  158. triton/runtime/tcc/include/float.h +57 -0
  159. triton/runtime/tcc/include/inttypes.h +297 -0
  160. triton/runtime/tcc/include/io.h +418 -0
  161. triton/runtime/tcc/include/limits.h +111 -0
  162. triton/runtime/tcc/include/locale.h +91 -0
  163. triton/runtime/tcc/include/malloc.h +181 -0
  164. triton/runtime/tcc/include/math.h +737 -0
  165. triton/runtime/tcc/include/mem.h +13 -0
  166. triton/runtime/tcc/include/memory.h +40 -0
  167. triton/runtime/tcc/include/process.h +176 -0
  168. triton/runtime/tcc/include/sec_api/conio_s.h +42 -0
  169. triton/runtime/tcc/include/sec_api/crtdbg_s.h +19 -0
  170. triton/runtime/tcc/include/sec_api/io_s.h +33 -0
  171. triton/runtime/tcc/include/sec_api/mbstring_s.h +52 -0
  172. triton/runtime/tcc/include/sec_api/search_s.h +25 -0
  173. triton/runtime/tcc/include/sec_api/stdio_s.h +145 -0
  174. triton/runtime/tcc/include/sec_api/stdlib_s.h +67 -0
  175. triton/runtime/tcc/include/sec_api/stralign_s.h +30 -0
  176. triton/runtime/tcc/include/sec_api/string_s.h +41 -0
  177. triton/runtime/tcc/include/sec_api/sys/timeb_s.h +34 -0
  178. triton/runtime/tcc/include/sec_api/tchar_s.h +266 -0
  179. triton/runtime/tcc/include/sec_api/time_s.h +61 -0
  180. triton/runtime/tcc/include/sec_api/wchar_s.h +128 -0
  181. triton/runtime/tcc/include/setjmp.h +160 -0
  182. triton/runtime/tcc/include/share.h +28 -0
  183. triton/runtime/tcc/include/signal.h +63 -0
  184. triton/runtime/tcc/include/stdarg.h +79 -0
  185. triton/runtime/tcc/include/stdbool.h +11 -0
  186. triton/runtime/tcc/include/stddef.h +54 -0
  187. triton/runtime/tcc/include/stdint.h +212 -0
  188. triton/runtime/tcc/include/stdio.h +429 -0
  189. triton/runtime/tcc/include/stdlib.h +580 -0
  190. triton/runtime/tcc/include/string.h +164 -0
  191. triton/runtime/tcc/include/sys/fcntl.h +13 -0
  192. triton/runtime/tcc/include/sys/file.h +14 -0
  193. triton/runtime/tcc/include/sys/locking.h +30 -0
  194. triton/runtime/tcc/include/sys/stat.h +290 -0
  195. triton/runtime/tcc/include/sys/time.h +69 -0
  196. triton/runtime/tcc/include/sys/timeb.h +133 -0
  197. triton/runtime/tcc/include/sys/types.h +118 -0
  198. triton/runtime/tcc/include/sys/unistd.h +14 -0
  199. triton/runtime/tcc/include/sys/utime.h +146 -0
  200. triton/runtime/tcc/include/tcc/tcc_libm.h +201 -0
  201. triton/runtime/tcc/include/tcclib.h +80 -0
  202. triton/runtime/tcc/include/tchar.h +1102 -0
  203. triton/runtime/tcc/include/time.h +287 -0
  204. triton/runtime/tcc/include/vadefs.h +11 -0
  205. triton/runtime/tcc/include/values.h +4 -0
  206. triton/runtime/tcc/include/varargs.h +12 -0
  207. triton/runtime/tcc/include/wchar.h +873 -0
  208. triton/runtime/tcc/include/wctype.h +172 -0
  209. triton/runtime/tcc/include/winapi/basetsd.h +149 -0
  210. triton/runtime/tcc/include/winapi/basetyps.h +85 -0
  211. triton/runtime/tcc/include/winapi/guiddef.h +156 -0
  212. triton/runtime/tcc/include/winapi/poppack.h +8 -0
  213. triton/runtime/tcc/include/winapi/pshpack1.h +8 -0
  214. triton/runtime/tcc/include/winapi/pshpack2.h +8 -0
  215. triton/runtime/tcc/include/winapi/pshpack4.h +8 -0
  216. triton/runtime/tcc/include/winapi/pshpack8.h +8 -0
  217. triton/runtime/tcc/include/winapi/winbase.h +2951 -0
  218. triton/runtime/tcc/include/winapi/wincon.h +301 -0
  219. triton/runtime/tcc/include/winapi/windef.h +293 -0
  220. triton/runtime/tcc/include/winapi/windows.h +127 -0
  221. triton/runtime/tcc/include/winapi/winerror.h +3166 -0
  222. triton/runtime/tcc/include/winapi/wingdi.h +4080 -0
  223. triton/runtime/tcc/include/winapi/winnt.h +5835 -0
  224. triton/runtime/tcc/include/winapi/winreg.h +272 -0
  225. triton/runtime/tcc/include/winapi/winuser.h +5651 -0
  226. triton/runtime/tcc/include/winapi/winver.h +160 -0
  227. triton/runtime/tcc/lib/cuda.def +697 -0
  228. triton/runtime/tcc/lib/gdi32.def +337 -0
  229. triton/runtime/tcc/lib/kernel32.def +770 -0
  230. triton/runtime/tcc/lib/libtcc1-64.a +0 -0
  231. triton/runtime/tcc/lib/msvcrt.def +1399 -0
  232. triton/runtime/tcc/lib/python3.def +810 -0
  233. triton/runtime/tcc/lib/user32.def +658 -0
  234. triton/runtime/tcc/libtcc.dll +0 -0
  235. triton/runtime/tcc/tcc.exe +0 -0
  236. triton/testing.py +496 -0
  237. triton/tools/__init__.py +0 -0
  238. triton/tools/build_extern.py +365 -0
  239. triton/tools/compile.c +67 -0
  240. triton/tools/compile.h +14 -0
  241. triton/tools/compile.py +145 -0
  242. triton/tools/disasm.py +142 -0
  243. triton/tools/link.py +322 -0
  244. triton/windows_utils.py +373 -0
  245. triton_windows-3.1.0.post17.dist-info/METADATA +41 -0
  246. triton_windows-3.1.0.post17.dist-info/RECORD +248 -0
  247. triton_windows-3.1.0.post17.dist-info/WHEEL +5 -0
  248. triton_windows-3.1.0.post17.dist-info/top_level.txt +14 -0
@@ -0,0 +1,1127 @@
1
+ import inspect
2
+ from typing import Tuple
3
+
4
+ import math
5
+ import numpy as np
6
+
7
+ import triton
8
+ import triton.language as tl
9
+ from dataclasses import dataclass
10
+ from .errors import InterpreterError
11
+ from functools import partial
12
+ from .._C.libtriton import interpreter as _interpreter
13
+ from .._C.libtriton import ir as _ir
14
+
15
+
16
+ class TensorHandle:
17
+
18
+ def __init__(self, data, dtype):
19
+ '''
20
+ data: numpy array
21
+ dtype: triton type, either pointer_type or scalar_type.
22
+ we don't store block_type here because the shape information is already availale in the data field
23
+ attr: a dictionary of attributes
24
+ '''
25
+ self.data = data
26
+ self.dtype = dtype
27
+ self.attr = {}
28
+
29
+ def __bool__(self):
30
+ return bool(self.data.all())
31
+
32
+ def get_element_ty(self):
33
+ dtype = self.dtype
34
+ while hasattr(dtype, "element_ty"):
35
+ dtype = dtype.element_ty
36
+ return dtype
37
+
38
+ def clone(self):
39
+ return TensorHandle(self.data.copy(), self.dtype)
40
+
41
+ def set_attr(self, key, value):
42
+ self.attr[key] = value
43
+
44
+
45
+ class BlockPointerHandle:
46
+
47
+ def __init__(self, base, shape, strides, offsets, tensor_shape, order):
48
+ self.base = base
49
+ self.shape = shape
50
+ self.strides = strides
51
+ self.offsets = offsets
52
+ self.tensor_shape = tensor_shape
53
+ self.order = order
54
+
55
+ def materialize_pointers(self, boundary_check):
56
+ dtype_tt = self.base.get_element_ty()
57
+ n_bytes = dtype_tt.primitive_bitwidth // 8
58
+ tensor_shape = self.tensor_shape
59
+ ptrs = np.broadcast_to(self.base.data, self.tensor_shape)
60
+ masks = np.ones(self.tensor_shape, dtype=bool)
61
+ for dim in range(len(tensor_shape)):
62
+ bcast_dims = [1] * len(tensor_shape)
63
+ bcast_dims[dim] = tensor_shape[dim]
64
+ off = (self.offsets[dim].data + np.arange(tensor_shape[dim])).reshape(bcast_dims)
65
+ ptrs = ptrs + (n_bytes * off * self.strides[dim].data).astype(np.uint64)
66
+ if dim in boundary_check:
67
+ masks = np.logical_and(masks, off < self.shape[dim].data)
68
+ ptrs = TensorHandle(ptrs, self.base.dtype.scalar)
69
+ return ptrs, masks
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class InterpreterOptions:
74
+ extern_libs: dict = None
75
+ debug: bool = False
76
+ arch: str = None
77
+ allow_fp8e4nv: bool = True
78
+ allow_fp8e4b15: bool = True
79
+ default_dot_input_precision: str = "tf32"
80
+ allowed_dot_input_precisions: Tuple[str] = ("tf32", "tf32x3", "ieee")
81
+ max_num_imprecise_acc_default: int = 0
82
+
83
+
84
+ def _get_signed_np_dtype(dtype):
85
+ if dtype == np.uint8:
86
+ return np.int8
87
+ if dtype == np.uint16:
88
+ return np.int16
89
+ if dtype == np.uint32:
90
+ return np.int32
91
+ if dtype == np.uint64:
92
+ return np.int64
93
+ return dtype
94
+
95
+
96
+ def _get_np_dtype(tt_dtype):
97
+ if isinstance(tt_dtype, tl.pointer_type):
98
+ return np.dtype(np.uint64)
99
+ np_types = {
100
+ tl.int1: np.dtype(bool),
101
+ tl.float16: np.dtype(np.float16),
102
+ tl.float32: np.dtype(np.float32),
103
+ tl.float64: np.dtype(np.float64),
104
+ tl.int8: np.dtype(np.int8),
105
+ tl.uint8: np.dtype(np.uint8),
106
+ tl.int16: np.dtype(np.int16),
107
+ tl.uint16: np.dtype(np.uint16),
108
+ tl.int32: np.dtype(np.int32),
109
+ tl.uint32: np.dtype(np.uint32),
110
+ tl.int64: np.dtype(np.int64),
111
+ tl.uint64: np.dtype(np.uint64),
112
+ # bfloat16 types are stored as uint16
113
+ tl.bfloat16: np.dtype(np.uint16),
114
+ # float8 types are stored as uint8
115
+ tl.float8e5: np.dtype(np.uint8),
116
+ tl.float8e5b16: np.dtype(np.uint8),
117
+ tl.float8e4nv: np.dtype(np.uint8),
118
+ tl.float8e4b8: np.dtype(np.uint8),
119
+ tl.float8e4b15: np.dtype(np.uint8),
120
+ }
121
+ if isinstance(tt_dtype, tl.block_type):
122
+ if isinstance(tt_dtype.element_ty, tl.pointer_type):
123
+ return np.dtype(np.uint64)
124
+ return np_types[tt_dtype.element_ty]
125
+ return np_types[tt_dtype]
126
+
127
+
128
+ def _convert_float(input, input_dtype, output_dtype, rounding_mode):
129
+ input_uint_dtype = getattr(np, f"uint{input_dtype.primitive_bitwidth}")
130
+ output_unint_dtype = getattr(np, f"uint{output_dtype.primitive_bitwidth}")
131
+ input_bin = np.frombuffer(input.tobytes(), dtype=input_uint_dtype)
132
+ sign = (input_bin >> (input_dtype.primitive_bitwidth - 1)) & 0x01
133
+ input_exponent_width = input_dtype.primitive_bitwidth - input_dtype.fp_mantissa_width - 1
134
+ output_exponent_width = output_dtype.primitive_bitwidth - output_dtype.fp_mantissa_width - 1
135
+ significand = input_bin & ((1 << input_dtype.fp_mantissa_width) - 1)
136
+ bias_input = input_dtype.exponent_bias
137
+ bias_output = output_dtype.exponent_bias
138
+ exponent = ((input_bin >> input_dtype.fp_mantissa_width) & ((1 << input_exponent_width) - 1)).astype(np.int32)
139
+ subnormal_index = exponent == 0
140
+ if np.any(subnormal_index):
141
+ # Credit to Phil: phil@openai.com
142
+ # subnormal repr: ((-1.0)**sign) * (2.0**(1 - exp_bias)) * (2^(m0) + 2^(m1) + ... + 2^(mn))
143
+ # where m0, m1, ..., mn are the 1-bit of the mantissa
144
+ # convert it to normal repr: ((-1.0)**sign) * (2.0**(1 + m0 - exp_bias)) * (1 + 2^(m1 - m0) + ... + 2^(mn - m0))
145
+ bit_pos = np.zeros_like(input_bin, dtype=np.int32)
146
+ # Find the most significant bit of the mantissa in the significand
147
+ for i in range(input_dtype.fp_mantissa_width):
148
+ bit_index = ((significand >> i) & 0x01)
149
+ # pos should be >= 1
150
+ bit_pos[bit_index == 1] = input_dtype.fp_mantissa_width - i
151
+ zero_significand_index = significand == 0
152
+ exponent[subnormal_index] = 1 - bit_pos[subnormal_index]
153
+ # 0 significand and subnormal should be treated as 0
154
+ exponent[zero_significand_index & subnormal_index] = bias_input - bias_output
155
+ significand[subnormal_index] = (significand[subnormal_index] << bit_pos[subnormal_index]) & (
156
+ (1 << input_dtype.fp_mantissa_width) - 1)
157
+ # Prevent overflow and underflow
158
+ exponent_output = np.maximum(0, np.minimum((exponent - bias_input + bias_output), (1 << output_exponent_width) - 1))
159
+ exponent_output = exponent_output.astype(output_unint_dtype)
160
+ sign_output = sign.astype(output_unint_dtype)
161
+ if input_dtype.primitive_bitwidth > output_dtype.primitive_bitwidth: # Downcast
162
+ significand_output = (significand >> (input_dtype.fp_mantissa_width - output_dtype.fp_mantissa_width)) & (
163
+ (1 << output_dtype.fp_mantissa_width) - 1)
164
+ if rounding_mode == _ir.ROUNDING_MODE.RTNE: # Round to nearst even
165
+ # find the cut-off bit
166
+ cut_off = significand & (1 << (input_dtype.fp_mantissa_width - output_dtype.fp_mantissa_width - 1))
167
+ significand_output = significand_output + (cut_off > 0)
168
+ significand_output = significand_output.astype(output_unint_dtype)
169
+ else: # Upcast
170
+ significand_output = (significand.astype(output_unint_dtype) <<
171
+ (output_dtype.fp_mantissa_width - input_dtype.fp_mantissa_width)) & (
172
+ (1 << output_dtype.fp_mantissa_width) - 1)
173
+ subnormal_index = exponent_output == 0
174
+ if np.any(subnormal_index): # underflow
175
+ # normal repr: ((-1.0)**sign) * (2.0**(exp - exp_bias_input)) * (1 + 2^(m0) + 2^(m1) + ... + 2^(mn))
176
+ # where m0, m1, ..., mn are the 1-bit of the mantissa
177
+ # shift = (1 - exp_bias_output) - (exp - exp_bias_input)
178
+ # convert it to subnormal repr: ((-1.0)**sign) * (2.0**(1 - exp_bias_output)) * (2^(-shift) + 2^(m0 - shift) + 2^(m1 - shift) + ... + 2^(mn - shift))
179
+ exponent = ((input_bin >> input_dtype.fp_mantissa_width) & ((1 << input_exponent_width) - 1)).astype(np.int32)
180
+ non_zero_exponent_index = exponent != 0
181
+ # If the original exponent is not zero, we still need to shift the significand and consider the 1.0 part in mantissa
182
+ subnormal_index = subnormal_index & non_zero_exponent_index
183
+ shift = np.zeros_like(input_bin, dtype=np.int32)
184
+ shift[subnormal_index] = (1 - bias_output) - (exponent[subnormal_index] - bias_input)
185
+ significand_output[subnormal_index] = (significand_output[subnormal_index] >> shift[subnormal_index]) | (
186
+ 1 << (output_dtype.fp_mantissa_width - shift[subnormal_index]))
187
+ output = (sign_output << (output_dtype.primitive_bitwidth - 1)) | (
188
+ exponent_output << output_dtype.fp_mantissa_width) | significand_output
189
+ return output.reshape(input.shape)
190
+
191
+
192
+ def _erf(x):
193
+ # Numpy does not support erf
194
+ return math.erf(x)
195
+
196
+
197
+ def _umulhi_64(a, b):
198
+ # Numpy does not support 128-bit multiplication
199
+ # So we have to implement it manually
200
+ return (int(a) * int(b)) >> 64
201
+
202
+
203
+ np_erf_fp32 = np.vectorize(_erf, otypes=[np.float32])
204
+ np_erf_fp64 = np.vectorize(_erf, otypes=[np.float64])
205
+ np_umulhi_u64 = np.vectorize(_umulhi_64, otypes=[np.uint64])
206
+
207
+
208
+ class ExtraFunctions:
209
+
210
+ @staticmethod
211
+ def _convert_custom_types(input, dst_ty, fp_downcast_rounding, _builder):
212
+ return tl.tensor(_builder.create_fp_to_fp(input.handle, dst_ty, fp_downcast_rounding), dst_ty)
213
+
214
+
215
+ class InterpreterBuilder:
216
+ ir_sem_to_interpreter_sem = {
217
+ _ir.MEM_SEMANTIC.ACQUIRE: _interpreter.MEM_SEMANTIC.ACQUIRE,
218
+ _ir.MEM_SEMANTIC.RELEASE: _interpreter.MEM_SEMANTIC.RELEASE,
219
+ _ir.MEM_SEMANTIC.RELAXED: _interpreter.MEM_SEMANTIC.RELAXED,
220
+ _ir.MEM_SEMANTIC.ACQUIRE_RELEASE: _interpreter.MEM_SEMANTIC.ACQUIRE_RELEASE,
221
+ }
222
+
223
+ ir_rmw_op_to_interpreter_rmw_op = {
224
+ _ir.ATOMIC_OP.ADD: _interpreter.RMW_OP.ADD,
225
+ _ir.ATOMIC_OP.FADD: _interpreter.RMW_OP.FADD,
226
+ _ir.ATOMIC_OP.MIN: _interpreter.RMW_OP.MIN,
227
+ _ir.ATOMIC_OP.UMIN: _interpreter.RMW_OP.UMIN,
228
+ _ir.ATOMIC_OP.MAX: _interpreter.RMW_OP.MAX,
229
+ _ir.ATOMIC_OP.UMAX: _interpreter.RMW_OP.UMAX,
230
+ _ir.ATOMIC_OP.AND: _interpreter.RMW_OP.AND,
231
+ _ir.ATOMIC_OP.OR: _interpreter.RMW_OP.OR,
232
+ _ir.ATOMIC_OP.XOR: _interpreter.RMW_OP.XOR,
233
+ _ir.ATOMIC_OP.XCHG: _interpreter.RMW_OP.XCHG,
234
+ }
235
+
236
+ def __init__(self) -> None:
237
+ self.arch = None
238
+ self.options = InterpreterOptions()
239
+ self.codegen_fns = {}
240
+ self.codegen_fns["convert_custom_types"] = ExtraFunctions._convert_custom_types
241
+
242
+ def set_grid_idx(self, x, y, z):
243
+ if not x < self.grid_dim[0]:
244
+ raise ValueError("x >= grid_dim[0]")
245
+ if not y < self.grid_dim[1]:
246
+ raise ValueError("y >= grid_dim[1]")
247
+ if not z < self.grid_dim[2]:
248
+ raise ValueError("z >= grid_dim[2]")
249
+ self.grid_idx = (x, y, z)
250
+
251
+ def set_grid_dim(self, nx, ny, nz):
252
+ self.grid_dim = (nx, ny, nz)
253
+
254
+ # constants
255
+
256
+ def get_half_ty(self):
257
+ return tl.float16
258
+
259
+ def get_bf16_ty(self):
260
+ return tl.bfloat16
261
+
262
+ def get_float_ty(self):
263
+ return tl.float32
264
+
265
+ def get_double_ty(self):
266
+ return tl.float64
267
+
268
+ def get_int8_ty(self):
269
+ return tl.int8
270
+
271
+ def get_uint8_ty(self):
272
+ return tl.uint8
273
+
274
+ def get_int16_ty(self):
275
+ return tl.int16
276
+
277
+ def get_uint16_ty(self):
278
+ return tl.uint16
279
+
280
+ def get_int32_ty(self):
281
+ return tl.int32
282
+
283
+ def get_uint32_ty(self):
284
+ return tl.uint32
285
+
286
+ def get_int64_ty(self):
287
+ return tl.int64
288
+
289
+ def get_uint64_ty(self):
290
+ return tl.uint64
291
+
292
+ def get_fp8e4nv_ty(self):
293
+ return tl.float8e4nv
294
+
295
+ def get_fp8e4b15_ty(self):
296
+ return tl.float8e4b15
297
+
298
+ def get_fp8e4b8_ty(self):
299
+ return tl.float8e4b8
300
+
301
+ def get_fp8e5_ty(self):
302
+ return tl.float8e5
303
+
304
+ def get_fp8e5b16_ty(self):
305
+ return tl.float8e5b16
306
+
307
+ def get_ptr_ty(self, elt_ty, addr_space):
308
+ return tl.pointer_type(elt_ty, addr_space)
309
+
310
+ def get_block_ty(self, dtype, shape):
311
+ return tl.block_type(dtype, shape)
312
+
313
+ def get_int1(self, value):
314
+ return TensorHandle(np.array([value], dtype=np.bool_), tl.int1)
315
+
316
+ def get_uint8(self, value):
317
+ return TensorHandle(np.array([value], dtype=np.uint8), tl.uint8)
318
+
319
+ def get_int8(self, value):
320
+ return TensorHandle(np.array([value], dtype=np.int8), tl.int8)
321
+
322
+ def get_uint16(self, value):
323
+ return TensorHandle(np.array([value], dtype=np.uint16), tl.uint16)
324
+
325
+ def get_int16(self, value):
326
+ return TensorHandle(np.array([value], dtype=np.int16), tl.int16)
327
+
328
+ def get_uint32(self, value):
329
+ return TensorHandle(np.array([value], dtype=np.uint32), tl.uint32)
330
+
331
+ def get_int32(self, value):
332
+ return TensorHandle(np.array([value], dtype=np.int32), tl.int32)
333
+
334
+ def get_uint64(self, value):
335
+ return TensorHandle(np.array([value], dtype=np.uint64), tl.uint64)
336
+
337
+ def get_int64(self, value):
338
+ return TensorHandle(np.array([value], dtype=np.int64), tl.int64)
339
+
340
+ def get_fp16(self, value):
341
+ return TensorHandle(np.array([value], dtype=np.float16), tl.float16)
342
+
343
+ def get_fp32(self, value):
344
+ return TensorHandle(np.array([value], dtype=np.float32), tl.float32)
345
+
346
+ def get_fp64(self, value):
347
+ return TensorHandle(np.array([value], dtype=np.float64), tl.float64)
348
+
349
+ def get_null_value(self, type):
350
+ return TensorHandle(np.array([0], dtype=_get_np_dtype(type)), type)
351
+
352
+ # programming model
353
+ def create_get_program_id(self, axis):
354
+ if self.grid_idx is None:
355
+ raise ValueError("grid_idx is None")
356
+ return TensorHandle(np.array([self.grid_idx[axis]], dtype=np.int32), tl.int32)
357
+
358
+ def create_get_num_programs(self, axis):
359
+ return TensorHandle(np.array([self.grid_dim[axis]], dtype=np.int32), tl.int32)
360
+
361
+ # memory ops
362
+ def create_load(self, ptr, _0, _1, is_volatile):
363
+ mask = TensorHandle(np.ones_like(ptr.data, dtype=bool), tl.int1)
364
+ other = None
365
+ return self.create_masked_load(ptr, mask, other, _0, _1, is_volatile)
366
+
367
+ def create_store(self, ptr, val, _0, _1):
368
+ mask = TensorHandle(np.ones_like(ptr.data, dtype=bool), tl.int1)
369
+ return self.create_masked_store(ptr, val, mask, None, None)
370
+
371
+ def create_masked_load(self, ptrs, mask, other, cache_modifier, eviction_policy, is_volatile):
372
+ dtype_tt = ptrs.get_element_ty()
373
+ dtype_np = _get_np_dtype(dtype_tt)
374
+ if other is None:
375
+ other = TensorHandle(np.zeros_like(ptrs.data, dtype=dtype_np), dtype_tt)
376
+ ret = _interpreter.load(ptrs.data, mask.data, other.data, dtype_np)
377
+ return TensorHandle(ret, dtype_tt)
378
+
379
+ def create_masked_store(self, ptrs, value, mask, cache_modifier, eviction_policy):
380
+ return _interpreter.store(ptrs.data, value.data, mask.data)
381
+
382
+ # casting ops
383
+ def cast_impl(self, src, dst_type):
384
+ src_element_type = src.dtype.scalar
385
+ dst_element_type = dst_type.scalar
386
+ if (src_element_type == tl.bfloat16 and dst_element_type == tl.float32) or \
387
+ (src_element_type == tl.float32 and dst_element_type == tl.bfloat16):
388
+ data = _convert_float(src.data, src_element_type, dst_element_type, None).view(_get_np_dtype(dst_type))
389
+ return TensorHandle(data, dst_type.scalar)
390
+ else:
391
+ return TensorHandle(src.data.astype(_get_np_dtype(dst_type)), dst_type.scalar)
392
+
393
+ create_si_to_fp = lambda self, src, dst_type: self.cast_impl(src, dst_type)
394
+ create_ui_to_fp = lambda self, src, dst_type: self.cast_impl(src, dst_type)
395
+ create_fp_to_si = lambda self, src, dst_type: self.cast_impl(src, dst_type)
396
+ create_fp_to_ui = lambda self, src, dst_type: self.cast_impl(src, dst_type)
397
+ create_fp_ext = lambda self, src, dst_type: self.cast_impl(src, dst_type)
398
+ create_fp_trunc = lambda self, src, dst_type: self.cast_impl(src, dst_type)
399
+ create_int_cast = lambda self, src, dst_type, is_signed: self.cast_impl(src, dst_type)
400
+
401
+ def create_fp_to_fp(self, src, dst_type, rounding_mode):
402
+ src_element_type = src.dtype.scalar
403
+ dst_element_type = dst_type.scalar
404
+ data = _convert_float(src.data, src_element_type, dst_element_type, rounding_mode).view(_get_np_dtype(dst_type))
405
+ return TensorHandle(data, dst_type.scalar)
406
+
407
+ def create_bitcast(self, src, dst_type):
408
+ return TensorHandle(src.data.view(_get_np_dtype(dst_type)), dst_type.scalar)
409
+
410
+ # binary operators
411
+ def binary_op(self, lhs, rhs, op):
412
+ return TensorHandle(op(lhs.data, rhs.data), lhs.dtype.scalar)
413
+
414
+ create_fadd = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.add)
415
+ create_fmul = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.multiply)
416
+ create_fdiv = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.divide)
417
+ create_frem = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.remainder)
418
+ create_fsub = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.subtract)
419
+ create_mul = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.multiply)
420
+ create_precise_divf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.divide)
421
+ create_sdiv = lambda self, lhs, rhs: self.create_idiv(lhs, rhs)
422
+ create_udiv = lambda self, lhs, rhs: self.create_idiv(lhs, rhs)
423
+ # LLVM has 'numpy.fmod', not 'numpy.remainder', semantics on integer remainders.
424
+ create_srem = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.fmod)
425
+ create_urem = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.fmod)
426
+ create_add = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.add)
427
+ create_sub = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.subtract)
428
+ create_shl = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.left_shift)
429
+ create_lshr = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.right_shift)
430
+ create_minsi = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum)
431
+ create_minui = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum)
432
+ create_minimumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum)
433
+ create_minnumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum)
434
+ create_maxsi = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum)
435
+ create_maxui = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum)
436
+ create_maximumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum)
437
+ create_maxnumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum)
438
+ create_icmpSLE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal)
439
+ create_icmpSLT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less)
440
+ create_icmpSGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal)
441
+ create_icmpSGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater)
442
+ create_icmpULE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal)
443
+ create_icmpULT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less)
444
+ create_icmpUGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal)
445
+ create_icmpUGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater)
446
+ create_icmpEQ = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.equal)
447
+ create_icmpNE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.not_equal)
448
+ create_fcmpOLT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less)
449
+ create_fcmpOGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater)
450
+ create_fcmpOLE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal)
451
+ create_fcmpOGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal)
452
+ create_fcmpOEQ = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.equal)
453
+ create_fcmpONE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.not_equal)
454
+ create_fcmpULT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less)
455
+ create_fcmpUGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater)
456
+ create_fcmpULE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal)
457
+ create_fcmpUGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal)
458
+ create_fcmpUEQ = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.equal)
459
+ create_fcmpUNE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.not_equal)
460
+ create_and = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.bitwise_and)
461
+ create_xor = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.bitwise_xor)
462
+ create_or = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.bitwise_or)
463
+
464
+ def create_idiv(self, lhs, rhs):
465
+ # Triton has IEEE, not numpy/torch, semantics for %, and those carry
466
+ # through to //, so we have to use a nonstandard expression to get a
467
+ # reference result for //.
468
+ return TensorHandle((lhs.data - np.fmod(lhs.data, rhs.data)) // rhs.data, lhs.dtype.scalar)
469
+
470
+ def create_ashr(self, lhs, rhs):
471
+ # Triton's rshift operator depends on the signedness of the left operand
472
+ lhs_dtype = _get_signed_np_dtype(lhs.data.dtype)
473
+ rhs_dtype = _get_signed_np_dtype(rhs.data.dtype)
474
+ lhs.data = lhs.data.astype(lhs_dtype)
475
+ rhs.data = rhs.data.astype(rhs_dtype)
476
+ return self.binary_op(lhs, rhs, np.right_shift)
477
+
478
+ def create_umulhi(self, lhs, rhs):
479
+ dtype = lhs.data.dtype
480
+ if dtype == np.int64 or dtype == np.uint64:
481
+ return TensorHandle(np_umulhi_u64(lhs.data, rhs.data), lhs.dtype.scalar)
482
+ else:
483
+ compute_dtype = getattr(np, f"uint{dtype.itemsize * 8 * 2}")
484
+ lhs_data = lhs.data.astype(compute_dtype)
485
+ rhs_data = rhs.data.astype(compute_dtype)
486
+ ret_data = np.multiply(lhs_data, rhs_data) >> (dtype.itemsize * 8)
487
+ return TensorHandle(ret_data.astype(dtype), lhs.dtype.scalar)
488
+
489
+ # ternary functions
490
+ def ternary_op(self, lhs, rhs, other, op):
491
+ return TensorHandle(op(lhs.data, rhs.data, other.data), other.dtype.scalar)
492
+
493
+ create_clampf = lambda self, arg, lo, hi, propagate_nans: self.ternary_op(arg, lo, hi, np.clip)
494
+ create_select = lambda self, cond, lhs, rhs: self.ternary_op(cond, lhs, rhs, np.where)
495
+
496
+ def create_fma(self, x, y, z):
497
+ return TensorHandle(x.data * y.data + z.data, z.dtype.scalar)
498
+
499
+ # unary functions
500
+ def unary_op(self, arg, op):
501
+ return TensorHandle(op(arg.data), arg.dtype.scalar)
502
+
503
+ def create_fabs(self, arg):
504
+ # Mask out the sign bit based on the primitive length
505
+ dtype_tt = arg.dtype
506
+ mask_bitwidth = dtype_tt.primitive_bitwidth - 1
507
+ np_uint_dtype = getattr(np, f"uint{dtype_tt.primitive_bitwidth}")
508
+ data = arg.data.view(np_uint_dtype)
509
+ mask = (1 << mask_bitwidth) - 1
510
+ ret = (data & mask).view(_get_np_dtype(dtype_tt))
511
+ return TensorHandle(ret, arg.dtype.scalar)
512
+
513
+ create_cos = lambda self, arg: self.unary_op(arg, np.cos)
514
+ create_exp = lambda self, arg: self.unary_op(arg, np.exp)
515
+ create_exp2 = lambda self, arg: self.unary_op(arg, np.exp2)
516
+ create_iabs = lambda self, arg: self.unary_op(arg, np.abs)
517
+ create_floor = lambda self, arg: self.unary_op(arg, np.floor)
518
+ create_ceil = lambda self, arg: self.unary_op(arg, np.ceil)
519
+ create_log = lambda self, arg: self.unary_op(arg, np.log)
520
+ create_log2 = lambda self, arg: self.unary_op(arg, np.log2)
521
+ create_precise_sqrt = lambda self, arg: self.unary_op(arg, np.sqrt)
522
+ create_sqrt = lambda self, arg: self.unary_op(arg, np.sqrt)
523
+ create_sin = lambda self, arg: self.unary_op(arg, np.sin)
524
+
525
+ def create_erf(self, arg):
526
+ ret = np_erf_fp32(arg.data) if arg.data.dtype == np.float32 else np_erf_fp64(arg.data)
527
+ return TensorHandle(ret, arg.dtype.scalar)
528
+
529
+ def create_rsqrt(self, arg):
530
+ return TensorHandle(1 / np.sqrt(arg.data), arg.dtype.scalar)
531
+
532
+ # tensor operators
533
+ create_reshape = lambda self, arg, shape, allow_reorder: TensorHandle(arg.data.reshape(shape), arg.dtype.scalar)
534
+
535
+ def create_trans(self, arg, perm):
536
+ return TensorHandle(np.transpose(arg.data, perm), arg.dtype.scalar)
537
+
538
+ def create_dot(self, a, b, d, input_precision, max_num_imprecise_acc):
539
+ a_data = a.data
540
+ b_data = b.data
541
+ if (a.dtype.primitive_bitwidth == 8 and a.dtype.is_floating()) or \
542
+ (b.dtype.primitive_bitwidth == 8 and b.dtype.is_floating()):
543
+ a_data = _convert_float(a_data, a.dtype, tl.float16, None).view(np.float16)
544
+ b_data = _convert_float(b_data, b.dtype, tl.float16, None).view(np.float16)
545
+ return TensorHandle(np.matmul(a_data, b_data, dtype=d.data.dtype) + d.data, d.dtype.scalar)
546
+
547
+ def create_make_range(self, start, stop):
548
+ return TensorHandle(np.arange(start, stop, dtype=np.int32), tl.int32)
549
+
550
+ def create_histogram(self, data, bins):
551
+ return TensorHandle(np.histogram(data.data, bins=bins, range=(0, bins))[0], tl.int32)
552
+
553
+ # pointer arithmetic
554
+
555
+ def create_addptr(self, ptr, offset):
556
+ dtype_tt = ptr.get_element_ty()
557
+ element_bitwidth = dtype_tt.primitive_bitwidth
558
+ # int1's bitwidth is 1, but we need to use 8 for pointer arithmetic
559
+ element_bytewidth = max(1, element_bitwidth // 8)
560
+ return TensorHandle(ptr.data + element_bytewidth * offset.data.astype(np.uint64), ptr.dtype)
561
+
562
+ def create_tensor_pointer_load(self, ptr, boundary_check, padding_option, cache_modifier, eviction_policy,
563
+ is_volatile):
564
+ ptrs, masks = ptr.materialize_pointers(boundary_check)
565
+ dtype_tt = ptrs.get_element_ty()
566
+ dtype_np = _get_np_dtype(dtype_tt)
567
+ if padding_option is None:
568
+ other = None
569
+ elif padding_option == _ir.PADDING_OPTION.PAD_ZERO:
570
+ other = TensorHandle(np.zeros_like(ptrs.data, dtype=dtype_np), dtype_tt)
571
+ elif padding_option == _ir.PADDING_OPTION.PAD_NAN:
572
+ other = TensorHandle(np.full_like(ptrs.data, float('nan'), dtype=dtype_np), dtype_tt)
573
+ else:
574
+ raise ValueError(f"unsupported padding option {padding_option}")
575
+ return self.create_masked_load(ptrs, masks, other, cache_modifier, eviction_policy, is_volatile)
576
+
577
+ def create_tensor_pointer_store(self, ptr, value, boundary_check, cache_modifier, eviction_policy):
578
+ ptrs, masks = ptr.materialize_pointers(boundary_check)
579
+ return self.create_masked_store(ptrs, value, masks, cache_modifier, eviction_policy)
580
+
581
+ def create_expand_dims(self, arg, axis):
582
+ return TensorHandle(np.expand_dims(arg.data, axis), arg.dtype.scalar)
583
+
584
+ def create_broadcast(self, arg, shape):
585
+ return TensorHandle(np.broadcast_to(arg.data, shape), arg.dtype.scalar)
586
+
587
+ def create_int_to_ptr(self, val, dst_ty):
588
+ return TensorHandle(val.data.astype(np.uint64), dst_ty.scalar)
589
+
590
+ def create_ptr_to_int(self, val, dst_ty):
591
+ return TensorHandle(val.data.astype(np.uint64), dst_ty.scalar)
592
+
593
+ def create_cat(self, lhs, rhs):
594
+ return TensorHandle(np.concatenate([lhs.data, rhs.data]), lhs.dtype.scalar)
595
+
596
+ def create_join(self, lhs, rhs):
597
+ # Triton only supports joining two original tensors into a new one along the last axis
598
+ return TensorHandle(np.stack([lhs.data, rhs.data], axis=-1), lhs.dtype.scalar)
599
+
600
+ def create_split(self, val):
601
+ # Triton only supports splitting the original tensor into two along the last axis
602
+ return (TensorHandle(val.data[..., 0], val.dtype.scalar), TensorHandle(val.data[..., 1], val.dtype.scalar))
603
+
604
+ def create_splat(self, arg, shape):
605
+ if isinstance(arg.dtype, tl.block_type):
606
+ return TensorHandle(np.full(shape, arg.data[0], dtype=_get_np_dtype(arg.dtype)), arg.dtype.scalar)
607
+ else: # scalar
608
+ return TensorHandle(np.full(shape, arg.data, dtype=_get_np_dtype(arg.dtype)), arg.dtype.scalar)
609
+
610
+ def create_atomic_cas(self, ptr, cmp, val, sem, scope):
611
+ if sem not in self.ir_sem_to_interpreter_sem:
612
+ raise ValueError(f"unsupported semantic {sem}")
613
+ sem = self.ir_sem_to_interpreter_sem[sem]
614
+ return TensorHandle(_interpreter.atomic_cas(ptr.data, cmp.data, val.data, sem), cmp.dtype.scalar)
615
+
616
+ def create_atomic_rmw(self, rmwOp, ptr, val, mask, sem, scope):
617
+ if rmwOp not in self.ir_rmw_op_to_interpreter_rmw_op:
618
+ raise ValueError(f"unsupported rmwOp {rmwOp}")
619
+ if sem not in self.ir_sem_to_interpreter_sem:
620
+ raise ValueError(f"unsupported semantic {sem}")
621
+ rmwOp = self.ir_rmw_op_to_interpreter_rmw_op[rmwOp]
622
+ sem = self.ir_sem_to_interpreter_sem[sem]
623
+ return TensorHandle(_interpreter.atomic_rmw(rmwOp, ptr.data, val.data, mask.data, sem), val.dtype.scalar)
624
+
625
+ def create_extern_elementwise(self, libName, libPath, symbol, argList, retType, isPure):
626
+ raise NotImplementedError("extern_elementwise not supported in interpreter mode")
627
+
628
+ def create_inline_asm(self, inlineAsm, constraints, values, type, isPure, pack):
629
+ raise NotImplementedError("inline_asm not supported in interpreter mode")
630
+
631
+ def create_print(self, prefix, hex, values):
632
+ # Interpreter's device_print function has a different format than Triton's device_print
633
+ msg = f"({self.grid_idx[0]}, {self.grid_idx[1]}, {self.grid_idx[2]})"
634
+ if prefix:
635
+ msg += f" {prefix}"
636
+ if hex:
637
+ np.set_printoptions(formatter={'all': lambda x: f"0x{x:02x}"})
638
+ for value in values:
639
+ print(msg + f" {value.data}")
640
+ if hex:
641
+ np.set_printoptions(formatter=None)
642
+
643
+ def create_assert(self, condition, message, fileName, funcName, lineNo):
644
+ # Interpreter's device_assert function has a different format than Triton's device_assert
645
+ assert condition, f"{message} in {fileName}:{funcName}:{lineNo}"
646
+
647
+ def create_barrier(self):
648
+ # Triton's barrier applies to each program in a grid, so it's a no-op in the interpreter
649
+ pass
650
+
651
+ def create_make_block_ptr(self, base, shape, strides, offsets, tensor_shape, order):
652
+ # Create new offsets to avoid modifying the original
653
+ new_offsets = [offset.clone() for offset in offsets]
654
+ return BlockPointerHandle(base, shape, strides, new_offsets, tensor_shape, order)
655
+
656
+ def create_advance(self, ptr, offsets):
657
+ if len(ptr.offsets) != len(offsets):
658
+ raise ValueError("len(ptr.offsets) != len(offsets)")
659
+ # Create new offsets to avoid modifying the original
660
+ new_offsets = [offset.clone() for offset in ptr.offsets]
661
+ ret = BlockPointerHandle(ptr.base, ptr.shape, ptr.strides, new_offsets, ptr.tensor_shape, ptr.order)
662
+ for i in range(len(offsets)):
663
+ ret.offsets[i].data += offsets[i].data
664
+ return ret
665
+
666
+ def get_all_ones_value(self, type):
667
+ np_type = _get_np_dtype(type)
668
+ if "int" in np_type.name:
669
+ return TensorHandle(np.full(1, -1, dtype=np_type), type.scalar)
670
+ else:
671
+ raise TypeError(f"unsupported type {type}")
672
+
673
+
674
+ def _patch_attr(obj, name, member, builder):
675
+ new_member = lambda *args, member=member, **kwargs: (member(*args, **
676
+ {k: v
677
+ for k, v in kwargs.items()
678
+ if k != "_builder"}, _builder=builder))
679
+ setattr(obj, name, new_member)
680
+
681
+
682
+ def _patch_builtin(pkg, builder):
683
+ for name, member in inspect.getmembers(pkg):
684
+ if tl.core.is_builtin(member):
685
+ _patch_attr(pkg, name, member, builder)
686
+
687
+
688
+ def _patch_lang_tensor(tensor):
689
+
690
+ def _get_bool(self):
691
+ data = self.handle.data
692
+ # in triton, only scalars can be converted to booleans
693
+ # here we need this hack because all scalars are tensors
694
+ return bool(data) if data.size == 1 else True
695
+
696
+ def _get_transpose(self):
697
+ return tl.core.tensor(TensorHandle(np.transpose(self.handle.data), self.handle.dtype), self.dtype.scalar)
698
+
699
+ tensor.__index__ = lambda self: int(self.handle.data)
700
+ tensor.__bool__ = lambda self: _get_bool(self)
701
+ tensor.__repr__ = lambda self: repr(self.handle.data)
702
+ tensor.__str__ = lambda self: str(self.handle.data)
703
+ tensor.T = property(_get_transpose)
704
+
705
+
706
+ class ReduceScanOpIneterface:
707
+
708
+ def __init__(self, axis, combine_fn):
709
+ self.axis = axis
710
+ self.combine_fn = combine_fn
711
+
712
+ def check_axis(self, shape, axis):
713
+ if axis is not None and axis >= len(shape):
714
+ raise ValueError(f"axis {axis} out of bounds for shape {shape}")
715
+
716
+ def check_tensor(self, input):
717
+ for arg in input:
718
+ if not isinstance(arg, tl.core.tensor):
719
+ raise ValueError(f"input must be a tensor, got {type(arg)}")
720
+ self.check_axis(arg.shape, self.axis)
721
+
722
+ def to_tensor(self, ret, dtype):
723
+ if hasattr(ret, "shape") and ret.shape:
724
+ ret_type = tl.block_type(dtype, ret.shape)
725
+ else:
726
+ ret = np.array([ret], dtype=_get_np_dtype(dtype))
727
+ ret_type = dtype
728
+ return tl.core.tensor(TensorHandle(ret, dtype.scalar), ret_type)
729
+
730
+ def apply(self, input):
731
+ if not isinstance(input, tuple):
732
+ input = (input, )
733
+ self.check_tensor(input)
734
+ return self.apply_impl(input)
735
+
736
+ def apply_impl(self, input):
737
+ raise NotImplementedError("apply_impl not implemented")
738
+
739
+
740
+ class ReduceOps(ReduceScanOpIneterface):
741
+
742
+ def __init__(self, axis, combine_fn, keep_dims):
743
+ super().__init__(axis, combine_fn)
744
+ self.keep_dims = keep_dims
745
+
746
+ def unravel(self, input, axis):
747
+ ret = []
748
+ for data in input:
749
+ if axis is not None:
750
+ ret.append(data)
751
+ else:
752
+ axis = 0
753
+ ret.append(self.to_tensor(data.handle.data.flatten(), data.dtype))
754
+ return tuple(ret), axis
755
+
756
+ def generic_reduce(self, input):
757
+ original_axis = self.axis
758
+ input, axis = self.unravel(input, self.axis)
759
+ input_data = []
760
+ output_data = []
761
+ input_shape = input[0].handle.data.shape
762
+ output_shape = input_shape[0:axis] + input_shape[axis + 1:]
763
+ for arg in input:
764
+ input_data.append(arg.handle.data)
765
+ output_data.append(np.zeros(output_shape, dtype=arg.handle.data.dtype))
766
+ # Reduce on axis
767
+ for i in range(input_data[0].size):
768
+ # Recover input_index from i using input_shape
769
+ input_index = np.unravel_index(i, input_shape)
770
+ output_index = input_index[0:axis] + input_index[axis + 1:]
771
+ input_tuple = tuple(self.to_tensor(d[input_index], input[ii].dtype) for ii, d in enumerate(input_data))
772
+ if input_index[axis] == 0:
773
+ # First element
774
+ for j in range(len(output_data)):
775
+ output_data[j][output_index] = input_tuple[j].handle.data.item()
776
+ else:
777
+ acc_tuple = tuple(self.to_tensor(o[output_index], input[oi].dtype) for oi, o in enumerate(output_data))
778
+ combine_fn_ret = self.combine_fn.fn(*acc_tuple, *input_tuple)
779
+ acc_tuple = (combine_fn_ret, ) if not isinstance(combine_fn_ret, tuple) else combine_fn_ret
780
+ for j in range(len(output_data)):
781
+ output_data[j][output_index] = acc_tuple[j].handle.data.item() if isinstance(
782
+ acc_tuple[j], tl.core.tensor) else acc_tuple[j]
783
+ # Pack output
784
+ ret = []
785
+ for i, data in enumerate(output_data):
786
+ if self.keep_dims:
787
+ if original_axis is not None:
788
+ data = np.expand_dims(data, axis)
789
+ else:
790
+ for _ in range(len(input_shape)):
791
+ data = np.expand_dims(data, 0)
792
+
793
+ elif original_axis is None:
794
+ # Take a scalar
795
+ data = data.item()
796
+ ret.append(self.to_tensor(data, input[i].dtype))
797
+ return ret[0] if len(ret) == 1 else tuple(ret)
798
+
799
+ def min_max(self, input, val_reduce_op, idx_reduce_op=None):
800
+ # If input is a tuple, it must be (val, index), and we only take val
801
+ input = input[0] if isinstance(input, tuple) else input
802
+ val = None
803
+ idx = None
804
+ if val_reduce_op:
805
+ val = self.to_tensor(val_reduce_op(input.handle.data, axis=self.axis, keepdims=self.keep_dims), input.dtype)
806
+ if idx_reduce_op:
807
+ idx = self.to_tensor(idx_reduce_op(input.handle.data, axis=self.axis, keepdims=self.keep_dims), tl.int32)
808
+ if val is not None and idx is not None:
809
+ return val, idx
810
+ elif val is not None:
811
+ return val
812
+ elif idx is not None:
813
+ return idx
814
+ else:
815
+ raise ValueError("val_reduce_op and idx_reduce_op are both None")
816
+
817
+ def sum(self, input):
818
+ return self.to_tensor(np.sum(input.handle.data, axis=self.axis, keepdims=self.keep_dims), input.dtype)
819
+
820
+ def apply_impl(self, input):
821
+ if self.combine_fn == tl.standard._argmin_combine_tie_break_left:
822
+ return self.min_max(input[0], val_reduce_op=np.min, idx_reduce_op=np.argmin)
823
+ elif self.combine_fn == tl.standard._argmax_combine_tie_break_left:
824
+ return self.min_max(input[0], val_reduce_op=np.max, idx_reduce_op=np.argmax)
825
+ elif self.combine_fn == tl.standard._elementwise_max:
826
+ return self.min_max(input[0], val_reduce_op=np.max, idx_reduce_op=None)
827
+ elif self.combine_fn == tl.standard._elementwise_min:
828
+ return self.min_max(input[0], val_reduce_op=np.min, idx_reduce_op=None)
829
+ elif self.combine_fn == tl.standard._sum_combine:
830
+ return self.sum(input[0])
831
+ else:
832
+ # Fall back to the slow mode
833
+ return self.generic_reduce(input)
834
+
835
+
836
+ class ScanOps(ReduceScanOpIneterface):
837
+
838
+ def __init__(self, axis, combine_fn, reverse):
839
+ super().__init__(axis, combine_fn)
840
+ self.reverse = reverse
841
+
842
+ def cumsum(self, input):
843
+ return [self.to_tensor(np.cumsum(input.handle.data, axis=self.axis), dtype=input.dtype)]
844
+
845
+ def cumprod(self, input):
846
+ return [self.to_tensor(np.cumprod(input.handle.data, axis=self.axis), dtype=input.dtype)]
847
+
848
+ def generic_scan(self, input):
849
+ input_data = []
850
+ output_data = []
851
+ shape = input[0].handle.data.shape
852
+ for arg in input:
853
+ input_data.append(arg.handle.data)
854
+ output_data.append(np.zeros(shape, dtype=arg.handle.data.dtype))
855
+ # Scan on axis
856
+ for i in range(input_data[0].size):
857
+ # Recover index from i using shape
858
+ index = np.unravel_index(i, shape)
859
+ data = tuple(self.to_tensor(d[index], input[ii].dtype) for ii, d in enumerate(input_data))
860
+ if index[self.axis] == 0:
861
+ # First element
862
+ for j in range(len(output_data)):
863
+ output_data[j][index] = data[j].handle.data.item()
864
+ else:
865
+ prev_index = tuple(index[i] - 1 if i == self.axis else index[i] for i in range(len(index)))
866
+ acc_tuple = tuple(self.to_tensor(o[prev_index], input[oi].dtype) for oi, o in enumerate(output_data))
867
+ combine_fn_ret = self.combine_fn.fn(*acc_tuple, *data)
868
+ acc_tuple = (combine_fn_ret, ) if not isinstance(combine_fn_ret, tuple) else combine_fn_ret
869
+ for j in range(len(output_data)):
870
+ output_data[j][index] = acc_tuple[j].handle.data.item() if isinstance(
871
+ acc_tuple[j], tl.core.tensor) else acc_tuple[j]
872
+ # Pack output
873
+ ret = []
874
+ for i, data in enumerate(output_data):
875
+ ret.append(self.to_tensor(data, input[i].dtype))
876
+ return ret
877
+
878
+ def apply_impl(self, input):
879
+ new_input = []
880
+ if self.reverse:
881
+ for arg in input:
882
+ new_input.append(self.to_tensor(np.flip(arg.handle.data, axis=self.axis), arg.dtype))
883
+ else:
884
+ new_input = input
885
+ if self.combine_fn == tl.standard._sum_combine:
886
+ ret = self.cumsum(new_input[0])
887
+ elif self.combine_fn == tl.standard._prod_combine:
888
+ ret = self.cumprod(new_input[0])
889
+ else:
890
+ # Fall back to the slow mode
891
+ ret = self.generic_scan(new_input)
892
+ if self.reverse:
893
+ for arg in ret:
894
+ arg.handle.data = np.flip(arg.handle.data, axis=self.axis)
895
+ return len(ret) == 1 and ret[0] or tuple(ret)
896
+
897
+
898
+ def _patch_reduce_scan():
899
+ # Because interpreter doesn't support region_builder_fn, we cannot patch the builder
900
+ # to use the new reduce and scan functions.
901
+ # Instead, we need to patch reduce and reduce functions in tl and tl.core
902
+ def _new_reduce(input, axis, combine_fn, keep_dims=False, **kwargs):
903
+ return ReduceOps(axis, combine_fn, keep_dims).apply(input)
904
+
905
+ def _new_scan(input, axis, combine_fn, reverse=False, **kwargs):
906
+ return ScanOps(axis, combine_fn, reverse).apply(input)
907
+
908
+ tl.reduce = _new_reduce
909
+ tl.associative_scan = _new_scan
910
+ tl.core.reduce = _new_reduce
911
+ tl.core.associative_scan = _new_scan
912
+
913
+
914
+ def _patch_lang_core(lang):
915
+
916
+ def _new_to_ir(self, builder):
917
+ # We need to specify signedness for integer types in the numpy mode
918
+ if self.name == 'void':
919
+ return builder.get_void_ty()
920
+ elif self.name == 'int1':
921
+ return builder.get_int1_ty()
922
+ elif self.name == 'int8':
923
+ return builder.get_int8_ty()
924
+ elif self.name == 'uint8':
925
+ return builder.get_uint8_ty()
926
+ elif self.name == 'int16':
927
+ return builder.get_int16_ty()
928
+ elif self.name == 'uint16':
929
+ return builder.get_uint16_ty()
930
+ elif self.name == 'int32':
931
+ return builder.get_int32_ty()
932
+ elif self.name == 'uint32':
933
+ return builder.get_uint32_ty()
934
+ elif self.name == 'int64':
935
+ return builder.get_int64_ty()
936
+ elif self.name == 'uint64':
937
+ return builder.get_uint64_ty()
938
+ elif self.name == 'fp8e5':
939
+ return builder.get_fp8e5_ty()
940
+ elif self.name == 'fp8e4nv':
941
+ return builder.get_fp8e4nv_ty()
942
+ elif self.name == 'fp8e4b15':
943
+ return builder.get_fp8e4b15_ty()
944
+ elif self.name == 'fp16':
945
+ return builder.get_half_ty()
946
+ elif self.name == 'bf16':
947
+ return builder.get_bf16_ty()
948
+ elif self.name == 'fp32':
949
+ return builder.get_float_ty()
950
+ elif self.name == 'fp64':
951
+ return builder.get_double_ty()
952
+ raise ValueError(f'fail to convert {self} to ir type')
953
+
954
+ # can't just map lang.static_range to `range`, because `tl.static_range`
955
+ # can get `step` passed by keyword
956
+ def _new_range(arg1, arg2=None, step=None, **kwargs):
957
+ if step is None:
958
+ step = 1
959
+ if arg2 is None:
960
+ start, end = 0, arg1
961
+ else:
962
+ start, end = arg1, arg2
963
+ return range(start, end, step)
964
+
965
+ def _new_static_assert(cond, msg=""):
966
+ assert cond, msg
967
+
968
+ def _set_attr(input, values, name):
969
+ # skip non tensor types. This may happen for induction variables.
970
+ if not isinstance(input, tl.tensor):
971
+ return input
972
+ # Unwrap constexpr
973
+ values = [values] if not isinstance(values, (list, tuple)) else values
974
+ values = [v.value if isinstance(v, tl.constexpr) else v for v in values]
975
+ if len(values) != max(1, len(input.shape)):
976
+ raise ValueError(f"len(values) != len(input.shape) for {name}")
977
+ input.handle.set_attr(name, values)
978
+ return input
979
+
980
+ lang.range = _new_range
981
+ lang.static_range = _new_range
982
+ lang.static_assert = _new_static_assert
983
+ lang.static_print = print
984
+ lang.dtype.to_ir = _new_to_ir
985
+ lang.multiple_of = partial(_set_attr, name="tt.divisiblity")
986
+ lang.max_contiguous = partial(_set_attr, name="tt.contiguity")
987
+ lang.max_constancy = partial(_set_attr, name="tt.constancy")
988
+
989
+ _patch_reduce_scan()
990
+
991
+
992
+ def _patch_lang(fn):
993
+ lang = [value for _, value in fn.__globals__.items() if value in [tl, tl.core]]
994
+ assert len(lang) == 1, "triton.language must be visible from within jit'd function"
995
+ _patch_builtin(lang[0], interpreter_builder)
996
+ _patch_builtin(lang[0].tensor, interpreter_builder)
997
+ if lang[0] == tl:
998
+ _patch_builtin(lang[0].math, interpreter_builder)
999
+ _patch_lang_tensor(lang[0].tensor)
1000
+ _patch_lang_core(lang[0])
1001
+
1002
+
1003
+ # TODO: wrap everything in triton tensors
1004
+ def _implicit_cvt(arg):
1005
+ if isinstance(arg, int):
1006
+ ty = tl.str_to_ty(triton.runtime.jit.JITFunction._type_of(triton.runtime.jit.JITFunction._key_of(arg)))
1007
+ dtype = np.int32
1008
+ if -2**31 <= arg < 2**31:
1009
+ dtype = np.int32
1010
+ elif 2**31 <= arg < 2**32:
1011
+ dtype = np.uint32
1012
+ elif -2**63 <= arg < 2**63:
1013
+ dtype = np.int64
1014
+ elif 2**63 <= arg < 2**64:
1015
+ dtype = np.uint64
1016
+ else:
1017
+ raise ValueError(f"Unsupported integer value {arg}")
1018
+ handle = TensorHandle(np.array([arg], dtype=dtype), ty)
1019
+ return tl.tensor(handle, ty)
1020
+ if hasattr(arg, "data_ptr"):
1021
+ ty = tl.str_to_ty(triton.runtime.jit.JITFunction._type_of(triton.runtime.jit.JITFunction._key_of(arg)))
1022
+ handle = TensorHandle(np.array([arg.data_ptr()], dtype=np.uint64), ty)
1023
+ return tl.tensor(handle, ty)
1024
+ return arg
1025
+
1026
+
1027
+ interpreter_builder = InterpreterBuilder()
1028
+
1029
+ # These keywords are not supported by the interpreter
1030
+ RESERVED_KWS = ["num_warps", "num_stages", "num_ctas", "enable_fp_fusion", "grid", "maxnreg"]
1031
+
1032
+
1033
+ class GridExecutor:
1034
+
1035
+ def __init__(self, fn, arg_names, grid):
1036
+ from .jit import _normalize_ty # TODO: modularize
1037
+
1038
+ self.fn = fn
1039
+ self.arg_names = arg_names
1040
+ self.grid = grid
1041
+ __annotations__ = {name: _normalize_ty(ty) for name, ty in fn.__annotations__.items()}
1042
+ self.constexprs = [name for name in arg_names if __annotations__.get(name) == "constexpr"]
1043
+
1044
+ def _init_args_hst(self, args_dev, kwargs):
1045
+ args_hst = []
1046
+ for arg in args_dev:
1047
+ if hasattr(arg, "data_ptr"):
1048
+ args_hst.append(arg.cpu())
1049
+ else:
1050
+ args_hst.append(arg)
1051
+ # Process keyword arguments
1052
+ kwargs_hst = {}
1053
+ for key, value in kwargs.items():
1054
+ if hasattr(value, "data_ptr"):
1055
+ kwargs_hst[key] = value.cpu()
1056
+ else:
1057
+ kwargs_hst[key] = value
1058
+ return args_hst, kwargs_hst
1059
+
1060
+ def _restore_args_dev(self, args_dev, args_hst, kwargs, kwargs_hst):
1061
+ for arg_dev, arg_hst in zip(args_dev, args_hst):
1062
+ if hasattr(arg_dev, "data_ptr"):
1063
+ arg_dev.data.copy_(arg_hst.to(arg_dev.device).data)
1064
+
1065
+ # Restore keyword arguments
1066
+ for key, kwarg_dev in kwargs.items():
1067
+ kwarg_hst = kwargs_hst[key]
1068
+ if hasattr(kwarg_dev, "data_ptr"):
1069
+ kwarg_dev.data.copy_(kwarg_hst.to(kwarg_dev.device).data)
1070
+
1071
+ def __call__(self, *args_dev, **kwargs):
1072
+ # removes reserved keywords from kwargs
1073
+ kwargs = {k: v for k, v in kwargs.items() if k not in RESERVED_KWS}
1074
+ if kwargs.pop("warmup", False):
1075
+ return
1076
+ # copy arguments to the host
1077
+ args_hst, kwargs_hst = self._init_args_hst(args_dev, kwargs)
1078
+ # remaps core language functions to interpreted ones
1079
+ _patch_lang(self.fn)
1080
+ # we need to copy arguments to the host for the interpreter
1081
+ # implicitly convert tensor arguments to their base pointers
1082
+ args = inspect.getcallargs(self.fn, *args_hst, **kwargs_hst)
1083
+ args = {name: arg if name in self.constexprs else _implicit_cvt(arg) for name, arg in args.items()}
1084
+ # iterate through grid
1085
+ grid = self.grid(args) if callable(self.grid) else self.grid
1086
+ assert len(grid) <= 3, "grid must have at most 3 dimensions"
1087
+ grid = grid + (1, ) * (3 - len(grid))
1088
+ interpreter_builder.set_grid_dim(*grid)
1089
+ try:
1090
+ for x in range(grid[0]):
1091
+ for y in range(grid[1]):
1092
+ for z in range(grid[2]):
1093
+ interpreter_builder.set_grid_idx(x, y, z)
1094
+ self.fn(**args)
1095
+ except Exception as e:
1096
+ raise InterpreterError(repr(e)) from e
1097
+ # copy arguments back to propagate side-effects
1098
+ self._restore_args_dev(args_dev, args_hst, kwargs, kwargs_hst)
1099
+
1100
+
1101
+ class InterpretedFunction:
1102
+
1103
+ def __init__(self, fn) -> None:
1104
+ self.fn = fn
1105
+
1106
+ def run(*args, **kwargs):
1107
+ grid = kwargs["grid"]
1108
+ return GridExecutor(self.fn, self.arg_names, grid)(*args, **kwargs)
1109
+
1110
+ self.run = run
1111
+ signature = inspect.signature(fn)
1112
+ self.arg_names = [v.name for v in signature.parameters.values()]
1113
+
1114
+ @property
1115
+ def __name__(self):
1116
+ return self.fn.__name__
1117
+
1118
+ def __getitem__(self, grid):
1119
+ return GridExecutor(self.fn, self.arg_names, grid)
1120
+
1121
+ def __call__(self, *args, **kwargs):
1122
+ # This is a device function call
1123
+ _patch_lang(self.fn)
1124
+ try:
1125
+ return self.fn(*args, **kwargs)
1126
+ except Exception as e:
1127
+ raise InterpreterError(repr(e)) from e