knobs.py 17 KB

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