memory.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  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, Literal, TYPE_CHECKING
  11. from typing_extensions import deprecated
  12. import torch
  13. from torch import _C
  14. from torch._utils import _augment_memory_snapshot_stack_traces, _dummy_type
  15. from . import (
  16. _get_amdsmi_device_index,
  17. _get_device_index,
  18. _get_nvml_device_index,
  19. _lazy_init,
  20. is_initialized,
  21. )
  22. from ._memory_viz import memory as _memory, segments as _segments
  23. if TYPE_CHECKING:
  24. from torch.types import Device
  25. __all__ = [
  26. "caching_allocator_alloc",
  27. "caching_allocator_delete",
  28. "caching_allocator_enable",
  29. "get_per_process_memory_fraction",
  30. "set_per_process_memory_fraction",
  31. "empty_cache",
  32. "memory_stats",
  33. "memory_stats_as_nested_dict",
  34. "reset_accumulated_memory_stats",
  35. "reset_peak_memory_stats",
  36. "reset_max_memory_allocated",
  37. "reset_max_memory_cached",
  38. "host_memory_stats",
  39. "host_memory_stats_as_nested_dict",
  40. "reset_accumulated_host_memory_stats",
  41. "reset_peak_host_memory_stats",
  42. "memory_allocated",
  43. "max_memory_allocated",
  44. "memory_reserved",
  45. "max_memory_reserved",
  46. "memory_cached",
  47. "max_memory_cached",
  48. "memory_snapshot",
  49. "memory_summary",
  50. "list_gpu_processes",
  51. "mem_get_info",
  52. "get_allocator_backend",
  53. "CUDAPluggableAllocator",
  54. "change_current_allocator",
  55. "MemPool",
  56. "use_mem_pool",
  57. ]
  58. if not hasattr(torch._C, "_cuda_CUDAAllocator"):
  59. # Define dummy base classes
  60. torch._C.__dict__["_cuda_CUDAAllocator"] = _dummy_type("_cuda_CUDAAllocator")
  61. if not hasattr(torch._C, "_MemPool"):
  62. # Define dummy base classes
  63. torch._C.__dict__["_MemPool"] = _dummy_type("_MemPool")
  64. torch._C.__dict__["_cuda_beginAllocateToPool"] = _dummy_type(
  65. "_cuda_beginAllocateToPool"
  66. )
  67. torch._C.__dict__["_cuda_beginAllocateCurrentThreadToPool"] = _dummy_type(
  68. "_cuda_beginAllocateCurrentThreadToPool"
  69. )
  70. torch._C.__dict__["_cuda_endAllocateToPool"] = _dummy_type(
  71. "_cuda_endAllocateToPool"
  72. )
  73. torch._C.__dict__["_cuda_releasePool"] = _dummy_type("_cuda_releasePool")
  74. from torch._C import ( # noqa: F401
  75. _cuda_beginAllocateCurrentThreadToPool,
  76. _cuda_beginAllocateToPool,
  77. _cuda_CUDAAllocator,
  78. _cuda_endAllocateToPool,
  79. _cuda_releasePool,
  80. _MemPool,
  81. )
  82. def _host_allocator():
  83. _lazy_init()
  84. return torch._C._cuda_cudaHostAllocator()
  85. @contextlib.contextmanager
  86. def _free_mutex():
  87. torch._C._cuda_lock_mutex()
  88. try:
  89. yield
  90. finally:
  91. torch._C._cuda_unlock_mutex()
  92. def caching_allocator_alloc(size, device: "Device" = None, stream=None):
  93. r"""Perform a memory allocation using the CUDA memory allocator.
  94. Memory is allocated for a given device and a stream, this
  95. function is intended to be used for interoperability with other
  96. frameworks. Allocated memory is released through
  97. :func:`~torch.cuda.caching_allocator_delete`.
  98. Args:
  99. size (int): number of bytes to be allocated.
  100. device (torch.device or int, optional): selected device. If it is
  101. ``None`` the default CUDA device is used.
  102. stream (torch.cuda.Stream or int, optional): selected stream. If is ``None`` then
  103. the default stream for the selected device is used.
  104. .. note::
  105. See :ref:`cuda-memory-management` for more details about GPU memory
  106. management.
  107. """
  108. if device is None:
  109. device = torch.cuda.current_device()
  110. device = _get_device_index(device)
  111. if stream is None:
  112. stream = torch.cuda.current_stream(device)
  113. if isinstance(stream, torch.cuda.streams.Stream):
  114. stream = stream.cuda_stream
  115. if not isinstance(stream, int):
  116. raise TypeError(
  117. "Invalid type for stream argument, must be "
  118. "`torch.cuda.Stream` or `int` representing a pointer "
  119. "to a existing stream"
  120. )
  121. with torch.cuda.device(device):
  122. return torch._C._cuda_cudaCachingAllocator_raw_alloc(size, stream)
  123. def caching_allocator_delete(mem_ptr):
  124. r"""Delete memory allocated using the CUDA memory allocator.
  125. Memory allocated with :func:`~torch.cuda.caching_allocator_alloc`.
  126. is freed here. The associated device and stream are tracked inside
  127. the allocator.
  128. Args:
  129. mem_ptr (int): memory address to be freed by the allocator.
  130. .. note::
  131. See :ref:`cuda-memory-management` for more details about GPU memory
  132. management.
  133. """
  134. torch._C._cuda_cudaCachingAllocator_raw_delete(mem_ptr)
  135. def caching_allocator_enable(value: bool = True) -> None:
  136. r"""Enable or disable the CUDA memory allocator. On by default."""
  137. if is_initialized():
  138. torch._C._cuda_cudaCachingAllocator_enable(value)
  139. def set_per_process_memory_fraction(fraction, device: "Device" = None) -> None:
  140. r"""Set memory fraction for a process.
  141. The fraction is used to limit an caching allocator to allocated memory on a CUDA device.
  142. The allowed value equals the total visible memory multiplied fraction.
  143. If trying to allocate more than the allowed value in a process, will raise an out of
  144. memory error in allocator.
  145. Args:
  146. fraction(float): Range: 0~1. Allowed memory equals total_memory * fraction.
  147. device (torch.device or int, optional): selected device. If it is
  148. ``None`` the default CUDA device is used.
  149. .. note::
  150. In general, the total available free memory is less than the total capacity.
  151. """
  152. _lazy_init()
  153. if device is None:
  154. device = torch.cuda.current_device()
  155. device = _get_device_index(device)
  156. if not isinstance(fraction, float):
  157. raise TypeError("Invalid type for fraction argument, must be `float`")
  158. if fraction < 0 or fraction > 1:
  159. raise ValueError(f"Invalid fraction value: {fraction}. Allowed range: 0~1")
  160. torch._C._cuda_setMemoryFraction(fraction, device)
  161. def get_per_process_memory_fraction(device: "Device" = None) -> float:
  162. r"""Get memory fraction for a process.
  163. Args:
  164. device (torch.device or int, optional): selected device. If it is
  165. ``None`` the default CUDA device is used.
  166. Returns:
  167. memory fraction, in range 0~1. Allowed memory equals total_memory * fraction.
  168. """
  169. _lazy_init()
  170. if device is None:
  171. device = torch.cuda.current_device()
  172. device = _get_device_index(device)
  173. return torch._C._cuda_getMemoryFraction(device)
  174. def empty_cache() -> None:
  175. r"""Release all unoccupied cached memory currently held by the caching
  176. allocator so that those can be used in other GPU application and visible in
  177. `nvidia-smi`.
  178. .. note::
  179. :func:`~torch.cuda.empty_cache` doesn't increase the amount of GPU
  180. memory available for PyTorch. However, it may help reduce fragmentation
  181. of GPU memory in certain cases. See :ref:`cuda-memory-management` for
  182. more details about GPU memory management.
  183. """
  184. if is_initialized():
  185. torch._C._cuda_emptyCache()
  186. def memory_stats(device: "Device" = None) -> dict[str, Any]:
  187. r"""Return a dictionary of CUDA memory allocator statistics for a given device.
  188. The return value of this function is a dictionary of statistics, each of
  189. which is a non-negative integer.
  190. Core statistics:
  191. - ``"allocated.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  192. number of allocation requests received by the memory allocator.
  193. - ``"allocated_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  194. amount of allocated memory.
  195. - ``"segment.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  196. number of reserved segments from ``cudaMalloc()``.
  197. - ``"reserved_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  198. amount of reserved memory.
  199. - ``"active.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  200. number of active memory blocks.
  201. - ``"active_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  202. amount of active memory.
  203. - ``"inactive_split.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  204. number of inactive, non-releasable memory blocks.
  205. - ``"inactive_split_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  206. amount of inactive, non-releasable memory.
  207. For these core statistics, values are broken down as follows.
  208. Pool type:
  209. - ``all``: combined statistics across all memory pools.
  210. - ``large_pool``: statistics for the large allocation pool
  211. (as of June 2025, for size >= 1MB allocations).
  212. - ``small_pool``: statistics for the small allocation pool
  213. (as of June 2025, for size < 1MB allocations).
  214. Metric type:
  215. - ``current``: current value of this metric.
  216. - ``peak``: maximum value of this metric.
  217. - ``allocated``: historical total increase in this metric.
  218. - ``freed``: historical total decrease in this metric.
  219. In addition to the core statistics, we also provide some simple event
  220. counters:
  221. - ``"num_alloc_retries"``: number of failed ``cudaMalloc`` calls that
  222. result in a cache flush and retry.
  223. - ``"num_ooms"``: number of out-of-memory errors thrown.
  224. - ``"num_sync_all_streams"``: number of ``synchronize_and_free_events`` calls.
  225. - ``"num_device_alloc"``: number of CUDA allocation calls. This includes both
  226. cuMemMap and cudaMalloc.
  227. - ``"num_device_free"``: number of CUDA free calls. This includes both cuMemUnmap
  228. and cudaFree.
  229. The caching allocator can be configured via ENV to not split blocks larger than a
  230. defined size (see Memory Management section of the Cuda Semantics documentation).
  231. This helps avoid memory fragmentation but may have a performance
  232. penalty. Additional outputs to assist with tuning and evaluating impact:
  233. - ``"max_split_size"``: blocks above this size will not be split.
  234. - ``"oversize_allocations.{current,peak,allocated,freed}"``:
  235. number of over-size allocation requests received by the memory allocator.
  236. - ``"oversize_segments.{current,peak,allocated,freed}"``:
  237. number of over-size reserved segments from ``cudaMalloc()``.
  238. The caching allocator can be configured via ENV to round memory allocations in order
  239. to reduce fragmentation. Sometimes the overhead from rounding can be higher than
  240. the fragmentation it helps reduce. The following stat can be used to check if
  241. rounding adds too much overhead:
  242. - ``"requested_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  243. memory requested by client code, compare this with allocated_bytes to check if
  244. allocation rounding adds too much overhead.
  245. Args:
  246. device (torch.device or int, optional): selected device. Returns
  247. statistics for the current device, given by :func:`~torch.cuda.current_device`,
  248. if :attr:`device` is ``None`` (default).
  249. .. note::
  250. See :ref:`cuda-memory-management` for more details about GPU memory
  251. management.
  252. .. note::
  253. With :ref:`backend:cudaMallocAsync<cuda-memory-envvars>`, some stats are not
  254. meaningful, and are always reported as zero.
  255. """
  256. result = []
  257. def _recurse_add_to_result(prefix, obj):
  258. if isinstance(obj, dict):
  259. if len(prefix) > 0:
  260. prefix += "."
  261. for k, v in obj.items():
  262. _recurse_add_to_result(prefix + k, v)
  263. else:
  264. result.append((prefix, obj))
  265. stats = memory_stats_as_nested_dict(device=device)
  266. _recurse_add_to_result("", stats)
  267. result.sort()
  268. return collections.OrderedDict(result)
  269. def memory_stats_as_nested_dict(device: "Device" = None) -> dict[str, Any]:
  270. r"""Return the result of :func:`~torch.cuda.memory_stats` as a nested dictionary."""
  271. if not is_initialized():
  272. return {}
  273. device = _get_device_index(device, optional=True)
  274. return torch._C._cuda_memoryStats(device)
  275. def reset_accumulated_memory_stats(device: "Device" = None) -> None:
  276. r"""Reset the "accumulated" (historical) stats tracked by the CUDA memory allocator.
  277. See :func:`~torch.cuda.memory_stats` for details. Accumulated stats correspond to
  278. the `"allocated"` and `"freed"` keys in each individual stat dict, as well as
  279. `"num_alloc_retries"` and `"num_ooms"`.
  280. Args:
  281. device (torch.device or int, optional): selected device. Returns
  282. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  283. if :attr:`device` is ``None`` (default).
  284. .. note::
  285. See :ref:`cuda-memory-management` for more details about GPU memory
  286. management.
  287. """
  288. device = _get_device_index(device, optional=True)
  289. return torch._C._cuda_resetAccumulatedMemoryStats(device)
  290. def reset_peak_memory_stats(device: "Device" = None) -> None:
  291. r"""Reset the "peak" stats tracked by the CUDA memory allocator.
  292. See :func:`~torch.cuda.memory_stats` for details. Peak stats correspond to the
  293. `"peak"` key in each individual stat dict.
  294. Args:
  295. device (torch.device or int, optional): selected device. Returns
  296. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  297. if :attr:`device` is ``None`` (default).
  298. .. note::
  299. See :ref:`cuda-memory-management` for more details about GPU memory
  300. management.
  301. """
  302. device = _get_device_index(device, optional=True)
  303. return torch._C._cuda_resetPeakMemoryStats(device)
  304. def host_memory_stats() -> dict[str, Any]:
  305. r"""Return a dictionary of pinned (host) allocator statistics.
  306. Core statistics (host pinned allocator):
  307. - ``"allocations.{current,peak,allocated,freed}"``:
  308. pinned blocks owned by the allocator (active + cached). Grows when a new
  309. block is created via CUDA and shrinks when cached blocks are returned.
  310. - ``"allocated_bytes.{current,peak,allocated,freed}"``:
  311. bytes of pinned blocks owned by the allocator (active + cached), using
  312. the rounded block size requested from CUDA.
  313. - ``"active_requests.{current,peak,allocated,freed}"``:
  314. blocks currently checked out to callers (increments on handout, decrements
  315. when the block becomes reusable after stream deps finish).
  316. - ``"active_bytes.{current,peak,allocated,freed}"``:
  317. bytes corresponding to active blocks.
  318. Metric type:
  319. - ``current``: current value.
  320. - ``peak``: maximum value.
  321. - ``allocated``: historical total increase.
  322. - ``freed``: historical total decrease.
  323. Event/timing counters:
  324. - ``"num_host_alloc"`` / ``"num_host_free"``: blocks created to grow the
  325. pool / cached blocks returned to CUDA (matches allocations allocated/freed).
  326. - ``"host_alloc_time.{total,max,min,count,avg}"``: time in CUDA alloc calls
  327. when growing the pool (microseconds).
  328. - ``"host_free_time.{total,max,min,count,avg}"``: time in CUDA free calls
  329. when cached blocks are returned (microseconds).
  330. Block sizes are rounded up to the next power of two before calling CUDA, so
  331. byte stats reflect the rounded size. Peak values are aggregated per bucket
  332. and are a best-effort approximation of the true peak.
  333. """
  334. result = []
  335. def _recurse_add_to_result(prefix, obj):
  336. if isinstance(obj, dict):
  337. if len(prefix) > 0:
  338. prefix += "."
  339. for k, v in obj.items():
  340. _recurse_add_to_result(prefix + k, v)
  341. else:
  342. result.append((prefix, obj))
  343. stats = host_memory_stats_as_nested_dict()
  344. _recurse_add_to_result("", stats)
  345. result.sort()
  346. return collections.OrderedDict(result)
  347. def host_memory_stats_as_nested_dict() -> dict[str, Any]:
  348. r"""Return the result of :func:`~torch.cuda.host_memory_stats` as a nested dictionary."""
  349. if not is_initialized():
  350. return {}
  351. return torch._C._cuda_hostMemoryStats()
  352. def reset_accumulated_host_memory_stats() -> None:
  353. r"""Reset the "accumulated" (historical) stats tracked by the host memory allocator.
  354. See :func:`~torch.cuda.host_memory_stats` for details. Accumulated stats correspond to
  355. the `"allocated"` and `"freed"` keys in each individual stat dict.
  356. """
  357. return torch._C._cuda_resetAccumulatedHostMemoryStats()
  358. def reset_peak_host_memory_stats() -> None:
  359. r"""Reset the "peak" stats tracked by the host memory allocator.
  360. See :func:`~torch.cuda.host_memory_stats` for details. Peak stats correspond to the
  361. `"peak"` key in each individual stat dict.
  362. """
  363. return torch._C._cuda_resetPeakHostMemoryStats()
  364. def reset_max_memory_allocated(device: "Device" = None) -> None:
  365. r"""Reset the starting point in tracking maximum GPU memory occupied by tensors for a given device.
  366. See :func:`~torch.cuda.max_memory_allocated` for details.
  367. Args:
  368. device (torch.device or int, optional): selected device. Returns
  369. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  370. if :attr:`device` is ``None`` (default).
  371. .. warning::
  372. This function now calls :func:`~torch.cuda.reset_peak_memory_stats`, which resets
  373. /all/ peak memory stats.
  374. .. note::
  375. See :ref:`cuda-memory-management` for more details about GPU memory
  376. management.
  377. """
  378. warnings.warn(
  379. "torch.cuda.reset_max_memory_allocated now calls torch.cuda.reset_peak_memory_stats, "
  380. "which resets /all/ peak memory stats.",
  381. FutureWarning,
  382. stacklevel=2,
  383. )
  384. return reset_peak_memory_stats(device=device)
  385. def reset_max_memory_cached(device: "Device" = None) -> None:
  386. r"""Reset the starting point in tracking maximum GPU memory managed by the caching allocator for a given device.
  387. See :func:`~torch.cuda.max_memory_cached` for details.
  388. Args:
  389. device (torch.device or int, optional): selected device. Returns
  390. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  391. if :attr:`device` is ``None`` (default).
  392. .. warning::
  393. This function now calls :func:`~torch.cuda.reset_peak_memory_stats`, which resets
  394. /all/ peak memory stats.
  395. .. note::
  396. See :ref:`cuda-memory-management` for more details about GPU memory
  397. management.
  398. """
  399. warnings.warn(
  400. "torch.cuda.reset_max_memory_cached now calls torch.cuda.reset_peak_memory_stats, "
  401. "which resets /all/ peak memory stats.",
  402. FutureWarning,
  403. stacklevel=2,
  404. )
  405. return reset_peak_memory_stats(device=device)
  406. def memory_allocated(device: "Device" = None) -> int:
  407. r"""Return the current GPU memory occupied by tensors in bytes for a given device.
  408. Args:
  409. device (torch.device or int, optional): selected device. Returns
  410. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  411. if :attr:`device` is ``None`` (default).
  412. .. note::
  413. This is likely less than the amount shown in `nvidia-smi` since some
  414. unused memory can be held by the caching allocator and some context
  415. needs to be created on GPU. See :ref:`cuda-memory-management` for more
  416. details about GPU memory management.
  417. """
  418. return memory_stats(device=device).get("allocated_bytes.all.current", 0)
  419. def max_memory_allocated(device: "Device" = None) -> int:
  420. r"""Return the maximum GPU memory occupied by tensors in bytes for a given device.
  421. By default, this returns the peak allocated memory since the beginning of
  422. this program. :func:`~torch.cuda.reset_peak_memory_stats` can be used to
  423. reset the starting point in tracking this metric. For example, these two
  424. functions can measure the peak allocated memory usage of each iteration in a
  425. training loop.
  426. Args:
  427. device (torch.device or int, optional): selected device. Returns
  428. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  429. if :attr:`device` is ``None`` (default).
  430. .. note::
  431. See :ref:`cuda-memory-management` for more details about GPU memory
  432. management.
  433. """
  434. return memory_stats(device=device).get("allocated_bytes.all.peak", 0)
  435. def memory_reserved(device: "Device" = None) -> int:
  436. r"""Return the current GPU memory managed by the caching allocator in bytes for a given device.
  437. Args:
  438. device (torch.device or int, optional): selected device. Returns
  439. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  440. if :attr:`device` is ``None`` (default).
  441. .. note::
  442. See :ref:`cuda-memory-management` for more details about GPU memory
  443. management.
  444. """
  445. return memory_stats(device=device).get("reserved_bytes.all.current", 0)
  446. def max_memory_reserved(device: "Device" = None) -> int:
  447. r"""Return the maximum GPU memory managed by the caching allocator in bytes for a given device.
  448. By default, this returns the peak cached memory since the beginning of this
  449. program. :func:`~torch.cuda.reset_peak_memory_stats` can be used to reset
  450. the starting point in tracking this metric. For example, these two functions
  451. can measure the peak cached memory amount of each iteration in a training
  452. loop.
  453. Args:
  454. device (torch.device or int, optional): selected device. Returns
  455. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  456. if :attr:`device` is ``None`` (default).
  457. .. note::
  458. See :ref:`cuda-memory-management` for more details about GPU memory
  459. management.
  460. """
  461. return memory_stats(device=device).get("reserved_bytes.all.peak", 0)
  462. @deprecated(
  463. "`torch.cuda.memory_cached` has been renamed to `torch.cuda.memory_reserved`",
  464. category=FutureWarning,
  465. )
  466. def memory_cached(device: "Device" = None) -> int:
  467. r"""Deprecated; see :func:`~torch.cuda.memory_reserved`."""
  468. return memory_reserved(device=device)
  469. @deprecated(
  470. "`torch.cuda.max_memory_cached` has been renamed to `torch.cuda.max_memory_reserved`",
  471. category=FutureWarning,
  472. )
  473. def max_memory_cached(device: "Device" = None) -> int:
  474. r"""Deprecated; see :func:`~torch.cuda.max_memory_reserved`."""
  475. return max_memory_reserved(device=device)
  476. def memory_snapshot(mempool_id=None, include_traces=True):
  477. r"""Return a snapshot of the CUDA memory allocator state across all devices.
  478. Interpreting the output of this function requires familiarity with the
  479. memory allocator internals.
  480. Args:
  481. mempool_id: Optional memory pool ID to get snapshot for a specific pool
  482. include_traces: Whether to include trace entries in the snapshot.
  483. If True (default), all trace entries are included.
  484. If False, no trace entries are included (lightweight/fast snapshot).
  485. .. note::
  486. See :ref:`cuda-memory-management` for more details about GPU memory
  487. management.
  488. """
  489. if mempool_id is None:
  490. # pyrefly: ignore [bad-argument-type]
  491. return torch._C._cuda_memorySnapshot((0, 0, include_traces))["segments"]
  492. else:
  493. return torch._C._cuda_memorySnapshot(
  494. # pyrefly: ignore [bad-argument-type]
  495. (mempool_id[0], mempool_id[1], include_traces)
  496. )["segments"]
  497. def memory_summary(device: "Device" = None, abbreviated: bool = False) -> str:
  498. r"""Return a human-readable printout of the current memory allocator statistics for a given device.
  499. This can be useful to display periodically during training, or when
  500. handling out-of-memory exceptions.
  501. Args:
  502. device (torch.device or int, optional): selected device. Returns
  503. printout for the current device, given by :func:`~torch.cuda.current_device`,
  504. if :attr:`device` is ``None`` (default).
  505. abbreviated (bool, optional): whether to return an abbreviated summary
  506. (default: False).
  507. .. note::
  508. See :ref:`cuda-memory-management` for more details about GPU memory
  509. management.
  510. """
  511. device = _get_device_index(device, optional=True)
  512. stats = memory_stats(device=device)
  513. def _format_size(sz, pref_sz):
  514. prefixes = ["B ", "KiB", "MiB", "GiB", "TiB", "PiB"]
  515. prefix = prefixes[0]
  516. for new_prefix in prefixes[1:]:
  517. if pref_sz < 768 * 1024:
  518. break
  519. prefix = new_prefix
  520. sz //= 1024
  521. pref_sz /= 1024
  522. return f"{sz:6d} {prefix}"
  523. def _format_count(cnt, pref_cnt):
  524. prefixes = [" ", "K", "M"]
  525. prefix = prefixes[0]
  526. for new_prefix in prefixes[1:]:
  527. if pref_cnt < 750 * 1000:
  528. break
  529. prefix = new_prefix
  530. cnt //= 1000
  531. pref_cnt /= 1000
  532. return f"{cnt:7d} {prefix} "
  533. metrics_to_display = [
  534. ("allocated_bytes", "Allocated memory", _format_size),
  535. ("active_bytes", "Active memory", _format_size),
  536. ("requested_bytes", "Requested memory", _format_size),
  537. ("reserved_bytes", "GPU reserved memory", _format_size),
  538. ("inactive_split_bytes", "Non-releasable memory", _format_size),
  539. ("allocation", "Allocations", _format_count),
  540. ("active", "Active allocs", _format_count),
  541. ("segment", "GPU reserved segments", _format_count),
  542. ("inactive_split", "Non-releasable allocs", _format_count),
  543. ]
  544. lines = []
  545. lines.append("=" * 75)
  546. lines.append(" {_:16} PyTorch CUDA memory summary, device ID {device:<17d} ")
  547. lines.append("-" * 75)
  548. lines.append(
  549. " {_:9} CUDA OOMs: {num_ooms:<12d} | {_:6} cudaMalloc retries: {num_alloc_retries:<8d} "
  550. )
  551. lines.append("=" * 75)
  552. lines.append(
  553. " Metric | Cur Usage | Peak Usage | Tot Alloc | Tot Freed "
  554. )
  555. for metric_key, metric_name, formatter in metrics_to_display:
  556. lines.append("-" * 75)
  557. submetrics = [("all", metric_name)]
  558. if not abbreviated:
  559. submetrics.append(("large_pool", " from large pool"))
  560. submetrics.append(("small_pool", " from small pool"))
  561. current_prefval, peak_prefval, allocated_prefval, freed_prefval = (
  562. None,
  563. None,
  564. None,
  565. None,
  566. )
  567. for submetric_key, submetric_name in submetrics:
  568. prefix = metric_key + "." + submetric_key + "."
  569. current = stats[prefix + "current"]
  570. peak = stats[prefix + "peak"]
  571. allocated = stats[prefix + "allocated"]
  572. freed = stats[prefix + "freed"]
  573. if current_prefval is None:
  574. current_prefval = current
  575. peak_prefval = peak
  576. allocated_prefval = allocated
  577. freed_prefval = freed
  578. lines.append(
  579. # pyrefly: ignore [bad-argument-type]
  580. f" {submetric_name:<21} | {formatter(current, current_prefval)} | {formatter(peak, peak_prefval)} | "
  581. f"{formatter(allocated, allocated_prefval)} | {formatter(freed, freed_prefval)} ",
  582. )
  583. metrics_to_display = [
  584. ("oversize_allocations", "Oversize allocations", _format_count),
  585. ("oversize_segments", "Oversize GPU segments", _format_count),
  586. ]
  587. for metric_key, metric_name, formatter in metrics_to_display:
  588. lines.append("-" * 75)
  589. prefix = metric_key + "."
  590. current = stats[prefix + "current"]
  591. peak = stats[prefix + "peak"]
  592. allocated = stats[prefix + "allocated"]
  593. freed = stats[prefix + "freed"]
  594. lines.append(
  595. # pyrefly: ignore [bad-argument-type]
  596. f" {metric_name:<21} | {formatter(current, current)} | {formatter(peak, peak)} | "
  597. f"{formatter(allocated, allocated)} | {formatter(freed, freed)} ",
  598. )
  599. lines.append("=" * 75)
  600. fmt_dict = {"_": "", "device": device}
  601. for k, v in stats.items():
  602. fmt_dict[k.replace(".", "-")] = v
  603. return "|" + "|\n|".join(lines).format(**fmt_dict) + "|\n"
  604. def list_gpu_processes(device: "Device" = None) -> str:
  605. r"""Return a human-readable printout of the running processes and their GPU memory use for a given device.
  606. This can be useful to display periodically during training, or when
  607. handling out-of-memory exceptions.
  608. Args:
  609. device (torch.device or int, optional): selected device. Returns
  610. printout for the current device, given by :func:`~torch.cuda.current_device`,
  611. if :attr:`device` is ``None`` (default).
  612. """
  613. if not torch.version.hip:
  614. try:
  615. import pynvml # type: ignore[import]
  616. except ModuleNotFoundError:
  617. return "pynvml module not found, please install nvidia-ml-py"
  618. # pyrefly: ignore [import-error, missing-import, missing-module-attribute]
  619. from pynvml import NVMLError_DriverNotLoaded
  620. try:
  621. pynvml.nvmlInit()
  622. except NVMLError_DriverNotLoaded:
  623. return "cuda driver can't be loaded, is cuda enabled?"
  624. device = _get_nvml_device_index(device)
  625. handle = pynvml.nvmlDeviceGetHandleByIndex(device)
  626. procs = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
  627. else:
  628. try:
  629. import amdsmi # type: ignore[import]
  630. except ModuleNotFoundError:
  631. return "amdsmi module not found, please install amdsmi"
  632. try:
  633. amdsmi.amdsmi_init() # type: ignore[attr-defined]
  634. except amdsmi.AmdSmiException: # type: ignore[attr-defined]
  635. return "amdsmi driver can't be loaded, is ROCm installed?"
  636. device = _get_amdsmi_device_index(device)
  637. try:
  638. handle = amdsmi.amdsmi_get_processor_handles()[device] # type: ignore[attr-defined]
  639. procs = amdsmi.amdsmi_get_gpu_process_list(handle) # type: ignore[attr-defined]
  640. except amdsmi.AmdSmiException: # type: ignore[attr-defined]
  641. return "amdsmi cannot list processes from other users"
  642. lines = []
  643. lines.append(f"GPU:{device}")
  644. if len(procs) == 0:
  645. lines.append("no processes are running")
  646. for p in procs:
  647. if not torch.version.hip:
  648. mem = p.usedGpuMemory / (1024 * 1024)
  649. pid = p.pid
  650. else:
  651. try:
  652. proc_info = amdsmi.amdsmi_get_gpu_process_info(handle, p) # type: ignore[possibly-undefined]
  653. except AttributeError:
  654. # https://github.com/ROCm/amdsmi/commit/c551c3caedbd903ba828e7fdffa5b56d475a15e7
  655. # is a BC-breaking change that removes amdsmi_get_gpu_process_info API from amdsmi
  656. proc_info = p
  657. mem = proc_info["memory_usage"]["vram_mem"] / (1024 * 1024)
  658. pid = proc_info["pid"]
  659. lines.append(f"process {pid:>10d} uses {mem:>12.3f} MB GPU memory")
  660. return "\n".join(lines)
  661. def mem_get_info(device: "Device" = None) -> tuple[int, int]:
  662. r"""Return the global free and total GPU memory for a given device using cudaMemGetInfo.
  663. Args:
  664. device (torch.device or int or str, optional): selected device. Returns
  665. statistic for the current device, given by :func:`~torch.cuda.current_device`,
  666. if :attr:`device` is ``None`` (default) or if the device index is not specified.
  667. .. note::
  668. See :ref:`cuda-memory-management` for more
  669. details about GPU memory management.
  670. """
  671. if device is None:
  672. device = torch.cuda.current_device()
  673. # optional=True allows `device = torch.device('cuda')` for which device.index is None
  674. device = _get_device_index(device, optional=True)
  675. return torch.cuda.cudart().cudaMemGetInfo(device)
  676. def _record_memory_history_legacy(
  677. enabled: bool,
  678. record_context=True,
  679. trace_alloc_max_entries=1,
  680. trace_alloc_record_context=False,
  681. device: "Device" = None,
  682. record_context_cpp=False,
  683. clear_history=False,
  684. compile_context=False,
  685. global_record_annotations=False,
  686. skip_actions=None,
  687. ):
  688. _C._cuda_record_memory_history_legacy( # type: ignore[call-arg]
  689. enabled,
  690. record_context,
  691. # pyrefly: ignore [bad-argument-type]
  692. trace_alloc_max_entries,
  693. trace_alloc_record_context,
  694. record_context_cpp,
  695. clear_history,
  696. compile_context,
  697. global_record_annotations,
  698. # pyrefly: ignore [bad-argument-count]
  699. skip_actions if skip_actions is not None else [],
  700. )
  701. def _record_memory_history(
  702. enabled: Literal["state", "all"] | None = "all", *args, **kwargs
  703. ) -> None:
  704. """Enable recording of stack traces associated with memory
  705. allocations, so you can tell what allocated any piece of memory in
  706. :func:`torch.cuda.memory._snapshot()`.
  707. In addition to keeping stack traces with each current allocation and free,
  708. this will also enable recording of a history of all alloc/free events.
  709. Use :func:`torch.cuda.memory._snapshot()` to retrieve this information,
  710. and the tools in `_memory_viz.py` to visualize snapshots.
  711. Buffer behavior
  712. ---------------
  713. This will store up to `max_entries` instances of `TraceEntry` when enabled.
  714. Python trace collection defaults to `sys.maxsize`, meaning long-running
  715. or indefinitely running jobs should set a reasonable limit to avoid excessive
  716. memory use. Expect each entry to be several KB.
  717. Longer running workflows or those with smaller `max_entries` values will only
  718. store the last accumulated `max_entries` entries, meaning new entries overwrite
  719. older entries.
  720. C++ implementation for reference to ring buffer implementation:
  721. .. code-block:: cpp
  722. if (record_history) {
  723. if (alloc_trace->size() < alloc_trace_max_entries_) {
  724. alloc_trace->emplace_back(te);
  725. } else {
  726. (*alloc_trace)[alloc_trace_next++] = te;
  727. if (alloc_trace_next == alloc_trace_max_entries_) {
  728. alloc_trace_next = 0;
  729. }
  730. }
  731. }
  732. Latency impact
  733. --------------
  734. The Python trace collection is fast (2us per trace), so you may consider
  735. enabling this on production jobs if you anticipate ever having to debug
  736. memory issues.
  737. C++ trace collection is also fast (~50ns/frame), which for many typical programs
  738. works out to ~2us per trace, but can vary depending on stack depth.
  739. Args:
  740. enabled (Literal[None, "state", "all"], optional):
  741. `None`, disable recording memory history.
  742. `"state"`, keep information for currently allocated memory.
  743. `"all"`, additionally keep a history of all alloc/free calls.
  744. Defaults to "all".
  745. context (Literal[None, "state", "alloc", "all"], optional):
  746. `None`, Do not record any tracebacks.
  747. `"state"`, Record tracebacks for currently allocated memory.
  748. `"alloc"`, additionally keep tracebacks for alloc calls.
  749. `"all"`, additionally keep tracebacks for free calls.
  750. Defaults to "all".
  751. stacks (Literal["python", "all"], optional):
  752. `"python"`, include Python, TorchScript, and inductor frames in tracebacks
  753. `"all"`, additionally include C++ frames
  754. Defaults to "all".
  755. max_entries (int, optional): Keep a maximum of `max_entries`
  756. alloc/free events in the recorded history recorded.
  757. clear_history (bool, optional): Clear history when enabling, defaults to False.
  758. skip_actions (list[str], optional): List of action types to skip when recording
  759. memory history. This can be used to reduce memory overhead by excluding
  760. certain types of events from being recorded. Valid action types are:
  761. - `"alloc"`: Memory allocation events
  762. - `"free_requested"`: Free requests (memory marked for freeing)
  763. - `"free_completed"`: Completed free operations (memory actually freed)
  764. - `"segment_alloc"`: Segment allocation from cudaMalloc
  765. - `"segment_free"`: Segment freed back to CUDA via cudaFree
  766. - `"oom"`: Out-of-memory exceptions
  767. - `"snapshot"`: Memory snapshot generation events
  768. For example, to skip recording free_requested events:
  769. `skip_actions=["free_requested"]`
  770. Defaults to None (record all actions).
  771. """
  772. if isinstance(enabled, bool):
  773. return _record_memory_history_legacy(enabled, *args, **kwargs)
  774. else:
  775. return _record_memory_history_impl(enabled, *args, **kwargs)
  776. def _record_memory_history_impl(
  777. enabled: str | None = "all",
  778. context: str | None = "all",
  779. stacks: str = "all",
  780. max_entries: int = sys.maxsize,
  781. device: "Device" = None,
  782. clear_history: bool = False,
  783. compile_context: bool = False,
  784. global_record_annotations: bool = False,
  785. skip_actions: list[str] | None = None,
  786. ):
  787. _C._cuda_record_memory_history( # type: ignore[call-arg]
  788. enabled,
  789. context,
  790. stacks,
  791. max_entries,
  792. clear_history,
  793. compile_context,
  794. global_record_annotations,
  795. # pyrefly: ignore [bad-argument-count]
  796. skip_actions if skip_actions is not None else [],
  797. )
  798. _record_memory_history.__signature__ = signature(_record_memory_history_impl) # type: ignore[attr-defined]
  799. def _snapshot(device: "Device" = None, augment_with_fx_traces=False):
  800. """Save a snapshot of CUDA memory state at the time it was called.
  801. The state is represented as a dictionary with the following structure.
  802. .. code-block:: python
  803. class Snapshot(TypedDict):
  804. segments: List[Segment]
  805. device_traces: List[List[TraceEntry]]
  806. class Segment(TypedDict):
  807. # Segments are memory returned from a cudaMalloc call.
  808. # The size of reserved memory is the sum of all Segments.
  809. # Segments are cached and reused for future allocations.
  810. # If the reuse is smaller than the segment, the segment
  811. # is split into more then one Block.
  812. # empty_cache() frees Segments that are entirely inactive.
  813. address: int
  814. total_size: int # cudaMalloc'd size of segment
  815. stream: int
  816. segment_type: Literal["small", "large"] # 'large' (>1MB)
  817. allocated_size: int # size of memory in use
  818. active_size: int # size of memory in use or in active_awaiting_free state
  819. blocks: List[Block]
  820. class Block(TypedDict):
  821. # A piece of memory returned from the allocator, or
  822. # current cached but inactive.
  823. size: int
  824. requested_size: int # size requested during malloc, may be smaller than
  825. # size due to rounding
  826. address: int
  827. state: Literal[
  828. "active_allocated", # used by a tensor
  829. "active_awaiting_free", # waiting for another stream to finish using
  830. # this, then it will become free
  831. "inactive",
  832. ] # free for reuse
  833. frames: List[Frame] # stack trace from where the allocation occurred
  834. class Frame(TypedDict):
  835. filename: str
  836. line: int
  837. name: str
  838. # Optional FX debug fields (present when augment_with_fx_traces=True
  839. # and the frame corresponds to FX-generated code)
  840. fx_node_op: str # FX node operation type (e.g., 'call_function', 'output')
  841. fx_node_name: str # FX node name (e.g., 'linear', 'relu_1')
  842. fx_original_trace: str # Original model source code stack trace
  843. class TraceEntry(TypedDict):
  844. # When `torch.cuda.memory._record_memory_history()` is enabled,
  845. # the snapshot will contain TraceEntry objects that record each
  846. # action the allocator took.
  847. action: Literal[
  848. "alloc" # memory allocated
  849. "free_requested", # the allocated received a call to free memory
  850. "free_completed", # the memory that was requested to be freed is now
  851. # able to be used in future allocation calls
  852. "segment_alloc", # the caching allocator ask cudaMalloc for more memory
  853. # and added it as a segment in its cache
  854. "segment_free", # the caching allocator called cudaFree to return memory
  855. # to cuda possibly trying free up memory to
  856. # allocate more segments or because empty_caches was called
  857. "oom", # the allocator threw an OOM exception. 'size' is
  858. # the requested number of bytes that did not succeed
  859. "snapshot", # the allocator generated a memory snapshot
  860. # useful to coorelate a previously taken
  861. # snapshot with this trace
  862. ]
  863. addr: int # not present for OOM
  864. frames: List[Frame]
  865. size: int
  866. stream: int
  867. device_free: int # only present for OOM, the amount of
  868. # memory cuda still reports to be free
  869. Args:
  870. device: Device to capture snapshot for. If None, captures for current device.
  871. augment_with_fx_traces: If True, augment stack trace frames with FX debug information
  872. that maps generated FX code back to original model source code.
  873. This adds fx_node_op, fx_node_name, fx_original_trace, and
  874. fx_node_info fields to Frame objects. Default: False.
  875. Returns:
  876. The Snapshot dictionary object
  877. """
  878. s = _C._cuda_memorySnapshot(None)
  879. if augment_with_fx_traces:
  880. s = _augment_memory_snapshot_stack_traces(s) # type: ignore[assignment, arg-type]
  881. return s
  882. def _dump_snapshot(filename="dump_snapshot.pickle", augment_with_fx_traces=False):
  883. """
  884. Save a pickled version of the `torch.memory._snapshot()` dictionary to a file.
  885. This file can be opened by the interactive snapshot viewer at pytorch.org/memory_viz
  886. Snapshot file sizes scale with `max_entries` and stack trace depth per entry,
  887. with several KB per entry. These can easily be in the GB range for longer running
  888. workflows with large `max_entries`.
  889. Args:
  890. filename (str, optional): Name of the file to create. Defaults to "dump_snapshot.pickle".
  891. augment_with_fx_traces (bool, optional): If True, augment the snapshot with FX debug information
  892. before dumping. This maps generated FX code stack traces
  893. back to original model source code. Defaults to False.
  894. """
  895. s = _snapshot(augment_with_fx_traces=augment_with_fx_traces)
  896. with open(filename, "wb") as f:
  897. pickle.dump(s, f)
  898. def _set_memory_metadata(metadata: str):
  899. """
  900. Set custom metadata that will be attached to all subsequent CUDA memory allocations.
  901. This metadata will be recorded in the memory snapshot for all allocations made
  902. after this call until the metadata is cleared or changed.
  903. Args:
  904. metadata (str): Custom metadata string to attach to allocations.
  905. Pass an empty string to clear the metadata.
  906. """
  907. # pyrefly: ignore [missing-attribute]
  908. torch._C._cuda_setMemoryMetadata(metadata)
  909. def _get_memory_metadata() -> str:
  910. """
  911. Get the current custom metadata that is being attached to CUDA memory allocations.
  912. Returns:
  913. str: The current metadata string, or empty string if no metadata is set.
  914. """
  915. # pyrefly: ignore [missing-attribute]
  916. return torch._C._cuda_getMemoryMetadata()
  917. def _save_segment_usage(filename="output.svg", snapshot=None):
  918. if snapshot is None:
  919. snapshot = _snapshot()
  920. with open(filename, "w") as f:
  921. f.write(_segments(snapshot))
  922. def _save_memory_usage(filename="output.svg", snapshot=None):
  923. if snapshot is None:
  924. snapshot = _snapshot()
  925. with open(filename, "w") as f:
  926. f.write(_memory(snapshot))
  927. @deprecated(
  928. "torch.cuda._set_allocator_settings is deprecated. Use torch._C._accelerator_setAllocatorSettings instead.",
  929. category=FutureWarning,
  930. )
  931. def _set_allocator_settings(env: str):
  932. # pyrefly: ignore [missing-attribute]
  933. return torch._C._accelerator_setAllocatorSettings(env)
  934. def get_allocator_backend() -> str:
  935. r"""Return a string describing the active allocator backend as set by
  936. ``PYTORCH_ALLOC_CONF``. Currently available backends are
  937. ``native`` (PyTorch's native caching allocator) and `cudaMallocAsync``
  938. (CUDA's built-in asynchronous allocator).
  939. .. note::
  940. See :ref:`cuda-memory-management` for details on choosing the allocator backend.
  941. """
  942. return torch._C._cuda_getAllocatorBackend()
  943. class _CUDAAllocator:
  944. r"""Wrapper over internal CUDA memory allocators."""
  945. def __init__(self, allocator: torch._C._cuda_CUDAAllocator):
  946. self._allocator = allocator
  947. def allocator(self):
  948. return self._allocator
  949. class CUDAPluggableAllocator(_CUDAAllocator):
  950. r"""CUDA memory allocator loaded from a so file."""
  951. def __init__(self, path_to_so_file: str, alloc_fn_name: str, free_fn_name: str):
  952. r"""Memory allocators are compiled in .so files and loaded dynamically using ctypes.
  953. To change the active allocator use the :func:`torch.memory.cuda.change_current_allocator` function.
  954. Args:
  955. path_to_so_file(str): Path in the filesystem to the `.so` file containing
  956. the allocator functions
  957. alloc_fn_name(str): Name of the function to perform the memory allocation
  958. in the so file. The signature must be:
  959. void* alloc_fn_name(ssize_t size, int device, cudaStream_t stream);
  960. free_fn_name(str): Name of the function to perform the memory release
  961. in the so file. The signature must be:
  962. void free_fn_name(void* ptr, size_t size, cudaStream_t stream);
  963. .. warning::
  964. This is currently supported only in unix OSs
  965. .. note::
  966. See :ref:`cuda-memory-management` for details on creating and using a custom allocator
  967. """
  968. allocator = ctypes.CDLL(path_to_so_file)
  969. alloc_fn = ctypes.cast(getattr(allocator, alloc_fn_name), ctypes.c_void_p).value
  970. free_fn = ctypes.cast(getattr(allocator, free_fn_name), ctypes.c_void_p).value
  971. if alloc_fn is None:
  972. raise AssertionError(f"alloc_fn '{alloc_fn_name}' is None")
  973. if free_fn is None:
  974. raise AssertionError(f"free_fn '{free_fn_name}' is None")
  975. self._allocator = torch._C._cuda_customAllocator(alloc_fn, free_fn)
  976. def change_current_allocator(allocator: _CUDAAllocator) -> None:
  977. r"""Change the currently used memory allocator to be the one provided.
  978. If the current allocator has already been used/initialized, this function will error.
  979. Args:
  980. allocator (torch.cuda.memory._CUDAAllocator): allocator to be set as the active one.
  981. .. note::
  982. See :ref:`cuda-memory-management` for details on creating and using a custom allocator
  983. """
  984. torch._C._cuda_changeCurrentAllocator(allocator.allocator())
  985. def _get_current_allocator() -> _CUDAAllocator:
  986. r"""Return the allocator being currently used.
  987. .. note::
  988. See :ref:`cuda-memory-management` for details on creating and using a custom allocator
  989. """
  990. return _CUDAAllocator(torch._C._cuda_getAllocator())
  991. class MemPool(_MemPool):
  992. r"""MemPool represents a pool of memory in a caching allocator. Currently,
  993. it's just the ID of the pool object maintained in the CUDACachingAllocator.
  994. Args:
  995. allocator(torch._C._cuda_CUDAAllocator, optional): a
  996. torch._C._cuda_CUDAAllocator object that can be used to
  997. define how memory gets allocated in the pool. If :attr:`allocator`
  998. is ``None`` (default), memory allocation follows the default/
  999. current configuration of the CUDACachingAllocator.
  1000. use_on_oom(bool): a bool that indicates if this pool can be used
  1001. as a last resort if a memory allocation outside of the pool fails due
  1002. to Out Of Memory. This is False by default.
  1003. no_split(bool): a bool that indicates if this pool should not split a segment.
  1004. This is False by default.
  1005. """
  1006. def __init__(
  1007. self,
  1008. allocator: _cuda_CUDAAllocator | None = None,
  1009. use_on_oom: bool = False,
  1010. no_split: bool = False,
  1011. ):
  1012. # pyrefly: ignore [bad-argument-count]
  1013. super().__init__(allocator, True, use_on_oom, no_split)
  1014. @property
  1015. def id(self) -> tuple[int, int]:
  1016. r"""Returns the ID of this pool as a tuple of two ints."""
  1017. return super().id
  1018. def use_count(self) -> int: # pylint: disable=useless-parent-delegation
  1019. r"""Returns the reference count of this pool."""
  1020. return super().use_count()
  1021. def snapshot(self, include_traces=True):
  1022. r"""Return a snapshot of the CUDA memory allocator pool state across all
  1023. devices.
  1024. Interpreting the output of this function requires familiarity with the
  1025. memory allocator internals.
  1026. Args:
  1027. include_traces: Whether to include trace entries in the snapshot.
  1028. If True (default), all trace entries are included.
  1029. If False, no trace entries are included (lightweight/fast snapshot).
  1030. .. note::
  1031. See :ref:`cuda-memory-management` for more details about GPU memory
  1032. management.
  1033. """
  1034. snapshot = torch.cuda.memory_snapshot(self.id, include_traces=include_traces)
  1035. return snapshot
  1036. @contextlib.contextmanager
  1037. def use_mem_pool(pool: MemPool, device: "Device" = None):
  1038. r"""A context manager that routes allocations to a given pool.
  1039. Args:
  1040. pool(torch.cuda.MemPool): a MemPool object to be made active so that
  1041. allocations route to this pool.
  1042. device (torch.device or int, optional): selected device. Uses MemPool on
  1043. the current device, given by :func:`~torch.cuda.current_device`,
  1044. if :attr:`device` is ``None`` (default).
  1045. .. note::
  1046. This context manager makes only current thread's allocations route to
  1047. the given pool. If a new thread is spawned inside the context manager
  1048. (e.g. by calling backward) the allocations in that thread will not
  1049. route to the given pool.
  1050. """
  1051. device_index = (
  1052. torch.cuda.current_device() if device is None else _get_device_index(device)
  1053. )
  1054. _cuda_beginAllocateCurrentThreadToPool(device_index, pool.id)
  1055. try:
  1056. yield
  1057. finally:
  1058. _cuda_endAllocateToPool(device_index, pool.id)
  1059. _cuda_releasePool(device_index, pool.id)