custom_all_reduce.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import os
  2. from contextlib import contextmanager
  3. from typing import Any, List, Optional, Union
  4. import torch
  5. import torch.distributed as dist
  6. from loguru import logger
  7. from torch.distributed import ProcessGroup
  8. from aphrodite import _custom_ops as ops
  9. from aphrodite.common.utils import cuda_device_count_stateless
  10. from aphrodite.distributed.device_communicators.custom_all_reduce_utils import (
  11. gpu_p2p_access_check)
  12. from aphrodite.distributed.parallel_state import in_the_same_node_as
  13. from aphrodite.platforms import current_platform
  14. try:
  15. ops.meta_size()
  16. custom_ar = True
  17. except Exception:
  18. # For AMD GPUs and CPUs
  19. custom_ar = False
  20. def _can_p2p(rank: int, world_size: int) -> bool:
  21. for i in range(world_size):
  22. if i == rank:
  23. continue
  24. if not gpu_p2p_access_check(rank, i):
  25. return False
  26. return True
  27. class CustomAllreduce:
  28. _SUPPORTED_WORLD_SIZES = [2, 4, 6, 8]
  29. # max_size: max supported allreduce size
  30. def __init__(self,
  31. group: ProcessGroup,
  32. device: Union[int, str, torch.device],
  33. max_size=8192 * 1024) -> None:
  34. """
  35. Args:
  36. group: the process group to work on. If None, it will use the
  37. default process group.
  38. device: the device to bind the CustomAllreduce to. If None,
  39. it will be bind to f"cuda:{local_rank}".
  40. It is the caller's responsibility to make sure each communicator
  41. is bind to a unique device, and all communicators in this group
  42. are in the same node.
  43. """
  44. self._IS_CAPTURING = False
  45. self.disabled = True
  46. if not custom_ar:
  47. # disable because of missing custom allreduce library
  48. # e.g. in a non-cuda environment
  49. return
  50. self.group = group
  51. assert dist.get_backend(group) != dist.Backend.NCCL, (
  52. "CustomAllreduce should be attached to a non-NCCL group.")
  53. if not all(in_the_same_node_as(group, source_rank=0)):
  54. # No need to initialize custom allreduce for multi-node case.
  55. logger.warning(
  56. "Custom allreduce is disabled because this process group"
  57. " spans across nodes.")
  58. return
  59. rank = dist.get_rank(group=self.group)
  60. world_size = dist.get_world_size(group=self.group)
  61. if world_size == 1:
  62. # No need to initialize custom allreduce for single GPU case.
  63. return
  64. if world_size not in CustomAllreduce._SUPPORTED_WORLD_SIZES:
  65. logger.warning(
  66. "Custom allreduce is disabled due to an unsupported world"
  67. f" size: {world_size}. Supported world sizes:"
  68. f"{str(CustomAllreduce._SUPPORTED_WORLD_SIZES)}. To silence "
  69. "this warning, specify disable_custom_all_reduce=True "
  70. "explicitly.")
  71. return
  72. if isinstance(device, int):
  73. device = torch.device(f"cuda:{device}")
  74. elif isinstance(device, str):
  75. device = torch.device(device)
  76. # now `device` is a `torch.device` object
  77. assert isinstance(device, torch.device)
  78. self.device = device
  79. cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES", None)
  80. if cuda_visible_devices:
  81. device_ids = list(map(int, cuda_visible_devices.split(",")))
  82. else:
  83. device_ids = list(range(cuda_device_count_stateless()))
  84. physical_device_id = device_ids[device.index]
  85. tensor = torch.tensor([physical_device_id],
  86. dtype=torch.int,
  87. device="cpu")
  88. gather_list = [
  89. torch.tensor([0], dtype=torch.int, device="cpu")
  90. for _ in range(world_size)
  91. ]
  92. dist.all_gather(gather_list, tensor, group=self.group)
  93. physical_device_ids = [t.item() for t in gather_list]
  94. # test nvlink first, this will filter out most of the cases
  95. # where custom allreduce is not supported
  96. # this checks hardware and driver support for NVLink
  97. assert current_platform.is_cuda()
  98. from aphrodite.platforms.cuda import CudaPlatform
  99. cuda_platform: CudaPlatform = current_platform
  100. full_nvlink = cuda_platform.is_full_nvlink(physical_device_ids)
  101. if world_size > 2 and not full_nvlink:
  102. logger.warning(
  103. "Custom allreduce is disabled because it's not supported on"
  104. " more than two PCIe-only GPUs. To silence this warning, "
  105. "specify disable_custom_all_reduce=True explicitly.")
  106. return
  107. # test P2P capability, this checks software/cudaruntime support
  108. # this is expensive to compute at the first time
  109. # then we cache the result
  110. if not _can_p2p(rank, world_size):
  111. logger.warning(
  112. "Custom allreduce is disabled because your platform lacks "
  113. "GPU P2P capability or P2P test failed. To silence this "
  114. "warning, specify disable_custom_all_reduce=True explicitly.")
  115. return
  116. self.disabled = False
  117. # buffers memory are owned by this Python class and passed to C++
  118. # meta data composes of two parts: meta data for synchronization
  119. # (256 bytes) and a temporary buffer for storing intermediate
  120. # allreduce results.
  121. self.meta = torch.zeros(ops.meta_size() + max_size,
  122. dtype=torch.uint8,
  123. device=self.device)
  124. # This is a pre-registered IPC buffer. In eager mode, input tensors
  125. # are first copied into this buffer before allreduce is performed
  126. self.buffer = torch.empty(max_size,
  127. dtype=torch.uint8,
  128. device=self.device)
  129. # This is a buffer for storing the tuples of pointers pointing to
  130. # IPC buffers from all ranks. Each registered tuple has size of
  131. # 8*world_size bytes where world_size is at most 8. Allocating 8MB
  132. # is enough for 131072 such tuples. The largest model I've seen only
  133. # needs less than 10000 of registered tuples.
  134. self.rank_data = torch.empty(8 * 1024 * 1024,
  135. dtype=torch.uint8,
  136. device=self.device)
  137. self.max_size = max_size
  138. self.rank = rank
  139. self.world_size = world_size
  140. handles, offsets = self._get_ipc_meta(self.meta)
  141. self.full_nvlink = full_nvlink
  142. self._ptr = ops.init_custom_ar(self.meta, self.rank_data, handles,
  143. offsets, rank, self.full_nvlink)
  144. self.register_buffer(self.buffer)
  145. @contextmanager
  146. def capture(self):
  147. """
  148. The main responsibility of this context manager is the
  149. `register_graph_buffers` call at the end of the context.
  150. It records all the buffer addresses used in the CUDA graph.
  151. """
  152. try:
  153. self._IS_CAPTURING = True
  154. yield
  155. finally:
  156. self._IS_CAPTURING = False
  157. if not self.disabled:
  158. self.register_graph_buffers()
  159. def _get_ipc_meta(self, inp: torch.Tensor):
  160. data = inp.untyped_storage()._share_cuda_()
  161. shard_data = (
  162. data[1], # ipc handle to base ptr
  163. data[3], # offset of base ptr
  164. )
  165. return self._gather_ipc_meta(shard_data)
  166. def _gather_ipc_meta(self, shard_data):
  167. # Note: don't use `[[None]] * self.world_size` here
  168. # because it will create a list of the same reference
  169. all_data: List[Optional[Any]] = [[None]
  170. for i in range(self.world_size)]
  171. all_data[self.rank][0] = shard_data
  172. ranks = dist.get_process_group_ranks(group=self.group)
  173. ranks.sort()
  174. for i, rank in enumerate(ranks):
  175. dist.broadcast_object_list(all_data[i],
  176. src=rank,
  177. group=self.group,
  178. device="cpu")
  179. # we cannot directly use `dist.all_gather_object` here
  180. # because it is incompatible with `gloo` backend under inference mode.
  181. # see https://github.com/pytorch/pytorch/issues/126032 for details.
  182. handles = []
  183. offsets = []
  184. for i in range(len(all_data)):
  185. handles.append(all_data[i][0][0]) # type: ignore
  186. offsets.append(all_data[i][0][1]) # type: ignore
  187. return handles, offsets
  188. def register_buffer(self, inp: torch.Tensor):
  189. handles, offsets = self._get_ipc_meta(inp)
  190. ops.register_buffer(self._ptr, inp, handles, offsets)
  191. def register_graph_buffers(self):
  192. handle, offset = ops.get_graph_buffer_ipc_meta(self._ptr)
  193. handles, offsets = self._gather_ipc_meta((bytes(handle), offset))
  194. if self.rank == 0:
  195. logger.info(f"Registering {len(offset)} cuda graph addresses")
  196. ops.register_graph_buffers(self._ptr, handles, offsets)
  197. def should_custom_ar(self, inp: torch.Tensor):
  198. return ops.should_custom_ar(inp, self.max_size, self.world_size,
  199. self.full_nvlink)
  200. # all reduce, assuming inp tensor is IPC registered with register_buffer,
  201. # or, in the context of cuda graphs, register_graph_buffers
  202. def all_reduce_reg(self, inp: torch.Tensor, out: torch.Tensor = None):
  203. if out is None:
  204. out = torch.empty_like(inp)
  205. ops.all_reduce_reg(self._ptr, inp, out)
  206. return out
  207. # all reduce, assuming inp tensor is NOT IPC registered
  208. def all_reduce_unreg(self, inp: torch.Tensor, out: torch.Tensor = None):
  209. if out is None:
  210. out = torch.empty_like(inp)
  211. ops.all_reduce_unreg(self._ptr, inp, self.buffer, out)
  212. return out
  213. def custom_all_reduce(self, input: torch.Tensor) -> Optional[torch.Tensor]:
  214. # when custom allreduce is disabled, this will be None
  215. if self.disabled:
  216. return None
  217. if self._IS_CAPTURING:
  218. if torch.cuda.is_current_stream_capturing():
  219. if self.should_custom_ar(input):
  220. return self.all_reduce_reg(input)
  221. else:
  222. if self.should_custom_ar(input):
  223. # if warm up, mimic the allocation pattern
  224. # since custom allreduce is out-of-place
  225. return torch.empty_like(input)
  226. else:
  227. # note: outside of cuda graph context,
  228. # custom allreduce incurs a cost of cudaMemcpy, which should
  229. # be small(<=1% of overall latency) compared to the performance
  230. # gains of using custom kernels
  231. if self.should_custom_ar(input):
  232. return self.all_reduce_unreg(input)
  233. return None
  234. def close(self):
  235. if not self.disabled and self._ptr:
  236. ops.dispose(self._ptr)
  237. self._ptr = 0
  238. def __del__(self):
  239. self.close()