triton-windows 3.2.0.post11__cp310-cp310-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,408 @@
1
+ from __future__ import annotations
2
+
3
+ import builtins
4
+ import os
5
+ import time
6
+ import inspect
7
+ from typing import Dict
8
+
9
+ from .jit import KernelInterface
10
+ from .errors import OutOfResources
11
+ from .driver import driver
12
+
13
+
14
+ class Autotuner(KernelInterface):
15
+
16
+ def __init__(
17
+ self,
18
+ fn,
19
+ arg_names,
20
+ configs,
21
+ key,
22
+ reset_to_zero,
23
+ restore_value,
24
+ pre_hook=None,
25
+ post_hook=None,
26
+ prune_configs_by: Dict = None,
27
+ warmup=None,
28
+ rep=None,
29
+ use_cuda_graph=False,
30
+ do_bench=None,
31
+ ):
32
+ """
33
+ :param prune_configs_by: a dict of functions that are used to prune configs, fields:
34
+ 'perf_model': performance model used to predicate running time with different configs, returns running time
35
+ 'top_k': number of configs to bench
36
+ 'prune_num_stages_by'(optional): a function used to prune num_stages. It takes configs:List[Config] as its input, and returns pruned configs.
37
+ """
38
+ if not configs:
39
+ self.configs = [
40
+ Config({}, num_warps=4, num_stages=2, num_ctas=1, num_buffers_warp_spec=0, num_consumer_groups=0,
41
+ reg_dec_producer=0, reg_inc_consumer=0)
42
+ ]
43
+ else:
44
+ self.configs = configs
45
+ self.keys = key
46
+ self.cache = {}
47
+ self.arg_names = arg_names
48
+
49
+ # Reset to zero or restore values
50
+ self.reset_to_zero = []
51
+ if reset_to_zero is not None:
52
+ self.reset_to_zero = list(reset_to_zero)
53
+ self.restore_value = []
54
+ if restore_value is not None:
55
+ self.restore_value = list(restore_value)
56
+
57
+ # Hook to reset or restore for required tensors
58
+ self.pre_hook = lambda kwargs, reset_only=False: 0
59
+ self.post_hook = lambda kwargs, exception: 0
60
+ self.user_defined_pre_hook = False
61
+ self.user_defined_post_hook = False
62
+ if pre_hook:
63
+ self.pre_hook = pre_hook
64
+ self.user_defined_pre_hook = True
65
+ elif (len(self.reset_to_zero) > 0 or len(self.restore_value) > 0):
66
+
67
+ def _pre_hook(kwargs, reset_only=False):
68
+ for name in self.reset_to_zero:
69
+ kwargs[name].zero_()
70
+ if not reset_only:
71
+ self.restore_copies = {name: kwargs[name].clone() for name in self.restore_value}
72
+
73
+ self.pre_hook = _pre_hook
74
+
75
+ if post_hook:
76
+ self.post_hook = post_hook
77
+ self.user_defined_post_hook = True
78
+ elif len(self.restore_value) > 0:
79
+
80
+ def _post_hook(kwargs, exception):
81
+ for name in self.restore_value:
82
+ kwargs[name].copy_(self.restore_copies[name])
83
+ self.restore_copies = {}
84
+
85
+ self.post_hook = _post_hook
86
+
87
+ self.perf_model = None
88
+ self.configs_top_k = 1.0
89
+ self.early_config_prune = None
90
+ if prune_configs_by:
91
+ self.perf_model = prune_configs_by.get("perf_model", self.perf_model)
92
+ self.configs_top_k = prune_configs_by.get("top_k", self.configs_top_k)
93
+ self.early_config_prune = prune_configs_by.get("early_config_prune", self.early_config_prune)
94
+
95
+ self.fn = fn
96
+ self.base_fn = fn
97
+ while not inspect.isfunction(self.base_fn):
98
+ self.base_fn = self.base_fn.fn
99
+
100
+ self.num_warmups = warmup
101
+ self.num_reps = rep
102
+ self.use_cuda_graph = use_cuda_graph
103
+
104
+ # If we got explicitly called via the old interface, raise a warning
105
+ # and proceed with the old behavior.
106
+ if warmup is not None or rep is not None or use_cuda_graph:
107
+ import warnings
108
+ warnings.warn(("warmup, rep, and use_cuda_graph parameters are deprecated. See "
109
+ "https://github.com/triton-lang/triton/pull/4496 for details."), DeprecationWarning,
110
+ stacklevel=1)
111
+ if use_cuda_graph:
112
+ from ..testing import do_bench_cudagraph
113
+ self.do_bench = lambda kernel_call, quantiles: do_bench_cudagraph(
114
+ kernel_call,
115
+ rep=rep if rep is not None else 100,
116
+ quantiles=quantiles,
117
+ )
118
+ return
119
+
120
+ import triton.testing
121
+ self.do_bench = lambda kernel_call, quantiles: triton.testing.do_bench(
122
+ kernel_call,
123
+ warmup=warmup if warmup is not None else 25,
124
+ rep=rep if rep is not None else 100,
125
+ quantiles=quantiles,
126
+ )
127
+ return
128
+
129
+ if do_bench is None:
130
+ self.do_bench = driver.active.get_benchmarker()
131
+ else:
132
+ self.do_bench = do_bench
133
+
134
+ def _bench(self, *args, config, **meta):
135
+ from ..compiler.errors import CompileTimeAssertionFailure
136
+
137
+ # check for conflicts, i.e. meta-parameters both provided
138
+ # as kwargs and by the autotuner
139
+ conflicts = meta.keys() & config.kwargs.keys()
140
+ if conflicts:
141
+ raise ValueError(f"Conflicting meta-parameters: {', '.join(conflicts)}."
142
+ " Make sure that you don't re-define auto-tuned symbols.")
143
+ # augment meta-parameters with tunable ones
144
+ current = dict(meta, **config.all_kwargs())
145
+ full_nargs = {**self.nargs, **current}
146
+
147
+ def kernel_call():
148
+ if config.pre_hook:
149
+ config.pre_hook(full_nargs)
150
+ self.pre_hook(full_nargs)
151
+ try:
152
+ self.fn.run(
153
+ *args,
154
+ **current,
155
+ )
156
+ except Exception as e:
157
+ try:
158
+ self.post_hook(full_nargs, exception=e)
159
+ finally:
160
+ # Throw exception raised by `self.fn.run`
161
+ raise
162
+
163
+ self.post_hook(full_nargs, exception=None)
164
+
165
+ try:
166
+ return self.do_bench(kernel_call, quantiles=(0.5, 0.2, 0.8))
167
+ except (OutOfResources, CompileTimeAssertionFailure):
168
+ return [float("inf"), float("inf"), float("inf")]
169
+
170
+ def run(self, *args, **kwargs):
171
+ self.nargs = dict(zip(self.arg_names, args))
172
+ used_cached_result = True
173
+ if len(self.configs) > 1:
174
+ all_args = {**self.nargs, **kwargs}
175
+ _args = {k: v for (k, v) in all_args.items() if k in self.arg_names}
176
+ key = [_args[key] for key in self.keys if key in _args]
177
+ for _, arg in _args.items():
178
+ if hasattr(arg, "dtype"):
179
+ key.append(str(arg.dtype))
180
+ key = tuple(key)
181
+ if key not in self.cache:
182
+ # prune configs
183
+ used_cached_result = False
184
+ pruned_configs = self.prune_configs(kwargs)
185
+ bench_start = time.time()
186
+ timings = {config: self._bench(*args, config=config, **kwargs) for config in pruned_configs}
187
+ bench_end = time.time()
188
+ self.bench_time = bench_end - bench_start
189
+ self.cache[key] = builtins.min(timings, key=timings.get)
190
+ full_nargs = {**self.nargs, **kwargs, **self.cache[key].all_kwargs()}
191
+ self.pre_hook(full_nargs, reset_only=True)
192
+ self.configs_timings = timings
193
+ config = self.cache[key]
194
+ else:
195
+ config = self.configs[0]
196
+ self.best_config = config
197
+ if os.getenv("TRITON_PRINT_AUTOTUNING", None) == "1" and not used_cached_result:
198
+ print(f"Triton autotuning for function {self.base_fn.__name__} finished after "
199
+ f"{self.bench_time:.2f}s; best config selected: {self.best_config};")
200
+ if config.pre_hook is not None:
201
+ full_nargs = {**self.nargs, **kwargs, **config.all_kwargs()}
202
+ config.pre_hook(full_nargs)
203
+ ret = self.fn.run(
204
+ *args,
205
+ **kwargs,
206
+ **config.all_kwargs(),
207
+ )
208
+ self.nargs = None
209
+ return ret
210
+
211
+ def prune_configs(self, kwargs):
212
+ pruned_configs = self.configs
213
+ if self.early_config_prune:
214
+ pruned_configs = self.early_config_prune(self.configs, self.nargs, **kwargs)
215
+ if self.perf_model:
216
+ top_k = self.configs_top_k
217
+ if isinstance(top_k, float) and top_k <= 1.0:
218
+ top_k = int(len(self.configs) * top_k)
219
+ if len(pruned_configs) > top_k:
220
+ est_timing = {
221
+ config: self.perf_model(
222
+ **self.nargs,
223
+ **kwargs,
224
+ **config.all_kwargs(),
225
+ )
226
+ for config in pruned_configs
227
+ }
228
+ pruned_configs = sorted(est_timing.keys(), key=lambda x: est_timing[x])[:top_k]
229
+ return pruned_configs
230
+
231
+ def warmup(self, *args, **kwargs):
232
+ self.nargs = dict(zip(self.arg_names, args))
233
+ ret = []
234
+ for config in self.prune_configs(kwargs):
235
+ ret.append(self.fn.warmup(
236
+ *args,
237
+ **kwargs,
238
+ **config.all_kwargs(),
239
+ ))
240
+ self.nargs = None
241
+ return ret
242
+
243
+
244
+ class Config:
245
+ """
246
+ An object that represents a possible kernel configuration for the auto-tuner to try.
247
+
248
+ :ivar kwargs: a dictionary of meta-parameters to pass to the kernel as keyword arguments.
249
+ :type kwargs: dict[Str, Any]
250
+ :ivar num_warps: the number of warps to use for the kernel when compiled for GPUs. For example, if
251
+ `num_warps=8`, then each kernel instance will be automatically parallelized to
252
+ cooperatively execute using `8 * 32 = 256` threads.
253
+ :type num_warps: int
254
+ :ivar num_stages: the number of stages that the compiler should use when software-pipelining loops.
255
+ Mostly useful for matrix multiplication workloads on SM80+ GPUs.
256
+ :type num_ctas: int
257
+ :ivar num_ctas: number of blocks in a block cluster. SM90+ only.
258
+ :type maxnreg: Optional[int]
259
+ :ivar maxnreg: maximum number of registers one thread can use. Corresponds
260
+ to ptx .maxnreg directive. Not supported on all platforms.
261
+ :ivar pre_hook: a function that will be called before the kernel is called. Parameters of this
262
+ function are args.
263
+ """
264
+
265
+ def __init__(self, kwargs, num_warps=4, num_stages=2, num_ctas=1, num_buffers_warp_spec=0, num_consumer_groups=0,
266
+ reg_dec_producer=0, reg_inc_consumer=0, maxnreg=None, pre_hook=None):
267
+ self.kwargs = kwargs
268
+ self.num_warps = num_warps
269
+ self.num_ctas = num_ctas
270
+ self.num_stages = num_stages
271
+ self.num_buffers_warp_spec = num_buffers_warp_spec
272
+ self.num_consumer_groups = num_consumer_groups
273
+ self.reg_dec_producer = reg_dec_producer
274
+ self.reg_inc_consumer = reg_inc_consumer
275
+ self.maxnreg = maxnreg
276
+ self.pre_hook = pre_hook
277
+
278
+ def all_kwargs(self):
279
+ return {
280
+ **self.kwargs, **{
281
+ k: v
282
+ for (k, v) in (
283
+ ("num_warps", self.num_warps),
284
+ ("num_ctas", self.num_ctas),
285
+ ("num_stages", self.num_stages),
286
+ ("num_buffers_warp_spec", self.num_buffers_warp_spec),
287
+ ("num_consumer_groups", self.num_consumer_groups),
288
+ ("reg_dec_producer", self.reg_dec_producer),
289
+ ("reg_inc_consumer", self.reg_inc_consumer),
290
+ ("maxnreg", self.maxnreg),
291
+ ) if v is not None
292
+ }
293
+ }
294
+
295
+ def __str__(self):
296
+ res = []
297
+ for k, v in self.kwargs.items():
298
+ res.append(f"{k}: {v}")
299
+ res.append(f"num_warps: {self.num_warps}")
300
+ res.append(f"num_ctas: {self.num_ctas}")
301
+ res.append(f"num_stages: {self.num_stages}")
302
+ res.append(f"num_buffers_warp_spec: {self.num_buffers_warp_spec}")
303
+ res.append(f"num_consumer_groups: {self.num_consumer_groups}")
304
+ res.append(f"reg_dec_producer: {self.reg_dec_producer}")
305
+ res.append(f"reg_inc_consumer: {self.reg_inc_consumer}")
306
+ res.append(f"maxnreg: {self.maxnreg}")
307
+ return ", ".join(res)
308
+
309
+
310
+ def autotune(configs, key, prune_configs_by=None, reset_to_zero=None, restore_value=None, pre_hook=None, post_hook=None,
311
+ warmup=None, rep=None, use_cuda_graph=False, do_bench=None):
312
+ """
313
+ Decorator for auto-tuning a :code:`triton.jit`'d function.
314
+
315
+ .. highlight:: python
316
+ .. code-block:: python
317
+
318
+ @triton.autotune(configs=[
319
+ triton.Config(kwargs={'BLOCK_SIZE': 128}, num_warps=4),
320
+ triton.Config(kwargs={'BLOCK_SIZE': 1024}, num_warps=8),
321
+ ],
322
+ key=['x_size'] # the two above configs will be evaluated anytime
323
+ # the value of x_size changes
324
+ )
325
+ @triton.jit
326
+ def kernel(x_ptr, x_size, **META):
327
+ BLOCK_SIZE = META['BLOCK_SIZE']
328
+ :note: When all the configurations are evaluated, the kernel will run multiple times.
329
+ This means that whatever value the kernel updates will be updated multiple times.
330
+ To avoid this undesired behavior, you can use the `reset_to_zero` argument, which
331
+ resets the value of the provided tensor to `zero` before running any configuration.
332
+
333
+ If the environment variable :code:`TRITON_PRINT_AUTOTUNING` is set to
334
+ :code:`"1"`, Triton will print a message to stdout after autotuning each
335
+ kernel, including the time spent autotuning and the best configuration.
336
+
337
+ :param configs: a list of :code:`triton.Config` objects
338
+ :type configs: list[triton.Config]
339
+ :param key: a list of argument names whose change in value will trigger the evaluation of all provided configs.
340
+ :type key: list[str]
341
+ :param prune_configs_by: a dict of functions that are used to prune configs, fields:
342
+ 'perf_model': performance model used to predicate running time with different configs, returns running time
343
+ 'top_k': number of configs to bench
344
+ 'early_config_prune'(optional): a function used to do early prune (eg, num_stages). It takes configs:List[Config] as its input, and returns pruned configs.
345
+ :param reset_to_zero: a list of argument names whose value will be reset to zero before evaluating any configs.
346
+ :type reset_to_zero: list[str]
347
+ :param restore_value: a list of argument names whose value will be restored after evaluating any configs.
348
+ :type restore_value: list[str]
349
+ :param pre_hook: a function that will be called before the kernel is called.
350
+ This overrides the default pre_hook used for 'reset_to_zero' and 'restore_value'.
351
+ 'kwargs': a dict of all arguments passed to the kernel.
352
+ 'reset_only': a boolean indicating whether the pre_hook is called to reset the values only, without a corresponding post_hook.
353
+ :type pre_hook: lambda args, reset_only
354
+ :param post_hook: a function that will be called after the kernel is called.
355
+ This overrides the default post_hook used for 'restore_value'.
356
+ 'kwargs': a dict of all arguments passed to the kernel.
357
+ 'exception': the exception raised by the kernel in case of a compilation or runtime error.
358
+ :type post_hook: lambda args, exception
359
+ :param warmup: warmup time (in ms) to pass to benchmarking (deprecated).
360
+ :type warmup: int
361
+ :param rep: repetition time (in ms) to pass to benchmarking (deprecated).
362
+ :type rep: int
363
+ :param do_bench: a benchmark function to measure the time of each run.
364
+ :type do_bench: lambda fn, quantiles
365
+ """
366
+
367
+ def decorator(fn):
368
+ return Autotuner(fn, fn.arg_names, configs, key, reset_to_zero, restore_value, pre_hook=pre_hook,
369
+ post_hook=post_hook, prune_configs_by=prune_configs_by, warmup=warmup, rep=rep,
370
+ use_cuda_graph=use_cuda_graph)
371
+
372
+ return decorator
373
+
374
+
375
+ class Heuristics(KernelInterface):
376
+
377
+ def __init__(self, fn, arg_names, values) -> None:
378
+ self.fn = fn
379
+ self.values = values
380
+ self.arg_names = arg_names
381
+
382
+ def run(self, *args, **kwargs):
383
+ for v, heur in self.values.items():
384
+ kwargs[v] = heur({**dict(zip(self.arg_names, args)), **kwargs})
385
+ return self.fn.run(*args, **kwargs)
386
+
387
+
388
+ def heuristics(values):
389
+ """
390
+ Decorator for specifying how the values of certain meta-parameters may be computed.
391
+ This is useful for cases where auto-tuning is prohibitevely expensive, or just not applicable.
392
+
393
+ .. highlight:: python
394
+ .. code-block:: python
395
+
396
+ @triton.heuristics(values={'BLOCK_SIZE': lambda args: 2 ** int(math.ceil(math.log2(args[1])))})
397
+ @triton.jit
398
+ def kernel(x_ptr, x_size, **META):
399
+ BLOCK_SIZE = META['BLOCK_SIZE'] # smallest power-of-two >= x_size
400
+ :param values: a dictionary of meta-parameter names and functions that compute the value of the meta-parameter.
401
+ each such function takes a list of positional arguments as input.
402
+ :type values: dict[str, Callable[[list[Any]], Any]]
403
+ """
404
+
405
+ def decorator(fn):
406
+ return Heuristics(fn, fn.arg_names, values)
407
+
408
+ return decorator
@@ -0,0 +1,111 @@
1
+ import contextlib
2
+ import sys
3
+ import io
4
+ import sysconfig
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import setuptools
9
+
10
+ if os.name == "nt":
11
+ from triton.windows_utils import find_msvc_winsdk, find_python
12
+
13
+
14
+ @contextlib.contextmanager
15
+ def quiet():
16
+ old_stdout, old_stderr = sys.stdout, sys.stderr
17
+ sys.stdout, sys.stderr = io.StringIO(), io.StringIO()
18
+ try:
19
+ yield
20
+ finally:
21
+ sys.stdout, sys.stderr = old_stdout, old_stderr
22
+
23
+
24
+ def _cc_cmd(cc, src, out, include_dirs, library_dirs, libraries):
25
+ if cc.lower().endswith("cl") or cc.lower().endswith("cl.exe"):
26
+ out_base = os.path.splitext(out)[0]
27
+ cc_cmd = [cc, src, "/nologo", "/O2", "/LD", "/wd4819"]
28
+ cc_cmd += [f"/I{dir}" for dir in include_dirs if dir is not None]
29
+ cc_cmd += [f"/Fo{out_base + '.obj'}"]
30
+ cc_cmd += ["/link"]
31
+ cc_cmd += [f"/LIBPATH:{dir}" for dir in library_dirs]
32
+ cc_cmd += [f'{lib}.lib' for lib in libraries]
33
+ cc_cmd += [f"/OUT:{out}"]
34
+ cc_cmd += [f"/IMPLIB:{out_base + '.lib'}"]
35
+ cc_cmd += [f"/PDB:{out_base + '.pdb'}"]
36
+ else:
37
+ # for -Wno-psabi, see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111047
38
+ cc_cmd = [cc, src, "-O3", "-shared", "-fPIC", "-Wno-psabi", "-o", out]
39
+ cc_cmd += [f'-l{lib}' for lib in libraries]
40
+ cc_cmd += [f"-L{dir}" for dir in library_dirs]
41
+ cc_cmd += [f"-I{dir}" for dir in include_dirs if dir is not None]
42
+ return cc_cmd
43
+
44
+
45
+ def _build(name, src, srcdir, library_dirs, include_dirs, libraries):
46
+ suffix = sysconfig.get_config_var('EXT_SUFFIX')
47
+ so = os.path.join(srcdir, '{name}{suffix}'.format(name=name, suffix=suffix))
48
+ # try to avoid setuptools if possible
49
+ cc = os.environ.get("CC")
50
+ if cc is None:
51
+ # TODO: support more things here.
52
+ cl = shutil.which("cl")
53
+ gcc = shutil.which("gcc")
54
+ clang = shutil.which("clang")
55
+ cc = cl if cl is not None else gcc if gcc is not None else clang
56
+ if cc is None:
57
+ raise RuntimeError("Failed to find C compiler. Please specify via CC environment variable.")
58
+ # This function was renamed and made public in Python 3.10
59
+ if hasattr(sysconfig, 'get_default_scheme'):
60
+ scheme = sysconfig.get_default_scheme()
61
+ else:
62
+ scheme = sysconfig._get_default_scheme()
63
+ # 'posix_local' is a custom scheme on Debian. However, starting Python 3.10, the default install
64
+ # path changes to include 'local'. This change is required to use triton with system-wide python.
65
+ if scheme == 'posix_local':
66
+ scheme = 'posix_prefix'
67
+ py_include_dir = sysconfig.get_paths(scheme=scheme)["include"]
68
+ custom_backend_dirs = set(os.getenv(var) for var in ('TRITON_CUDACRT_PATH', 'TRITON_CUDART_PATH'))
69
+ include_dirs = include_dirs + [srcdir, py_include_dir, *custom_backend_dirs]
70
+ if os.name == "nt":
71
+ library_dirs += find_python()
72
+ libraries += ["python3"]
73
+ msvc_winsdk_inc_dirs, msvc_winsdk_lib_dirs = find_msvc_winsdk()
74
+ include_dirs += msvc_winsdk_inc_dirs
75
+ library_dirs += msvc_winsdk_lib_dirs
76
+ cc_cmd = _cc_cmd(cc, src, so, include_dirs, library_dirs, libraries)
77
+ ret = subprocess.check_call(cc_cmd)
78
+ if ret == 0:
79
+ return so
80
+ # fallback on setuptools
81
+ extra_compile_args = []
82
+ if cc.lower().endswith("cl") or cc.lower().endswith("cl.exe"):
83
+ extra_compile_args += ["/O2"]
84
+ else:
85
+ extra_compile_args += ["-O3"]
86
+ # extra arguments
87
+ extra_link_args = []
88
+ # create extension module
89
+ ext = setuptools.Extension(
90
+ name=name,
91
+ language='c',
92
+ sources=[src],
93
+ include_dirs=include_dirs,
94
+ extra_compile_args=extra_compile_args,
95
+ extra_link_args=extra_link_args,
96
+ library_dirs=library_dirs,
97
+ libraries=libraries,
98
+ )
99
+ # build extension module
100
+ args = ['build_ext']
101
+ args.append('--build-temp=' + srcdir)
102
+ args.append('--build-lib=' + srcdir)
103
+ args.append('-q')
104
+ args = dict(
105
+ name=name,
106
+ ext_modules=[ext],
107
+ script_args=args,
108
+ )
109
+ with quiet():
110
+ setuptools.setup(**args)
111
+ return so