__init__.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930
  1. # mypy: allow-untyped-defs
  2. r"""
  3. This package adds support for CUDA tensor types.
  4. It implements the same function as CPU tensors, but they utilize
  5. GPUs for computation.
  6. It is lazily initialized, so you can always import it, and use
  7. :func:`is_available()` to determine if your system supports CUDA.
  8. :ref:`cuda-semantics` has more details about working with CUDA.
  9. """
  10. import importlib
  11. import os
  12. import sys
  13. import threading
  14. import traceback
  15. import warnings
  16. from functools import lru_cache
  17. from typing import Any, Callable, cast, NewType, Optional, TYPE_CHECKING, Union
  18. import torch
  19. import torch._C
  20. from torch import device as _device
  21. from torch._utils import _dummy_type, _LazySeedTracker, classproperty
  22. from . import gds
  23. from ._utils import _get_device_index
  24. from .graphs import (
  25. CUDAGraph,
  26. graph,
  27. graph_pool_handle,
  28. is_current_stream_capturing,
  29. make_graphed_callables,
  30. )
  31. from .streams import Event, ExternalStream, Stream
  32. if TYPE_CHECKING:
  33. from torch.types import Device
  34. try:
  35. from torch._C import _cudart # type: ignore[attr-defined]
  36. except ImportError:
  37. _cudart = None
  38. _initialized = False
  39. _tls = threading.local()
  40. _initialization_lock = threading.Lock()
  41. _queued_calls: list[
  42. tuple[Callable[[], None], list[str]]
  43. ] = [] # don't invoke these until initialization occurs
  44. _is_in_bad_fork = getattr(torch._C, "_cuda_isInBadFork", lambda: False)
  45. _HAS_PYNVML = False
  46. _PYNVML_ERR = None
  47. try:
  48. from torch import version as _version
  49. try:
  50. if not _version.hip:
  51. import pynvml # type: ignore[import]
  52. else:
  53. import ctypes
  54. from pathlib import Path
  55. # In ROCm (at least up through 6.3.2) there're 2 copies of libamd_smi.so:
  56. # - One at lib/libamd_smi.so
  57. # - One at share/amd_smi/amdsmi/libamd_smi.so
  58. #
  59. # The amdsmi python module hardcodes loading the second one in share-
  60. # https://github.com/ROCm/amdsmi/blob/1d305dc9708e87080f64f668402887794cd46584/py-interface/amdsmi_wrapper.py#L174
  61. #
  62. # See also https://github.com/ROCm/amdsmi/issues/72.
  63. #
  64. # This creates an ODR violation if the copy of libamd_smi.so from lib
  65. # is also loaded (via `ld` linking, `LD_LIBRARY_PATH` or `rpath`).
  66. #
  67. # In order to avoid the violation we hook CDLL and try using the
  68. # already loaded version of amdsmi, or any version in the processes
  69. # rpath/LD_LIBRARY_PATH first, so that we only load a single copy
  70. # of the .so.
  71. class _amdsmi_cdll_hook:
  72. def __init__(self) -> None:
  73. self.original_CDLL = ctypes.CDLL # type: ignore[misc,assignment]
  74. paths = ["libamd_smi.so"]
  75. if rocm_home := os.getenv("ROCM_HOME", os.getenv("ROCM_PATH")):
  76. paths = [os.path.join(rocm_home, "lib/libamd_smi.so")] + paths
  77. self.paths: list[str] = paths
  78. def hooked_CDLL(
  79. self, name: Union[str, Path, None], *args: Any, **kwargs: Any
  80. ) -> ctypes.CDLL:
  81. if name and Path(name).name == "libamd_smi.so":
  82. for path in self.paths:
  83. try:
  84. return self.original_CDLL(path, *args, **kwargs)
  85. except OSError:
  86. pass
  87. return self.original_CDLL(name, *args, **kwargs) # type: ignore[arg-type]
  88. def __enter__(self) -> None:
  89. ctypes.CDLL = self.hooked_CDLL # type: ignore[misc,assignment]
  90. def __exit__(self, type: Any, value: Any, traceback: Any) -> None:
  91. ctypes.CDLL = self.original_CDLL # type: ignore[misc]
  92. with _amdsmi_cdll_hook():
  93. import amdsmi # type: ignore[import]
  94. _HAS_PYNVML = True
  95. except ModuleNotFoundError:
  96. pass
  97. finally:
  98. del _version
  99. except ImportError as err:
  100. _PYNVML_ERR = err # sometimes a lib is installed but the import fails for some other reason, so we log the error for later
  101. _lazy_seed_tracker = _LazySeedTracker()
  102. # Define dummy _CudaDeviceProperties type if PyTorch was compiled without CUDA
  103. if hasattr(torch._C, "_CudaDeviceProperties"):
  104. _CudaDeviceProperties = torch._C._CudaDeviceProperties
  105. else:
  106. _CudaDeviceProperties = _dummy_type("_CudaDeviceProperties") # type: ignore[assignment, misc]
  107. if hasattr(torch._C, "_cuda_exchangeDevice"):
  108. _exchange_device = torch._C._cuda_exchangeDevice
  109. else:
  110. def _exchange_device(device: int) -> int:
  111. if device < 0:
  112. return -1
  113. raise RuntimeError("PyTorch was compiled without CUDA support")
  114. if hasattr(torch._C, "_cuda_maybeExchangeDevice"):
  115. _maybe_exchange_device = torch._C._cuda_maybeExchangeDevice
  116. else:
  117. def _maybe_exchange_device(device: int) -> int:
  118. if device < 0:
  119. return -1
  120. raise RuntimeError("PyTorch was compiled without CUDA support")
  121. has_half: bool = True
  122. has_magma: bool = torch._C._has_magma
  123. default_generators: tuple[torch._C.Generator] = () # type: ignore[assignment]
  124. def _is_compiled() -> bool:
  125. r"""Return true if compile with CUDA support."""
  126. return hasattr(torch._C, "_cuda_getDeviceCount")
  127. def _nvml_based_avail() -> bool:
  128. return os.getenv("PYTORCH_NVML_BASED_CUDA_CHECK") == "1"
  129. def is_available() -> bool:
  130. r"""
  131. Return a bool indicating if CUDA is currently available.
  132. .. note:: This function will NOT poison fork if the environment variable
  133. ``PYTORCH_NVML_BASED_CUDA_CHECK=1`` is set. For more details, see
  134. :ref:`multiprocessing-poison-fork-note`.
  135. """
  136. if not _is_compiled():
  137. return False
  138. if _nvml_based_avail():
  139. # The user has set an env variable to request this availability check that attempts to avoid fork poisoning by
  140. # using NVML at the cost of a weaker CUDA availability assessment. Note that if NVML discovery/initialization
  141. # fails, this assessment falls back to the default CUDA Runtime API assessment (`cudaGetDeviceCount`)
  142. return device_count() > 0
  143. else:
  144. # The default availability inspection never throws and returns 0 if the driver is missing or can't
  145. # be initialized. This uses the CUDA Runtime API `cudaGetDeviceCount` which in turn initializes the CUDA Driver
  146. # API via `cuInit`
  147. return torch._C._cuda_getDeviceCount() > 0
  148. def is_bf16_supported(including_emulation: bool = True):
  149. r"""Return a bool indicating if the current CUDA/ROCm device supports dtype bfloat16."""
  150. # Check for ROCm, if true return true, no ROCM_VERSION check required,
  151. # since it is supported on AMD GPU archs.
  152. if torch.version.hip:
  153. return True
  154. # If CUDA is not available, than it does not support bf16 either
  155. if not is_available():
  156. return False
  157. device = torch.cuda.current_device()
  158. # Check for CUDA version and device compute capability.
  159. # This is a fast way to check for it.
  160. cuda_version = torch.version.cuda
  161. if cuda_version is not None and torch.cuda.get_device_properties(device).major >= 8:
  162. return True
  163. if not including_emulation:
  164. return False
  165. # Finally try to create a bfloat16 device.
  166. return _check_bf16_tensor_supported(device)
  167. @lru_cache(maxsize=16)
  168. def _check_bf16_tensor_supported(device: "Device"):
  169. try:
  170. torch.tensor([1.0], dtype=torch.bfloat16, device=device)
  171. return True
  172. except Exception:
  173. return False
  174. def is_tf32_supported() -> bool:
  175. r"""Return a bool indicating if the current CUDA/ROCm device supports dtype tf32."""
  176. if torch.version.hip:
  177. prop_name = torch.cuda.get_device_properties().gcnArchName
  178. archs = ("gfx94", "gfx95")
  179. for arch in archs:
  180. if arch in prop_name:
  181. return True
  182. return False
  183. # Otherwise, tf32 is supported on CUDA platforms that natively (i.e. no emulation)
  184. # support bfloat16.
  185. return is_bf16_supported(including_emulation=False)
  186. def _sleep(cycles):
  187. torch._C._cuda_sleep(cycles)
  188. def _extract_arch_version(arch_string: str) -> int:
  189. """Extracts the architecture string from a CUDA version"""
  190. base = arch_string.split("_", maxsplit=2)[1]
  191. base = base.removesuffix("a").removesuffix("f")
  192. return int(base)
  193. def _check_capability():
  194. incompatible_gpu_warn = """
  195. Found GPU%d %s which is of cuda capability %d.%d.
  196. Minimum and Maximum cuda capability supported by this version of PyTorch is
  197. (%d.%d) - (%d.%d)
  198. """
  199. matched_cuda_warn = """
  200. Please install PyTorch with a following CUDA
  201. configurations: {} following instructions at
  202. https://pytorch.org/get-started/locally/
  203. """
  204. # Binary CUDA_ARCHES SUPPORTED by PyTorch
  205. CUDA_ARCHES_SUPPORTED = {
  206. "12.6": {"min": 50, "max": 90},
  207. "12.8": {"min": 70, "max": 120},
  208. "13.0": {"min": 75, "max": 120},
  209. }
  210. if (
  211. torch.version.cuda is not None and torch.cuda.get_arch_list()
  212. ): # on ROCm we don't want this check
  213. for d in range(device_count()):
  214. capability = get_device_capability(d)
  215. major = capability[0]
  216. minor = capability[1]
  217. name = get_device_name(d)
  218. current_arch = major * 10 + minor
  219. min_arch = min(
  220. (_extract_arch_version(arch) for arch in torch.cuda.get_arch_list()),
  221. default=50,
  222. )
  223. max_arch = max(
  224. (_extract_arch_version(arch) for arch in torch.cuda.get_arch_list()),
  225. default=50,
  226. )
  227. if current_arch < min_arch or current_arch > max_arch:
  228. warnings.warn(
  229. incompatible_gpu_warn
  230. % (
  231. d,
  232. name,
  233. major,
  234. minor,
  235. min_arch // 10,
  236. min_arch % 10,
  237. max_arch // 10,
  238. max_arch % 10,
  239. )
  240. )
  241. matched_arches = ""
  242. for arch, arch_info in CUDA_ARCHES_SUPPORTED.items():
  243. if (
  244. current_arch >= arch_info["min"]
  245. and current_arch <= arch_info["max"]
  246. ):
  247. matched_arches += f" {arch}"
  248. if matched_arches != "":
  249. warnings.warn(matched_cuda_warn.format(matched_arches))
  250. def _check_cubins():
  251. incompatible_device_warn = """
  252. {} with CUDA capability sm_{} is not compatible with the current PyTorch installation.
  253. The current PyTorch install supports CUDA capabilities {}.
  254. If you want to use the {} GPU with PyTorch, please check the instructions at https://pytorch.org/get-started/locally/
  255. """
  256. if torch.version.cuda is None: # on ROCm we don't want this check
  257. return
  258. arch_list = get_arch_list()
  259. if len(arch_list) == 0:
  260. return
  261. supported_sm = [_extract_arch_version(arch) for arch in arch_list if "sm_" in arch]
  262. for idx in range(device_count()):
  263. cap_major, cap_minor = get_device_capability(idx)
  264. # NVIDIA GPU compute architectures are backward compatible within major version
  265. supported = any(sm // 10 == cap_major for sm in supported_sm)
  266. if not supported:
  267. device_name = get_device_name(idx)
  268. capability = cap_major * 10 + cap_minor
  269. warnings.warn(
  270. incompatible_device_warn.format(
  271. device_name, capability, " ".join(arch_list), device_name
  272. )
  273. )
  274. def is_initialized():
  275. r"""Return whether PyTorch's CUDA state has been initialized."""
  276. return _initialized and not _is_in_bad_fork()
  277. def _lazy_call(callable, **kwargs):
  278. with _initialization_lock:
  279. if is_initialized():
  280. callable()
  281. else:
  282. # TODO(torch_deploy): this accesses linecache, which attempts to read the
  283. # file system to get traceback info. Patch linecache or do something
  284. # else here if this ends up being important.
  285. global _lazy_seed_tracker
  286. if kwargs.get("seed_all", False):
  287. _lazy_seed_tracker.queue_seed_all(callable, traceback.format_stack())
  288. elif kwargs.get("seed", False):
  289. _lazy_seed_tracker.queue_seed(callable, traceback.format_stack())
  290. else:
  291. # Don't store the actual traceback to avoid memory cycle
  292. _queued_calls.append((callable, traceback.format_stack()))
  293. _lazy_call(_check_capability)
  294. _lazy_call(_check_cubins)
  295. class DeferredCudaCallError(Exception):
  296. pass
  297. AcceleratorError = torch._C.AcceleratorError
  298. OutOfMemoryError = torch._C.OutOfMemoryError
  299. def init():
  300. r"""Initialize PyTorch's CUDA state.
  301. You may need to call this explicitly if you are interacting with
  302. PyTorch via its C API, as Python bindings for CUDA functionality
  303. will not be available until this initialization takes place.
  304. Ordinary users should not need this, as all of PyTorch's CUDA methods
  305. automatically initialize CUDA state on-demand.
  306. Does nothing if the CUDA state is already initialized.
  307. """
  308. _lazy_init()
  309. def _lazy_init():
  310. global _initialized, _queued_calls
  311. if is_initialized() or hasattr(_tls, "is_initializing"):
  312. return
  313. with _initialization_lock:
  314. # We be double-checked locking, boys! This is OK because
  315. # the above test was GIL protected anyway. The inner test
  316. # is for when a thread blocked on some other thread which was
  317. # doing the initialization; when they get the lock, they will
  318. # find there is nothing left to do.
  319. if is_initialized():
  320. return
  321. # It is important to prevent other threads from entering _lazy_init
  322. # immediately, while we are still guaranteed to have the GIL, because some
  323. # of the C calls we make below will release the GIL
  324. if _is_in_bad_fork():
  325. raise RuntimeError(
  326. "Cannot re-initialize CUDA in forked subprocess. To use CUDA with "
  327. "multiprocessing, you must use the 'spawn' start method"
  328. )
  329. if not hasattr(torch._C, "_cuda_getDeviceCount"):
  330. raise AssertionError("Torch not compiled with CUDA enabled")
  331. if _cudart is None:
  332. raise AssertionError(
  333. "libcudart functions unavailable. It looks like you have a broken build?"
  334. )
  335. # This function throws if there's a driver initialization error, no GPUs
  336. # are found or any other error occurs
  337. torch._C._cuda_init()
  338. # Some of the queued calls may reentrantly call _lazy_init();
  339. # we need to just return without initializing in that case.
  340. # However, we must not let any *other* threads in!
  341. _tls.is_initializing = True
  342. _queued_calls.extend(calls for calls in _lazy_seed_tracker.get_calls() if calls)
  343. try:
  344. for queued_call, orig_traceback in _queued_calls:
  345. try:
  346. queued_call()
  347. except Exception as e:
  348. msg = (
  349. f"CUDA call failed lazily at initialization with error: {str(e)}\n\n"
  350. f"CUDA call was originally invoked at:\n\n{''.join(orig_traceback)}"
  351. )
  352. raise DeferredCudaCallError(msg) from e
  353. finally:
  354. delattr(_tls, "is_initializing")
  355. _initialized = True
  356. def cudart():
  357. r"""Retrieves the CUDA runtime API module.
  358. This function initializes the CUDA runtime environment if it is not already
  359. initialized and returns the CUDA runtime API module (_cudart). The CUDA
  360. runtime API module provides access to various CUDA runtime functions.
  361. Args:
  362. ``None``
  363. Returns:
  364. module: The CUDA runtime API module (_cudart).
  365. Raises:
  366. RuntimeError: If CUDA cannot be re-initialized in a forked subprocess.
  367. AssertionError: If PyTorch is not compiled with CUDA support or if libcudart functions are unavailable.
  368. Example of CUDA operations with profiling:
  369. >>> import torch
  370. >>> from torch.cuda import cudart, check_error
  371. >>> import os
  372. >>>
  373. >>> os.environ["CUDA_PROFILE"] = "1"
  374. >>>
  375. >>> def perform_cuda_operations_with_streams():
  376. >>> stream = torch.cuda.Stream()
  377. >>> with torch.cuda.stream(stream):
  378. >>> x = torch.randn(100, 100, device='cuda')
  379. >>> y = torch.randn(100, 100, device='cuda')
  380. >>> z = torch.mul(x, y)
  381. >>> return z
  382. >>>
  383. >>> torch.cuda.synchronize()
  384. >>> print("====== Start nsys profiling ======")
  385. >>> check_error(cudart().cudaProfilerStart())
  386. >>> with torch.autograd.profiler.emit_nvtx():
  387. >>> result = perform_cuda_operations_with_streams()
  388. >>> print("CUDA operations completed.")
  389. >>> check_error(torch.cuda.cudart().cudaProfilerStop())
  390. >>> print("====== End nsys profiling ======")
  391. To run this example and save the profiling information, execute:
  392. >>> $ nvprof --profile-from-start off --csv --print-summary -o trace_name.prof -f -- python cudart_test.py
  393. This command profiles the CUDA operations in the provided script and saves
  394. the profiling information to a file named `trace_name.prof`.
  395. The `--profile-from-start off` option ensures that profiling starts only
  396. after the `cudaProfilerStart` call in the script.
  397. The `--csv` and `--print-summary` options format the profiling output as a
  398. CSV file and print a summary, respectively.
  399. The `-o` option specifies the output file name, and the `-f` option forces the
  400. overwrite of the output file if it already exists.
  401. """
  402. _lazy_init()
  403. return _cudart
  404. class cudaStatus:
  405. SUCCESS: int = 0
  406. ERROR_NOT_READY: int = 34
  407. class CudaError(RuntimeError):
  408. def __init__(self, code: int) -> None:
  409. msg = _cudart.cudaGetErrorString(_cudart.cudaError(code))
  410. super().__init__(f"{msg} ({code})")
  411. def check_error(res: int) -> None:
  412. if res != _cudart.cudaError.success:
  413. raise CudaError(res)
  414. class _DeviceGuard:
  415. def __init__(self, index: int):
  416. self.idx = index
  417. self.prev_idx = -1
  418. def __enter__(self):
  419. self.prev_idx = torch.cuda._exchange_device(self.idx)
  420. def __exit__(self, type: Any, value: Any, traceback: Any):
  421. self.idx = torch.cuda._maybe_exchange_device(self.prev_idx)
  422. return False
  423. class device:
  424. r"""Context-manager that changes the selected device.
  425. Args:
  426. device (torch.device or int): device index to select. It's a no-op if
  427. this argument is a negative integer or ``None``.
  428. """
  429. def __init__(self, device: Any):
  430. self.idx = _get_device_index(device, optional=True)
  431. self.prev_idx = -1
  432. def __enter__(self):
  433. self.prev_idx = torch.cuda._exchange_device(self.idx)
  434. def __exit__(self, type: Any, value: Any, traceback: Any):
  435. self.idx = torch.cuda._maybe_exchange_device(self.prev_idx)
  436. return False
  437. class device_of(device):
  438. r"""Context-manager that changes the current device to that of given object.
  439. You can use both tensors and storages as arguments. If a given object is
  440. not allocated on a GPU, this is a no-op.
  441. Args:
  442. obj (Tensor or Storage): object allocated on the selected device.
  443. """
  444. def __init__(self, obj):
  445. idx = obj.get_device() if obj.is_cuda else -1
  446. super().__init__(idx)
  447. def set_device(device: "Device") -> None:
  448. r"""Set the current device.
  449. Usage of this function is discouraged in favor of :any:`device`. In most
  450. cases it's better to use ``CUDA_VISIBLE_DEVICES`` environmental variable.
  451. Args:
  452. device (torch.device or int): selected device. This function is a no-op
  453. if this argument is negative.
  454. """
  455. device = _get_device_index(device)
  456. if device >= 0:
  457. torch._C._cuda_setDevice(device)
  458. def get_device_name(device: "Device" = None) -> str:
  459. r"""Get the name of a device.
  460. Args:
  461. device (torch.device or int or str, optional): device for which to return the
  462. name. This function is a no-op if this argument is a negative
  463. integer. It uses the current device, given by :func:`~torch.cuda.current_device`,
  464. if :attr:`device` is ``None`` (default).
  465. Returns:
  466. str: the name of the device
  467. """
  468. return get_device_properties(device).name
  469. def get_device_capability(device: "Device" = None) -> tuple[int, int]:
  470. r"""Get the cuda capability of a device.
  471. Args:
  472. device (torch.device or int or str, optional): device for which to return the
  473. device capability. This function is a no-op if this argument is
  474. a negative integer. It uses the current device, given by
  475. :func:`~torch.cuda.current_device`, if :attr:`device` is ``None``
  476. (default).
  477. Returns:
  478. tuple(int, int): the major and minor cuda capability of the device
  479. """
  480. prop = get_device_properties(device)
  481. return prop.major, prop.minor
  482. def get_device_properties(device: "Device" = None) -> _CudaDeviceProperties:
  483. r"""Get the properties of a device.
  484. Args:
  485. device (torch.device or int or str, optional): device for which to return the
  486. properties of the device. It uses the current device, given by
  487. :func:`~torch.cuda.current_device`, if :attr:`device` is ``None``
  488. (default).
  489. Returns:
  490. _CudaDeviceProperties: the properties of the device
  491. """
  492. _lazy_init() # will define _get_device_properties
  493. device = _get_device_index(device, optional=True)
  494. if device < 0 or device >= device_count():
  495. raise AssertionError("Invalid device id")
  496. return _get_device_properties(device) # type: ignore[name-defined]
  497. def can_device_access_peer(device: "Device", peer_device: "Device") -> bool:
  498. r"""Check if peer access between two devices is possible."""
  499. _lazy_init()
  500. device = _get_device_index(device, optional=True)
  501. peer_device = _get_device_index(peer_device)
  502. if device < 0 or device >= device_count():
  503. raise AssertionError("Invalid device id")
  504. if peer_device < 0 or peer_device >= device_count():
  505. raise AssertionError("Invalid peer device id")
  506. return torch._C._cuda_canDeviceAccessPeer(device, peer_device)
  507. class StreamContext:
  508. r"""Context-manager that selects a given stream.
  509. All CUDA kernels queued within its context will be enqueued on a selected
  510. stream.
  511. Args:
  512. Stream (Stream): selected stream. This manager is a no-op if it's
  513. ``None``.
  514. .. note:: Streams are per-device.
  515. """
  516. cur_stream: Optional["torch.cuda.Stream"]
  517. def __init__(self, stream: Optional["torch.cuda.Stream"]):
  518. self.stream = stream
  519. self.idx = _get_device_index(None, True)
  520. if not torch.jit.is_scripting():
  521. if self.idx is None:
  522. self.idx = -1
  523. self.src_prev_stream = (
  524. None if not torch.jit.is_scripting() else torch.cuda.default_stream(None)
  525. )
  526. self.dst_prev_stream = (
  527. None if not torch.jit.is_scripting() else torch.cuda.default_stream(None)
  528. )
  529. def __enter__(self):
  530. # Local cur_stream variable for type refinement
  531. cur_stream = self.stream
  532. # Return if stream is None or CUDA device not available
  533. if cur_stream is None or self.idx == -1:
  534. return
  535. self.src_prev_stream = torch.cuda.current_stream(None)
  536. # If the stream is not on the current device, then
  537. # set the current stream on the device
  538. if self.src_prev_stream.device != cur_stream.device:
  539. with device(cur_stream.device):
  540. self.dst_prev_stream = torch.cuda.current_stream(cur_stream.device)
  541. torch.cuda.set_stream(cur_stream)
  542. def __exit__(self, type: Any, value: Any, traceback: Any):
  543. # Local cur_stream variable for type refinement
  544. cur_stream = self.stream
  545. # If stream is None or no CUDA device available, return
  546. if cur_stream is None or self.idx == -1:
  547. return
  548. # Reset the stream on the original device
  549. # and destination device
  550. if self.src_prev_stream.device != cur_stream.device: # type: ignore[union-attr]
  551. torch.cuda.set_stream(self.dst_prev_stream) # type: ignore[arg-type]
  552. torch.cuda.set_stream(self.src_prev_stream) # type: ignore[arg-type]
  553. def stream(stream: Optional["torch.cuda.Stream"]) -> StreamContext:
  554. r"""Wrap around the Context-manager StreamContext that selects a given stream.
  555. Arguments:
  556. stream (Stream): selected stream. This manager is a no-op if it's
  557. ``None``.
  558. .. note::
  559. In eager mode stream is of type Stream class while in JIT it is
  560. an object of the custom class ``torch.classes.cuda.Stream``.
  561. """
  562. return StreamContext(stream)
  563. def _set_stream_by_id(stream_id, device_index, device_type):
  564. r"""set stream specified by the stream id, device index and
  565. device type
  566. Args: stream_id (int): stream id in stream pool
  567. device_index (int): device index in topo
  568. device_type (int): enum device type
  569. """
  570. torch._C._cuda_setStream(
  571. stream_id=stream_id,
  572. device_index=device_index,
  573. device_type=device_type,
  574. )
  575. def set_stream(stream: Stream):
  576. r"""Set the current stream.This is a wrapper API to set the stream.
  577. Usage of this function is discouraged in favor of the ``stream``
  578. context manager.
  579. Args:
  580. stream (Stream): selected stream. This function is a no-op
  581. if this argument is ``None``.
  582. """
  583. if stream is None:
  584. return
  585. _set_stream_by_id(
  586. stream_id=stream.stream_id,
  587. device_index=stream.device_index,
  588. device_type=stream.device_type,
  589. )
  590. def _parse_visible_devices() -> Union[list[int], list[str]]:
  591. r"""Parse CUDA_VISIBLE_DEVICES environment variable."""
  592. var = os.getenv("CUDA_VISIBLE_DEVICES")
  593. if torch.version.hip:
  594. hip_devices = os.getenv("HIP_VISIBLE_DEVICES")
  595. rocr_devices = os.getenv("ROCR_VISIBLE_DEVICES")
  596. # You must take care if both HIP and ROCR env vars are set as they have
  597. # different meanings. Both env vars accept either a list of ints or a
  598. # list of UUIDs. The ROCR env var is processed first which then reduces
  599. # the number of GPUs that HIP can select from.
  600. if rocr_devices is not None:
  601. rocr_count = len(rocr_devices.split(","))
  602. if hip_devices is not None:
  603. # sanity check if both env vars are set
  604. if len(hip_devices.split(",")) > rocr_count:
  605. raise RuntimeError(
  606. "HIP_VISIBLE_DEVICES contains more devices than ROCR_VISIBLE_DEVICES"
  607. )
  608. # HIP_VISIBLE_DEVICES is preferred over ROCR_VISIBLE_DEVICES
  609. var = hip_devices
  610. else:
  611. return list(range(rocr_count))
  612. elif hip_devices is not None:
  613. var = hip_devices
  614. if var is None:
  615. return list(range(64))
  616. def _strtoul(s: str) -> int:
  617. """Return -1 or positive integer sequence string starts with."""
  618. if not s:
  619. return -1
  620. for idx, c in enumerate(s):
  621. if not (c.isdigit() or (idx == 0 and c in "+-")):
  622. break
  623. if idx + 1 == len(s):
  624. idx += 1
  625. return int(s[:idx]) if idx > 0 else -1
  626. def parse_list_with_prefix(lst: str, prefix: str) -> list[str]:
  627. rcs: list[str] = []
  628. for elem in lst.split(","):
  629. # Repeated id results in empty set
  630. if elem in rcs:
  631. return cast(list[str], [])
  632. # Anything other but prefix is ignored
  633. if not elem.startswith(prefix):
  634. break
  635. rcs.append(elem)
  636. return rcs
  637. if var.startswith("GPU-"):
  638. return parse_list_with_prefix(var, "GPU-")
  639. if var.startswith("MIG-"):
  640. return parse_list_with_prefix(var, "MIG-")
  641. # CUDA_VISIBLE_DEVICES uses something like strtoul
  642. # which makes `1gpu2,2ampere` is equivalent to `1,2`
  643. rc: list[int] = []
  644. for elem in var.split(","):
  645. x = _strtoul(elem.strip())
  646. # Repeated ordinal results in empty set
  647. if x in rc:
  648. return cast(list[int], [])
  649. # Negative value aborts the sequence
  650. if x < 0:
  651. break
  652. rc.append(x)
  653. return rc
  654. def _raw_device_count_amdsmi() -> int:
  655. if not _HAS_PYNVML: # If amdsmi is not available
  656. return -1
  657. try:
  658. amdsmi.amdsmi_init()
  659. except amdsmi.AmdSmiException as e:
  660. warnings.warn(f"Can't initialize amdsmi - Error code: {e.err_code}")
  661. return -1
  662. socket_handles = amdsmi.amdsmi_get_processor_handles()
  663. return len(socket_handles)
  664. def _raw_device_count_nvml() -> int:
  665. r"""Return number of devices as reported by NVML or negative value if NVML discovery/initialization failed."""
  666. from ctypes import byref, c_int, CDLL
  667. nvml_h = CDLL("libnvidia-ml.so.1")
  668. rc = nvml_h.nvmlInit()
  669. if rc != 0:
  670. warnings.warn("Can't initialize NVML")
  671. return -1
  672. dev_count = c_int(-1)
  673. rc = nvml_h.nvmlDeviceGetCount_v2(byref(dev_count))
  674. if rc != 0:
  675. warnings.warn("Can't get nvml device count")
  676. return -1
  677. del nvml_h
  678. return dev_count.value
  679. def _raw_device_uuid_amdsmi() -> Optional[list[str]]:
  680. from ctypes import byref, c_int, c_void_p, CDLL, create_string_buffer
  681. if not _HAS_PYNVML: # If amdsmi is not available
  682. return None
  683. try:
  684. amdsmi.amdsmi_init()
  685. except amdsmi.AmdSmiException:
  686. warnings.warn("Can't initialize amdsmi")
  687. return None
  688. try:
  689. socket_handles = amdsmi.amdsmi_get_processor_handles()
  690. dev_count = len(socket_handles)
  691. except amdsmi.AmdSmiException:
  692. warnings.warn("Can't get amdsmi device count")
  693. return None
  694. uuids: list[str] = []
  695. for idx in range(dev_count):
  696. try:
  697. handler = amdsmi.amdsmi_get_processor_handles()[idx]
  698. except amdsmi.AmdSmiException:
  699. warnings.warn("Cannot get amd device handler")
  700. return None
  701. try:
  702. uuid = amdsmi.amdsmi_get_gpu_asic_info(handler)["asic_serial"][
  703. 2:
  704. ] # Removes 0x prefix from serial
  705. except amdsmi.AmdSmiException:
  706. warnings.warn("Cannot get uuid for amd device")
  707. return None
  708. uuids.append(
  709. str(uuid).lower()
  710. ) # Lower-case to match expected HIP_VISIBLE_DEVICES uuid input
  711. return uuids
  712. def _raw_device_uuid_nvml() -> Optional[list[str]]:
  713. r"""Return list of device UUID as reported by NVML or None if NVM discovery/initialization failed."""
  714. from ctypes import byref, c_int, c_void_p, CDLL, create_string_buffer
  715. nvml_h = CDLL("libnvidia-ml.so.1")
  716. rc = nvml_h.nvmlInit()
  717. if rc != 0:
  718. warnings.warn("Can't initialize NVML")
  719. return None
  720. dev_count = c_int(-1)
  721. rc = nvml_h.nvmlDeviceGetCount_v2(byref(dev_count))
  722. if rc != 0:
  723. warnings.warn("Can't get nvml device count")
  724. return None
  725. uuids: list[str] = []
  726. for idx in range(dev_count.value):
  727. dev_id = c_void_p()
  728. rc = nvml_h.nvmlDeviceGetHandleByIndex_v2(idx, byref(dev_id))
  729. if rc != 0:
  730. warnings.warn("Can't get device handle")
  731. return None
  732. buf_len = 96
  733. buf = create_string_buffer(buf_len)
  734. rc = nvml_h.nvmlDeviceGetUUID(dev_id, buf, buf_len)
  735. if rc != 0:
  736. warnings.warn("Can't get device UUID")
  737. return None
  738. uuids.append(buf.raw.decode("ascii").strip("\0"))
  739. del nvml_h
  740. return uuids
  741. def _transform_uuid_to_ordinals(candidates: list[str], uuids: list[str]) -> list[int]:
  742. r"""Given the set of partial uuids and list of known uuids builds a set of ordinals excluding ambiguous partials IDs."""
  743. def uuid_to_ordinal(candidate: str, uuids: list[str]) -> int:
  744. best_match = -1
  745. for idx, uuid in enumerate(uuids):
  746. if not uuid.startswith(candidate):
  747. continue
  748. # Ambiguous candidate
  749. if best_match != -1:
  750. return -1
  751. best_match = idx
  752. return best_match
  753. rc: list[int] = []
  754. for candidate in candidates:
  755. if torch.version.hip:
  756. candidate = candidate.replace(
  757. "GPU-", "", 1
  758. ) # Remove GPU-prefix to match amdsmi asic serial
  759. idx = uuid_to_ordinal(candidate, uuids)
  760. # First invalid ordinal stops parsing
  761. if idx < 0:
  762. break
  763. # Duplicates result in empty set
  764. if idx in rc:
  765. return cast(list[int], [])
  766. rc.append(idx)
  767. return rc
  768. def _device_count_amdsmi() -> int:
  769. visible_devices = _parse_visible_devices()
  770. if not visible_devices:
  771. return 0
  772. try:
  773. if type(visible_devices[0]) is str:
  774. uuids = _raw_device_uuid_amdsmi()
  775. if uuids is None:
  776. return -1
  777. # Create string version of visible devices to avoid mypy warnings
  778. visible_device_str = cast(list[str], visible_devices)
  779. visible_devices = _transform_uuid_to_ordinals(visible_device_str, uuids)
  780. else:
  781. raw_cnt = _raw_device_count_amdsmi()
  782. if raw_cnt <= 0:
  783. return raw_cnt
  784. # Trim the list up to a maximum available device
  785. for idx, val in enumerate(visible_devices):
  786. if cast(int, val) >= raw_cnt:
  787. return idx
  788. except OSError:
  789. return -1
  790. except AttributeError:
  791. return -1
  792. return len(visible_devices)
  793. def _device_count_nvml() -> int:
  794. r"""Return number of devices as reported by NVML taking CUDA_VISIBLE_DEVICES into account.
  795. Negative value is returned if NVML discovery or initialization has failed.
  796. """
  797. visible_devices = _parse_visible_devices()
  798. if not visible_devices:
  799. return 0
  800. try:
  801. if type(visible_devices[0]) is str:
  802. # Skip MIG parsing
  803. if visible_devices[0].startswith("MIG-"):
  804. return -1
  805. uuids = _raw_device_uuid_nvml()
  806. if uuids is None:
  807. return -1
  808. visible_devices = _transform_uuid_to_ordinals(
  809. cast(list[str], visible_devices), uuids
  810. )
  811. else:
  812. raw_cnt = _raw_device_count_nvml()
  813. if raw_cnt <= 0:
  814. return raw_cnt
  815. # Trim the list up to a maximum available device
  816. for idx, val in enumerate(visible_devices):
  817. if cast(int, val) >= raw_cnt:
  818. return idx
  819. except OSError:
  820. return -1
  821. except AttributeError:
  822. return -1
  823. return len(visible_devices)
  824. def _get_nvml_device_index(device: "Device") -> int:
  825. r"""Return the NVML index of the device, taking CUDA_VISIBLE_DEVICES into account."""
  826. idx = _get_device_index(device, optional=True)
  827. visible_devices = _parse_visible_devices()
  828. if type(visible_devices[0]) is str:
  829. uuids = _raw_device_uuid_nvml()
  830. if uuids is None:
  831. raise RuntimeError("Can't get device UUIDs")
  832. visible_devices = _transform_uuid_to_ordinals(
  833. cast(list[str], visible_devices), uuids
  834. )
  835. visible_devices = cast(list[int], visible_devices)
  836. if idx < 0 or idx >= len(visible_devices):
  837. raise RuntimeError(
  838. f"device {idx} is not visible (CUDA_VISIBLE_DEVICES={visible_devices})"
  839. )
  840. return visible_devices[idx]
  841. _cached_device_count: Optional[int] = None
  842. def device_count() -> int:
  843. r"""
  844. Return the number of GPUs available.
  845. .. note:: This API will NOT poison fork if NVML discovery succeeds.
  846. See :ref:`multiprocessing-poison-fork-note` for more details.
  847. """
  848. global _cached_device_count
  849. if not _is_compiled():
  850. return 0
  851. if _cached_device_count is not None:
  852. return _cached_device_count
  853. # bypass _device_count_nvml() if rocm (not supported)
  854. nvml_count = _device_count_amdsmi() if torch.version.hip else _device_count_nvml()
  855. r = torch._C._cuda_getDeviceCount() if nvml_count < 0 else nvml_count
  856. # NB: Do not cache the device count prior to CUDA initialization, because
  857. # the number of devices can change due to changes to CUDA_VISIBLE_DEVICES
  858. # setting prior to CUDA initialization.
  859. if _initialized:
  860. _cached_device_count = r
  861. return r
  862. def get_arch_list() -> list[str]:
  863. r"""Return list CUDA architectures this library was compiled for."""
  864. if not is_available():
  865. return []
  866. arch_flags = torch._C._cuda_getArchFlags()
  867. if arch_flags is None:
  868. return []
  869. return arch_flags.split()
  870. def get_gencode_flags() -> str:
  871. r"""Return NVCC gencode flags this library was compiled with."""
  872. arch_list = get_arch_list()
  873. if len(arch_list) == 0:
  874. return ""
  875. arch_list_ = [arch.split("_") for arch in arch_list]
  876. return " ".join(
  877. [
  878. f"-gencode compute=compute_{arch},code={kind}_{arch}"
  879. for (kind, arch) in arch_list_
  880. ]
  881. )
  882. def current_device() -> int:
  883. r"""Return the index of a currently selected device."""
  884. _lazy_init()
  885. return torch._C._cuda_getDevice()
  886. def synchronize(device: "Device" = None) -> None:
  887. r"""Wait for all kernels in all streams on a CUDA device to complete.
  888. Args:
  889. device (torch.device or int, optional): device for which to synchronize.
  890. It uses the current device, given by :func:`~torch.cuda.current_device`,
  891. if :attr:`device` is ``None`` (default).
  892. """
  893. _lazy_init()
  894. with torch.cuda.device(device):
  895. return torch._C._cuda_synchronize()
  896. def ipc_collect():
  897. r"""Force collects GPU memory after it has been released by CUDA IPC.
  898. .. note::
  899. Checks if any sent CUDA tensors could be cleaned from the memory. Force
  900. closes shared memory file used for reference counting if there is no
  901. active counters. Useful when the producer process stopped actively sending
  902. tensors and want to release unused memory.
  903. """
  904. _lazy_init()
  905. return torch._C._cuda_ipc_collect()
  906. def current_stream(device: "Device" = None) -> Stream:
  907. r"""Return the currently selected :class:`Stream` for a given device.
  908. Args:
  909. device (torch.device or int, optional): selected device. Returns
  910. the currently selected :class:`Stream` for the current device, given
  911. by :func:`~torch.cuda.current_device`, if :attr:`device` is ``None``
  912. (default).
  913. """
  914. _lazy_init()
  915. streamdata = torch._C._cuda_getCurrentStream(
  916. _get_device_index(device, optional=True)
  917. )
  918. return Stream(
  919. stream_id=streamdata[0], device_index=streamdata[1], device_type=streamdata[2]
  920. )
  921. def default_stream(device: "Device" = None) -> Stream:
  922. r"""Return the default :class:`Stream` for a given device.
  923. Args:
  924. device (torch.device or int, optional): selected device. Returns
  925. the default :class:`Stream` for the current device, given by
  926. :func:`~torch.cuda.current_device`, if :attr:`device` is ``None``
  927. (default).
  928. """
  929. _lazy_init()
  930. streamdata = torch._C._cuda_getDefaultStream(
  931. _get_device_index(device, optional=True)
  932. )
  933. return Stream(
  934. stream_id=streamdata[0], device_index=streamdata[1], device_type=streamdata[2]
  935. )
  936. def get_stream_from_external(data_ptr: int, device: "Device" = None) -> Stream:
  937. r"""Return a :class:`Stream` from an externally allocated CUDA stream.
  938. This function is used to wrap streams allocated in other libraries in order
  939. to facilitate data exchange and multi-library interactions.
  940. .. note:: This function doesn't manage the stream life-cycle, it is the user
  941. responsibility to keep the referenced stream alive while this returned
  942. stream is being used.
  943. Args:
  944. data_ptr(int): Integer representation of the `cudaStream_t` value that
  945. is allocated externally.
  946. device(torch.device or int, optional): the device where the stream
  947. was originally allocated. If device is specified incorrectly,
  948. subsequent launches using this stream may fail.
  949. """
  950. _lazy_init()
  951. streamdata = torch._C._cuda_getStreamFromExternal(
  952. data_ptr, _get_device_index(device, optional=True)
  953. )
  954. return Stream(
  955. stream_id=streamdata[0], device_index=streamdata[1], device_type=streamdata[2]
  956. )
  957. def current_blas_handle():
  958. r"""Return cublasHandle_t pointer to current cuBLAS handle"""
  959. _lazy_init()
  960. return torch._C._cuda_getCurrentBlasHandle()
  961. def set_sync_debug_mode(debug_mode: Union[int, str]) -> None:
  962. r"""Set the debug mode for cuda synchronizing operations.
  963. Args:
  964. debug_mode(str or int): if "default" or 0, don't error or warn on synchronizing operations,
  965. if "warn" or 1, warn on synchronizing operations, if "error" or 2, error out synchronizing operations.
  966. Warning:
  967. This is an experimental feature, and not all synchronizing operations will trigger warning or error. In
  968. particular, operations in torch.distributed and torch.sparse namespaces are not covered yet.
  969. """
  970. _lazy_init()
  971. if isinstance(debug_mode, str):
  972. if debug_mode == "default":
  973. debug_mode = 0
  974. elif debug_mode == "warn":
  975. debug_mode = 1
  976. elif debug_mode == "error":
  977. debug_mode = 2
  978. else:
  979. raise RuntimeError(
  980. "invalid value of debug_mode, expected one of `default`, `warn`, `error`"
  981. )
  982. torch._C._cuda_set_sync_debug_mode(debug_mode)
  983. def get_sync_debug_mode() -> int:
  984. r"""Return current value of debug mode for cuda synchronizing operations."""
  985. _lazy_init()
  986. return torch._C._cuda_get_sync_debug_mode()
  987. def _get_pynvml_handler(device: "Device" = None):
  988. if not _HAS_PYNVML:
  989. raise ModuleNotFoundError(
  990. "pynvml does not seem to be installed or it can't be imported."
  991. ) from _PYNVML_ERR
  992. from pynvml import NVMLError_DriverNotLoaded
  993. try:
  994. pynvml.nvmlInit()
  995. except NVMLError_DriverNotLoaded as e:
  996. raise RuntimeError("cuda driver can't be loaded, is cuda enabled?") from e
  997. device = _get_nvml_device_index(device)
  998. handle = pynvml.nvmlDeviceGetHandleByIndex(device)
  999. return handle
  1000. def _get_amdsmi_handler(device: "Device" = None):
  1001. if not _HAS_PYNVML:
  1002. raise ModuleNotFoundError(
  1003. "amdsmi does not seem to be installed or it can't be imported."
  1004. ) from _PYNVML_ERR
  1005. try:
  1006. amdsmi.amdsmi_init()
  1007. except amdsmi.AmdSmiException as e:
  1008. raise RuntimeError(
  1009. "amdsmi driver can't be loaded, requires >=ROCm5.6 installation"
  1010. ) from e
  1011. device = _get_amdsmi_device_index(device)
  1012. handle = amdsmi.amdsmi_get_processor_handles()[device]
  1013. return handle
  1014. def _get_amdsmi_device_index(device: "Device") -> int:
  1015. r"""Return the amdsmi index of the device, taking visible_devices into account."""
  1016. idx = _get_device_index(device, optional=True)
  1017. visible_devices = _parse_visible_devices()
  1018. if type(visible_devices[0]) is str:
  1019. uuids = _raw_device_uuid_amdsmi()
  1020. if uuids is None:
  1021. raise RuntimeError("Can't get device UUIDs")
  1022. visible_devices_str = cast(
  1023. list[str], visible_devices
  1024. ) # Create str variable for mypy
  1025. visible_devices = _transform_uuid_to_ordinals(visible_devices_str, uuids)
  1026. idx_map = dict(enumerate(cast(list[int], visible_devices)))
  1027. if idx not in idx_map:
  1028. raise RuntimeError(
  1029. f"device {idx} is not visible (HIP_VISIBLE_DEVICES={visible_devices})"
  1030. )
  1031. return idx_map[idx]
  1032. def _get_amdsmi_device_memory_used(device: "Device" = None) -> int:
  1033. handle = _get_amdsmi_handler(device)
  1034. # amdsmi_get_gpu_vram_usage returns mem usage in megabytes
  1035. mem_mega_bytes = amdsmi.amdsmi_get_gpu_vram_usage(handle)["vram_used"]
  1036. mem_bytes = mem_mega_bytes * 1024 * 1024
  1037. return mem_bytes
  1038. def _get_amdsmi_memory_usage(device: "Device" = None) -> int:
  1039. handle = _get_amdsmi_handler(device)
  1040. return amdsmi.amdsmi_get_gpu_activity(handle)["umc_activity"]
  1041. def _get_amdsmi_utilization(device: "Device" = None) -> int:
  1042. handle = _get_amdsmi_handler(device)
  1043. return amdsmi.amdsmi_get_gpu_activity(handle)["gfx_activity"]
  1044. def _get_amdsmi_temperature(device: "Device" = None) -> int:
  1045. handle = _get_amdsmi_handler(device)
  1046. return amdsmi.amdsmi_get_temp_metric(
  1047. handle,
  1048. amdsmi.AmdSmiTemperatureType.JUNCTION,
  1049. amdsmi.AmdSmiTemperatureMetric.CURRENT,
  1050. )
  1051. def _get_amdsmi_power_draw(device: "Device" = None) -> int:
  1052. handle = _get_amdsmi_handler(device)
  1053. socket_power = amdsmi.amdsmi_get_power_info(handle)["average_socket_power"]
  1054. if socket_power != "N/A":
  1055. return socket_power
  1056. else:
  1057. socket_power = amdsmi.amdsmi_get_power_info(handle)["current_socket_power"]
  1058. if socket_power != "N/A":
  1059. return socket_power
  1060. else:
  1061. return 0
  1062. def _get_amdsmi_clock_rate(device: "Device" = None) -> int:
  1063. handle = _get_amdsmi_handler(device)
  1064. clock_info = amdsmi.amdsmi_get_clock_info(handle, amdsmi.AmdSmiClkType.GFX)
  1065. if "cur_clk" in clock_info: # ROCm 6.2 deprecation
  1066. clock_rate = clock_info["cur_clk"]
  1067. else:
  1068. clock_rate = clock_info["clk"]
  1069. if clock_rate != "N/A":
  1070. return clock_rate
  1071. else:
  1072. return 0
  1073. def device_memory_used(device: "Device" = None) -> int:
  1074. r"""Return used global (device) memory in bytes as given by `nvidia-smi` or `amd-smi`.
  1075. Args:
  1076. device (torch.device or int, optional): selected device. Returns
  1077. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  1078. if :attr:`device` is ``None`` (default).
  1079. """
  1080. if not torch.version.hip:
  1081. handle = _get_pynvml_handler()
  1082. device = _get_nvml_device_index(device)
  1083. handle = pynvml.nvmlDeviceGetHandleByIndex(device)
  1084. return pynvml.nvmlDeviceGetMemoryInfo(handle).used
  1085. else:
  1086. return _get_amdsmi_device_memory_used(device)
  1087. def memory_usage(device: "Device" = None) -> int:
  1088. r"""Return the percent of time over the past sample period during which global (device)
  1089. memory was being read or written as given by `nvidia-smi`.
  1090. Args:
  1091. device (torch.device or int, optional): selected device. Returns
  1092. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  1093. if :attr:`device` is ``None`` (default).
  1094. Warning: Each sample period may be between 1 second and 1/6 second,
  1095. depending on the product being queried.
  1096. """
  1097. if not torch.version.hip:
  1098. handle = _get_pynvml_handler()
  1099. device = _get_nvml_device_index(device)
  1100. handle = pynvml.nvmlDeviceGetHandleByIndex(device)
  1101. return pynvml.nvmlDeviceGetUtilizationRates(handle).memory
  1102. else:
  1103. return _get_amdsmi_memory_usage(device)
  1104. def utilization(device: "Device" = None) -> int:
  1105. r"""Return the percent of time over the past sample period during which one or
  1106. more kernels was executing on the GPU as given by `nvidia-smi`.
  1107. Args:
  1108. device (torch.device or int, optional): selected device. Returns
  1109. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  1110. if :attr:`device` is ``None`` (default).
  1111. Warning: Each sample period may be between 1 second and 1/6 second,
  1112. depending on the product being queried.
  1113. """
  1114. if not torch.version.hip:
  1115. handle = _get_pynvml_handler(device)
  1116. device = _get_nvml_device_index(device)
  1117. handle = pynvml.nvmlDeviceGetHandleByIndex(device)
  1118. return pynvml.nvmlDeviceGetUtilizationRates(handle).gpu
  1119. else:
  1120. return _get_amdsmi_utilization(device)
  1121. def temperature(device: "Device" = None) -> int:
  1122. r"""Return the average temperature of the GPU sensor in Degrees C (Centigrades).
  1123. The average temperature is computed based on past sample period as given by `nvidia-smi`.
  1124. Args:
  1125. device (torch.device or int, optional): selected device. Returns
  1126. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  1127. if :attr:`device` is ``None`` (default).
  1128. Warning: Each sample period may be between 1 second and 1/6 second,
  1129. depending on the product being queried.
  1130. """
  1131. if not torch.version.hip:
  1132. handle = _get_pynvml_handler(device)
  1133. # 0 refers to the temperature sensor for the GPU die.
  1134. return pynvml.nvmlDeviceGetTemperature(handle, 0)
  1135. else:
  1136. return _get_amdsmi_temperature(device)
  1137. def power_draw(device: "Device" = None) -> int:
  1138. r"""Return the average power draw of the GPU sensor in mW (MilliWatts)
  1139. over the past sample period as given by `nvidia-smi` for Fermi or newer fully supported devices.
  1140. Args:
  1141. device (torch.device or int, optional): selected device. Returns
  1142. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  1143. if :attr:`device` is ``None`` (default).
  1144. Warning: Each sample period may be between 1 second and 1/6 second,
  1145. depending on the product being queried.
  1146. """
  1147. if not torch.version.hip:
  1148. handle = _get_pynvml_handler(device)
  1149. return pynvml.nvmlDeviceGetPowerUsage(handle)
  1150. else:
  1151. return _get_amdsmi_power_draw(device)
  1152. def clock_rate(device: "Device" = None) -> int:
  1153. r"""Return the clock speed of the GPU SM in MHz (megahertz) over the past sample period as given by `nvidia-smi`.
  1154. Args:
  1155. device (torch.device or int, optional): selected device. Returns
  1156. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  1157. if :attr:`device` is ``None`` (default).
  1158. Warning: Each sample period may be between 1 second and 1/6 second,
  1159. depending on the product being queried.
  1160. """
  1161. if not torch.version.hip:
  1162. handle = _get_pynvml_handler(device)
  1163. return pynvml.nvmlDeviceGetClockInfo(handle, 1)
  1164. else:
  1165. return _get_amdsmi_clock_rate(device)
  1166. def _get_device(device: Union[int, str, torch.device]) -> torch.device:
  1167. r"""Return the torch.device type object from the passed in device.
  1168. Args:
  1169. device (torch.device or int): selected device.
  1170. """
  1171. if isinstance(device, str):
  1172. device = torch.device(device)
  1173. elif isinstance(device, int):
  1174. device = torch.device("cuda", device)
  1175. return device
  1176. def _get_generator(device: torch.device) -> torch._C.Generator:
  1177. r"""Return the CUDA Generator object for the given device.
  1178. Args:
  1179. device (torch.device): selected device.
  1180. """
  1181. idx = device.index
  1182. if idx is None:
  1183. idx = current_device()
  1184. return torch.cuda.default_generators[idx]
  1185. def _set_rng_state_offset(
  1186. offset: int, device: Union[int, str, torch.device] = "cuda"
  1187. ) -> None:
  1188. r"""Set the random number generator state offset of the specified GPU.
  1189. Args:
  1190. offset (int): The desired offset
  1191. device (torch.device or int, optional): The device to set the RNG state.
  1192. Default: ``'cuda'`` (i.e., ``torch.device('cuda')``, the current CUDA device).
  1193. """
  1194. final_device = _get_device(device)
  1195. def cb():
  1196. default_generator = _get_generator(final_device)
  1197. default_generator.set_offset(offset)
  1198. _lazy_call(cb)
  1199. def _get_rng_state_offset(device: Union[int, str, torch.device] = "cuda") -> int:
  1200. r"""Return the random number generator state offset of the specified GPU.
  1201. Args:
  1202. device (torch.device or int, optional): The device to return the RNG state offset of.
  1203. Default: ``'cuda'`` (i.e., ``torch.device('cuda')``, the current CUDA device).
  1204. .. warning::
  1205. This function eagerly initializes CUDA.
  1206. """
  1207. _lazy_init()
  1208. final_device = _get_device(device)
  1209. default_generator = _get_generator(final_device)
  1210. return default_generator.get_offset()
  1211. from .memory import * # noqa: F403
  1212. from .random import * # noqa: F403
  1213. ################################################################################
  1214. # Define Storage and Tensor classes
  1215. ################################################################################
  1216. @staticmethod # type: ignore[misc]
  1217. def _lazy_new(cls, *args, **kwargs):
  1218. _lazy_init()
  1219. # We may need to call lazy init again if we are a forked child
  1220. # del _CudaBase.__new__
  1221. return super(_CudaBase, cls).__new__(cls, *args, **kwargs)
  1222. class _CudaBase:
  1223. is_cuda = True
  1224. is_sparse = False
  1225. def type(self, *args, **kwargs):
  1226. # We could use a Protocol here to tell mypy that self has `get_device` method
  1227. # but it is only available in the typing module on Python >= 3.8
  1228. # or on typing_extensions module on Python >= 3.6
  1229. with device(self.get_device()): # type: ignore[attr-defined]
  1230. return super().type(*args, **kwargs) # type: ignore[misc]
  1231. __new__ = _lazy_new
  1232. from torch.storage import _LegacyStorage, _warn_typed_storage_removal
  1233. class _CudaLegacyStorage(_LegacyStorage):
  1234. @classmethod
  1235. def from_buffer(cls, *args, **kwargs):
  1236. _warn_typed_storage_removal()
  1237. raise RuntimeError("from_buffer: Not available for CUDA storage")
  1238. @classmethod
  1239. def _new_with_weak_ptr(cls, *args, **kwargs):
  1240. raise RuntimeError("_new_with_weak_ptr: Not available for CUDA storage")
  1241. @classmethod
  1242. def _new_shared_filename(cls, manager, obj, size, *, device=None, dtype=None):
  1243. raise RuntimeError("_new_shared_filename: Not available for CUDA storage")
  1244. class ByteStorage(_CudaLegacyStorage):
  1245. @classproperty
  1246. def dtype(self):
  1247. _warn_typed_storage_removal()
  1248. return self._dtype
  1249. @classproperty
  1250. def _dtype(self):
  1251. return torch.uint8
  1252. class DoubleStorage(_CudaLegacyStorage):
  1253. @classproperty
  1254. def dtype(self):
  1255. _warn_typed_storage_removal()
  1256. return self._dtype
  1257. @classproperty
  1258. def _dtype(self):
  1259. return torch.double
  1260. class FloatStorage(_CudaLegacyStorage):
  1261. @classproperty
  1262. def dtype(self):
  1263. _warn_typed_storage_removal()
  1264. return self._dtype
  1265. @classproperty
  1266. def _dtype(self):
  1267. return torch.float
  1268. class HalfStorage(_CudaLegacyStorage):
  1269. @classproperty
  1270. def dtype(self):
  1271. _warn_typed_storage_removal()
  1272. return self._dtype
  1273. @classproperty
  1274. def _dtype(self):
  1275. return torch.half
  1276. class LongStorage(_CudaLegacyStorage):
  1277. @classproperty
  1278. def dtype(self):
  1279. _warn_typed_storage_removal()
  1280. return self._dtype
  1281. @classproperty
  1282. def _dtype(self):
  1283. return torch.long
  1284. class IntStorage(_CudaLegacyStorage):
  1285. @classproperty
  1286. def dtype(self):
  1287. _warn_typed_storage_removal()
  1288. return self._dtype
  1289. @classproperty
  1290. def _dtype(self):
  1291. return torch.int
  1292. class ShortStorage(_CudaLegacyStorage):
  1293. @classproperty
  1294. def dtype(self):
  1295. _warn_typed_storage_removal()
  1296. return self._dtype
  1297. @classproperty
  1298. def _dtype(self):
  1299. return torch.short
  1300. class CharStorage(_CudaLegacyStorage):
  1301. @classproperty
  1302. def dtype(self):
  1303. _warn_typed_storage_removal()
  1304. return self._dtype
  1305. @classproperty
  1306. def _dtype(self):
  1307. return torch.int8
  1308. class BoolStorage(_CudaLegacyStorage):
  1309. @classproperty
  1310. def dtype(self):
  1311. _warn_typed_storage_removal()
  1312. return self._dtype
  1313. @classproperty
  1314. def _dtype(self):
  1315. return torch.bool
  1316. class BFloat16Storage(_CudaLegacyStorage):
  1317. @classproperty
  1318. def dtype(self):
  1319. _warn_typed_storage_removal()
  1320. return self._dtype
  1321. @classproperty
  1322. def _dtype(self):
  1323. return torch.bfloat16
  1324. class ComplexDoubleStorage(_CudaLegacyStorage):
  1325. @classproperty
  1326. def dtype(self):
  1327. _warn_typed_storage_removal()
  1328. return self._dtype
  1329. @classproperty
  1330. def _dtype(self):
  1331. return torch.cdouble
  1332. class ComplexFloatStorage(_CudaLegacyStorage):
  1333. @classproperty
  1334. def dtype(self):
  1335. _warn_typed_storage_removal()
  1336. return self._dtype
  1337. @classproperty
  1338. def _dtype(self):
  1339. return torch.cfloat
  1340. del _LegacyStorage
  1341. del _CudaLegacyStorage
  1342. torch._storage_classes.add(DoubleStorage)
  1343. torch._storage_classes.add(FloatStorage)
  1344. torch._storage_classes.add(LongStorage)
  1345. torch._storage_classes.add(IntStorage)
  1346. torch._storage_classes.add(ShortStorage)
  1347. torch._storage_classes.add(CharStorage)
  1348. torch._storage_classes.add(ByteStorage)
  1349. torch._storage_classes.add(HalfStorage)
  1350. torch._storage_classes.add(BoolStorage)
  1351. torch._storage_classes.add(BFloat16Storage)
  1352. torch._storage_classes.add(ComplexDoubleStorage)
  1353. torch._storage_classes.add(ComplexFloatStorage)
  1354. class _WrappedTritonKernel:
  1355. """Just a simple wrapper to store some metadata for testing purposes."""
  1356. def __init__(self, kernel):
  1357. self.kernel = kernel
  1358. self.kernel_invoked = False
  1359. def __call__(self, *args, **kwargs):
  1360. res = self.kernel(*args, **kwargs)
  1361. self.kernel_invoked = True
  1362. return res
  1363. def _register_triton_kernels():
  1364. @_WrappedTritonKernel
  1365. def kernel_impl(*args, **kwargs):
  1366. from torch.sparse._triton_ops import bsr_dense_mm
  1367. return bsr_dense_mm(*args, skip_checks=True, **kwargs)
  1368. @_WrappedTritonKernel
  1369. def addmm_kernel_impl(*args, **kwargs):
  1370. from torch.sparse._triton_ops import bsr_dense_addmm
  1371. return bsr_dense_addmm(*args, skip_checks=True, **kwargs)
  1372. has_triton = importlib.util.find_spec("triton") is not None
  1373. if has_triton:
  1374. torch._TritonLibrary.registerOp(
  1375. "_triton_bsr_dense_mm_out",
  1376. "_triton_bsr_dense_mm_out(Tensor bsr, Tensor dense, *, Tensor(a!) out) -> Tensor(a!)",
  1377. kernel_impl,
  1378. "SparseCsrCUDA",
  1379. )
  1380. torch._TritonLibrary.registerOp(
  1381. "_triton_bsr_dense_addmm_out",
  1382. (
  1383. "_triton_bsr_dense_addmm_out(Tensor input, Tensor bsr, Tensor dense,"
  1384. " *, Scalar beta, Scalar alpha, Tensor(a!) out) -> Tensor(a!)"
  1385. ),
  1386. addmm_kernel_impl,
  1387. "SparseCsrCUDA",
  1388. )
  1389. _lazy_call(_register_triton_kernels)
  1390. def _compile_kernel(
  1391. kernel_source: str,
  1392. kernel_name: str,
  1393. compute_capability: Optional[str] = None,
  1394. header_code: str = "",
  1395. cuda_include_dirs: Optional[list] = None,
  1396. nvcc_options: Optional[list] = None,
  1397. ):
  1398. """
  1399. Compiles a CUDA kernel using NVRTC and returns a callable function.
  1400. This function is a wrapper for NVRTC that enables runtime compilation of CUDA kernels.
  1401. Note that this returns a raw CUDA kernel that operates on raw memory pointers.
  1402. To use this kernel as a proper PyTorch operator, you should wrap it following the guide at:
  1403. pytorch.org/tutorials/advanced/python_custom_ops.html
  1404. Args:
  1405. kernel_source (str): The CUDA kernel source code as a string
  1406. kernel_name (str): The name of the kernel function to compile
  1407. compute_capability (str, optional): The compute capability to target (e.g., "86").
  1408. If None, will detect from current device.
  1409. header_code (str, optional): Additional header code to prepend to the kernel source
  1410. cuda_include_dirs (list, optional): List of directories containing CUDA headers
  1411. nvcc_options (list, optional): Additional options to pass to NVRTC
  1412. Returns:
  1413. callable: A Python function that can be called with PyTorch tensor arguments to execute the kernel
  1414. Example:
  1415. >>> # xdoctest: +SKIP
  1416. >>> kernel_code = '''
  1417. extern "C"
  1418. __global__ void add_tensors(const float* a, const float* b, float* c, int n) {
  1419. int i = threadIdx.x + blockIdx.x * blockDim.x;
  1420. if (i < n)
  1421. c[i] = a[i] + b[i];
  1422. }
  1423. '''
  1424. >>> add_kernel = torch.cuda.compile_kernel(kernel_code, "add_tensors")
  1425. >>> a = torch.randn(1024, device="cuda")
  1426. >>> b = torch.randn(1024, device="cuda")
  1427. >>> c = torch.empty_like(a)
  1428. >>> add_kernel(grid=(4, 1, 1), block=(256, 1, 1), args=[a, b, c, a.numel()])
  1429. """
  1430. import ctypes
  1431. from torch.cuda._utils import _cuda_load_module, _nvrtc_compile
  1432. # Compile the kernel to PTX
  1433. ptx = _nvrtc_compile(
  1434. kernel_source,
  1435. kernel_name,
  1436. compute_capability,
  1437. header_code,
  1438. cuda_include_dirs,
  1439. nvcc_options,
  1440. )
  1441. # Load the module and get the kernel
  1442. result = _cuda_load_module(ptx, [kernel_name])
  1443. if isinstance(result, dict):
  1444. return result[kernel_name]
  1445. else:
  1446. # This branch shouldn't be executed if kernel_names is provided,
  1447. # but MyPy needs this to understand type narrowing
  1448. return getattr(result, kernel_name)
  1449. from . import amp, jiterator, nvtx, profiler, sparse, tunable
  1450. _POOL_HANDLE = NewType("_POOL_HANDLE", tuple[int, int])
  1451. __all__ = [
  1452. # Typed storage and tensors
  1453. "BFloat16Storage",
  1454. "BFloat16Tensor",
  1455. "BoolStorage",
  1456. "BoolTensor",
  1457. "ByteStorage",
  1458. "ByteTensor",
  1459. "CharStorage",
  1460. "CharTensor",
  1461. "ComplexDoubleStorage",
  1462. "ComplexFloatStorage",
  1463. "DoubleStorage",
  1464. "DoubleTensor",
  1465. "FloatStorage",
  1466. "FloatTensor",
  1467. "HalfStorage",
  1468. "HalfTensor",
  1469. "IntStorage",
  1470. "IntTensor",
  1471. "LongStorage",
  1472. "LongTensor",
  1473. "ShortStorage",
  1474. "ShortTensor",
  1475. "CUDAGraph",
  1476. "CudaError",
  1477. "DeferredCudaCallError",
  1478. "Event",
  1479. "ExternalStream",
  1480. "Stream",
  1481. "StreamContext",
  1482. "amp",
  1483. "caching_allocator_alloc",
  1484. "caching_allocator_delete",
  1485. "caching_allocator_enable",
  1486. "can_device_access_peer",
  1487. "check_error",
  1488. "cudaStatus",
  1489. "cudart",
  1490. "current_blas_handle",
  1491. "current_device",
  1492. "current_stream",
  1493. "default_generators",
  1494. "default_stream",
  1495. "device",
  1496. "device_count",
  1497. "device_memory_used",
  1498. "device_of",
  1499. "empty_cache",
  1500. "get_allocator_backend",
  1501. "CUDAPluggableAllocator",
  1502. "change_current_allocator",
  1503. "get_arch_list",
  1504. "get_device_capability",
  1505. "get_device_name",
  1506. "get_device_properties",
  1507. "get_gencode_flags",
  1508. "get_per_process_memory_fraction",
  1509. "get_rng_state",
  1510. "get_rng_state_all",
  1511. "get_stream_from_external",
  1512. "get_sync_debug_mode",
  1513. "graph",
  1514. "graph_pool_handle",
  1515. "graphs",
  1516. "has_half",
  1517. "has_magma",
  1518. "host_memory_stats",
  1519. "host_memory_stats_as_nested_dict",
  1520. "init",
  1521. "initial_seed",
  1522. "ipc_collect",
  1523. "is_available",
  1524. "is_bf16_supported",
  1525. "is_current_stream_capturing",
  1526. "is_initialized",
  1527. "is_tf32_supported",
  1528. "jiterator",
  1529. "list_gpu_processes",
  1530. "make_graphed_callables",
  1531. "manual_seed",
  1532. "manual_seed_all",
  1533. "max_memory_allocated",
  1534. "max_memory_cached",
  1535. "max_memory_reserved",
  1536. "mem_get_info",
  1537. "memory",
  1538. "memory_allocated",
  1539. "memory_cached",
  1540. "memory_reserved",
  1541. "memory_snapshot",
  1542. "memory_stats",
  1543. "memory_stats_as_nested_dict",
  1544. "memory_summary",
  1545. "memory_usage",
  1546. "MemPool",
  1547. "use_mem_pool",
  1548. "temperature",
  1549. "power_draw",
  1550. "clock_rate",
  1551. "nccl",
  1552. "nvtx",
  1553. "profiler",
  1554. "random",
  1555. "reset_accumulated_host_memory_stats",
  1556. "reset_accumulated_memory_stats",
  1557. "reset_max_memory_allocated",
  1558. "reset_max_memory_cached",
  1559. "reset_peak_host_memory_stats",
  1560. "reset_peak_memory_stats",
  1561. "seed",
  1562. "seed_all",
  1563. "set_device",
  1564. "set_per_process_memory_fraction",
  1565. "set_rng_state",
  1566. "set_rng_state_all",
  1567. "set_stream",
  1568. "set_sync_debug_mode",
  1569. "sparse",
  1570. "stream",
  1571. "streams",
  1572. "synchronize",
  1573. "tunable",
  1574. "utilization",
  1575. ]