__init__.py 67 KB

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