forked from triton-lang/triton
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknobs.py
More file actions
542 lines (385 loc) · 16.8 KB
/
knobs.py
File metadata and controls
542 lines (385 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
from __future__ import annotations
import functools
import importlib
import os
import re
import subprocess
import sysconfig
import pathlib
from dataclasses import dataclass
from contextlib import contextmanager
from typing import cast, Any, Callable, Generator, Generic, Optional, Protocol, Type, TypeVar, TypedDict, TYPE_CHECKING, Union
from triton._C.libtriton import getenv, getenv_bool # type: ignore
if TYPE_CHECKING:
from .runtime.cache import CacheManager, RemoteCacheBackend
from .runtime.jit import JitFunctionInfo, KernelParam
from .compiler.compiler import ASTSource, LazyDict, IRSource
class Env:
pass
env = Env()
propagate_env: bool = True
def setenv(key: str, value: Optional[str]) -> None:
if not propagate_env:
return
if value is not None:
os.environ[key] = value
elif key in os.environ:
del os.environ[key]
def toenv(val: Any) -> Union[None, tuple[Optional[str]]]:
if val is None:
return (None, )
t = type(val)
if t is bool:
return ("1" if val else "0", )
if t is str:
return (val, )
if t is int:
return (str(val), )
return None
# There's an asymmetry here so that e.g. env_nvidia_tool can be specified with a
# a string but return an NvidiaTool.
SetType = TypeVar("SetType")
GetType = TypeVar("GetType")
_NOTHING = object()
class env_base(Generic[SetType, GetType]):
def __init__(self, key: str) -> None:
self.key = key
def __set_name__(self, objclass: Type[object], name: str) -> None:
self.name = name
def __get__(self, obj: Optional[object], objclass: Optional[Type[object]]) -> GetType:
py_val = obj.__dict__.get(self.name, _NOTHING)
if py_val is _NOTHING:
return self.get()
return self.transform(py_val)
def get(self) -> GetType:
raise NotImplementedError()
def __set__(self, obj: object, value: Union[SetType, Env]) -> None:
if isinstance(value, Env):
obj.__dict__.pop(self.name, None)
else:
obj.__dict__[self.name] = value
if env_val := toenv(value):
setenv(self.key, env_val[0])
def __delete__(self, obj: object) -> None:
obj.__dict__.pop(self.name, None)
def transform(self, val: SetType) -> GetType:
# See comment about GetType/SetType in their definition above. Only needed
# if GetType != SetType.
return cast(GetType, val)
class env_str(env_base[str, str]):
def __init__(self, key: str, default: str):
super().__init__(key)
self.default = default
def get(self) -> str:
return getenv(self.key, self.default)
class env_str_callable_default(env_base[str, str]):
def __init__(self, key: str, default_factory: Callable[[], str]):
super().__init__(key)
self.default_factory = default_factory
def get(self) -> str:
env_val = getenv(self.key)
if env_val is None:
return self.default_factory()
return env_val
class env_bool(env_base[bool, bool]):
def __init__(self, key: str, default: bool = False) -> None:
super().__init__(key)
self.default = default
def get(self) -> bool:
return getenv_bool(self.key, self.default)
class env_int(env_base[int, int]):
def __init__(self, key: str, default: int = 0) -> None:
super().__init__(key)
self.default = default
def get(self) -> int:
val = getenv(self.key)
if val is None:
return self.default
try:
return int(val)
except ValueError as exc:
raise RuntimeError(f"Unable to use {self.key}={val}: expected int") from exc
ClassType = TypeVar("ClassType")
class env_class(Generic[ClassType], env_base[Optional[Type[ClassType]], Optional[Type[ClassType]]]):
def __init__(self, key: str, type: str) -> None:
super().__init__(key)
# We can't pass the type directly to avoid import cycles
self.type = type
def get(self) -> Optional[Type[ClassType]]:
val = getenv(self.key)
if val is None:
return None
comps = val.split(":", 1)
if len(comps) != 2:
raise RuntimeError(f"Unable to read {self.key}: '{val}' isn't of the form MODULE:CLASS")
cls = getattr(importlib.import_module(comps[0]), comps[1])
if not any((c.__name__ == self.type for c in cls.mro())):
raise RuntimeError(f"Unable to use '{val}' from {self.key}: not of type '{self.type}'")
return cast(Type[ClassType], cls)
@dataclass
class NvidiaTool:
path: str
version: str
@staticmethod
@functools.lru_cache
def from_path(path: str) -> Optional[NvidiaTool]:
try:
result = subprocess.check_output([path, "--version"], stderr=subprocess.STDOUT)
version = re.search(r".*release (\d+\.\d+).*", result.decode("utf-8"), flags=re.MULTILINE)
if version is None:
return None
return NvidiaTool(path, version.group(1))
except (subprocess.CalledProcessError, FileNotFoundError):
return None
class env_nvidia_tool(env_base[str, NvidiaTool]):
def __init__(self, binary: str) -> None:
binary += sysconfig.get_config_var("EXE")
self.binary = binary
self.default_path = os.path.join(os.path.dirname(__file__), "backends", "nvidia", "bin", binary)
super().__init__(f"TRITON_{binary.upper()}_PATH")
def get(self) -> NvidiaTool:
return self.transform(getenv(self.key))
def transform(self, path: str) -> NvidiaTool:
# We still add default as fallback in case the pointed binary isn't
# accessible.
if path is not None:
paths = [path, self.default_path]
else:
paths = [self.default_path]
for path in paths:
if tool := NvidiaTool.from_path(path):
return tool
raise RuntimeError(f"Cannot find {self.binary}")
# Separate classes so that types are correct
class env_opt_str(env_base[Optional[str], Optional[str]]):
def get(self) -> Optional[str]:
return getenv(self.key)
class env_opt_bool(env_base):
def get(self) -> Optional[str]:
return getenv_bool(self.key, None)
@dataclass(frozen=True)
class CompileTimes:
"""
Model holding timing information for an invocation of the compiler.
All times in microseconds.
"""
# Duration of make_ir
ir_initialization: int
# Ordered mapping from lowering stage to duration spent in that stage.
# Keyed by stage extension, e.g. ttir, ttgir
lowering_stages: list[tuple[str, int]]
# Duration of saving artifacts/metadata to cache
store_results: int
@property
def total_lowering(self) -> int:
return sum((stage[1] for stage in self.lowering_stages))
@property
def total(self) -> int:
return self.ir_initialization + self.total_lowering + self.store_results
class CompilationListener(Protocol):
def __call__(self, *, src: Union[ASTSource, IRSource], metadata: dict[str, Any], metadata_group: dict[str, str],
times: CompileTimes, cache_hit: bool) -> None:
...
knobs_type = TypeVar("knobs_type", bound='base_knobs')
class base_knobs:
@property
def knob_descriptors(self) -> dict[str, env_base]:
return {
k: v
# data descriptors live on the class object
for k, v in type(self).__dict__.items()
if isinstance(v, env_base)
}
@property
def knobs(self) -> dict[str, Any]:
return {k: getattr(self, k) for k in self.knob_descriptors.keys()}
def copy(self: knobs_type) -> knobs_type:
res = type(self)()
res.__dict__.update(self.__dict__)
return res
def reset(self: knobs_type) -> knobs_type:
for knob in self.knob_descriptors.keys():
delattr(self, knob)
return self
@contextmanager
def scope(self) -> Generator[None, None, None]:
try:
initial_env = {knob.key: getenv(knob.key) for knob in self.knob_descriptors.values()}
orig = dict(self.__dict__)
yield
finally:
self.__dict__.clear()
self.__dict__.update(orig)
for k, v in initial_env.items():
if v is not None:
os.environ[k] = v
elif k in os.environ:
del os.environ[k]
class BuildImpl(Protocol):
def __call__(self, name: str, src: str, srcdir: str, library_dirs: list[str], include_dirs: list[str],
libraries: list[str], /) -> str:
...
class build_knobs(base_knobs):
"""Configuration controlling how the native compiler is invoked"""
cc: env_opt_str = env_opt_str("CC")
cudacrt_path: env_opt_str = env_opt_str("TRITON_CUDACRT_PATH")
cudart_path: env_opt_str = env_opt_str("TRITON_CUDART_PATH")
impl: Optional[BuildImpl] = None
@property
def backend_dirs(self) -> set[str]:
return {path for path in (self.cudacrt_path, self.cudart_path) if path is not None}
class redis_knobs(base_knobs):
key_format: env_str = env_str("TRITON_REDIS_KEY_FORMAT", "triton:{key}:{filename}")
host: env_str = env_str("TRITON_REDIS_HOST", "localhost")
port: env_int = env_int("TRITON_REDIS_PORT", 6379)
cache: cache_knobs
class cache_knobs(base_knobs):
home_dir: env_str = env_str("TRITON_HOME", os.path.expanduser("~/"))
dump_dir = env_str_callable_default("TRITON_DUMP_DIR", lambda: cache.get_triton_dir("dump"))
override_dir = env_str_callable_default("TRITON_OVERRIDE_DIR", lambda: cache.get_triton_dir("override"))
dir = env_str_callable_default("TRITON_CACHE_DIR", lambda: cache.get_triton_dir("cache"))
manager_class: env_class[CacheManager] = env_class("TRITON_CACHE_MANAGER", "CacheManager")
remote_manager_class: env_class[RemoteCacheBackend] = env_class("TRITON_REMOTE_CACHE_BACKEND", "RemoteCacheBackend")
def get_triton_dir(self, dirname: str) -> str:
return os.path.join(self.home_dir, ".triton", dirname)
class compilation_knobs(base_knobs):
override: env_bool = env_bool("TRITON_KERNEL_OVERRIDE")
dump_ir: env_bool = env_bool("TRITON_KERNEL_DUMP")
dump_ir_extract_di_local_variables: env_bool = env_bool("LLVM_EXTRACT_DI_LOCAL_VARIABLES")
store_binary_only: env_bool = env_bool("TRITON_STORE_BINARY_ONLY")
always_compile: env_bool = env_bool("TRITON_ALWAYS_COMPILE")
# TODO: Use enum to constrain / 'typecheck' the values
use_ir_loc: env_opt_str = env_opt_str("USE_IR_LOC")
enable_asan: env_bool = env_bool("TRITON_ENABLE_ASAN")
disable_line_info: env_bool = env_bool("TRITON_DISABLE_LINE_INFO")
front_end_debugging: env_bool = env_bool("TRITON_FRONT_END_DEBUGGING")
allow_non_constexpr_globals: env_bool = env_bool("TRITON_ALLOW_NON_CONSTEXPR_GLOBALS")
# Instrumentation mode is checked on every run, which is expensive.
# We cache the value here to avoid the expensive check on every run.
instrumentation_mode: str = env_str("TRITON_INSTRUMENTATION_MODE", "").get()
listener: Union[CompilationListener, None] = None
class autotuning_knobs(base_knobs):
cache: env_bool = env_bool("TRITON_CACHE_AUTOTUNING")
print: env_bool = env_bool("TRITON_PRINT_AUTOTUNING")
class LaunchHook(Protocol):
"""Hook invoked before and after kernel launching
"""
def __call__(self, metadata: LazyDict) -> None:
...
class InitHandleHook(Protocol):
"""Hook invoked around kernel binary/module loading.
module/function can be None for the *start* hook (before loading).
"""
def __call__(
self,
module: Optional[object],
function: Optional[Callable],
name: str,
metadata_group: dict[str, str],
hash: str,
) -> None:
...
F = TypeVar("F", bound=Callable)
class HookChain(Generic[F]):
"""A chain of hooks of the same type F to be called in order.
"""
def __init__(self, reversed: bool = False):
self.calls: list[F] = []
self.reversed = reversed
def add(self, func: F) -> None:
if func not in self.calls:
self.calls.append(func)
def remove(self, func: F) -> None:
if func in self.calls:
self.calls.remove(func)
def __call__(self, *args, **kwargs):
for call in self.calls if not self.reversed else reversed(self.calls):
call(*args, **kwargs)
# This is of the form [attr_name, attr_val]
# TODO: Use tuple instead of list for better typing.
KernelAttr = list[Union[str, int]]
class JITHookCompileInfo(TypedDict):
key: str
signature: dict[KernelParam, str]
device: int
constants: None
num_warps: int
num_ctas: int
num_stages: int
enable_fp_fusion: bool
launch_cooperative_grid: bool
extern_libs: tuple[tuple[str, str], ...]
configs: list[dict[tuple[int, ...], list[KernelAttr]]]
specialization_data: str
is_warmup: bool
class JITHook(Protocol):
def __call__(self, *, key: str, repr: str, fn: JitFunctionInfo, compile: JITHookCompileInfo, is_manual_warmup: bool,
already_compiled: bool) -> Optional[bool]:
...
class PipelineStagesHook(Protocol):
def __call__(self, stages, options, language, capability):
...
class runtime_knobs(base_knobs):
interpret: env_bool = env_bool("TRITON_INTERPRET")
# debug is on critical path for kernel launches
# avoid repeated reads from env-var by calling get directly
debug: bool = env_bool("TRITON_DEBUG").get()
override_arch: env_opt_str = env_opt_str("TRITON_OVERRIDE_ARCH")
launch_enter_hook: HookChain[LaunchHook] = HookChain()
launch_exit_hook: HookChain[LaunchHook] = HookChain(reversed=True)
kernel_load_start_hook: HookChain[InitHandleHook] = HookChain()
kernel_load_end_hook: HookChain[InitHandleHook] = HookChain(reversed=True)
# Hook for inspecting compiled functions and modules
jit_cache_hook: Optional[JITHook] = None
# Hook to signal that a kernel is done compiling and inspect compiled function.
# jit_cache_hook will always be called before compilation and jit_post_compile_hook after.
jit_post_compile_hook: Optional[JITHook] = None
# Hook for inspecting compiler pipeline stages
add_stages_inspection_hook: Optional[PipelineStagesHook] = None
class language_knobs(base_knobs):
fp32_default: env_opt_str = env_opt_str("TRITON_F32_DEFAULT")
default_fp_fusion: env_bool = env_bool("TRITON_DEFAULT_FP_FUSION", True)
class nvidia_knobs(base_knobs):
cuobjdump: env_nvidia_tool = env_nvidia_tool("cuobjdump")
nvdisasm: env_nvidia_tool = env_nvidia_tool("nvdisasm")
ptxas: env_nvidia_tool = env_nvidia_tool("ptxas")
ptxas_blackwell: env_nvidia_tool = env_nvidia_tool("ptxas-blackwell")
dump_nvptx: env_bool = env_bool("NVPTX_ENABLE_DUMP")
disable_ptxas_opt: env_bool = env_bool("DISABLE_PTXAS_OPT")
ptxas_options: env_opt_str = env_opt_str("PTXAS_OPTIONS")
mock_ptx_version: env_opt_str = env_opt_str("TRITON_MOCK_PTX_VERSION")
dump_ptxas_log: env_bool = env_bool("TRITON_DUMP_PTXAS_LOG")
libdevice_path: env_opt_str = env_opt_str("TRITON_LIBDEVICE_PATH")
libcuda_path: env_opt_str = env_opt_str("TRITON_LIBCUDA_PATH")
class amd_knobs(base_knobs):
use_buffer_ops: env_bool = env_bool("AMDGCN_USE_BUFFER_OPS", True)
# Note: This requires use_buffer_ops be true to have any effect
use_buffer_atomics: env_bool = env_bool("AMDGCN_USE_BUFFER_ATOMICS", True)
# Note: This requires use_buffer_ops be true to have any effect
buffer_ops_analyze_small_tensor_range: env_bool = env_bool("AMDGCN_ANALYZE_SMALL_TENSOR_RANGE", False)
dump_amdgcn: env_bool = env_bool("AMDGCN_ENABLE_DUMP")
libhip_path: env_opt_str = env_opt_str("TRITON_LIBHIP_PATH")
# We use strs so that we can have a default value based on other runtime info
use_block_pingpong: env_opt_bool = env_opt_bool("TRITON_HIP_USE_BLOCK_PINGPONG")
use_in_thread_transpose: env_opt_bool = env_opt_bool("TRITON_HIP_USE_IN_THREAD_TRANSPOSE")
use_async_copy: env_bool = env_bool("TRITON_HIP_USE_ASYNC_COPY")
scalarize_packed_fops: env_bool = env_bool("AMDGCN_SCALARIZE_PACKED_FOPS")
class proton_knobs(base_knobs):
disable: env_bool = env_bool("TRITON_PROTON_DISABLE", False)
cupti_lib_dir: env_str = env_str(
"TRITON_CUPTI_LIB_PATH",
str(pathlib.Path(__file__).parent.absolute() / "backends" / "nvidia" / "lib" / "cupti"))
enable_nvtx: env_bool = env_bool("TRITON_ENABLE_NVTX", True)
build = build_knobs()
redis = redis_knobs()
cache = cache_knobs()
compilation = compilation_knobs()
autotuning = autotuning_knobs()
runtime = runtime_knobs()
language = language_knobs()
nvidia = nvidia_knobs()
amd = amd_knobs()
proton = proton_knobs()
def refresh_knobs():
runtime.debug = env_bool("TRITON_DEBUG").get()
compilation.instrumentation_mode = env_str("TRITON_INSTRUMENTATION_MODE", "").get()