__init__.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. r"""
  2. This package enables an interface for accessing MPS backend in python
  3. """
  4. import torch
  5. from .. import Tensor
  6. _is_in_bad_fork = getattr(torch._C, "_mps_is_in_bad_fork", lambda: False)
  7. _default_mps_generator: torch._C.Generator = None # type: ignore[assignment]
  8. # local helper function (not public or exported)
  9. def _get_default_mps_generator() -> torch._C.Generator:
  10. global _default_mps_generator
  11. if _default_mps_generator is None:
  12. _default_mps_generator = torch._C._mps_get_default_generator()
  13. return _default_mps_generator
  14. def synchronize() -> None:
  15. r"""Waits for all kernels in all streams on a MPS device to complete."""
  16. return torch._C._mps_synchronize()
  17. def get_rng_state() -> Tensor:
  18. r"""Returns the random number generator state as a ByteTensor."""
  19. return _get_default_mps_generator().get_state()
  20. def set_rng_state(new_state: Tensor) -> None:
  21. r"""Sets the random number generator state.
  22. Args:
  23. new_state (torch.ByteTensor): The desired state
  24. """
  25. new_state_copy = new_state.clone(memory_format=torch.contiguous_format)
  26. _get_default_mps_generator().set_state(new_state_copy)
  27. def manual_seed(seed: int) -> None:
  28. r"""Sets the seed for generating random numbers.
  29. Args:
  30. seed (int): The desired seed.
  31. """
  32. # the torch.mps.manual_seed() can be called from the global
  33. # torch.manual_seed() in torch/random.py. So we need to make
  34. # sure mps is available (otherwise we just return without
  35. # erroring out)
  36. if not torch.has_mps:
  37. return
  38. seed = int(seed)
  39. _get_default_mps_generator().manual_seed(seed)
  40. def seed() -> None:
  41. r"""Sets the seed for generating random numbers to a random number."""
  42. _get_default_mps_generator().seed()
  43. def empty_cache() -> None:
  44. r"""Releases all unoccupied cached memory currently held by the caching
  45. allocator so that those can be used in other GPU applications.
  46. """
  47. torch._C._mps_emptyCache()
  48. def set_per_process_memory_fraction(fraction) -> None:
  49. r"""Set memory fraction for limiting process's memory allocation on MPS device.
  50. The allowed value equals the fraction multiplied by recommended maximum device memory
  51. (obtained from Metal API device.recommendedMaxWorkingSetSize).
  52. If trying to allocate more than the allowed value in a process, it will raise an out of
  53. memory error in allocator.
  54. Args:
  55. fraction(float): Range: 0~2. Allowed memory equals total_memory * fraction.
  56. .. note::
  57. Passing 0 to fraction means unlimited allocations
  58. (may cause system failure if out of memory).
  59. Passing fraction greater than 1.0 allows limits beyond the value
  60. returned from device.recommendedMaxWorkingSetSize.
  61. """
  62. if not isinstance(fraction, float):
  63. raise TypeError('Invalid type for fraction argument, must be `float`')
  64. if fraction < 0 or fraction > 2:
  65. raise ValueError('Invalid fraction value: {}. Allowed range: 0~2'.format(fraction))
  66. torch._C._mps_setMemoryFraction(fraction)
  67. def current_allocated_memory() -> int:
  68. r"""Returns the current GPU memory occupied by tensors in bytes.
  69. .. note::
  70. The returned size does not include cached allocations in
  71. memory pools of MPSAllocator.
  72. """
  73. return torch._C._mps_currentAllocatedMemory()
  74. def driver_allocated_memory() -> int:
  75. r"""Returns total GPU memory allocated by Metal driver for the process in bytes.
  76. .. note::
  77. The returned size includes cached allocations in MPSAllocator pools
  78. as well as allocations from MPS/MPSGraph frameworks.
  79. """
  80. return torch._C._mps_driverAllocatedMemory()
  81. __all__ = [
  82. 'get_rng_state', 'manual_seed', 'seed', 'set_rng_state', 'synchronize',
  83. 'empty_cache', 'set_per_process_memory_fraction', 'current_allocated_memory',
  84. 'driver_allocated_memory']