__init__.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. # mypy: allow-untyped-defs
  2. r"""
  3. This package enables an interface for accessing MTIA backend in python
  4. """
  5. import threading
  6. import traceback
  7. from collections.abc import Callable
  8. from typing import Any
  9. import torch
  10. from torch import Tensor
  11. from torch._environment import is_fbcode, is_prod
  12. from torch._utils import _LazySeedTracker
  13. from torch.types import Device
  14. from ._utils import _get_device_index
  15. # torch.mtia.Event/Stream is alias of torch.Event/Stream
  16. Event = torch.Event
  17. Stream = torch.Stream
  18. # Default generators are initialized inside _mtia_init
  19. default_generators: tuple[torch._C.Generator, ...] = () # type: ignore[assignment]
  20. _initialized = False
  21. _queued_calls: list[
  22. tuple[Callable[[], None], list[str]]
  23. ] = [] # don't invoke these until initialization occurs
  24. _tls = threading.local()
  25. _initialization_lock = threading.Lock()
  26. _lazy_seed_tracker = _LazySeedTracker()
  27. if hasattr(torch._C, "_mtia_exchangeDevice"):
  28. _exchange_device = torch._C._mtia_exchangeDevice
  29. else:
  30. def _exchange_device(device: int) -> int:
  31. if device < 0:
  32. return -1
  33. raise RuntimeError("PyTorch was compiled without MTIA support")
  34. if hasattr(torch._C, "_mtia_maybeExchangeDevice"):
  35. _maybe_exchange_device = torch._C._mtia_maybeExchangeDevice
  36. else:
  37. def _maybe_exchange_device(device: int) -> int:
  38. if device < 0:
  39. return -1
  40. raise RuntimeError("PyTorch was compiled without MTIA support")
  41. def init():
  42. _lazy_init()
  43. def is_initialized():
  44. r"""Return whether PyTorch's MTIA state has been initialized."""
  45. return _initialized and not _is_in_bad_fork()
  46. def _lazy_call(callable, **kwargs):
  47. with _initialization_lock:
  48. if is_initialized():
  49. return callable()
  50. else:
  51. global _lazy_seed_tracker
  52. if kwargs.get("seed_all", False):
  53. _lazy_seed_tracker.queue_seed_all(callable, traceback.format_stack())
  54. elif kwargs.get("seed", False):
  55. _lazy_seed_tracker.queue_seed(callable, traceback.format_stack())
  56. else:
  57. _queued_calls.append((callable, traceback.format_stack()))
  58. def _is_in_bad_fork() -> bool:
  59. return torch._C._mtia_isInBadFork()
  60. def _lazy_init() -> None:
  61. global _initialized, _queued_calls
  62. if is_initialized() or hasattr(_tls, "is_initializing"):
  63. return
  64. with _initialization_lock:
  65. # We be double-checking locking, boys! This is OK because
  66. # the above test was GIL protected anyway. The inner test
  67. # is for when a thread blocked on some other thread which was
  68. # doing the initialization; when they get the lock, they will
  69. # find there is nothing left to do.
  70. if is_initialized():
  71. return
  72. # It is important to prevent other threads from entering _lazy_init
  73. # immediately, while we are still guaranteed to have the GIL, because some
  74. # of the C calls we make below will release the GIL
  75. if _is_in_bad_fork():
  76. raise RuntimeError(
  77. "Cannot re-initialize MTIA in forked subprocess. To use MTIA with "
  78. "multiprocessing, you must use the 'spawn' start method"
  79. )
  80. if not _is_compiled():
  81. raise AssertionError(
  82. "Torch not compiled with MTIA enabled. "
  83. "Ensure you have `import mtia.host_runtime.torch_mtia.dynamic_library` in your python "
  84. "src file and include `//mtia/host_runtime/torch_mtia:torch_mtia` as "
  85. "your target dependency!"
  86. )
  87. # Install the C++ resource manager to enable Buck resource lookup from Python.
  88. # This must be called before _mtia_init() which may access Buck resources.
  89. if is_fbcode() and is_prod():
  90. try:
  91. from libfb.py.cxx_resources import cxx_resource_manager
  92. cxx_resource_manager.install()
  93. except ModuleNotFoundError:
  94. # cxx_resource_manager is not available in all build configurations
  95. pass
  96. torch._C._mtia_init()
  97. # Some of the queued calls may reentrantly call _lazy_init();
  98. # we need to just return without initializing in that case.
  99. # However, we must not let any *other* threads in!
  100. _tls.is_initializing = True
  101. _queued_calls.extend(calls for calls in _lazy_seed_tracker.get_calls() if calls)
  102. try:
  103. for queued_call, orig_traceback in _queued_calls:
  104. try:
  105. queued_call()
  106. except Exception as e:
  107. msg = (
  108. f"MTIA call failed lazily at initialization with error: {str(e)}\n\n"
  109. f"MTIA call was originally invoked at:\n\n{''.join(orig_traceback)}"
  110. )
  111. raise DeferredMtiaCallError(msg) from e
  112. finally:
  113. delattr(_tls, "is_initializing")
  114. _initialized = True
  115. class DeferredMtiaCallError(Exception):
  116. pass
  117. def _is_compiled() -> bool:
  118. r"""Return true if compiled with MTIA support."""
  119. return torch._C._mtia_isBuilt()
  120. def is_available() -> bool:
  121. r"""Return true if MTIA device is available"""
  122. if not _is_compiled():
  123. return False
  124. # MTIA has to init devices first to know if there is any devices available.
  125. return device_count() > 0
  126. def synchronize(device: Device = None) -> None:
  127. r"""Waits for all jobs in all streams on a MTIA device to complete."""
  128. with torch.mtia.device(device):
  129. return torch._C._mtia_deviceSynchronize()
  130. def device_count() -> int:
  131. r"""Return the number of MTIA devices available."""
  132. # TODO: Update _accelerator_hooks_device_count to abstract a MTIA device count API
  133. return torch._C._mtia_getDeviceCount()
  134. def current_device() -> int:
  135. r"""Return the index of a currently selected device."""
  136. return torch._C._accelerator_hooks_get_current_device()
  137. def current_stream(device: Device = None) -> Stream:
  138. r"""Return the currently selected :class:`Stream` for a given device.
  139. Args:
  140. device (torch.device or int, optional): selected device. Returns
  141. the currently selected :class:`Stream` for the current device, given
  142. by :func:`~torch.mtia.current_device`, if :attr:`device` is ``None``
  143. (default).
  144. """
  145. return torch._C._mtia_getCurrentStream(_get_device_index(device, optional=True))
  146. def default_stream(device: Device = None) -> Stream:
  147. r"""Return the default :class:`Stream` for a given device.
  148. Args:
  149. device (torch.device or int, optional): selected device. Returns
  150. the default :class:`Stream` for the current device, given by
  151. :func:`~torch.mtia.current_device`, if :attr:`device` is ``None``
  152. (default).
  153. """
  154. return torch._C._mtia_getDefaultStream(_get_device_index(device, optional=True))
  155. def record_memory_history(
  156. enabled: str | None = "all", stacks: str = "python", max_entries: int = 0
  157. ) -> None:
  158. r"""Enable/Disable the memory profiler on MTIA allocator
  159. Args:
  160. enabled (all or state, optional) selected device. Returns
  161. statistics for the current device, given by current_device(),
  162. if device is None (default).
  163. stacks ("python" or "cpp", optional). Select the stack trace to record.
  164. max_entries (int, optional). Maximum number of entries to record.
  165. """
  166. if not is_initialized():
  167. return
  168. torch._C._mtia_recordMemoryHistory(enabled, stacks, max_entries)
  169. def snapshot() -> dict[str, Any]:
  170. r"""Return a dictionary of MTIA memory allocator history"""
  171. return torch._C._mtia_memorySnapshot()
  172. def attach_out_of_memory_observer(
  173. observer: Callable[[int, int, int, int], None],
  174. ) -> None:
  175. r"""Attach an out-of-memory observer to MTIA memory allocator"""
  176. torch._C._mtia_attachOutOfMemoryObserver(observer)
  177. def is_bf16_supported(including_emulation: bool = True):
  178. r"""Return a bool indicating if the current MTIA device supports dtype bfloat16."""
  179. return True
  180. def get_device_capability(device: Device = None) -> tuple[int, int]:
  181. r"""Return capability of a given device as a tuple of (major version, minor version).
  182. Args:
  183. device (torch.device or int, optional) selected device. Returns
  184. statistics for the current device, given by current_device(),
  185. if device is None (default).
  186. """
  187. return torch._C._mtia_getDeviceCapability(_get_device_index(device, optional=True))
  188. def empty_cache() -> None:
  189. r"""Empty the MTIA device cache."""
  190. return torch._C._mtia_emptyCache()
  191. def set_stream(stream: Stream):
  192. r"""Set the current stream. This is a wrapper API to set the stream.
  193. Usage of this function is discouraged in favor of the ``stream``
  194. context manager.
  195. Args:
  196. stream (Stream): selected stream. This function is a no-op
  197. if this argument is ``None``.
  198. """
  199. if stream is None:
  200. return
  201. torch._C._mtia_setCurrentStream(stream)
  202. def set_device(device: Device) -> None:
  203. r"""Set the current device.
  204. Args:
  205. device (torch.device or int): selected device. This function is a no-op
  206. if this argument is negative.
  207. """
  208. device = _get_device_index(device)
  209. if device >= 0:
  210. torch._C._accelerator_hooks_set_current_device(device)
  211. def get_device_properties(device: Device = None) -> dict[str, Any]:
  212. r"""Return a dictionary of MTIA device properties
  213. Args:
  214. device (torch.device or int, optional) selected device. Returns
  215. statistics for the current device, given by current_device(),
  216. if device is None (default).
  217. """
  218. return torch._C._mtia_getDeviceProperties(_get_device_index(device, optional=True))
  219. class device:
  220. r"""Context-manager that changes the selected device.
  221. Args:
  222. device (torch.device or int): device index to select. It's a no-op if
  223. this argument is a negative integer or ``None``.
  224. """
  225. def __init__(self, device: Any):
  226. self.idx = _get_device_index(device, optional=True)
  227. self.prev_idx = -1
  228. def __enter__(self):
  229. self.prev_idx = torch._C._accelerator_hooks_maybe_exchange_device(self.idx)
  230. def __exit__(self, type: Any, value: Any, traceback: Any):
  231. self.idx = torch._C._accelerator_hooks_maybe_exchange_device(self.prev_idx)
  232. return False
  233. class StreamContext:
  234. r"""Context-manager that selects a given stream.
  235. All MTIA kernels queued within its context will be enqueued on a selected
  236. stream.
  237. Args:
  238. Stream (Stream): selected stream. This manager is a no-op if it's
  239. ``None``.
  240. .. note:: Streams are per-device.
  241. """
  242. cur_stream: Stream | None
  243. def __init__(self, stream: Stream | None):
  244. self.cur_stream = None
  245. self.stream = stream
  246. self.idx = _get_device_index(None, True)
  247. if not torch.jit.is_scripting():
  248. if self.idx is None:
  249. self.idx = -1 # pyrefly: ignore [bad-assignment]
  250. self.src_prev_stream = (
  251. None if not torch.jit.is_scripting() else torch.mtia.default_stream(None)
  252. )
  253. self.dst_prev_stream = (
  254. None if not torch.jit.is_scripting() else torch.mtia.default_stream(None)
  255. )
  256. def __enter__(self):
  257. # Local cur_stream variable for type refinement
  258. cur_stream = self.stream
  259. # Return if stream is None or MTIA device not available
  260. if cur_stream is None or self.idx == -1:
  261. return
  262. self.src_prev_stream = torch.mtia.current_stream(None)
  263. # If the stream is not on the current device, then
  264. # set the current stream on the device
  265. if self.src_prev_stream.device != cur_stream.device:
  266. with device(cur_stream.device):
  267. self.dst_prev_stream = torch.mtia.current_stream(cur_stream.device)
  268. torch.mtia.set_stream(cur_stream)
  269. def __exit__(self, type: Any, value: Any, traceback: Any):
  270. # Local cur_stream variable for type refinement
  271. cur_stream = self.stream
  272. # If stream is None or no MTIA device available, return
  273. if cur_stream is None or self.idx == -1:
  274. return
  275. # Reset the stream on the original device
  276. # and destination device
  277. if self.src_prev_stream.device != cur_stream.device: # type: ignore[union-attr]
  278. torch.mtia.set_stream(self.dst_prev_stream) # type: ignore[arg-type]
  279. torch.mtia.set_stream(self.src_prev_stream) # type: ignore[arg-type]
  280. def _set_stream_by_id(stream_id, device_index, device_type):
  281. r"""set stream specified by the stream id, device index and
  282. device type
  283. Args: stream_id (int): stream id in stream pool
  284. device_index (int): device index in topo
  285. device_type (int): enum device type
  286. """
  287. torch._C._mtia_setStream(stream_id, device_index, device_type)
  288. def stream(stream: Stream | None) -> StreamContext:
  289. r"""Wrap around the Context-manager StreamContext that selects a given stream.
  290. Arguments:
  291. stream (Stream): selected stream. This manager is a no-op if it's
  292. ``None``.
  293. .. note:: In eager mode stream is of type Stream class while in JIT it doesn't support torch.mtia.stream
  294. """
  295. return StreamContext(stream)
  296. def get_rng_state(device: Device = "mtia") -> Tensor:
  297. r"""Returns the random number generator state of the specified MTIA device as a ByteTensor.
  298. Args:
  299. device (torch.device or int, optional): The device to return the RNG state of.
  300. Default: ``'mtia'`` (i.e., ``torch.device('mtia')``, the current mtia device).
  301. .. warning::
  302. This function eagerly initializes MTIA.
  303. """
  304. _lazy_init()
  305. idx = _get_device_index(device, optional=True)
  306. if idx is None:
  307. idx = current_device()
  308. default_generator = default_generators[idx]
  309. return default_generator.get_state()
  310. def get_rng_state_all() -> list[Tensor]:
  311. r"""Returns a list of ByteTensor representing the random number states of all devices."""
  312. results = [get_rng_state(i) for i in range(device_count())]
  313. return results
  314. def set_rng_state(new_state: Tensor, device: Device = "mtia") -> None:
  315. r"""Sets the random number generator state of the specified MTIA device.
  316. Args:
  317. new_state (torch.ByteTensor): The desired state
  318. device (torch.device or int, optional): The device to set the RNG state.
  319. Default: ``'mtia'`` (i.e., ``torch.device('mtia')``, the current mtia device).
  320. """
  321. if not is_initialized():
  322. with torch._C._DisableFuncTorch():
  323. # Clone the state because the callback will be triggered
  324. # later when MTIA is lazy initialized.
  325. new_state = new_state.clone(memory_format=torch.contiguous_format)
  326. idx = _get_device_index(device, optional=True)
  327. if idx is None:
  328. idx = current_device()
  329. def cb():
  330. default_generator = default_generators[idx]
  331. default_generator.set_state(new_state)
  332. _lazy_call(cb)
  333. def set_rng_state_all(new_states: list[Tensor]) -> None:
  334. r"""Sets the random number generator state of all devices.
  335. Args:
  336. new_states (Iterable of torch.ByteTensor): The desired state for each device.
  337. """
  338. for i, state in enumerate(new_states):
  339. set_rng_state(state, i)
  340. def manual_seed(seed: int) -> None:
  341. r"""Sets the seed for generating random numbers for the current MTIA device.
  342. It's safe to call this function if MTIA is not available; in that case, it is silently ignored.
  343. Args:
  344. seed (int): The desired seed.
  345. .. warning::
  346. If you are working with a multi-GPU model, this function is insufficient
  347. to get determinism. To seed all GPUs, use :func:`manual_seed_all`.
  348. """
  349. seed = int(seed)
  350. def cb():
  351. idx = current_device()
  352. default_generator = default_generators[idx]
  353. default_generator.manual_seed(seed)
  354. _lazy_call(cb, seed=True)
  355. def manual_seed_all(seed: int) -> None:
  356. r"""Sets the seed for generating random numbers on all MTIA devices.
  357. It's safe to call this function if MTIA is not available; in that case, it is silently ignored.
  358. Args:
  359. seed (int): The desired seed.
  360. """
  361. seed = int(seed)
  362. def cb():
  363. for i in range(device_count()):
  364. default_generator = default_generators[i]
  365. default_generator.manual_seed(seed)
  366. _lazy_call(cb, seed_all=True)
  367. def seed() -> int:
  368. r"""Sets the seed for generating random numbers to a random number for the current MTIA device.
  369. It's safe to call this function if MTIA is not available; in that case, it is silently ignored.
  370. .. warning::
  371. If you are working with a multi-GPU model, this function will only initialize
  372. the seed on one GPU. To initialize all GPUs, use :func:`seed_all`.
  373. """
  374. def cb():
  375. idx = current_device()
  376. default_generator = default_generators[idx]
  377. return default_generator.seed()
  378. return _lazy_call(cb, seed=True)
  379. def seed_all() -> int:
  380. r"""Sets the seed for generating random numbers to a random number on all MTIA devices.
  381. It's safe to call this function if MTIA is not available; in that case, it is silently ignored.
  382. """
  383. def cb():
  384. random_seed = 0
  385. seeded = False
  386. for i in range(device_count()):
  387. default_generator = default_generators[i]
  388. if not seeded:
  389. random_seed = default_generator.seed()
  390. seeded = True
  391. else:
  392. default_generator.manual_seed(random_seed)
  393. return random_seed
  394. return _lazy_call(cb, seed_all=True)
  395. def initial_seed() -> int:
  396. r"""Returns the current random seed of the current MTIA device.
  397. .. warning::
  398. This function eagerly initializes MTIA.
  399. """
  400. _lazy_init()
  401. idx = current_device()
  402. return default_generators[idx].initial_seed()
  403. from .memory import * # noqa: F403
  404. from .mtia_graph import * # noqa: F403
  405. __all__ = [
  406. "init",
  407. "is_available",
  408. "is_initialized",
  409. "synchronize",
  410. "device_count",
  411. "current_device",
  412. "current_stream",
  413. "default_stream",
  414. "memory_stats",
  415. "max_memory_allocated",
  416. "memory_allocated",
  417. "reset_peak_memory_stats",
  418. "get_device_capability",
  419. "get_device_properties",
  420. "record_memory_history",
  421. "snapshot",
  422. "attach_out_of_memory_observer",
  423. "empty_cache",
  424. "set_device",
  425. "set_stream",
  426. "stream",
  427. "device",
  428. "set_rng_state",
  429. "get_rng_state",
  430. "set_rng_state_all",
  431. "get_rng_state_all",
  432. "manual_seed",
  433. "manual_seed_all",
  434. "seed",
  435. "seed_all",
  436. "initial_seed",
  437. "is_bf16_supported",
  438. "MTIAGraph",
  439. "graph",
  440. "graph_pool_handle",
  441. ]