memory.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. # mypy: allow-untyped-defs
  2. r"""This package adds support for device memory management implemented in CUDA."""
  3. import collections
  4. import contextlib
  5. import ctypes
  6. import pickle
  7. import sys
  8. import warnings
  9. from inspect import signature
  10. from typing import Any, Dict, Optional, Tuple, Union
  11. from typing_extensions import deprecated
  12. import torch
  13. from torch import _C
  14. from torch.types import Device
  15. from .._utils import _dummy_type
  16. from . import (
  17. _get_amdsmi_device_index,
  18. _get_device_index,
  19. _get_nvml_device_index,
  20. _lazy_init,
  21. is_initialized,
  22. )
  23. from ._memory_viz import memory as _memory, segments as _segments
  24. __all__ = [
  25. "caching_allocator_alloc",
  26. "caching_allocator_delete",
  27. "set_per_process_memory_fraction",
  28. "empty_cache",
  29. "memory_stats",
  30. "memory_stats_as_nested_dict",
  31. "reset_accumulated_memory_stats",
  32. "reset_peak_memory_stats",
  33. "reset_max_memory_allocated",
  34. "reset_max_memory_cached",
  35. "memory_allocated",
  36. "max_memory_allocated",
  37. "memory_reserved",
  38. "max_memory_reserved",
  39. "memory_cached",
  40. "max_memory_cached",
  41. "memory_snapshot",
  42. "memory_summary",
  43. "list_gpu_processes",
  44. "mem_get_info",
  45. "get_allocator_backend",
  46. "CUDAPluggableAllocator",
  47. "change_current_allocator",
  48. ]
  49. if not hasattr(torch._C, "_cuda_CUDAAllocator"):
  50. # Define dummy base classes
  51. torch._C.__dict__["_cuda_CUDAAllocator"] = _dummy_type("_cuda_CUDAAllocator")
  52. def _host_allocator():
  53. _lazy_init()
  54. return torch._C._cuda_cudaHostAllocator()
  55. @contextlib.contextmanager
  56. def _free_mutex():
  57. torch._C._cuda_lock_mutex()
  58. try:
  59. yield
  60. finally:
  61. torch._C._cuda_unlock_mutex()
  62. def caching_allocator_alloc(size, device: Union[Device, int] = None, stream=None):
  63. r"""Perform a memory allocation using the CUDA memory allocator.
  64. Memory is allocated for a given device and a stream, this
  65. function is intended to be used for interoperability with other
  66. frameworks. Allocated memory is released through
  67. :func:`~torch.cuda.caching_allocator_delete`.
  68. Args:
  69. size (int): number of bytes to be allocated.
  70. device (torch.device or int, optional): selected device. If it is
  71. ``None`` the default CUDA device is used.
  72. stream (torch.cuda.Stream or int, optional): selected stream. If is ``None`` then
  73. the default stream for the selected device is used.
  74. .. note::
  75. See :ref:`cuda-memory-management` for more details about GPU memory
  76. management.
  77. """
  78. if device is None:
  79. device = torch.cuda.current_device()
  80. device = _get_device_index(device)
  81. if stream is None:
  82. stream = torch.cuda.current_stream(device)
  83. if isinstance(stream, torch.cuda.streams.Stream):
  84. stream = stream.cuda_stream
  85. if not isinstance(stream, int):
  86. raise TypeError(
  87. "Invalid type for stream argument, must be "
  88. "`torch.cuda.Stream` or `int` representing a pointer "
  89. "to a existing stream"
  90. )
  91. with torch.cuda.device(device):
  92. return torch._C._cuda_cudaCachingAllocator_raw_alloc(size, stream)
  93. def caching_allocator_delete(mem_ptr):
  94. r"""Delete memory allocated using the CUDA memory allocator.
  95. Memory allocated with :func:`~torch.cuda.caching_allocator_alloc`.
  96. is freed here. The associated device and stream are tracked inside
  97. the allocator.
  98. Args:
  99. mem_ptr (int): memory address to be freed by the allocator.
  100. .. note::
  101. See :ref:`cuda-memory-management` for more details about GPU memory
  102. management.
  103. """
  104. torch._C._cuda_cudaCachingAllocator_raw_delete(mem_ptr)
  105. def set_per_process_memory_fraction(
  106. fraction, device: Union[Device, int] = None
  107. ) -> None:
  108. r"""Set memory fraction for a process.
  109. The fraction is used to limit an caching allocator to allocated memory on a CUDA device.
  110. The allowed value equals the total visible memory multiplied fraction.
  111. If trying to allocate more than the allowed value in a process, will raise an out of
  112. memory error in allocator.
  113. Args:
  114. fraction(float): Range: 0~1. Allowed memory equals total_memory * fraction.
  115. device (torch.device or int, optional): selected device. If it is
  116. ``None`` the default CUDA device is used.
  117. .. note::
  118. In general, the total available free memory is less than the total capacity.
  119. """
  120. _lazy_init()
  121. if device is None:
  122. device = torch.cuda.current_device()
  123. device = _get_device_index(device)
  124. if not isinstance(fraction, float):
  125. raise TypeError("Invalid type for fraction argument, must be `float`")
  126. if fraction < 0 or fraction > 1:
  127. raise ValueError(f"Invalid fraction value: {fraction}. Allowed range: 0~1")
  128. torch._C._cuda_setMemoryFraction(fraction, device)
  129. def empty_cache() -> None:
  130. r"""Release all unoccupied cached memory currently held by the caching
  131. allocator so that those can be used in other GPU application and visible in
  132. `nvidia-smi`.
  133. .. note::
  134. :func:`~torch.cuda.empty_cache` doesn't increase the amount of GPU
  135. memory available for PyTorch. However, it may help reduce fragmentation
  136. of GPU memory in certain cases. See :ref:`cuda-memory-management` for
  137. more details about GPU memory management.
  138. """
  139. if is_initialized():
  140. torch._C._cuda_emptyCache()
  141. def memory_stats(device: Union[Device, int] = None) -> Dict[str, Any]:
  142. r"""Return a dictionary of CUDA memory allocator statistics for a given device.
  143. The return value of this function is a dictionary of statistics, each of
  144. which is a non-negative integer.
  145. Core statistics:
  146. - ``"allocated.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  147. number of allocation requests received by the memory allocator.
  148. - ``"allocated_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  149. amount of allocated memory.
  150. - ``"segment.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  151. number of reserved segments from ``cudaMalloc()``.
  152. - ``"reserved_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  153. amount of reserved memory.
  154. - ``"active.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  155. number of active memory blocks.
  156. - ``"active_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  157. amount of active memory.
  158. - ``"inactive_split.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  159. number of inactive, non-releasable memory blocks.
  160. - ``"inactive_split_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  161. amount of inactive, non-releasable memory.
  162. For these core statistics, values are broken down as follows.
  163. Pool type:
  164. - ``all``: combined statistics across all memory pools.
  165. - ``large_pool``: statistics for the large allocation pool
  166. (as of October 2019, for size >= 1MB allocations).
  167. - ``small_pool``: statistics for the small allocation pool
  168. (as of October 2019, for size < 1MB allocations).
  169. Metric type:
  170. - ``current``: current value of this metric.
  171. - ``peak``: maximum value of this metric.
  172. - ``allocated``: historical total increase in this metric.
  173. - ``freed``: historical total decrease in this metric.
  174. In addition to the core statistics, we also provide some simple event
  175. counters:
  176. - ``"num_alloc_retries"``: number of failed ``cudaMalloc`` calls that
  177. result in a cache flush and retry.
  178. - ``"num_ooms"``: number of out-of-memory errors thrown.
  179. - ``"num_sync_all_streams"``: number of ``synchronize_and_free_events`` calls.
  180. - ``"num_device_alloc"``: number of CUDA allocation calls. This includes both
  181. cuMemMap and cudaMalloc.
  182. - ``"num_device_free"``: number of CUDA free calls. This includes both cuMemUnmap
  183. and cudaFree.
  184. The caching allocator can be configured via ENV to not split blocks larger than a
  185. defined size (see Memory Management section of the Cuda Semantics documentation).
  186. This helps avoid memory fragmentation but may have a performance
  187. penalty. Additional outputs to assist with tuning and evaluating impact:
  188. - ``"max_split_size"``: blocks above this size will not be split.
  189. - ``"oversize_allocations.{current,peak,allocated,freed}"``:
  190. number of over-size allocation requests received by the memory allocator.
  191. - ``"oversize_segments.{current,peak,allocated,freed}"``:
  192. number of over-size reserved segments from ``cudaMalloc()``.
  193. The caching allocator can be configured via ENV to round memory allocations in order
  194. to reduce fragmentation. Sometimes the overhead from rounding can be higher than
  195. the fragmentation it helps reduce. The following stat can be used to check if
  196. rounding adds too much overhead:
  197. - ``"requested_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  198. memory requested by client code, compare this with allocated_bytes to check if
  199. allocation rounding adds too much overhead.
  200. Args:
  201. device (torch.device or int, optional): selected device. Returns
  202. statistics for the current device, given by :func:`~torch.cuda.current_device`,
  203. if :attr:`device` is ``None`` (default).
  204. .. note::
  205. See :ref:`cuda-memory-management` for more details about GPU memory
  206. management.
  207. .. note::
  208. With :ref:`backend:cudaMallocAsync<cuda-memory-envvars>`, some stats are not
  209. meaningful, and are always reported as zero.
  210. """
  211. result = []
  212. def _recurse_add_to_result(prefix, obj):
  213. if isinstance(obj, dict):
  214. if len(prefix) > 0:
  215. prefix += "."
  216. for k, v in obj.items():
  217. _recurse_add_to_result(prefix + k, v)
  218. else:
  219. result.append((prefix, obj))
  220. stats = memory_stats_as_nested_dict(device=device)
  221. _recurse_add_to_result("", stats)
  222. result.sort()
  223. return collections.OrderedDict(result)
  224. def memory_stats_as_nested_dict(device: Union[Device, int] = None) -> Dict[str, Any]:
  225. r"""Return the result of :func:`~torch.cuda.memory_stats` as a nested dictionary."""
  226. if not is_initialized():
  227. return {}
  228. device = _get_device_index(device, optional=True)
  229. return torch._C._cuda_memoryStats(device)
  230. def reset_accumulated_memory_stats(device: Union[Device, int] = None) -> None:
  231. r"""Reset the "accumulated" (historical) stats tracked by the CUDA memory allocator.
  232. See :func:`~torch.cuda.memory_stats` for details. Accumulated stats correspond to
  233. the `"allocated"` and `"freed"` keys in each individual stat dict, as well as
  234. `"num_alloc_retries"` and `"num_ooms"`.
  235. Args:
  236. device (torch.device or int, optional): selected device. Returns
  237. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  238. if :attr:`device` is ``None`` (default).
  239. .. note::
  240. See :ref:`cuda-memory-management` for more details about GPU memory
  241. management.
  242. """
  243. device = _get_device_index(device, optional=True)
  244. return torch._C._cuda_resetAccumulatedMemoryStats(device)
  245. def reset_peak_memory_stats(device: Union[Device, int] = None) -> None:
  246. r"""Reset the "peak" stats tracked by the CUDA memory allocator.
  247. See :func:`~torch.cuda.memory_stats` for details. Peak stats correspond to the
  248. `"peak"` key in each individual stat dict.
  249. Args:
  250. device (torch.device or int, optional): selected device. Returns
  251. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  252. if :attr:`device` is ``None`` (default).
  253. .. note::
  254. See :ref:`cuda-memory-management` for more details about GPU memory
  255. management.
  256. """
  257. device = _get_device_index(device, optional=True)
  258. return torch._C._cuda_resetPeakMemoryStats(device)
  259. def reset_max_memory_allocated(device: Union[Device, int] = None) -> None:
  260. r"""Reset the starting point in tracking maximum GPU memory occupied by tensors for a given device.
  261. See :func:`~torch.cuda.max_memory_allocated` for details.
  262. Args:
  263. device (torch.device or int, optional): selected device. Returns
  264. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  265. if :attr:`device` is ``None`` (default).
  266. .. warning::
  267. This function now calls :func:`~torch.cuda.reset_peak_memory_stats`, which resets
  268. /all/ peak memory stats.
  269. .. note::
  270. See :ref:`cuda-memory-management` for more details about GPU memory
  271. management.
  272. """
  273. warnings.warn(
  274. "torch.cuda.reset_max_memory_allocated now calls torch.cuda.reset_peak_memory_stats, "
  275. "which resets /all/ peak memory stats.",
  276. FutureWarning,
  277. )
  278. return reset_peak_memory_stats(device=device)
  279. def reset_max_memory_cached(device: Union[Device, int] = None) -> None:
  280. r"""Reset the starting point in tracking maximum GPU memory managed by the caching allocator for a given device.
  281. See :func:`~torch.cuda.max_memory_cached` for details.
  282. Args:
  283. device (torch.device or int, optional): selected device. Returns
  284. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  285. if :attr:`device` is ``None`` (default).
  286. .. warning::
  287. This function now calls :func:`~torch.cuda.reset_peak_memory_stats`, which resets
  288. /all/ peak memory stats.
  289. .. note::
  290. See :ref:`cuda-memory-management` for more details about GPU memory
  291. management.
  292. """
  293. warnings.warn(
  294. "torch.cuda.reset_max_memory_cached now calls torch.cuda.reset_peak_memory_stats, "
  295. "which resets /all/ peak memory stats.",
  296. FutureWarning,
  297. )
  298. return reset_peak_memory_stats(device=device)
  299. def memory_allocated(device: Union[Device, int] = None) -> int:
  300. r"""Return the current GPU memory occupied by tensors in bytes for a given device.
  301. Args:
  302. device (torch.device or int, optional): selected device. Returns
  303. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  304. if :attr:`device` is ``None`` (default).
  305. .. note::
  306. This is likely less than the amount shown in `nvidia-smi` since some
  307. unused memory can be held by the caching allocator and some context
  308. needs to be created on GPU. See :ref:`cuda-memory-management` for more
  309. details about GPU memory management.
  310. """
  311. return memory_stats(device=device).get("allocated_bytes.all.current", 0)
  312. def max_memory_allocated(device: Union[Device, int] = None) -> int:
  313. r"""Return the maximum GPU memory occupied by tensors in bytes for a given device.
  314. By default, this returns the peak allocated memory since the beginning of
  315. this program. :func:`~torch.cuda.reset_peak_memory_stats` can be used to
  316. reset the starting point in tracking this metric. For example, these two
  317. functions can measure the peak allocated memory usage of each iteration in a
  318. training loop.
  319. Args:
  320. device (torch.device or int, optional): selected device. Returns
  321. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  322. if :attr:`device` is ``None`` (default).
  323. .. note::
  324. See :ref:`cuda-memory-management` for more details about GPU memory
  325. management.
  326. """
  327. return memory_stats(device=device).get("allocated_bytes.all.peak", 0)
  328. def memory_reserved(device: Union[Device, int] = None) -> int:
  329. r"""Return the current GPU memory managed by the caching allocator in bytes for a given device.
  330. Args:
  331. device (torch.device or int, optional): selected device. Returns
  332. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  333. if :attr:`device` is ``None`` (default).
  334. .. note::
  335. See :ref:`cuda-memory-management` for more details about GPU memory
  336. management.
  337. """
  338. return memory_stats(device=device).get("reserved_bytes.all.current", 0)
  339. def max_memory_reserved(device: Union[Device, int] = None) -> int:
  340. r"""Return the maximum GPU memory managed by the caching allocator in bytes for a given device.
  341. By default, this returns the peak cached memory since the beginning of this
  342. program. :func:`~torch.cuda.reset_peak_memory_stats` can be used to reset
  343. the starting point in tracking this metric. For example, these two functions
  344. can measure the peak cached memory amount of each iteration in a training
  345. loop.
  346. Args:
  347. device (torch.device or int, optional): selected device. Returns
  348. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  349. if :attr:`device` is ``None`` (default).
  350. .. note::
  351. See :ref:`cuda-memory-management` for more details about GPU memory
  352. management.
  353. """
  354. return memory_stats(device=device).get("reserved_bytes.all.peak", 0)
  355. @deprecated(
  356. "`torch.cuda.memory_cached` has been renamed to `torch.cuda.memory_reserved`",
  357. category=FutureWarning,
  358. )
  359. def memory_cached(device: Union[Device, int] = None) -> int:
  360. r"""Deprecated; see :func:`~torch.cuda.memory_reserved`."""
  361. return memory_reserved(device=device)
  362. @deprecated(
  363. "`torch.cuda.max_memory_cached` has been renamed to `torch.cuda.max_memory_reserved`",
  364. category=FutureWarning,
  365. )
  366. def max_memory_cached(device: Union[Device, int] = None) -> int:
  367. r"""Deprecated; see :func:`~torch.cuda.max_memory_reserved`."""
  368. return max_memory_reserved(device=device)
  369. def memory_snapshot():
  370. r"""Return a snapshot of the CUDA memory allocator state across all devices.
  371. Interpreting the output of this function requires familiarity with the
  372. memory allocator internals.
  373. .. note::
  374. See :ref:`cuda-memory-management` for more details about GPU memory
  375. management.
  376. """
  377. return torch._C._cuda_memorySnapshot()["segments"]
  378. def memory_summary(device: Union[Device, int] = None, abbreviated: bool = False) -> str:
  379. r"""Return a human-readable printout of the current memory allocator statistics for a given device.
  380. This can be useful to display periodically during training, or when
  381. handling out-of-memory exceptions.
  382. Args:
  383. device (torch.device or int, optional): selected device. Returns
  384. printout for the current device, given by :func:`~torch.cuda.current_device`,
  385. if :attr:`device` is ``None`` (default).
  386. abbreviated (bool, optional): whether to return an abbreviated summary
  387. (default: False).
  388. .. note::
  389. See :ref:`cuda-memory-management` for more details about GPU memory
  390. management.
  391. """
  392. device = _get_device_index(device, optional=True)
  393. stats = memory_stats(device=device)
  394. def _format_size(sz, pref_sz):
  395. prefixes = ["B ", "KiB", "MiB", "GiB", "TiB", "PiB"]
  396. prefix = prefixes[0]
  397. for new_prefix in prefixes[1:]:
  398. if pref_sz < 768 * 1024:
  399. break
  400. prefix = new_prefix
  401. sz //= 1024
  402. pref_sz /= 1024
  403. return f"{sz:6d} {prefix}"
  404. def _format_count(cnt, pref_cnt):
  405. prefixes = [" ", "K", "M"]
  406. prefix = prefixes[0]
  407. for new_prefix in prefixes[1:]:
  408. if pref_cnt < 750 * 1000:
  409. break
  410. prefix = new_prefix
  411. cnt //= 1000
  412. pref_cnt /= 1000
  413. return f"{cnt:7d} {prefix} "
  414. metrics_to_display = [
  415. ("allocated_bytes", "Allocated memory", _format_size),
  416. ("active_bytes", "Active memory", _format_size),
  417. ("requested_bytes", "Requested memory", _format_size),
  418. ("reserved_bytes", "GPU reserved memory", _format_size),
  419. ("inactive_split_bytes", "Non-releasable memory", _format_size),
  420. ("allocation", "Allocations", _format_count),
  421. ("active", "Active allocs", _format_count),
  422. ("segment", "GPU reserved segments", _format_count),
  423. ("inactive_split", "Non-releasable allocs", _format_count),
  424. ]
  425. lines = []
  426. lines.append("=" * 75)
  427. lines.append(" {_:16} PyTorch CUDA memory summary, device ID {device:<17d} ")
  428. lines.append("-" * 75)
  429. lines.append(
  430. " {_:9} CUDA OOMs: {num_ooms:<12d} | {_:6} cudaMalloc retries: {num_alloc_retries:<8d} "
  431. )
  432. lines.append("=" * 75)
  433. lines.append(
  434. " Metric | Cur Usage | Peak Usage | Tot Alloc | Tot Freed "
  435. )
  436. for metric_key, metric_name, formatter in metrics_to_display:
  437. lines.append("-" * 75)
  438. submetrics = [("all", metric_name)]
  439. if not abbreviated:
  440. submetrics.append(("large_pool", " from large pool"))
  441. submetrics.append(("small_pool", " from small pool"))
  442. current_prefval, peak_prefval, allocated_prefval, freed_prefval = (
  443. None,
  444. None,
  445. None,
  446. None,
  447. )
  448. for submetric_key, submetric_name in submetrics:
  449. prefix = metric_key + "." + submetric_key + "."
  450. current = stats[prefix + "current"]
  451. peak = stats[prefix + "peak"]
  452. allocated = stats[prefix + "allocated"]
  453. freed = stats[prefix + "freed"]
  454. if current_prefval is None:
  455. current_prefval = current
  456. peak_prefval = peak
  457. allocated_prefval = allocated
  458. freed_prefval = freed
  459. lines.append(
  460. f" {submetric_name:<21} | {formatter(current, current_prefval)} | {formatter(peak, peak_prefval)} | "
  461. f"{formatter(allocated, allocated_prefval)} | {formatter(freed, freed_prefval)} ",
  462. )
  463. metrics_to_display = [
  464. ("oversize_allocations", "Oversize allocations", _format_count),
  465. ("oversize_segments", "Oversize GPU segments", _format_count),
  466. ]
  467. for metric_key, metric_name, formatter in metrics_to_display:
  468. lines.append("-" * 75)
  469. prefix = metric_key + "."
  470. current = stats[prefix + "current"]
  471. peak = stats[prefix + "peak"]
  472. allocated = stats[prefix + "allocated"]
  473. freed = stats[prefix + "freed"]
  474. lines.append(
  475. f" {metric_name:<21} | {formatter(current, current)} | {formatter(peak, peak)} | "
  476. f"{formatter(allocated, allocated)} | {formatter(freed, freed)} ",
  477. )
  478. lines.append("=" * 75)
  479. fmt_dict = {"_": "", "device": device}
  480. for k, v in stats.items():
  481. fmt_dict[k.replace(".", "-")] = v
  482. return "|" + "|\n|".join(lines).format(**fmt_dict) + "|\n"
  483. def list_gpu_processes(device: Union[Device, int] = None) -> str:
  484. r"""Return a human-readable printout of the running processes and their GPU memory use for a given device.
  485. This can be useful to display periodically during training, or when
  486. handling out-of-memory exceptions.
  487. Args:
  488. device (torch.device or int, optional): selected device. Returns
  489. printout for the current device, given by :func:`~torch.cuda.current_device`,
  490. if :attr:`device` is ``None`` (default).
  491. """
  492. if not torch.version.hip:
  493. try:
  494. import pynvml # type: ignore[import]
  495. except ModuleNotFoundError:
  496. return "pynvml module not found, please install pynvml"
  497. from pynvml import NVMLError_DriverNotLoaded
  498. try:
  499. pynvml.nvmlInit()
  500. except NVMLError_DriverNotLoaded:
  501. return "cuda driver can't be loaded, is cuda enabled?"
  502. device = _get_nvml_device_index(device)
  503. handle = pynvml.nvmlDeviceGetHandleByIndex(device)
  504. procs = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
  505. else:
  506. try:
  507. import amdsmi # type: ignore[import]
  508. except ModuleNotFoundError:
  509. return "amdsmi module not found, please install amdsmi"
  510. try:
  511. amdsmi.amdsmi_init() # type: ignore[attr-defined]
  512. except amdsmi.AmdSmiException: # type: ignore[attr-defined]
  513. return "amdsmi driver can't be loaded, is ROCm installed?"
  514. device = _get_amdsmi_device_index(device)
  515. handle = amdsmi.amdsmi_get_processor_handles()[device] # type: ignore[attr-defined]
  516. procs = amdsmi.amdsmi_get_gpu_process_list(handle) # type: ignore[attr-defined]
  517. lines = []
  518. lines.append(f"GPU:{device}")
  519. if len(procs) == 0:
  520. lines.append("no processes are running")
  521. for p in procs:
  522. if not torch.version.hip:
  523. mem = p.usedGpuMemory / (1024 * 1024)
  524. pid = p.pid
  525. else:
  526. try:
  527. proc_info = amdsmi.amdsmi_get_gpu_process_info(handle, p) # type: ignore[possibly-undefined]
  528. except AttributeError:
  529. # https://github.com/ROCm/amdsmi/commit/c551c3caedbd903ba828e7fdffa5b56d475a15e7
  530. # is a BC-breaking change that removes amdsmi_get_gpu_process_info API from amdsmi
  531. proc_info = p
  532. mem = proc_info["memory_usage"]["vram_mem"] / (1024 * 1024)
  533. pid = proc_info["pid"]
  534. lines.append(f"process {pid:>10d} uses {mem:>12.3f} MB GPU memory")
  535. return "\n".join(lines)
  536. def mem_get_info(device: Union[Device, int] = None) -> Tuple[int, int]:
  537. r"""Return the global free and total GPU memory for a given device using cudaMemGetInfo.
  538. Args:
  539. device (torch.device or int, optional): selected device. Returns
  540. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  541. if :attr:`device` is ``None`` (default).
  542. .. note::
  543. See :ref:`cuda-memory-management` for more
  544. details about GPU memory management.
  545. """
  546. if device is None:
  547. device = torch.cuda.current_device()
  548. device = _get_device_index(device)
  549. return torch.cuda.cudart().cudaMemGetInfo(device)
  550. def _record_memory_history_legacy(
  551. enabled: bool,
  552. record_context=True,
  553. trace_alloc_max_entries=1,
  554. trace_alloc_record_context=False,
  555. device: Union[Device, int] = None,
  556. record_context_cpp=False,
  557. ):
  558. _C._cuda_record_memory_history_legacy(
  559. enabled,
  560. record_context,
  561. trace_alloc_max_entries,
  562. trace_alloc_record_context,
  563. record_context_cpp,
  564. )
  565. def _record_memory_history(enabled="all", *args, **kwargs):
  566. """Enable recording of stack traces associated with memory
  567. allocations, so you can tell what allocated any piece of memory in
  568. :func:`torch.cuda.memory._snapshot()`.
  569. In addition too keeping stack traces with each current allocation and free,
  570. this will also enable recording of a history of all alloc/free events.
  571. Use :func:`torch.cuda.memory._snapshot()` to retrieve this information,
  572. and the tools in `_memory_viz.py` to visualize snapshots.
  573. The Python trace collection is fast (2us per trace), so you may consider
  574. enabling this on production jobs if you anticipate ever having to debug
  575. memory issues.
  576. C++ trace collection is also fast (~50ns/frame), which for many typical programs
  577. works out to ~2us per trace, but can vary depending on stack depth.
  578. Args:
  579. enabled (Literal[None, "state", "all"], optional):
  580. `None`, disable recording memory history.
  581. `"state"`, keep information for currenly allocated memory.
  582. `"all"`, additionally keep a history of all alloc/free calls.
  583. Defaults to "all".
  584. context (Literal[None, "state", "alloc", "all"], optional):
  585. `None`, Do not record any tracebacks.
  586. `"state"`, Record tracebacks for currently allocated memory.
  587. `"alloc"`, additionally keep tracebacks for alloc calls.
  588. `"all"`, additionally keep tracebacks for free calls.
  589. Defaults to "all".
  590. stacks (Literal["python", "all"], optional):
  591. `"python"`, include Python, TorchScript, and inductor frames in tracebacks
  592. `"all"`, additionally include C++ frames
  593. Defaults to "all".
  594. max_entries (int, optional): Keep a maximum of `max_entries`
  595. alloc/free events in the recorded history recorded.
  596. """
  597. if isinstance(enabled, bool):
  598. return _record_memory_history_legacy(enabled, *args, **kwargs)
  599. else:
  600. return _record_memory_history_impl(enabled, *args, **kwargs)
  601. def _record_memory_history_impl(
  602. enabled: Optional[str] = "all",
  603. context: Optional[str] = "all",
  604. stacks: str = "all",
  605. max_entries: int = sys.maxsize,
  606. device: Union[Device, int] = None,
  607. ):
  608. _C._cuda_record_memory_history(enabled, context, stacks, max_entries)
  609. _record_memory_history.__signature__ = signature(_record_memory_history_impl) # type: ignore[attr-defined]
  610. def _snapshot(device: Union[Device, int] = None):
  611. """Save a snapshot of CUDA memory state at the time it was called.
  612. The state is represented as a dictionary with the following structure.
  613. .. code-block:: python
  614. class Snapshot(TypedDict):
  615. segments : List[Segment]
  616. device_traces: List[List[TraceEntry]]
  617. class Segment(TypedDict):
  618. # Segments are memory returned from a cudaMalloc call.
  619. # The size of reserved memory is the sum of all Segments.
  620. # Segments are cached and reused for future allocations.
  621. # If the reuse is smaller than the segment, the segment
  622. # is split into more then one Block.
  623. # empty_cache() frees Segments that are entirely inactive.
  624. address: int
  625. total_size: int # cudaMalloc'd size of segment
  626. stream: int
  627. segment_type: Literal['small', 'large'] # 'large' (>1MB)
  628. allocated_size: int # size of memory in use
  629. active_size: int # size of memory in use or in active_awaiting_free state
  630. blocks : List[Block]
  631. class Block(TypedDict):
  632. # A piece of memory returned from the allocator, or
  633. # current cached but inactive.
  634. size: int
  635. requested_size: int # size requested during malloc, may be smaller than
  636. # size due to rounding
  637. address: int
  638. state: Literal['active_allocated', # used by a tensor
  639. 'active_awaiting_free', # waiting for another stream to finish using
  640. # this, then it will become free
  641. 'inactive',] # free for reuse
  642. frames: List[Frame] # stack trace from where the allocation occurred
  643. class Frame(TypedDict):
  644. filename: str
  645. line: int
  646. name: str
  647. class TraceEntry(TypedDict):
  648. # When `torch.cuda.memory._record_memory_history()` is enabled,
  649. # the snapshot will contain TraceEntry objects that record each
  650. # action the allocator took.
  651. action: Literal[
  652. 'alloc' # memory allocated
  653. 'free_requested', # the allocated received a call to free memory
  654. 'free_completed', # the memory that was requested to be freed is now
  655. # able to be used in future allocation calls
  656. 'segment_alloc', # the caching allocator ask cudaMalloc for more memory
  657. # and added it as a segment in its cache
  658. 'segment_free', # the caching allocator called cudaFree to return memory
  659. # to cuda possibly trying free up memory to
  660. # allocate more segments or because empty_caches was called
  661. 'oom', # the allocator threw an OOM exception. 'size' is
  662. # the requested number of bytes that did not succeed
  663. 'snapshot' # the allocator generated a memory snapshot
  664. # useful to coorelate a previously taken
  665. # snapshot with this trace
  666. ]
  667. addr: int # not present for OOM
  668. frames: List[Frame]
  669. size: int
  670. stream: int
  671. device_free: int # only present for OOM, the amount of
  672. # memory cuda still reports to be free
  673. Returns:
  674. The Snapshot dictionary object
  675. """
  676. return _C._cuda_memorySnapshot()
  677. def _dump_snapshot(filename="dump_snapshot.pickle"):
  678. """
  679. Save a pickled version of the `torch.memory._snapshot()` dictionary to a file.
  680. This file can be opened by the interactive snapshot viewer at pytorch.org/memory_viz
  681. Args:
  682. filename (str, optional): Name of the file to create. Defaults to "dump_snapshot.pickle".
  683. """
  684. s = _snapshot()
  685. with open(filename, "wb") as f:
  686. pickle.dump(s, f)
  687. def _save_segment_usage(filename="output.svg", snapshot=None):
  688. if snapshot is None:
  689. snapshot = _snapshot()
  690. with open(filename, "w") as f:
  691. f.write(_segments(snapshot))
  692. def _save_memory_usage(filename="output.svg", snapshot=None):
  693. if snapshot is None:
  694. snapshot = _snapshot()
  695. with open(filename, "w") as f:
  696. f.write(_memory(snapshot))
  697. def _set_allocator_settings(env: str):
  698. return torch._C._cuda_cudaCachingAllocator_set_allocator_settings(env)
  699. def get_allocator_backend() -> str:
  700. r"""Return a string describing the active allocator backend as set by
  701. ``PYTORCH_CUDA_ALLOC_CONF``. Currently available backends are
  702. ``native`` (PyTorch's native caching allocator) and `cudaMallocAsync``
  703. (CUDA's built-in asynchronous allocator).
  704. .. note::
  705. See :ref:`cuda-memory-management` for details on choosing the allocator backend.
  706. """
  707. return torch._C._cuda_getAllocatorBackend()
  708. class _CUDAAllocator:
  709. r"""Wrapper over internal CUDA memory allocators."""
  710. def __init__(self, allocator: torch._C._cuda_CUDAAllocator):
  711. self._allocator = allocator
  712. def allocator(self):
  713. return self._allocator
  714. class CUDAPluggableAllocator(_CUDAAllocator):
  715. r"""CUDA memory allocator loaded from a so file."""
  716. def __init__(self, path_to_so_file: str, alloc_fn_name: str, free_fn_name: str):
  717. r"""Memory allocators are compiled in .so files and loaded dynamically using ctypes.
  718. To change the active allocator use the :func:`torch.memory.cuda.change_current_allocator` function.
  719. Args:
  720. path_to_so_file(str): Path in the filesystem to the `.so` file containing
  721. the allocator functions
  722. alloc_fn_name(str): Name of the function to perform the memory allocation
  723. in the so file. The signature must be:
  724. void* alloc_fn_name(ssize_t size, int device, cudaStream_t stream);
  725. free_fn_name(str): Name of the function to perform the memory release
  726. in the so file. The signature must be:
  727. void free_fn_name(void* ptr, size_t size, cudaStream_t stream);
  728. .. warning::
  729. This is currently supported only in unix OSs
  730. .. note::
  731. See :ref:`cuda-memory-management` for details on creating and using a custom allocator
  732. """
  733. allocator = ctypes.CDLL(path_to_so_file)
  734. alloc_fn = ctypes.cast(getattr(allocator, alloc_fn_name), ctypes.c_void_p).value
  735. free_fn = ctypes.cast(getattr(allocator, free_fn_name), ctypes.c_void_p).value
  736. assert alloc_fn is not None
  737. assert free_fn is not None
  738. self._allocator = torch._C._cuda_customAllocator(alloc_fn, free_fn)
  739. def change_current_allocator(allocator: _CUDAAllocator) -> None:
  740. r"""Change the currently used memory allocator to be the one provided.
  741. If the current allocator has already been used/initialized, this function will error.
  742. Args:
  743. allocator (torch.cuda.memory._CUDAAllocator): allocator to be set as the active one.
  744. .. note::
  745. See :ref:`cuda-memory-management` for details on creating and using a custom allocator
  746. """
  747. torch._C._cuda_changeCurrentAllocator(allocator.allocator())
  748. def _get_current_allocator() -> _CUDAAllocator:
  749. r"""Return the allocator being currently used.
  750. .. note::
  751. See :ref:`cuda-memory-management` for details on creating and using a custom allocator
  752. """
  753. return _CUDAAllocator(torch._C._cuda_getAllocator())