__init__.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. r"""
  2. This package adds support for CUDA tensor types, that implement the same
  3. function as CPU tensors, but they utilize GPUs for computation.
  4. It is lazily initialized, so you can always import it, and use
  5. :func:`is_available()` to determine if your system supports CUDA.
  6. :ref:`cuda-semantics` has more details about working with CUDA.
  7. """
  8. import contextlib
  9. import os
  10. import torch
  11. from torch.types import Device
  12. import traceback
  13. import warnings
  14. import threading
  15. from functools import lru_cache
  16. from typing import Any, List, Optional, Tuple, Union, cast
  17. from ._utils import _get_device_index, _dummy_type
  18. from .._utils import classproperty
  19. from .graphs import CUDAGraph, graph_pool_handle, graph, \
  20. make_graphed_callables, is_current_stream_capturing
  21. from .streams import ExternalStream, Stream, Event
  22. from .. import device as _device
  23. import torch._C
  24. try:
  25. from torch._C import _cudart # type: ignore[attr-defined]
  26. except ImportError:
  27. _cudart = None
  28. _initialized = False
  29. _tls = threading.local()
  30. _initialization_lock = threading.Lock()
  31. _queued_calls = [] # don't invoke these until initialization occurs
  32. _is_in_bad_fork = getattr(torch._C, "_cuda_isInBadFork", lambda: False)
  33. _device_t = Union[_device, str, int, None]
  34. class _LazySeedTracker:
  35. # Since seeding is memory-less, only track the latest seed.
  36. # Note: `manual_seed_all` followed by `manual_seed` overwrites
  37. # the seed on current device. We track the order of **latest**
  38. # calls between these two API.
  39. def __init__(self):
  40. self.manual_seed_all_cb = None
  41. self.manual_seed_cb = None
  42. self.call_order = []
  43. def queue_seed_all(self, cb, traceback):
  44. self.manual_seed_all_cb = (cb, traceback)
  45. # update seed_all to be latest
  46. self.call_order = [self.manual_seed_cb, self.manual_seed_all_cb]
  47. def queue_seed(self, cb, traceback):
  48. self.manual_seed_cb = (cb, traceback)
  49. # update seed to be latest
  50. self.call_order = [self.manual_seed_all_cb, self.manual_seed_cb]
  51. def get_calls(self) -> List:
  52. return self.call_order
  53. _lazy_seed_tracker = _LazySeedTracker()
  54. # Define dummy _CudaDeviceProperties type if PyTorch was compiled without CUDA
  55. if hasattr(torch._C, '_CudaDeviceProperties'):
  56. _CudaDeviceProperties = torch._C._CudaDeviceProperties
  57. else:
  58. _CudaDeviceProperties = _dummy_type('_CudaDeviceProperties') # type: ignore[assignment, misc]
  59. if hasattr(torch._C, '_cuda_exchangeDevice'):
  60. _exchange_device = torch._C._cuda_exchangeDevice
  61. else:
  62. def _exchange_device(device: int) -> int:
  63. if device < 0:
  64. return -1
  65. raise RuntimeError("PyTorch was compiled without CUDA support")
  66. if hasattr(torch._C, '_cuda_maybeExchangeDevice'):
  67. _maybe_exchange_device = torch._C._cuda_maybeExchangeDevice
  68. else:
  69. def _maybe_exchange_device(device: int) -> int:
  70. if device < 0:
  71. return -1
  72. raise RuntimeError("PyTorch was compiled without CUDA support")
  73. # Global variables dynamically populated by native code
  74. has_magma: bool = False
  75. has_half: bool = False
  76. default_generators: Tuple[torch._C.Generator] = () # type: ignore[assignment]
  77. def _is_compiled() -> bool:
  78. r"""Returns true if compile with CUDA support."""
  79. return hasattr(torch._C, '_cuda_getDeviceCount')
  80. def _nvml_based_avail() -> bool:
  81. return os.getenv('PYTORCH_NVML_BASED_CUDA_CHECK') == '1'
  82. def is_available() -> bool:
  83. r"""Returns a bool indicating if CUDA is currently available."""
  84. if not _is_compiled():
  85. return False
  86. if _nvml_based_avail():
  87. # The user has set an env variable to request this availability check that attempts to avoid fork poisoning by
  88. # using NVML at the cost of a weaker CUDA availability assessment. Note that if NVML discovery/initialization
  89. # fails, this assessment falls back to the default CUDA Runtime API assessment (`cudaGetDeviceCount`)
  90. return device_count() > 0
  91. else:
  92. # The default availability inspection never throws and returns 0 if the driver is missing or can't
  93. # be initialized. This uses the CUDA Runtime API `cudaGetDeviceCount` which in turn initializes the CUDA Driver
  94. # API via `cuInit`
  95. return torch._C._cuda_getDeviceCount() > 0
  96. def is_bf16_supported():
  97. r"""Returns a bool indicating if the current CUDA/ROCm device supports dtype bfloat16"""
  98. # Check for ROCm, if true return true, no ROCM_VERSION check required,
  99. # since it is supported on AMD GPU archs.
  100. if torch.version.hip:
  101. return True
  102. cu_vers = torch.version.cuda
  103. if cu_vers is not None:
  104. cuda_maj_decide = int(cu_vers.split('.')[0]) >= 11
  105. else:
  106. cuda_maj_decide = False
  107. return torch.cuda.get_device_properties(torch.cuda.current_device()).major >= 8 and cuda_maj_decide
  108. def _sleep(cycles):
  109. torch._C._cuda_sleep(cycles)
  110. def _check_capability():
  111. incorrect_binary_warn = """
  112. Found GPU%d %s which requires CUDA_VERSION >= %d to
  113. work properly, but your PyTorch was compiled
  114. with CUDA_VERSION %d. Please install the correct PyTorch binary
  115. using instructions from https://pytorch.org
  116. """
  117. old_gpu_warn = """
  118. Found GPU%d %s which is of cuda capability %d.%d.
  119. PyTorch no longer supports this GPU because it is too old.
  120. The minimum cuda capability supported by this library is %d.%d.
  121. """
  122. if torch.version.cuda is not None: # on ROCm we don't want this check
  123. CUDA_VERSION = torch._C._cuda_getCompiledVersion()
  124. for d in range(device_count()):
  125. capability = get_device_capability(d)
  126. major = capability[0]
  127. minor = capability[1]
  128. name = get_device_name(d)
  129. current_arch = major * 10 + minor
  130. min_arch = min((int(arch.split("_")[1]) for arch in torch.cuda.get_arch_list()), default=35)
  131. if current_arch < min_arch:
  132. warnings.warn(old_gpu_warn % (d, name, major, minor, min_arch // 10, min_arch % 10))
  133. def _check_cubins():
  134. incompatible_device_warn = """
  135. {} with CUDA capability sm_{} is not compatible with the current PyTorch installation.
  136. The current PyTorch install supports CUDA capabilities {}.
  137. If you want to use the {} GPU with PyTorch, please check the instructions at https://pytorch.org/get-started/locally/
  138. """
  139. if torch.version.cuda is None: # on ROCm we don't want this check
  140. return
  141. arch_list = get_arch_list()
  142. if len(arch_list) == 0:
  143. return
  144. supported_sm = [int(arch.split('_')[1]) for arch in arch_list if 'sm_' in arch]
  145. for idx in range(device_count()):
  146. cap_major, cap_minor = get_device_capability(idx)
  147. # NVIDIA GPU compute architectures are backward compatible within major version
  148. supported = any([sm // 10 == cap_major for sm in supported_sm])
  149. if not supported:
  150. device_name = get_device_name(idx)
  151. capability = cap_major * 10 + cap_minor
  152. warnings.warn(incompatible_device_warn.format(device_name, capability, " ".join(arch_list), device_name))
  153. def is_initialized():
  154. r"""Returns whether PyTorch's CUDA state has been initialized."""
  155. return _initialized and not _is_in_bad_fork()
  156. def _lazy_call(callable, **kwargs):
  157. if is_initialized():
  158. callable()
  159. else:
  160. # TODO(torch_deploy): this accesses linecache, which attempts to read the
  161. # file system to get traceback info. Patch linecache or do something
  162. # else here if this ends up being important.
  163. global _lazy_seed_tracker
  164. if kwargs.get("seed_all", False):
  165. _lazy_seed_tracker.queue_seed_all(callable, traceback.format_stack())
  166. elif kwargs.get("seed", False):
  167. _lazy_seed_tracker.queue_seed(callable, traceback.format_stack())
  168. else:
  169. # Don't store the actual traceback to avoid memory cycle
  170. _queued_calls.append((callable, traceback.format_stack()))
  171. _lazy_call(_check_capability)
  172. _lazy_call(_check_cubins)
  173. class DeferredCudaCallError(Exception):
  174. pass
  175. OutOfMemoryError = torch._C._OutOfMemoryError
  176. def init():
  177. r"""Initialize PyTorch's CUDA state. You may need to call
  178. this explicitly if you are interacting with PyTorch via
  179. its C API, as Python bindings for CUDA functionality will not
  180. be available until this initialization takes place. Ordinary users
  181. should not need this, as all of PyTorch's CUDA methods
  182. automatically initialize CUDA state on-demand.
  183. Does nothing if the CUDA state is already initialized.
  184. """
  185. _lazy_init()
  186. def _lazy_init():
  187. global _initialized, _queued_calls
  188. if is_initialized() or hasattr(_tls, 'is_initializing'):
  189. return
  190. with _initialization_lock:
  191. # We be double-checked locking, boys! This is OK because
  192. # the above test was GIL protected anyway. The inner test
  193. # is for when a thread blocked on some other thread which was
  194. # doing the initialization; when they get the lock, they will
  195. # find there is nothing left to do.
  196. if is_initialized():
  197. return
  198. # It is important to prevent other threads from entering _lazy_init
  199. # immediately, while we are still guaranteed to have the GIL, because some
  200. # of the C calls we make below will release the GIL
  201. if _is_in_bad_fork():
  202. raise RuntimeError(
  203. "Cannot re-initialize CUDA in forked subprocess. To use CUDA with "
  204. "multiprocessing, you must use the 'spawn' start method")
  205. if not hasattr(torch._C, '_cuda_getDeviceCount'):
  206. raise AssertionError("Torch not compiled with CUDA enabled")
  207. if _cudart is None:
  208. raise AssertionError(
  209. "libcudart functions unavailable. It looks like you have a broken build?")
  210. # This function throws if there's a driver initialization error, no GPUs
  211. # are found or any other error occurs
  212. if 'CUDA_MODULE_LOADING' not in os.environ:
  213. os.environ['CUDA_MODULE_LOADING'] = 'LAZY'
  214. torch._C._cuda_init()
  215. # Some of the queued calls may reentrantly call _lazy_init();
  216. # we need to just return without initializing in that case.
  217. # However, we must not let any *other* threads in!
  218. _tls.is_initializing = True
  219. for calls in _lazy_seed_tracker.get_calls():
  220. if calls:
  221. _queued_calls.append(calls)
  222. try:
  223. for queued_call, orig_traceback in _queued_calls:
  224. try:
  225. queued_call()
  226. except Exception as e:
  227. msg = (f"CUDA call failed lazily at initialization with error: {str(e)}\n\n"
  228. f"CUDA call was originally invoked at:\n\n{orig_traceback}")
  229. raise DeferredCudaCallError(msg) from e
  230. finally:
  231. delattr(_tls, 'is_initializing')
  232. _initialized = True
  233. def cudart():
  234. _lazy_init()
  235. return _cudart
  236. class cudaStatus:
  237. SUCCESS: int = 0
  238. ERROR_NOT_READY: int = 34
  239. class CudaError(RuntimeError):
  240. def __init__(self, code: int) -> None:
  241. msg = _cudart.cudaGetErrorString(_cudart.cudaError(code))
  242. super().__init__('{0} ({1})'.format(msg, code))
  243. def check_error(res: int) -> None:
  244. if res != _cudart.cudaError.success:
  245. raise CudaError(res)
  246. class _DeviceGuard:
  247. def __init__(self, index: int):
  248. self.idx = index
  249. self.prev_idx = -1
  250. def __enter__(self):
  251. self.prev_idx = torch.cuda._exchange_device(self.idx)
  252. def __exit__(self, type: Any, value: Any, traceback: Any):
  253. self.idx = torch.cuda._maybe_exchange_device(self.prev_idx)
  254. return False
  255. class device:
  256. r"""Context-manager that changes the selected device.
  257. Args:
  258. device (torch.device or int): device index to select. It's a no-op if
  259. this argument is a negative integer or ``None``.
  260. """
  261. def __init__(self, device: Any):
  262. self.idx = _get_device_index(device, optional=True)
  263. self.prev_idx = -1
  264. def __enter__(self):
  265. self.prev_idx = torch.cuda._exchange_device(self.idx)
  266. def __exit__(self, type: Any, value: Any, traceback: Any):
  267. self.idx = torch.cuda._maybe_exchange_device(self.prev_idx)
  268. return False
  269. class device_of(device):
  270. r"""Context-manager that changes the current device to that of given object.
  271. You can use both tensors and storages as arguments. If a given object is
  272. not allocated on a GPU, this is a no-op.
  273. Args:
  274. obj (Tensor or Storage): object allocated on the selected device.
  275. """
  276. def __init__(self, obj):
  277. idx = obj.get_device() if obj.is_cuda else -1
  278. super().__init__(idx)
  279. def set_device(device: _device_t) -> None:
  280. r"""Sets the current device.
  281. Usage of this function is discouraged in favor of :any:`device`. In most
  282. cases it's better to use ``CUDA_VISIBLE_DEVICES`` environmental variable.
  283. Args:
  284. device (torch.device or int): selected device. This function is a no-op
  285. if this argument is negative.
  286. """
  287. device = _get_device_index(device)
  288. if device >= 0:
  289. torch._C._cuda_setDevice(device)
  290. def get_device_name(device: Optional[_device_t] = None) -> str:
  291. r"""Gets the name of a device.
  292. Args:
  293. device (torch.device or int, optional): device for which to return the
  294. name. This function is a no-op if this argument is a negative
  295. integer. It uses the current device, given by :func:`~torch.cuda.current_device`,
  296. if :attr:`device` is ``None`` (default).
  297. Returns:
  298. str: the name of the device
  299. """
  300. return get_device_properties(device).name
  301. def get_device_capability(device: Optional[_device_t] = None) -> Tuple[int, int]:
  302. r"""Gets the cuda capability of a device.
  303. Args:
  304. device (torch.device or int, optional): device for which to return the
  305. device capability. This function is a no-op if this argument is
  306. a negative integer. It uses the current device, given by
  307. :func:`~torch.cuda.current_device`, if :attr:`device` is ``None``
  308. (default).
  309. Returns:
  310. tuple(int, int): the major and minor cuda capability of the device
  311. """
  312. prop = get_device_properties(device)
  313. return prop.major, prop.minor
  314. def get_device_properties(device: _device_t) -> _CudaDeviceProperties:
  315. r"""Gets the properties of a device.
  316. Args:
  317. device (torch.device or int or str): device for which to return the
  318. properties of the device.
  319. Returns:
  320. _CudaDeviceProperties: the properties of the device
  321. """
  322. _lazy_init() # will define _get_device_properties
  323. device = _get_device_index(device, optional=True)
  324. if device < 0 or device >= device_count():
  325. raise AssertionError("Invalid device id")
  326. return _get_device_properties(device) # type: ignore[name-defined]
  327. def can_device_access_peer(device: _device_t, peer_device: _device_t) -> bool:
  328. r"""Checks if peer access between two devices is possible.
  329. """
  330. _lazy_init()
  331. device = _get_device_index(device, optional=True)
  332. peer_device = _get_device_index(peer_device)
  333. if device < 0 or device >= device_count():
  334. raise AssertionError("Invalid device id")
  335. if peer_device < 0 or peer_device >= device_count():
  336. raise AssertionError("Invalid peer device id")
  337. return torch._C._cuda_canDeviceAccessPeer(device, peer_device)
  338. class StreamContext:
  339. r"""Context-manager that selects a given stream.
  340. All CUDA kernels queued within its context will be enqueued on a selected
  341. stream.
  342. Args:
  343. Stream (Stream): selected stream. This manager is a no-op if it's
  344. ``None``.
  345. .. note:: Streams are per-device.
  346. """
  347. cur_stream : Optional['torch.cuda.Stream']
  348. def __init__(self, stream: Optional['torch.cuda.Stream']):
  349. self.stream = stream
  350. self.idx = _get_device_index(None, True)
  351. if not torch.jit.is_scripting():
  352. if self.idx is None:
  353. self.idx = -1
  354. self.src_prev_stream = None if not torch.jit.is_scripting() else torch.cuda.default_stream(None)
  355. self.dst_prev_stream = None if not torch.jit.is_scripting() else torch.cuda.default_stream(None)
  356. def __enter__(self):
  357. # Local cur_stream variable for type refinement
  358. cur_stream = self.stream
  359. # Return if stream is None or CUDA device not available
  360. if cur_stream is None or self.idx == -1:
  361. return
  362. self.src_prev_stream = torch.cuda.current_stream(None)
  363. # If the stream is not on the current device, then
  364. # set the current stream on the device
  365. if self.src_prev_stream.device != cur_stream.device:
  366. with device(cur_stream.device):
  367. self.dst_prev_stream = torch.cuda.current_stream(cur_stream.device)
  368. torch.cuda.set_stream(cur_stream)
  369. def __exit__(self, type: Any, value: Any, traceback: Any):
  370. # Local cur_stream variable for type refinement
  371. cur_stream = self.stream
  372. # If stream is None or no CUDA device available, return
  373. if cur_stream is None or self.idx == -1:
  374. return
  375. # Reset the stream on the original device
  376. # and destination device
  377. if self.src_prev_stream.device != cur_stream.device: # type: ignore[union-attr]
  378. torch.cuda.set_stream(self.dst_prev_stream) # type: ignore[arg-type]
  379. torch.cuda.set_stream(self.src_prev_stream) # type: ignore[arg-type]
  380. def stream(stream: Optional['torch.cuda.Stream']) -> StreamContext:
  381. r"""Wrapper around the Context-manager StreamContext that
  382. selects a given stream.
  383. Arguments:
  384. stream (Stream): selected stream. This manager is a no-op if it's
  385. ``None``.
  386. ..Note:: In eager mode stream is of type Stream class while in JIT it is
  387. an object of the custom class ``torch.classes.cuda.Stream``.
  388. """
  389. return StreamContext(stream)
  390. def set_stream(stream: Stream):
  391. r"""Sets the current stream.This is a wrapper API to set the stream.
  392. Usage of this function is discouraged in favor of the ``stream``
  393. context manager.
  394. Args:
  395. stream (Stream): selected stream. This function is a no-op
  396. if this argument is ``None``.
  397. """
  398. if stream is None:
  399. return
  400. torch._C._cuda_setStream(stream_id=stream.stream_id, device_index=stream.device_index, device_type=stream.device_type)
  401. def _parse_visible_devices() -> Union[List[int], List[str]]:
  402. """Parse CUDA_VISIBLE_DEVICES environment variable."""
  403. var = os.getenv("CUDA_VISIBLE_DEVICES")
  404. if var is None:
  405. return list(range(64))
  406. def _strtoul(s: str) -> int:
  407. """Return -1 or positive integer sequence string starts with,"""
  408. if not s:
  409. return -1
  410. for idx, c in enumerate(s):
  411. if not (c.isdigit() or (idx == 0 and c in '+-')):
  412. break
  413. if idx + 1 == len(s):
  414. idx += 1
  415. return int(s[:idx]) if idx > 0 else -1
  416. def parse_list_with_prefix(lst: str, prefix: str) -> List[str]:
  417. rcs: List[str] = []
  418. for elem in lst.split(","):
  419. # Repeated id results in empty set
  420. if elem in rcs:
  421. return cast(List[str], [])
  422. # Anything other but prefix is ignored
  423. if not elem.startswith(prefix):
  424. break
  425. rcs.append(elem)
  426. return rcs
  427. if var.startswith("GPU-"):
  428. return parse_list_with_prefix(var, "GPU-")
  429. if var.startswith("MIG-"):
  430. return parse_list_with_prefix(var, "MIG-")
  431. # CUDA_VISIBLE_DEVICES uses something like strtoul
  432. # which makes `1gpu2,2ampere` is equivalent to `1,2`
  433. rc: List[int] = []
  434. for elem in var.split(","):
  435. x = _strtoul(elem.strip())
  436. # Repeated ordinal results in empty set
  437. if x in rc:
  438. return cast(List[int], [])
  439. # Negative value aborts the sequence
  440. if x < 0:
  441. break
  442. rc.append(x)
  443. return rc
  444. def _raw_device_count_nvml() -> int:
  445. """Return number of devices as reported by NVML
  446. or negative value if NVML discovery/initialization failed."""
  447. from ctypes import CDLL, c_int, byref
  448. nvml_h = CDLL("libnvidia-ml.so.1")
  449. rc = nvml_h.nvmlInit()
  450. if rc != 0:
  451. warnings.warn("Can't initialize NVML")
  452. return -1
  453. dev_count = c_int(-1)
  454. rc = nvml_h.nvmlDeviceGetCount_v2(byref(dev_count))
  455. if rc != 0:
  456. warnings.warn("Can't get nvml device count")
  457. return -1
  458. del nvml_h
  459. return dev_count.value
  460. def _raw_device_uuid_nvml() -> Optional[List[str]]:
  461. """Return list of device UUID as reported by NVML
  462. or None if NVM discovery/initialization failed."""
  463. from ctypes import CDLL, c_int, c_void_p, create_string_buffer, byref
  464. nvml_h = CDLL("libnvidia-ml.so.1")
  465. rc = nvml_h.nvmlInit()
  466. if rc != 0:
  467. warnings.warn("Can't initialize NVML")
  468. return None
  469. dev_count = c_int(-1)
  470. rc = nvml_h.nvmlDeviceGetCount_v2(byref(dev_count))
  471. if rc != 0:
  472. warnings.warn("Can't get nvml device count")
  473. return None
  474. uuids: List[str] = []
  475. for idx in range(dev_count.value):
  476. dev_id = c_void_p()
  477. rc = nvml_h.nvmlDeviceGetHandleByIndex_v2(idx, byref(dev_id))
  478. if rc != 0:
  479. warnings.warn("Can't get device handle")
  480. return None
  481. buf_len = 96
  482. buf = create_string_buffer(buf_len)
  483. rc = nvml_h.nvmlDeviceGetUUID(dev_id, buf, buf_len)
  484. if rc != 0:
  485. warnings.warn("Can't get device UUID")
  486. return None
  487. uuids.append(buf.raw.decode("ascii").strip('\0'))
  488. del nvml_h
  489. return uuids
  490. def _transform_uuid_to_ordinals(candidates: List[str], uuids: List[str]) -> List[int]:
  491. """Given the set of partial uuids and list of known uuids builds
  492. a set of ordinals excluding ambiguous partials IDs"""
  493. def uuid_to_orinal(candidate: str, uuids: List[str]) -> int:
  494. best_match = -1
  495. for idx, uuid in enumerate(uuids):
  496. if not uuid.startswith(candidate):
  497. continue
  498. # Ambigous candidate
  499. if best_match != -1:
  500. return -1
  501. best_match = idx
  502. return best_match
  503. rc: List[int] = []
  504. for candidate in candidates:
  505. idx = uuid_to_orinal(candidate, uuids)
  506. # First invalid ordinal stops parsing
  507. if idx < 0:
  508. break
  509. # Duplicates result in empty set
  510. if idx in rc:
  511. return cast(List[int], [])
  512. rc.append(idx)
  513. return rc
  514. def _device_count_nvml() -> int:
  515. """Return number of devices as reported by NVML taking CUDA_VISIBLE_DEVICES into account.
  516. Negative value is returned if NVML discovery or initialization has failed."""
  517. visible_devices = _parse_visible_devices()
  518. if not visible_devices:
  519. return 0
  520. try:
  521. if type(visible_devices[0]) is str:
  522. # Skip MIG parsing
  523. if visible_devices[0].startswith("MIG-"):
  524. return -1
  525. uuids = _raw_device_uuid_nvml()
  526. if uuids is None:
  527. return -1
  528. visible_devices = _transform_uuid_to_ordinals(cast(List[str], visible_devices), uuids)
  529. else:
  530. raw_cnt = _raw_device_count_nvml()
  531. if raw_cnt <= 0:
  532. return raw_cnt
  533. # Trim the list up to a maximum available device
  534. for idx, val in enumerate(visible_devices):
  535. if cast(int, val) >= raw_cnt:
  536. return idx
  537. except OSError:
  538. return -1
  539. except AttributeError:
  540. return -1
  541. return len(visible_devices)
  542. @lru_cache(maxsize=1)
  543. def device_count() -> int:
  544. r"""Returns the number of GPUs available."""
  545. if not _is_compiled():
  546. return 0
  547. nvml_count = _device_count_nvml()
  548. return torch._C._cuda_getDeviceCount() if nvml_count < 0 else nvml_count
  549. def get_arch_list() -> List[str]:
  550. r"""Returns list CUDA architectures this library was compiled for."""
  551. if not is_available():
  552. return []
  553. arch_flags = torch._C._cuda_getArchFlags()
  554. if arch_flags is None:
  555. return []
  556. return arch_flags.split()
  557. def get_gencode_flags() -> str:
  558. r"""Returns NVCC gencode flags this library was compiled with."""
  559. arch_list = get_arch_list()
  560. if len(arch_list) == 0:
  561. return ""
  562. arch_list_ = [arch.split("_") for arch in arch_list]
  563. return " ".join([f"-gencode compute=compute_{arch},code={kind}_{arch}" for (kind, arch) in arch_list_])
  564. def current_device() -> int:
  565. r"""Returns the index of a currently selected device."""
  566. _lazy_init()
  567. return torch._C._cuda_getDevice()
  568. def synchronize(device: _device_t = None) -> None:
  569. r"""Waits for all kernels in all streams on a CUDA device to complete.
  570. Args:
  571. device (torch.device or int, optional): device for which to synchronize.
  572. It uses the current device, given by :func:`~torch.cuda.current_device`,
  573. if :attr:`device` is ``None`` (default).
  574. """
  575. _lazy_init()
  576. with torch.cuda.device(device):
  577. return torch._C._cuda_synchronize()
  578. def ipc_collect():
  579. r"""Force collects GPU memory after it has been released by CUDA IPC.
  580. .. note::
  581. Checks if any sent CUDA tensors could be cleaned from the memory. Force
  582. closes shared memory file used for reference counting if there is no
  583. active counters. Useful when the producer process stopped actively sending
  584. tensors and want to release unused memory.
  585. """
  586. _lazy_init()
  587. return torch._C._cuda_ipc_collect()
  588. def current_stream(device: Optional[_device_t] = None) -> Stream:
  589. r"""Returns the currently selected :class:`Stream` for a given device.
  590. Args:
  591. device (torch.device or int, optional): selected device. Returns
  592. the currently selected :class:`Stream` for the current device, given
  593. by :func:`~torch.cuda.current_device`, if :attr:`device` is ``None``
  594. (default).
  595. """
  596. _lazy_init()
  597. streamdata = torch._C._cuda_getCurrentStream(
  598. _get_device_index(device, optional=True))
  599. return Stream(stream_id=streamdata[0], device_index=streamdata[1], device_type=streamdata[2])
  600. def default_stream(device: Optional[_device_t] = None) -> Stream:
  601. r"""Returns the default :class:`Stream` for a given device.
  602. Args:
  603. device (torch.device or int, optional): selected device. Returns
  604. the default :class:`Stream` for the current device, given by
  605. :func:`~torch.cuda.current_device`, if :attr:`device` is ``None``
  606. (default).
  607. """
  608. _lazy_init()
  609. streamdata = torch._C._cuda_getDefaultStream(
  610. _get_device_index(device, optional=True))
  611. return Stream(stream_id=streamdata[0], device_index=streamdata[1], device_type=streamdata[2])
  612. def current_blas_handle():
  613. r"""Returns cublasHandle_t pointer to current cuBLAS handle"""
  614. _lazy_init()
  615. return torch._C._cuda_getCurrentBlasHandle()
  616. def set_sync_debug_mode(debug_mode: Union[int, str]) -> None:
  617. r"""Sets the debug mode for cuda synchronizing operations.
  618. Args:
  619. debug_mode(str or int): if "default" or 0, don't error or warn on synchronizing operations,
  620. if "warn" or 1, warn on synchronizing operations, if "error" or 2, error out synchronizing operations.
  621. Warning:
  622. This is an experimental feature, and not all synchronizing operations will trigger warning or error. In
  623. particular, operations in torch.distributed and torch.sparse namespaces are not covered yet.
  624. """
  625. _lazy_init()
  626. if isinstance(debug_mode, str):
  627. if debug_mode == "default":
  628. debug_mode = 0
  629. elif debug_mode == "warn":
  630. debug_mode = 1
  631. elif debug_mode == "error":
  632. debug_mode = 2
  633. else:
  634. raise RuntimeError("invalid value of debug_mode, expected one of `default`, `warn`, `error`")
  635. torch._C._cuda_set_sync_debug_mode(debug_mode)
  636. def get_sync_debug_mode() -> int:
  637. r"""Returns current value of debug mode for cuda synchronizing operations."""
  638. _lazy_init()
  639. return torch._C._cuda_get_sync_debug_mode()
  640. def memory_usage(device: Optional[Union[Device, int]] = None) -> int:
  641. r"""Returns the percent of time over the past sample period during which global (device)
  642. memory was being read or written. as given by `nvidia-smi`.
  643. Args:
  644. device (torch.device or int, optional): selected device. Returns
  645. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  646. if :attr:`device` is ``None`` (default).
  647. Warning: Each sample period may be between 1 second and 1/6 second,
  648. depending on the product being queried.
  649. """
  650. try:
  651. import pynvml # type: ignore[import]
  652. except ModuleNotFoundError as e:
  653. raise ModuleNotFoundError("pynvml module not found, please install pynvml") from e
  654. from pynvml import NVMLError_DriverNotLoaded
  655. try:
  656. pynvml.nvmlInit()
  657. except NVMLError_DriverNotLoaded as e:
  658. raise RuntimeError("cuda driver can't be loaded, is cuda enabled?") from e
  659. device = _get_device_index(device, optional=True)
  660. handle = pynvml.nvmlDeviceGetHandleByIndex(device)
  661. return pynvml.nvmlDeviceGetUtilizationRates(handle).memory
  662. def utilization(device: Optional[Union[Device, int]] = None) -> int:
  663. r"""Returns the percent of time over the past sample period during which one or
  664. more kernels was executing on the GPU as given by `nvidia-smi`.
  665. Args:
  666. device (torch.device or int, optional): selected device. Returns
  667. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  668. if :attr:`device` is ``None`` (default).
  669. Warning: Each sample period may be between 1 second and 1/6 second,
  670. depending on the product being queried.
  671. """
  672. try:
  673. import pynvml # type: ignore[import]
  674. except ModuleNotFoundError as e:
  675. raise ModuleNotFoundError("pynvml module not found, please install pynvml") from e
  676. from pynvml import NVMLError_DriverNotLoaded
  677. try:
  678. pynvml.nvmlInit()
  679. except NVMLError_DriverNotLoaded as e:
  680. raise RuntimeError("cuda driver can't be loaded, is cuda enabled?") from e
  681. device = _get_device_index(device, optional=True)
  682. handle = pynvml.nvmlDeviceGetHandleByIndex(device)
  683. return pynvml.nvmlDeviceGetUtilizationRates(handle).gpu
  684. from .memory import * # noqa: F403
  685. from .random import * # noqa: F403
  686. ################################################################################
  687. # Define Storage and Tensor classes
  688. ################################################################################
  689. @staticmethod # type: ignore[misc]
  690. def _lazy_new(cls, *args, **kwargs):
  691. _lazy_init()
  692. # We may need to call lazy init again if we are a forked child
  693. # del _CudaBase.__new__
  694. return super(_CudaBase, cls).__new__(cls, *args, **kwargs)
  695. class _CudaBase:
  696. is_cuda = True
  697. is_sparse = False
  698. def type(self, *args, **kwargs):
  699. # We could use a Protocol here to tell mypy that self has `get_device` method
  700. # but it is only available in the typing module on Python >= 3.8
  701. # or on typing_extensions module on Python >= 3.6
  702. with device(self.get_device()): # type: ignore[attr-defined]
  703. return super().type(*args, **kwargs) # type: ignore[misc]
  704. __new__ = _lazy_new
  705. from torch.storage import _LegacyStorage, _warn_typed_storage_removal
  706. class _CudaLegacyStorage(_LegacyStorage):
  707. @classmethod
  708. def from_buffer(cls, *args, **kwargs):
  709. _warn_typed_storage_removal()
  710. raise RuntimeError('from_buffer: Not available for CUDA storage')
  711. @classmethod
  712. def _new_with_weak_ptr(cls, *args, **kwargs):
  713. raise RuntimeError('_new_with_weak_ptr: Not available for CUDA storage')
  714. @classmethod
  715. def _new_shared_filename(cls, manager, obj, size, *, device=None, dtype=None):
  716. raise RuntimeError('_new_shared_filename: Not available for CUDA storage')
  717. class ByteStorage(_CudaLegacyStorage):
  718. @classproperty
  719. def dtype(self):
  720. _warn_typed_storage_removal()
  721. return self._dtype
  722. @classproperty
  723. def _dtype(self):
  724. return torch.uint8
  725. class DoubleStorage(_CudaLegacyStorage):
  726. @classproperty
  727. def dtype(self):
  728. _warn_typed_storage_removal()
  729. return self._dtype
  730. @classproperty
  731. def _dtype(self):
  732. return torch.double
  733. class FloatStorage(_CudaLegacyStorage):
  734. @classproperty
  735. def dtype(self):
  736. _warn_typed_storage_removal()
  737. return self._dtype
  738. @classproperty
  739. def _dtype(self):
  740. return torch.float
  741. class HalfStorage(_CudaLegacyStorage):
  742. @classproperty
  743. def dtype(self):
  744. _warn_typed_storage_removal()
  745. return self._dtype
  746. @classproperty
  747. def _dtype(self):
  748. return torch.half
  749. class LongStorage(_CudaLegacyStorage):
  750. @classproperty
  751. def dtype(self):
  752. _warn_typed_storage_removal()
  753. return self._dtype
  754. @classproperty
  755. def _dtype(self):
  756. return torch.long
  757. class IntStorage(_CudaLegacyStorage):
  758. @classproperty
  759. def dtype(self):
  760. _warn_typed_storage_removal()
  761. return self._dtype
  762. @classproperty
  763. def _dtype(self):
  764. return torch.int
  765. class ShortStorage(_CudaLegacyStorage):
  766. @classproperty
  767. def dtype(self):
  768. _warn_typed_storage_removal()
  769. return self._dtype
  770. @classproperty
  771. def _dtype(self):
  772. return torch.short
  773. class CharStorage(_CudaLegacyStorage):
  774. @classproperty
  775. def dtype(self):
  776. _warn_typed_storage_removal()
  777. return self._dtype
  778. @classproperty
  779. def _dtype(self):
  780. return torch.int8
  781. class BoolStorage(_CudaLegacyStorage):
  782. @classproperty
  783. def dtype(self):
  784. _warn_typed_storage_removal()
  785. return self._dtype
  786. @classproperty
  787. def _dtype(self):
  788. return torch.bool
  789. class BFloat16Storage(_CudaLegacyStorage):
  790. @classproperty
  791. def dtype(self):
  792. _warn_typed_storage_removal()
  793. return self._dtype
  794. @classproperty
  795. def _dtype(self):
  796. return torch.bfloat16
  797. class ComplexDoubleStorage(_CudaLegacyStorage):
  798. @classproperty
  799. def dtype(self):
  800. _warn_typed_storage_removal()
  801. return self._dtype
  802. @classproperty
  803. def _dtype(self):
  804. return torch.cdouble
  805. class ComplexFloatStorage(_CudaLegacyStorage):
  806. @classproperty
  807. def dtype(self):
  808. _warn_typed_storage_removal()
  809. return self._dtype
  810. @classproperty
  811. def _dtype(self):
  812. return torch.cfloat
  813. del _LegacyStorage
  814. del _CudaLegacyStorage
  815. torch._storage_classes.add(DoubleStorage)
  816. torch._storage_classes.add(FloatStorage)
  817. torch._storage_classes.add(LongStorage)
  818. torch._storage_classes.add(IntStorage)
  819. torch._storage_classes.add(ShortStorage)
  820. torch._storage_classes.add(CharStorage)
  821. torch._storage_classes.add(ByteStorage)
  822. torch._storage_classes.add(HalfStorage)
  823. torch._storage_classes.add(BoolStorage)
  824. torch._storage_classes.add(BFloat16Storage)
  825. torch._storage_classes.add(ComplexDoubleStorage)
  826. torch._storage_classes.add(ComplexFloatStorage)
  827. from . import sparse
  828. from . import profiler
  829. from . import nvtx
  830. from . import amp
  831. from . import jiterator
  832. __all__ = [
  833. # Typed storage and tensors
  834. 'BFloat16Storage', 'BFloat16Tensor',
  835. 'BoolStorage', 'BoolTensor',
  836. 'ByteStorage', 'ByteTensor',
  837. 'CharStorage', 'CharTensor',
  838. 'ComplexDoubleStorage', 'ComplexFloatStorage',
  839. 'DoubleStorage', 'DoubleTensor',
  840. 'FloatStorage', 'FloatTensor',
  841. 'HalfStorage', 'HalfTensor',
  842. 'IntStorage', 'IntTensor',
  843. 'LongStorage', 'LongTensor',
  844. 'ShortStorage', 'ShortTensor',
  845. 'CUDAGraph', 'CudaError', 'DeferredCudaCallError', 'Event', 'ExternalStream', 'OutOfMemoryError',
  846. 'Stream', 'StreamContext', 'amp', 'caching_allocator_alloc', 'caching_allocator_delete', 'can_device_access_peer',
  847. 'check_error', 'cudaStatus', 'cudart', 'current_blas_handle', 'current_device', 'current_stream', 'default_generators',
  848. 'default_stream', 'device', 'device_count', 'device_of', 'empty_cache', 'get_allocator_backend', 'CUDAPluggableAllocator',
  849. 'change_current_allocator', 'get_arch_list', 'get_device_capability', 'get_device_name', 'get_device_properties',
  850. 'get_gencode_flags', 'get_rng_state', 'get_rng_state_all', 'get_sync_debug_mode', 'graph', 'graph_pool_handle', 'graphs',
  851. 'has_half', 'has_magma', 'init', 'initial_seed', 'ipc_collect', 'is_available', 'is_bf16_supported',
  852. 'is_current_stream_capturing', 'is_initialized', 'jiterator', 'list_gpu_processes', 'make_graphed_callables',
  853. 'manual_seed', 'manual_seed_all', 'max_memory_allocated', 'max_memory_cached', 'max_memory_reserved',
  854. 'mem_get_info', 'memory', 'memory_allocated', 'memory_cached', 'memory_reserved', 'memory_snapshot',
  855. 'memory_stats', 'memory_stats_as_nested_dict', 'memory_summary', 'memory_usage', 'nccl', 'nvtx', 'profiler',
  856. 'random', 'reset_accumulated_memory_stats', 'reset_max_memory_allocated', 'reset_max_memory_cached',
  857. 'reset_peak_memory_stats', 'seed', 'seed_all', 'set_device', 'set_per_process_memory_fraction', 'set_rng_state',
  858. 'set_rng_state_all', 'set_stream', 'set_sync_debug_mode', 'sparse', 'stream', 'streams', 'synchronize', 'utilization']