_utils_internal.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. # mypy: allow-untyped-defs
  2. import functools
  3. import logging
  4. import os
  5. import sys
  6. import tempfile
  7. import typing_extensions
  8. from collections.abc import Callable
  9. from typing import Any, TypeVar
  10. from typing_extensions import ParamSpec
  11. import torch
  12. from torch._strobelight.compile_time_profiler import StrobelightCompileTimeProfiler
  13. _T = TypeVar("_T")
  14. _P = ParamSpec("_P")
  15. log = logging.getLogger(__name__)
  16. if os.environ.get("TORCH_COMPILE_STROBELIGHT", False):
  17. import shutil
  18. if not shutil.which("strobeclient"):
  19. log.info(
  20. "TORCH_COMPILE_STROBELIGHT is true, but seems like you are not on a FB machine."
  21. )
  22. else:
  23. log.info("Strobelight profiler is enabled via environment variable")
  24. StrobelightCompileTimeProfiler.enable()
  25. # this arbitrary-looking assortment of functionality is provided here
  26. # to have a central place for overridable behavior. The motivating
  27. # use is the FB build environment, where this source file is replaced
  28. # by an equivalent.
  29. if os.path.basename(os.path.dirname(__file__)) == "shared":
  30. torch_parent = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
  31. else:
  32. torch_parent = os.path.dirname(os.path.dirname(__file__))
  33. def get_file_path(*path_components: str) -> str:
  34. return os.path.join(torch_parent, *path_components)
  35. def get_file_path_2(*path_components: str) -> str:
  36. return os.path.join(*path_components)
  37. def get_writable_path(path: str) -> str:
  38. if os.access(path, os.W_OK):
  39. return path
  40. return tempfile.mkdtemp(suffix=os.path.basename(path))
  41. def prepare_multiprocessing_environment(path: str) -> None:
  42. pass
  43. def resolve_library_path(path: str) -> str:
  44. return os.path.realpath(path)
  45. def throw_abstract_impl_not_imported_error(opname, module, context):
  46. if module in sys.modules:
  47. raise NotImplementedError(
  48. f"{opname}: We could not find the fake impl for this operator. "
  49. )
  50. else:
  51. raise NotImplementedError(
  52. f"{opname}: We could not find the fake impl for this operator. "
  53. f"The operator specified that you may need to import the '{module}' "
  54. f"Python module to load the fake impl. {context}"
  55. )
  56. # NB! This treats "skip" kwarg specially!!
  57. def compile_time_strobelight_meta(
  58. phase_name: str,
  59. ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
  60. def compile_time_strobelight_meta_inner(
  61. function: Callable[_P, _T],
  62. ) -> Callable[_P, _T]:
  63. @functools.wraps(function)
  64. def wrapper_function(*args: _P.args, **kwargs: _P.kwargs) -> _T:
  65. if "skip" in kwargs and isinstance(
  66. skip := kwargs["skip"],
  67. int,
  68. ):
  69. kwargs["skip"] = skip + 1
  70. # This is not needed but we have it here to avoid having profile_compile_time
  71. # in stack traces when profiling is not enabled.
  72. if not StrobelightCompileTimeProfiler.enabled:
  73. return function(*args, **kwargs)
  74. return StrobelightCompileTimeProfiler.profile_compile_time(
  75. function, phase_name, *args, **kwargs
  76. )
  77. return wrapper_function
  78. return compile_time_strobelight_meta_inner
  79. # Meta only, see
  80. # https://www.internalfb.com/intern/wiki/ML_Workflow_Observability/User_Guides/Adding_instrumentation_to_your_code/
  81. #
  82. # This will cause an event to get logged to Scuba via the signposts API. You
  83. # can view samples on the API at https://fburl.com/scuba/workflow_signpost/zh9wmpqs
  84. # we log to subsystem "torch", and the category and name you provide here.
  85. # Each of the arguments translate into a Scuba column. We're still figuring
  86. # out local conventions in PyTorch, but category should be something like
  87. # "dynamo" or "inductor", and name should be a specific string describing what
  88. # kind of event happened.
  89. #
  90. # Killswitch is at
  91. # https://www.internalfb.com/intern/justknobs/?name=pytorch%2Fsignpost#event
  92. def signpost_event(category: str, name: str, parameters: dict[str, Any]):
  93. log.info("%s %s: %r", category, name, parameters)
  94. def add_mlhub_insight(category: str, insight: str, insight_description: str):
  95. pass
  96. def log_compilation_event(metrics):
  97. log.info("%s", metrics)
  98. def upload_graph(graph):
  99. pass
  100. def set_pytorch_distributed_envs_from_justknobs():
  101. pass
  102. def log_export_usage(**kwargs):
  103. pass
  104. def log_draft_export_usage(**kwargs):
  105. pass
  106. def log_trace_structured_event(*args, **kwargs) -> None:
  107. pass
  108. def log_cache_bypass(*args, **kwargs) -> None:
  109. pass
  110. def log_torchscript_usage(api: str, **kwargs):
  111. _ = api
  112. return
  113. def check_if_torch_exportable():
  114. return False
  115. def export_training_ir_rollout_check() -> bool:
  116. return True
  117. def full_aoti_runtime_assert() -> bool:
  118. return True
  119. def log_torch_jit_trace_exportability(
  120. api: str,
  121. type_of_export: str,
  122. export_outcome: str,
  123. result: str,
  124. ):
  125. _, _, _, _ = api, type_of_export, export_outcome, result
  126. return
  127. DISABLE_JUSTKNOBS = True
  128. def justknobs_check(name: str, default: bool = True) -> bool:
  129. """
  130. This function can be used to killswitch functionality in FB prod,
  131. where you can toggle this value to False in JK without having to
  132. do a code push. In OSS, we always have everything turned on all
  133. the time, because downstream users can simply choose to not update
  134. PyTorch. (If more fine-grained enable/disable is needed, we could
  135. potentially have a map we lookup name in to toggle behavior. But
  136. the point is that it's all tied to source code in OSS, since there's
  137. no live server to query.)
  138. This is the bare minimum functionality I needed to do some killswitches.
  139. We have a more detailed plan at
  140. https://docs.google.com/document/d/1Ukerh9_42SeGh89J-tGtecpHBPwGlkQ043pddkKb3PU/edit
  141. In particular, in some circumstances it may be necessary to read in
  142. a knob once at process start, and then use it consistently for the
  143. rest of the process. Future functionality will codify these patterns
  144. into a better high level API.
  145. WARNING: Do NOT call this function at module import time, JK is not
  146. fork safe and you will break anyone who forks the process and then
  147. hits JK again.
  148. """
  149. return default
  150. def justknobs_getval_int(name: str) -> int:
  151. """
  152. Read warning on justknobs_check
  153. """
  154. return 0
  155. def is_fb_unit_test() -> bool:
  156. return False
  157. @functools.cache
  158. def max_clock_rate():
  159. """
  160. unit: MHz
  161. """
  162. if not torch.version.hip:
  163. from triton.testing import nvsmi
  164. return nvsmi(["clocks.max.sm"])[0]
  165. else:
  166. # Manually set max-clock speeds on ROCm until equivalent nvmsi
  167. # functionality in triton.testing or via pyamdsmi enablement. Required
  168. # for test_snode_runtime unit tests.
  169. gcn_arch = str(torch.cuda.get_device_properties(0).gcnArchName.split(":", 1)[0])
  170. if "gfx94" in gcn_arch:
  171. return 1700
  172. elif "gfx90a" in gcn_arch:
  173. return 1700
  174. elif "gfx908" in gcn_arch:
  175. return 1502
  176. elif "gfx12" in gcn_arch:
  177. return 1700
  178. elif "gfx11" in gcn_arch:
  179. return 1700
  180. elif "gfx103" in gcn_arch:
  181. return 1967
  182. elif "gfx101" in gcn_arch:
  183. return 1144
  184. elif "gfx95" in gcn_arch:
  185. return 1700 # TODO: placeholder, get actual value
  186. else:
  187. return 1100
  188. def get_mast_job_name_version() -> tuple[str, int] | None:
  189. return None
  190. TEST_MASTER_ADDR = "127.0.0.1"
  191. TEST_MASTER_PORT = 29500
  192. # USE_GLOBAL_DEPS controls whether __init__.py tries to load
  193. # libtorch_global_deps, see Note [Global dependencies]
  194. USE_GLOBAL_DEPS = True
  195. # USE_RTLD_GLOBAL_WITH_LIBTORCH controls whether __init__.py tries to load
  196. # _C.so with RTLD_GLOBAL during the call to dlopen.
  197. USE_RTLD_GLOBAL_WITH_LIBTORCH = False
  198. # If an op was defined in C++ and extended from Python using the
  199. # torch.library.register_fake, returns if we require that there be a
  200. # m.set_python_module("mylib.ops") call from C++ that associates
  201. # the C++ op with a python module.
  202. REQUIRES_SET_PYTHON_MODULE = False
  203. def maybe_upload_prof_stats_to_manifold(profile_path: str) -> str | None:
  204. print("Uploading profile stats (fb-only otherwise no-op)")
  205. return None
  206. def log_chromium_event_internal(
  207. event: dict[str, Any],
  208. stack: list[str],
  209. logger_uuid: str,
  210. start_time_ns: int,
  211. ):
  212. return None
  213. def record_chromium_event_internal(
  214. event: dict[str, Any],
  215. ):
  216. return None
  217. def profiler_allow_cudagraph_cupti_lazy_reinit_cuda12():
  218. return True
  219. def deprecated():
  220. """
  221. When we deprecate a function that might still be in use, we make it internal
  222. by adding a leading underscore. This decorator is used with a private function,
  223. and creates a public alias without the leading underscore, but has a deprecation
  224. warning. This tells users "THIS FUNCTION IS DEPRECATED, please use something else"
  225. without breaking them, however, if they still really really want to use the
  226. deprecated function without the warning, they can do so by using the internal
  227. function name.
  228. """
  229. def decorator(func: Callable[_P, _T]) -> Callable[_P, _T]:
  230. # Validate naming convention - single leading underscore, not dunder
  231. if not (func.__name__.startswith("_")):
  232. raise ValueError(
  233. "@deprecate must decorate a function whose name "
  234. "starts with a single leading underscore (e.g. '_foo') as the api should be considered internal for deprecation."
  235. )
  236. public_name = func.__name__[1:] # drop exactly one leading underscore
  237. module = sys.modules[func.__module__]
  238. # Don't clobber an existing symbol accidentally.
  239. if hasattr(module, public_name):
  240. raise RuntimeError(
  241. f"Cannot create alias '{public_name}' -> symbol already exists in {module.__name__}. \
  242. Please rename it or consult a pytorch developer on what to do"
  243. )
  244. warning_msg = f"{func.__name__[1:]} is DEPRECATED, please consider using an alternative API(s). "
  245. # public deprecated alias
  246. alias = typing_extensions.deprecated(
  247. # pyrefly: ignore [bad-argument-type]
  248. warning_msg,
  249. category=UserWarning,
  250. stacklevel=1,
  251. )(func)
  252. alias.__name__ = public_name
  253. # Adjust qualname if nested inside a class or another function
  254. if "." in func.__qualname__:
  255. alias.__qualname__ = func.__qualname__.rsplit(".", 1)[0] + "." + public_name
  256. else:
  257. alias.__qualname__ = public_name
  258. setattr(module, public_name, alias)
  259. return func
  260. return decorator
  261. def get_default_numa_options():
  262. """
  263. When using elastic agent, if no numa options are provided, we will use these
  264. as the default.
  265. For external use cases, we return None, i.e. no numa binding. If you would like
  266. to use torch's automatic numa binding capabilities, you should provide
  267. NumaOptions to your launch config directly or use the numa binding option
  268. available in torchrun.
  269. Must return None or NumaOptions, but not specifying to avoid circular import.
  270. """
  271. return None
  272. def log_triton_builds(fail: str | None):
  273. pass
  274. def find_compile_subproc_binary() -> str | None:
  275. """
  276. Allows overriding the binary used for subprocesses
  277. """
  278. return None