_config_module.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. import contextlib
  2. import copy
  3. import hashlib
  4. import importlib
  5. import inspect
  6. import io
  7. import os
  8. import pickle
  9. import sys
  10. import tokenize
  11. import unittest
  12. from dataclasses import dataclass
  13. from types import FunctionType, ModuleType
  14. from typing import (
  15. Any,
  16. Callable,
  17. Generic,
  18. NoReturn,
  19. Optional,
  20. TYPE_CHECKING,
  21. TypeVar,
  22. Union,
  23. )
  24. from typing_extensions import deprecated
  25. from unittest import mock
  26. from torch._utils_internal import justknobs_check
  27. # Types saved/loaded in configs
  28. CONFIG_TYPES = (int, float, bool, type(None), str, list, set, tuple, dict)
  29. # Duplicated, because mypy needs these types statically
  30. T = TypeVar("T", bound=Union[int, float, bool, None, str, list, set, tuple, dict])
  31. _UNSET_SENTINEL = object()
  32. @dataclass
  33. class _Config(Generic[T]):
  34. """Represents a config with richer behaviour than just a default value.
  35. ::
  36. i.e.
  37. foo = Config(justknob="//foo:bar", default=False)
  38. install_config_module(...)
  39. This configs must be installed with install_config_module to be used
  40. Precedence Order:
  41. alias: If set, the directly use the value of the alias.
  42. env_name_force: If set, this environment variable has precedence over
  43. everything after this.
  44. If multiple env variables are given, the precedence order is from
  45. left to right.
  46. user_override: If a user sets a value (i.e. foo.bar=True), that
  47. has precedence over everything after this.
  48. env_name_default: If set, this environment variable will override everything
  49. after this.
  50. If multiple env variables are given, the precedence order is from
  51. left to right.
  52. justknob: If this pytorch installation supports justknobs, that will
  53. override defaults, but will not override the user_override precedence.
  54. default: This value is the lowest precedence, and will be used if nothing is
  55. set.
  56. Environment Variables:
  57. These are interpreted to be either "0" or "1" to represent true and false.
  58. Arguments:
  59. justknob: the name of the feature / JK. In OSS this is unused.
  60. default: is the value to default this knob to in OSS.
  61. alias: The alias config to read instead.
  62. env_name_force: The environment variable, or list of, to read that is a FORCE
  63. environment variable. I.e. it overrides everything except for alias.
  64. env_name_default: The environment variable, or list of, to read that changes the
  65. default behaviour. I.e. user overrides take preference.
  66. """
  67. default: Union[T, object]
  68. justknob: Optional[str] = None
  69. env_name_default: Optional[list[str]] = None
  70. env_name_force: Optional[list[str]] = None
  71. alias: Optional[str] = None
  72. def __init__(
  73. self,
  74. default: Union[T, object] = _UNSET_SENTINEL,
  75. justknob: Optional[str] = None,
  76. env_name_default: Optional[Union[str, list[str]]] = None,
  77. env_name_force: Optional[Union[str, list[str]]] = None,
  78. value_type: Optional[type] = None,
  79. alias: Optional[str] = None,
  80. ):
  81. # python 3.9 does not support kw_only on the dataclass :(.
  82. self.default = default
  83. self.justknob = justknob
  84. self.env_name_default = _Config.string_or_list_of_string_to_list(
  85. env_name_default
  86. )
  87. self.env_name_force = _Config.string_or_list_of_string_to_list(env_name_force)
  88. self.value_type = value_type
  89. self.alias = alias
  90. if self.alias is not None:
  91. assert (
  92. default is _UNSET_SENTINEL
  93. and justknob is None
  94. and env_name_default is None
  95. and env_name_force is None
  96. ), "if alias is set, none of {default, justknob and env var} can be set"
  97. @staticmethod
  98. def string_or_list_of_string_to_list(
  99. val: Optional[Union[str, list[str]]],
  100. ) -> Optional[list[str]]:
  101. if val is None:
  102. return None
  103. if isinstance(val, str):
  104. return [val]
  105. assert isinstance(val, list)
  106. return val
  107. # In runtime, we unbox the Config[T] to a T, but typechecker cannot see this,
  108. # so in order to allow for this dynamic behavior to work correctly with
  109. # typechecking we are going to lie to the typechecker that Config[T] returns
  110. # a T.
  111. if TYPE_CHECKING:
  112. def Config(
  113. default: Union[T, object] = _UNSET_SENTINEL,
  114. justknob: Optional[str] = None,
  115. env_name_default: Optional[Union[str, list[str]]] = None,
  116. env_name_force: Optional[Union[str, list[str]]] = None,
  117. value_type: Optional[type] = None,
  118. alias: Optional[str] = None,
  119. ) -> T: ...
  120. else:
  121. def Config(
  122. default: Union[T, object] = _UNSET_SENTINEL,
  123. justknob: Optional[str] = None,
  124. env_name_default: Optional[Union[str, list[str]]] = None,
  125. env_name_force: Optional[Union[str, list[str]]] = None,
  126. value_type: Optional[type] = None,
  127. alias: Optional[str] = None,
  128. ) -> _Config[T]:
  129. return _Config(
  130. default, justknob, env_name_default, env_name_force, value_type, alias
  131. )
  132. def _read_env_variable(name: str) -> Optional[Union[bool, str]]:
  133. value = os.environ.get(name)
  134. if value == "1":
  135. return True
  136. if value == "0":
  137. return False
  138. return value
  139. def install_config_module(module: ModuleType) -> None:
  140. """
  141. Converts a module-level config into a `ConfigModule()`.
  142. See _config_typing.pyi for instructions on how to get the converted module to typecheck.
  143. """
  144. class ConfigModuleInstance(ConfigModule):
  145. # __annotations__ is written to by Sphinx autodoc
  146. _bypass_keys = set({"_is_dirty", "_hash_digest", "__annotations__"})
  147. def visit(
  148. source: Union[ModuleType, type],
  149. dest: Union[ModuleType, SubConfigProxy],
  150. prefix: str,
  151. ) -> None:
  152. """Walk the module structure and move everything to module._config"""
  153. if sys.version_info[:2] < (3, 10):
  154. type_hints = getattr(source, "__annotations__", {})
  155. else:
  156. type_hints = inspect.get_annotations(source)
  157. for key, value in list(source.__dict__.items()):
  158. if (
  159. key.startswith("__")
  160. or isinstance(value, (ModuleType, FunctionType))
  161. or (hasattr(value, "__module__") and value.__module__ == "typing")
  162. # Handle from torch.utils._config_module import Config
  163. or (isinstance(value, type) and issubclass(value, _Config))
  164. ):
  165. continue
  166. name = f"{prefix}{key}"
  167. annotated_type = type_hints.get(key, None)
  168. if isinstance(value, CONFIG_TYPES):
  169. config[name] = _ConfigEntry(
  170. _Config(default=value, value_type=annotated_type)
  171. )
  172. if dest is module:
  173. delattr(module, key)
  174. elif isinstance(value, _Config):
  175. if annotated_type is not None and value.value_type is None:
  176. value.value_type = annotated_type
  177. config[name] = _ConfigEntry(value)
  178. if dest is module:
  179. delattr(module, key)
  180. elif isinstance(value, type):
  181. assert value.__module__ == module.__name__
  182. # a subconfig with `class Blah:` syntax
  183. proxy = SubConfigProxy(module, f"{name}.")
  184. visit(value, proxy, f"{name}.")
  185. if dest is module:
  186. setattr(dest, key, proxy)
  187. else:
  188. dest.__dict__[key] = proxy
  189. else:
  190. raise AssertionError(f"Unhandled config {key}={value} ({type(value)})")
  191. config: dict[str, _ConfigEntry] = {}
  192. compile_ignored_keys = get_assignments_with_compile_ignored_comments(module)
  193. visit(module, module, "")
  194. module._config = config # type: ignore[attr-defined]
  195. module._compile_ignored_keys = compile_ignored_keys # type: ignore[attr-defined]
  196. module.__class__ = ConfigModuleInstance
  197. module._is_dirty = True # type: ignore[attr-defined]
  198. module._hash_digest = None # type: ignore[attr-defined]
  199. COMPILE_IGNORED_MARKER = "@compile_ignored"
  200. # Gets all the keys (i.e. assignments) with a @compile_ignored comment
  201. def get_assignments_with_compile_ignored_comments(module: ModuleType) -> set[str]:
  202. source_code = inspect.getsource(module)
  203. assignments = set()
  204. # Tokenize the source code to retrieve comments
  205. tokens = tokenize.tokenize(io.BytesIO(source_code.encode("utf-8")).readline)
  206. current_comment = "", -1
  207. prev_name = ""
  208. for token in tokens:
  209. if token.type == tokenize.COMMENT:
  210. prev_name = ""
  211. maybe_current = token.string.strip()
  212. if COMPILE_IGNORED_MARKER in maybe_current:
  213. assert current_comment == (
  214. "",
  215. -1,
  216. ), f"unconsumed {COMPILE_IGNORED_MARKER}"
  217. current_comment = maybe_current, token.start[0]
  218. elif token.type == tokenize.NAME:
  219. # Only accept the first name token, to handle if you have
  220. # something like foo: Bar = ...
  221. if not prev_name:
  222. prev_name = token.string
  223. elif token.type == tokenize.OP and token.string == "=":
  224. # Check if the current assignment follows a comment
  225. # with COMPILE_IGNORED_MARKER
  226. if (
  227. COMPILE_IGNORED_MARKER in current_comment[0]
  228. and current_comment[1] == token.start[0] - 1
  229. ):
  230. assignments.add(prev_name)
  231. current_comment = "", -1 # reset
  232. prev_name = ""
  233. assert current_comment == ("", -1), f"unconsumed {COMPILE_IGNORED_MARKER}"
  234. return assignments
  235. @dataclass
  236. class _ConfigEntry:
  237. # The default value specified in the configuration
  238. default: Any
  239. # The type of the configuration value
  240. value_type: type
  241. # The value specified by the user when they overrode the configuration
  242. # _UNSET_SENTINEL indicates the value is not set.
  243. user_override: Any = _UNSET_SENTINEL
  244. # The justknob to check for this config
  245. justknob: Optional[str] = None
  246. # environment variables are read at install time
  247. env_value_force: Any = _UNSET_SENTINEL
  248. env_value_default: Any = _UNSET_SENTINEL
  249. # Used to work arounds bad assumptions in unittest.mock.patch
  250. # The code to blame is
  251. # https://github.com/python/cpython/blob/94a7a4e22fb8f567090514785c69e65298acca42/Lib/unittest/mock.py#L1637
  252. # Essentially, mock.patch requires, that if __dict__ isn't accessible
  253. # (which it isn't), that after delattr is called on the object, the
  254. # object must throw when hasattr is called. Otherwise, it doesn't call
  255. # setattr again.
  256. # Technically we'll have an intermediate state of hiding the config while
  257. # mock.patch is unpatching itself, but it calls setattr after the delete
  258. # call so the final state is correct. It's just very unintuitive.
  259. # upstream bug - python/cpython#126886
  260. hide: bool = False
  261. alias: Optional[str] = None
  262. def __init__(self, config: _Config):
  263. self.default = config.default
  264. self.value_type = (
  265. config.value_type if config.value_type is not None else type(self.default)
  266. )
  267. self.justknob = config.justknob
  268. self.alias = config.alias
  269. if config.env_name_default is not None:
  270. for val in config.env_name_default:
  271. if (env_value := _read_env_variable(val)) is not None:
  272. self.env_value_default = env_value
  273. break
  274. if config.env_name_force is not None:
  275. for val in config.env_name_force:
  276. if (env_value := _read_env_variable(val)) is not None:
  277. self.env_value_force = env_value
  278. break
  279. # Ensure justknobs and envvars are allowlisted types
  280. if self.justknob is not None and self.default is not None:
  281. assert isinstance(self.default, bool), (
  282. f"justknobs only support booleans, {self.default} is not a boolean"
  283. )
  284. if self.value_type is not None and (
  285. config.env_name_default is not None or config.env_name_force is not None
  286. ):
  287. assert self.value_type in (
  288. bool,
  289. str,
  290. Optional[bool],
  291. Optional[str],
  292. ), (
  293. f"envvar configs only support (optional) booleans or strings, {self.value_type} is neither"
  294. )
  295. class ConfigModule(ModuleType):
  296. # NOTE: This should be kept in sync with _config_typing.pyi.
  297. # The actual configuration settings. E.g., torch._dynamo.config.debug
  298. # would live as "debug" in the key, and torch._inductor.config.triton.cudagraphs
  299. # maps as "triton.cudagraphs". See discussion on the class for meaning of various sub items
  300. _config: dict[str, _ConfigEntry]
  301. _bypass_keys: set[str]
  302. _compile_ignored_keys: set[str]
  303. _is_dirty: bool
  304. _hash_digest: Optional[bytes]
  305. def __init__(self) -> None:
  306. raise NotImplementedError(
  307. f"use {__name__}.install_config_module(sys.modules[__name__])"
  308. )
  309. def __setattr__(self, name: str, value: object) -> None:
  310. if name in self._bypass_keys:
  311. super().__setattr__(name, value)
  312. elif name not in self._config:
  313. raise AttributeError(f"{self.__name__}.{name} does not exist")
  314. elif self._config[name].alias is not None:
  315. self._set_alias_val(self._config[name], value)
  316. else:
  317. self._config[name].user_override = value
  318. self._is_dirty = True
  319. self._config[name].hide = False
  320. def __getattr__(self, name: str) -> Any:
  321. try:
  322. config = self._config[name]
  323. if config.hide:
  324. raise AttributeError(f"{self.__name__}.{name} does not exist")
  325. alias_val = self._get_alias_val(config)
  326. if alias_val is not _UNSET_SENTINEL:
  327. return alias_val
  328. if config.env_value_force is not _UNSET_SENTINEL:
  329. return config.env_value_force
  330. if config.user_override is not _UNSET_SENTINEL:
  331. return config.user_override
  332. if config.env_value_default is not _UNSET_SENTINEL:
  333. return config.env_value_default
  334. if config.justknob is not None:
  335. # JK only supports bools and ints
  336. return justknobs_check(name=config.justknob, default=config.default)
  337. # Note that reference types can still be modified, so we
  338. # copy them to user_overrides in case the user overrides
  339. # them
  340. if isinstance(config.default, (list, set, dict)):
  341. config.user_override = copy.deepcopy(config.default)
  342. return config.user_override
  343. return config.default
  344. except KeyError as e:
  345. # make hasattr() work properly
  346. raise AttributeError(f"{self.__name__}.{name} does not exist") from e
  347. def __delattr__(self, name: str) -> None:
  348. self._is_dirty = True
  349. # must support delete because unittest.mock.patch deletes
  350. # then recreate things
  351. self._config[name].user_override = _UNSET_SENTINEL
  352. self._config[name].hide = True
  353. def _get_alias_module_and_name(
  354. self, entry: _ConfigEntry
  355. ) -> Optional[tuple[ModuleType, str]]:
  356. alias = entry.alias
  357. if alias is None:
  358. return None
  359. module_name, constant_name = alias.rsplit(".", 1)
  360. try:
  361. module = importlib.import_module(module_name)
  362. except ImportError as e:
  363. raise AttributeError("config alias {alias} does not exist") from e
  364. return module, constant_name
  365. def _get_alias_val(self, entry: _ConfigEntry) -> Any:
  366. data = self._get_alias_module_and_name(entry)
  367. if data is None:
  368. return _UNSET_SENTINEL
  369. module, constant_name = data
  370. constant_value = getattr(module, constant_name)
  371. return constant_value
  372. def _set_alias_val(self, entry: _ConfigEntry, val: Any) -> None:
  373. data = self._get_alias_module_and_name(entry)
  374. assert data is not None
  375. module, constant_name = data
  376. setattr(module, constant_name, val)
  377. def _is_default(self, name: str) -> bool:
  378. """
  379. Returns true if the config is at its default value.
  380. configs overridden by the env are not considered default.
  381. """
  382. config_val = self._config[name]
  383. # The config is not overridden by the user, and the env_value_default
  384. # is different from the default value (meaning user has set the env to
  385. # change the default value).
  386. not_set_env_default = (
  387. config_val.env_value_default is _UNSET_SENTINEL
  388. or config_val.env_value_default == config_val.default
  389. )
  390. not_set_env_force = (
  391. config_val.env_value_force is _UNSET_SENTINEL
  392. or config_val.env_value_force == config_val.default
  393. )
  394. unset = config_val.user_override is _UNSET_SENTINEL
  395. # Handle reference types specially to avoid spammy warnings
  396. if isinstance(config_val.default, (list, set, dict)):
  397. unset = unset or config_val.user_override == config_val.default
  398. return unset and not_set_env_default and not_set_env_force
  399. def _get_dict(
  400. self,
  401. ignored_keys: Optional[list[str]] = None,
  402. ignored_prefixes: Optional[list[str]] = None,
  403. skip_default: bool = False,
  404. ) -> dict[str, Any]:
  405. """Export a dictionary of current configuration keys and values.
  406. This function is design to provide a single point which handles
  407. accessing config options and exporting them into a dictionary.
  408. This is used by a number of different user facing export methods
  409. which all have slightly different semantics re: how and what to
  410. skip.
  411. If a config is aliased, it skips this config.
  412. Arguments:
  413. ignored_keys are keys that should not be exported.
  414. ignored_prefixes are prefixes that if a key matches should
  415. not be exported
  416. skip_default does two things. One if a key has not been modified
  417. it skips it.
  418. """
  419. config: dict[str, Any] = {}
  420. for key in self._config:
  421. if ignored_keys and key in ignored_keys:
  422. continue
  423. if ignored_prefixes:
  424. if any(key.startswith(prefix) for prefix in ignored_prefixes):
  425. continue
  426. if skip_default and self._is_default(key):
  427. continue
  428. if self._config[key].alias is not None:
  429. continue
  430. config[key] = copy.deepcopy(getattr(self, key))
  431. return config
  432. def get_type(self, config_name: str) -> type:
  433. return self._config[config_name].value_type
  434. def save_config(self) -> bytes:
  435. """Convert config to a pickled blob"""
  436. ignored_keys = getattr(self, "_save_config_ignore", [])
  437. return pickle.dumps(
  438. self._get_dict(ignored_keys=ignored_keys),
  439. protocol=2,
  440. )
  441. def save_config_portable(
  442. self, *, ignore_private_configs: bool = True
  443. ) -> dict[str, Any]:
  444. """Convert config to portable format"""
  445. prefixes = []
  446. if ignore_private_configs:
  447. prefixes.append("_")
  448. prefixes.extend(getattr(self, "_cache_config_ignore_prefix", []))
  449. return self._get_dict(ignored_prefixes=prefixes)
  450. def codegen_config(self) -> str:
  451. """Convert config to Python statements that replicate current config.
  452. This does NOT include config settings that are at default values.
  453. """
  454. # additional imports required
  455. imports = set()
  456. def get_module_name(func: Callable, add_dot: bool) -> str:
  457. module_name = func.__module__
  458. if module_name == "builtins":
  459. module_name = ""
  460. if add_dot and module_name != "":
  461. module_name += "."
  462. return module_name
  463. def add_import(func: Callable) -> None:
  464. module_name = get_module_name(func, False)
  465. if module_name:
  466. imports.add(module_name)
  467. def list_of_callables_to_string(v: Union[list, set]) -> list[str]:
  468. return [f"{get_module_name(item, True)}{item.__name__}" for item in v]
  469. def importable_callable(v: Any) -> bool:
  470. # functools.partial has no attributes below but is a callable
  471. return callable(v) and hasattr(v, "__module__") and hasattr(v, "__name__")
  472. def get_config_line(mod, k, v) -> str: # type: ignore[no-untyped-def]
  473. """
  474. Return a string version of the config line.
  475. Handle v when v is a callable, or a list/dict of callables. Add import statements for callables if necessary.
  476. We assume that the value of a single config won't be a mix of callables and non-callables.
  477. Example output:
  478. import logging
  479. import _warnings
  480. torch._dynamo.config.reorderable_logging_functions = { _warnings.warn, logging.warn, print }
  481. """
  482. if importable_callable(v):
  483. add_import(v)
  484. return f"{mod}.{k} = {get_module_name(v, True)}{v.__name__}"
  485. elif isinstance(v, (list, set)) and all(
  486. importable_callable(item) for item in v
  487. ):
  488. for item in v:
  489. add_import(item)
  490. v_list = list_of_callables_to_string(v)
  491. if isinstance(v, list):
  492. return f"{mod}.{k} = {v_list}"
  493. else:
  494. return f"{mod}.{k} = {{ {', '.join(v_list)} }}"
  495. else:
  496. return f"{mod}.{k} = {v!r}"
  497. lines = []
  498. mod = self.__name__
  499. for k, v in self._get_dict(
  500. ignored_keys=getattr(self, "_save_config_ignore", []), skip_default=True
  501. ).items():
  502. lines.append(get_config_line(mod, k, v))
  503. for import_name in imports:
  504. lines.insert(0, f"import {import_name}")
  505. return "\n".join(lines)
  506. def get_hash(self) -> bytes:
  507. """Hashes the configs that are not compile_ignored"""
  508. if self._is_dirty or self._hash_digest is None:
  509. dict_to_hash = self._get_dict(ignored_keys=list(self._compile_ignored_keys))
  510. string_to_hash = repr(sorted(dict_to_hash.items()))
  511. self._hash_digest = hashlib.md5(
  512. string_to_hash.encode("utf-8"), usedforsecurity=False
  513. ).digest()
  514. self._is_dirty = False
  515. return self._hash_digest
  516. @deprecated(
  517. "`config.to_dict()` has been deprecated. It no longer changes the underlying config."
  518. " use `config.get_config_copy()` instead if you just want a copy of the config, or "
  519. "config.load_config if you need mutable access",
  520. category=FutureWarning,
  521. )
  522. def to_dict(self) -> dict[str, Any]:
  523. return self.get_config_copy()
  524. @deprecated(
  525. "`config.shallow_copy_dict()` has been deprecated. It no longer changes the underlying config."
  526. " use `config.get_config_copy()` instead if you just want a copy of the config, or "
  527. "config.load_config if you need mutable access",
  528. category=FutureWarning,
  529. )
  530. def shallow_copy_dict(self) -> dict[str, Any]:
  531. return self.get_config_copy()
  532. def load_config(self, maybe_pickled_config: Union[bytes, dict[str, Any]]) -> None:
  533. """Restore from a prior call to save_config() or shallow_copy_dict()"""
  534. if not isinstance(maybe_pickled_config, dict):
  535. config = pickle.loads(maybe_pickled_config)
  536. else:
  537. config = maybe_pickled_config
  538. for k, v in config.items():
  539. if k in self._config:
  540. setattr(self, k, v)
  541. else:
  542. from torch._dynamo.utils import warn_once
  543. warn_once(f"key {k} with value {v} is not understood by this config")
  544. def get_config_copy(self) -> dict[str, Any]:
  545. return self._get_dict()
  546. def patch(
  547. self,
  548. arg1: Optional[Union[str, dict[str, Any]]] = None,
  549. arg2: Any = None,
  550. **kwargs: dict[str, Any],
  551. ) -> "ContextDecorator":
  552. """
  553. Decorator and/or context manager to make temporary changes to a config.
  554. As a decorator:
  555. @config.patch("name", val)
  556. @config.patch(name1=val1, name2=val2)
  557. @config.patch({"name1": val1, "name2", val2})
  558. def foo(...):
  559. ...
  560. As a context manager:
  561. with config.patch("name", val):
  562. ...
  563. """
  564. changes: dict[str, Any]
  565. if arg1 is not None:
  566. if arg2 is not None:
  567. assert isinstance(arg1, str)
  568. # patch("key", True) syntax
  569. changes = {arg1: arg2}
  570. else:
  571. assert isinstance(arg1, dict)
  572. # patch({"key": True}) syntax
  573. changes = arg1
  574. assert not kwargs
  575. else:
  576. # patch(key=True) syntax
  577. changes = kwargs
  578. assert arg2 is None
  579. assert isinstance(changes, dict), f"expected `dict` got {type(changes)}"
  580. prior: dict[str, Any] = {}
  581. config = self
  582. class ConfigPatch(ContextDecorator):
  583. def __init__(self) -> None:
  584. self.changes = changes
  585. def __enter__(self) -> None:
  586. assert not prior
  587. for key in self.changes.keys():
  588. # KeyError on invalid entry
  589. prior[key] = config.__getattr__(key)
  590. for k, v in self.changes.items():
  591. config.__setattr__(k, v)
  592. def __exit__(self, exc_type, exc_val, exc_tb): # type: ignore[no-untyped-def]
  593. for k, v in prior.items():
  594. config.__setattr__(k, v)
  595. prior.clear()
  596. return ConfigPatch()
  597. def _make_closure_patcher(self, **changes: dict[str, Any]) -> Any:
  598. """
  599. A lower-overhead version of patch() for things on the critical path.
  600. Usage:
  601. # do this off the critical path
  602. change_fn = config.make_closure_patcher(foo=True)
  603. ...
  604. revert = change_fn()
  605. try:
  606. ...
  607. finally:
  608. revert()
  609. """
  610. config = self._config
  611. def change() -> Callable[[], None]:
  612. prior = {k: config[k].user_override for k in changes}
  613. for k, v in changes.items():
  614. self._config[k].user_override = v
  615. def revert() -> None:
  616. for k, v in prior.items():
  617. self._config[k].user_override = v
  618. return revert
  619. return change
  620. class ContextDecorator(contextlib.ContextDecorator):
  621. """
  622. Same as contextlib.ContextDecorator, but with support for
  623. `unittest.TestCase`
  624. """
  625. def __enter__(self) -> None:
  626. raise NotImplementedError("NYI")
  627. def __exit__(self, exc_type, exc_val, exc_tb) -> NoReturn: # type: ignore[no-untyped-def]
  628. raise NotImplementedError("NYI")
  629. def __call__(self, func: Callable[[Any], Any]) -> Any:
  630. if isinstance(func, type) and issubclass(func, unittest.TestCase):
  631. class _TestCase(func): # type: ignore[valid-type, misc]
  632. @classmethod
  633. def setUpClass(cls) -> None:
  634. self.__enter__()
  635. try:
  636. super().setUpClass()
  637. except Exception:
  638. self.__exit__(None, None, None)
  639. raise
  640. @classmethod
  641. def tearDownClass(cls) -> None:
  642. try:
  643. super().tearDownClass()
  644. finally:
  645. self.__exit__(None, None, None)
  646. _TestCase.__name__ = func.__name__
  647. _TestCase.__qualname__ = func.__qualname__
  648. _TestCase.__module__ = func.__module__
  649. return _TestCase
  650. return super().__call__(func)
  651. class SubConfigProxy:
  652. """
  653. Shim to redirect to main config.
  654. `config.triton.cudagraphs` maps to _config["triton.cudagraphs"]
  655. """
  656. def __init__(self, config: object, prefix: str):
  657. # `super().__setattr__` to bypass custom `__setattr__`
  658. super().__setattr__("_config", config)
  659. super().__setattr__("_prefix", prefix)
  660. def __setattr__(self, name: str, value: object) -> None:
  661. return self._config.__setattr__(self._prefix + name, value)
  662. def __getattr__(self, name: str) -> Any:
  663. return self._config.__getattr__(self._prefix + name)
  664. def __delattr__(self, name: str) -> None:
  665. return self._config.__delattr__(self._prefix + name)
  666. def patch_object(obj: object, name: str, value: object) -> object:
  667. """
  668. Workaround `mock.patch.object` issue with ConfigModule
  669. """
  670. if isinstance(obj, ConfigModule):
  671. return obj.patch(name, value)
  672. return mock.patch.object(obj, name, value)
  673. def get_tristate_env(name: str, default: Any = None) -> Optional[bool]:
  674. value = os.environ.get(name)
  675. if value == "1":
  676. return True
  677. if value == "0":
  678. return False
  679. return default