memory.py 53 KB

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