parallel_state.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. # Copyright 2023 The PygmalionAI team.
  2. # Copyright 2023 The vLLM team.
  3. # Adapted from
  4. # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py
  5. # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
  6. """Aphrodite distributed state.
  7. It takes over the control of the distributed environment from PyTorch.
  8. The typical workflow is:
  9. - call `init_distributed_environment` to initialize the distributed environment.
  10. - call `initialize_model_parallel` or `ensure_model_parallel_initialized` to
  11. initialize the model parallel groups.
  12. - any code dealing with the distributed stuff
  13. - call `destroy_model_parallel` to destroy the model parallel groups.
  14. - call `destroy_distributed_environment` to destroy the distributed environment.
  15. If you only need to use the distributed environment without model/pipeline
  16. parallelism, you can skip the model parallel initialization and destruction
  17. steps.
  18. """
  19. import contextlib
  20. import os
  21. import pickle
  22. from collections import namedtuple
  23. from contextlib import contextmanager, nullcontext
  24. from dataclasses import dataclass
  25. from multiprocessing import shared_memory
  26. from typing import Any, Dict, List, Optional, Tuple, Union
  27. from unittest.mock import patch
  28. import torch
  29. import torch.distributed
  30. from loguru import logger
  31. from torch.distributed import Backend, ProcessGroup
  32. @dataclass
  33. class GraphCaptureContext:
  34. stream: torch.cuda.Stream
  35. TensorMetadata = namedtuple("TensorMetadata", ["device", "dtype", "size"])
  36. def _split_tensor_dict(
  37. tensor_dict: Dict[str, Union[torch.Tensor, Any]]
  38. ) -> Tuple[List[Tuple[str, Any]], List[torch.Tensor]]:
  39. """Split the tensor dictionary into two parts:
  40. 1. A list of (key, value) pairs. If the value is a tensor, it is replaced
  41. by its metadata.
  42. 2. A list of tensors.
  43. """
  44. metadata_list: List[Tuple[str, Any]] = []
  45. tensor_list: List[torch.Tensor] = []
  46. for key, value in tensor_dict.items():
  47. if isinstance(value, torch.Tensor):
  48. # Note: we cannot use `value.device` here,
  49. # because it contains not only the device type but also the device
  50. # index (e.g. "cuda:0"). We only need the device type.
  51. # receiving side will set the device index.
  52. device = value.device.type
  53. metadata_list.append(
  54. (key, TensorMetadata(device, value.dtype, value.size())))
  55. tensor_list.append(value)
  56. else:
  57. metadata_list.append((key, value))
  58. return metadata_list, tensor_list
  59. class GroupCoordinator:
  60. """
  61. PyTorch ProcessGroup wrapper for a group of processes.
  62. PyTorch ProcessGroup is bound to one specific communication backend,
  63. e.g. NCCL, Gloo, MPI, etc.
  64. GroupCoordinator takes charge of all the communication operations among
  65. the processes in the group. It can route the communication to
  66. a specific implementation (e.g. switch allreduce implementation
  67. based on the tensor size and cuda graph mode).
  68. """
  69. # available attributes:
  70. rank: int # global rank
  71. ranks: List[int] # global ranks in the group
  72. world_size: int # size of the group
  73. # difference between `local_rank` and `rank_in_group`:
  74. # if we have a group of size 4 across two nodes:
  75. # Process | Node | Rank | Local Rank | Rank in Group
  76. # 0 | 0 | 0 | 0 | 0
  77. # 1 | 0 | 1 | 1 | 1
  78. # 2 | 1 | 2 | 0 | 2
  79. # 3 | 1 | 3 | 1 | 3
  80. local_rank: int # local rank used to assign devices
  81. rank_in_group: int # rank inside the group
  82. cpu_group: ProcessGroup # group for CPU communication
  83. device_group: ProcessGroup # group for device communication
  84. use_pynccl: bool # a hint of whether to use PyNccl
  85. use_custom_allreduce: bool # a hint of whether to use CustomAllreduce
  86. # communicators are only created for world size > 1
  87. pynccl_comm: Optional[Any] # PyNccl communicator
  88. ca_comm: Optional[Any] # Custom allreduce communicator
  89. mq_broadcaster: Optional[Any] # shared memory broadcaster
  90. def __init__(
  91. self,
  92. group_ranks: List[List[int]],
  93. local_rank: int,
  94. torch_distributed_backend: Union[str, Backend],
  95. use_pynccl: bool,
  96. use_custom_allreduce: bool,
  97. use_tpu_communicator: bool,
  98. use_message_queue_broadcaster: bool = False,
  99. ):
  100. self.rank = torch.distributed.get_rank()
  101. self.local_rank = local_rank
  102. self.device_group = None
  103. self.cpu_group = None
  104. for ranks in group_ranks:
  105. device_group = torch.distributed.new_group(
  106. ranks, backend=torch_distributed_backend)
  107. # a group with `gloo` backend, to allow direct coordination between
  108. # processes through the CPU.
  109. cpu_group = torch.distributed.new_group(ranks, backend="gloo")
  110. if self.rank in ranks:
  111. self.ranks = ranks
  112. self.world_size = len(ranks)
  113. self.rank_in_group = ranks.index(self.rank)
  114. self.device_group = device_group
  115. self.cpu_group = cpu_group
  116. assert self.cpu_group is not None
  117. assert self.device_group is not None
  118. if torch.cuda.is_available():
  119. self.device = torch.device(f"cuda:{local_rank}")
  120. else:
  121. self.device = torch.device("cpu")
  122. self.use_pynccl = use_pynccl
  123. self.use_custom_allreduce = use_custom_allreduce
  124. self.use_tpu_communicator = use_tpu_communicator
  125. # lazy import to avoid documentation build error
  126. from aphrodite.distributed.device_communicators.custom_all_reduce import ( # noqa: E501
  127. CustomAllreduce)
  128. from aphrodite.distributed.device_communicators.pynccl import (
  129. PyNcclCommunicator)
  130. self.pynccl_comm: Optional[PyNcclCommunicator]
  131. if use_pynccl and self.world_size > 1:
  132. self.pynccl_comm = PyNcclCommunicator(
  133. group=self.cpu_group,
  134. device=self.device,
  135. )
  136. else:
  137. self.pynccl_comm = None
  138. self.ca_comm: Optional[CustomAllreduce]
  139. if use_custom_allreduce and self.world_size > 1:
  140. # Initialize a custom fast all-reduce implementation.
  141. self.ca_comm = CustomAllreduce(
  142. group=self.cpu_group,
  143. device=self.device,
  144. )
  145. else:
  146. self.ca_comm = None
  147. from aphrodite.distributed.device_communicators.tpu_communicator import ( # noqa: E501
  148. TpuCommunicator)
  149. self.tpu_communicator: Optional[TpuCommunicator]
  150. if use_tpu_communicator and self.world_size > 1:
  151. self.tpu_communicator = TpuCommunicator(group=self.cpu_group)
  152. from aphrodite.distributed.device_communicators.shm_broadcast import (
  153. MessageQueue)
  154. self.mq_broadcaster: Optional[MessageQueue] = None
  155. if use_message_queue_broadcaster and self.world_size > 1:
  156. self.mq_broadcaster = MessageQueue.create_from_process_group(
  157. self.cpu_group, 1 << 22, 6)
  158. @property
  159. def first_rank(self):
  160. """Return the global rank of the first process in the group"""
  161. return self.ranks[0]
  162. @property
  163. def last_rank(self):
  164. """Return the global rank of the last process in the group"""
  165. return self.ranks[-1]
  166. @property
  167. def is_first_rank(self):
  168. """Return whether the caller is the first process in the group"""
  169. return self.rank == self.first_rank
  170. @property
  171. def is_last_rank(self):
  172. """Return whether the caller is the last process in the group"""
  173. return self.rank == self.last_rank
  174. @property
  175. def next_rank(self):
  176. """Return the global rank of the process that follows the caller"""
  177. rank_in_group = self.rank_in_group
  178. world_size = self.world_size
  179. return self.ranks[(rank_in_group + 1) % world_size]
  180. @property
  181. def prev_rank(self):
  182. """Return the global rank of the process that precedes the caller"""
  183. rank_in_group = self.rank_in_group
  184. world_size = self.world_size
  185. return self.ranks[(rank_in_group - 1) % world_size]
  186. @contextmanager
  187. def graph_capture(
  188. self, graph_capture_context: Optional[GraphCaptureContext] = None):
  189. if graph_capture_context is None:
  190. stream = torch.cuda.Stream()
  191. graph_capture_context = GraphCaptureContext(stream)
  192. else:
  193. stream = graph_capture_context.stream
  194. ca_comm = self.ca_comm
  195. maybe_ca_context = nullcontext(
  196. ) if ca_comm is None else ca_comm.capture()
  197. # ensure all initialization operations complete before attempting to
  198. # capture the graph on another stream
  199. curr_stream = torch.cuda.current_stream()
  200. if curr_stream != stream:
  201. stream.wait_stream(curr_stream)
  202. with torch.cuda.stream(stream), maybe_ca_context:
  203. # In graph mode, we have to be very careful about the collective
  204. # operations. The current status is:
  205. # allreduce \ Mode | Eager | Graph |
  206. # --------------------------------------------
  207. # custom allreduce | enabled | enabled |
  208. # PyNccl | disabled| enabled |
  209. # torch.distributed | enabled | disabled|
  210. #
  211. # Note that custom allreduce will have a runtime check, if the
  212. # tensor size is too large, it will fallback to the next
  213. # available option.
  214. # In summary: When using CUDA graph, we use
  215. # either custom all-reduce kernel or pynccl. When not using
  216. # CUDA graph, we use either custom all-reduce kernel or
  217. # PyTorch NCCL. We always prioritize using custom all-reduce
  218. # kernel but fall back to PyTorch or pynccl if it is
  219. # disabled or not supported.
  220. pynccl_comm = self.pynccl_comm
  221. maybe_pynccl_context: Any
  222. if not pynccl_comm:
  223. maybe_pynccl_context = nullcontext()
  224. else:
  225. maybe_pynccl_context = pynccl_comm.change_state(
  226. enable=True, stream=torch.cuda.current_stream())
  227. with maybe_pynccl_context:
  228. yield graph_capture_context
  229. def all_reduce(self, input_: torch.Tensor) -> torch.Tensor:
  230. """
  231. NOTE: This operation will be applied in-place or out-of-place.
  232. Always assume this function modifies its input, but use the return
  233. value as the output.
  234. """
  235. ca_comm = self.ca_comm
  236. # Bypass the function if we are using only 1 GPU.
  237. if self.world_size == 1:
  238. return input_
  239. # For TPUs, use TPU communicator.
  240. tpu_comm = self.tpu_communicator
  241. if tpu_comm is not None and not tpu_comm.disabled:
  242. return tpu_comm.all_reduce(input_)
  243. if ca_comm is not None:
  244. out = ca_comm.custom_all_reduce(input_)
  245. if out is not None:
  246. return out
  247. pynccl_comm = self.pynccl_comm
  248. if (pynccl_comm is not None and not pynccl_comm.disabled):
  249. pynccl_comm.all_reduce(input_)
  250. elif input_.is_cpu:
  251. import intel_extension_for_pytorch as ipex
  252. ipex.distributed.all_reduce(input_, group=self.device_group)
  253. else:
  254. torch.distributed.all_reduce(input_, group=self.device_group)
  255. return input_
  256. def all_gather(self, input_: torch.Tensor, dim: int = -1) -> torch.Tensor:
  257. world_size = self.world_size
  258. # Bypass the function if we are using only 1 GPU.
  259. if world_size == 1:
  260. return input_
  261. assert -input_.dim() <= dim < input_.dim(), (
  262. f"Invalid dim ({dim}) for input tensor with shape {input_.size()}")
  263. # For TPUs, use TPU communicator.
  264. tpu_comm = self.tpu_communicator
  265. if tpu_comm is not None and not tpu_comm.disabled:
  266. return tpu_comm.all_gather(input_, dim)
  267. if dim < 0:
  268. # Convert negative dim to positive.
  269. dim += input_.dim()
  270. input_size = input_.size()
  271. # Allocate output tensor.
  272. output_tensor = torch.empty((world_size, ) + input_size,
  273. dtype=input_.dtype,
  274. device=input_.device)
  275. # All-gather.
  276. torch.distributed.all_gather_into_tensor(output_tensor,
  277. input_,
  278. group=self.device_group)
  279. # Reshape
  280. output_tensor = output_tensor.movedim(0, dim)
  281. output_tensor = output_tensor.reshape(input_size[:dim] +
  282. (world_size *
  283. input_size[dim], ) +
  284. input_size[dim + 1:])
  285. return output_tensor
  286. def gather(self,
  287. input_: torch.Tensor,
  288. dst: int = 0,
  289. dim: int = -1) -> Optional[torch.Tensor]:
  290. """
  291. NOTE: We assume that the input tensor is on the same device across
  292. all the ranks.
  293. NOTE: `dst` is the local rank of the destination rank.
  294. """
  295. world_size = self.world_size
  296. # Bypass the function if we are using only 1 GPU.
  297. if world_size == 1:
  298. return input_
  299. assert -input_.dim() <= dim < input_.dim(), (
  300. f"Invalid dim ({dim}) for input tensor with shape {input_.size()}")
  301. if dim < 0:
  302. # Convert negative dim to positive.
  303. dim += input_.dim()
  304. # Allocate output tensor.
  305. if self.rank_in_group == dst:
  306. gather_list = [torch.empty_like(input_) for _ in range(world_size)]
  307. else:
  308. gather_list = None
  309. # Gather.
  310. torch.distributed.gather(input_,
  311. gather_list,
  312. dst=self.ranks[dst],
  313. group=self.device_group)
  314. if self.rank_in_group == dst:
  315. output_tensor = torch.cat(gather_list, dim=dim)
  316. else:
  317. output_tensor = None
  318. return output_tensor
  319. def broadcast(self, input_: torch.Tensor, src: int = 0):
  320. """Broadcast the input tensor.
  321. NOTE: `src` is the local rank of the source rank.
  322. """
  323. assert src < self.world_size, f"Invalid src rank ({src})"
  324. # Bypass the function if we are using only 1 GPU.
  325. if self.world_size == 1:
  326. return input_
  327. # Broadcast.
  328. torch.distributed.broadcast(input_,
  329. src=self.ranks[src],
  330. group=self.device_group)
  331. return input_
  332. def broadcast_object(self, obj: Optional[Any] = None, src: int = 0):
  333. """Broadcast the input object.
  334. NOTE: `src` is the local rank of the source rank.
  335. """
  336. assert src < self.world_size, f"Invalid src rank ({src})"
  337. # Bypass the function if we are using only 1 GPU.
  338. if self.world_size == 1:
  339. return obj
  340. if self.mq_broadcaster is not None:
  341. assert src == 0, "Message queue broadcaster only supports src=0"
  342. return self.mq_broadcaster.broadcast_object(obj)
  343. if self.rank_in_group == src:
  344. torch.distributed.broadcast_object_list([obj],
  345. src=self.ranks[src],
  346. group=self.cpu_group)
  347. return obj
  348. else:
  349. recv = [None]
  350. torch.distributed.broadcast_object_list(recv,
  351. src=self.ranks[src],
  352. group=self.cpu_group)
  353. return recv[0]
  354. def broadcast_object_list(self,
  355. obj_list: List[Any],
  356. src: int = 0,
  357. group: Optional[ProcessGroup] = None):
  358. """Broadcast the input object list.
  359. NOTE: `src` is the local rank of the source rank.
  360. """
  361. assert src < self.world_size, f"Invalid src rank ({src})"
  362. # Bypass the function if we are using only 1 GPU.
  363. if self.world_size == 1:
  364. return obj_list
  365. # Broadcast.
  366. torch.distributed.broadcast_object_list(obj_list,
  367. src=self.ranks[src],
  368. group=self.device_group)
  369. return obj_list
  370. def send_object(self, obj: Any, dst: int) -> None:
  371. """Send the input object list to the destination rank."""
  372. """NOTE: `dst` is the local rank of the destination rank."""
  373. assert dst < self.world_size, f"Invalid dst rank ({dst})"
  374. assert dst != self.rank_in_group, (
  375. "Invalid destination rank. Destination rank is the same "
  376. "as the current rank.")
  377. # Serialize object to tensor and get the size as well
  378. object_tensor = torch.frombuffer(pickle.dumps(obj), dtype=torch.uint8)
  379. size_tensor = torch.tensor([object_tensor.numel()],
  380. dtype=torch.long,
  381. device="cpu")
  382. # Send object size
  383. torch.distributed.send(size_tensor,
  384. dst=self.ranks[dst],
  385. group=self.cpu_group)
  386. # Send object
  387. torch.distributed.send(object_tensor,
  388. dst=self.ranks[dst],
  389. group=self.cpu_group)
  390. return None
  391. def recv_object(self, src: int) -> Any:
  392. """Receive the input object list from the source rank."""
  393. """NOTE: `src` is the local rank of the source rank."""
  394. assert src < self.world_size, f"Invalid src rank ({src})"
  395. assert src != self.rank_in_group, (
  396. "Invalid source rank. Source rank is the same as the current rank."
  397. )
  398. size_tensor = torch.empty(1, dtype=torch.long, device="cpu")
  399. # Receive object size
  400. rank_size = torch.distributed.recv(size_tensor,
  401. src=self.ranks[src],
  402. group=self.cpu_group)
  403. # Tensor to receive serialized objects into.
  404. object_tensor = torch.empty( # type: ignore[call-overload]
  405. size_tensor.item(), # type: ignore[arg-type]
  406. dtype=torch.uint8,
  407. device="cpu")
  408. rank_object = torch.distributed.recv(object_tensor,
  409. src=self.ranks[src],
  410. group=self.cpu_group)
  411. assert rank_object == rank_size, (
  412. "Received object sender rank does not match the size sender rank.")
  413. obj = pickle.loads(object_tensor.numpy().tobytes())
  414. return obj
  415. def broadcast_tensor_dict(
  416. self,
  417. tensor_dict: Optional[Dict[str, Union[torch.Tensor, Any]]] = None,
  418. src: int = 0,
  419. group: Optional[ProcessGroup] = None,
  420. metadata_group: Optional[ProcessGroup] = None
  421. ) -> Optional[Dict[str, Union[torch.Tensor, Any]]]:
  422. """Broadcast the input tensor dictionary.
  423. NOTE: `src` is the local rank of the source rank.
  424. """
  425. # Bypass the function if we are using only 1 GPU.
  426. if (not torch.distributed.is_initialized() or self.world_size == 1):
  427. return tensor_dict
  428. group = self.device_group
  429. metadata_group = self.cpu_group
  430. assert src < self.world_size, f"Invalid src rank ({src})"
  431. rank_in_group = self.rank_in_group
  432. if rank_in_group == src:
  433. metadata_list: List[Tuple[Any, Any]] = []
  434. assert isinstance(
  435. tensor_dict,
  436. dict), (f"Expecting a dictionary, got {type(tensor_dict)}")
  437. metadata_list, tensor_list = _split_tensor_dict(tensor_dict)
  438. # `metadata_list` lives in CPU memory.
  439. # `broadcast_object_list` has serialization & deserialization,
  440. # all happening on CPU. Therefore, we can use the CPU group.
  441. self.broadcast_object(metadata_list, src=src)
  442. async_handles = []
  443. for tensor in tensor_list:
  444. if tensor.numel() == 0:
  445. # Skip broadcasting empty tensors.
  446. continue
  447. if tensor.is_cpu:
  448. # use metadata_group for CPU tensors
  449. handle = torch.distributed.broadcast(tensor,
  450. src=self.ranks[src],
  451. group=metadata_group,
  452. async_op=True)
  453. else:
  454. # use group for GPU tensors
  455. handle = torch.distributed.broadcast(tensor,
  456. src=self.ranks[src],
  457. group=group,
  458. async_op=True)
  459. async_handles.append(handle)
  460. for async_handle in async_handles:
  461. async_handle.wait()
  462. else:
  463. metadata_list = self.broadcast_object(None, src=src)
  464. tensor_dict = {}
  465. async_handles = []
  466. for key, value in metadata_list:
  467. if isinstance(value, TensorMetadata):
  468. tensor = torch.empty(value.size,
  469. dtype=value.dtype,
  470. device=value.device)
  471. if tensor.numel() == 0:
  472. # Skip broadcasting empty tensors.
  473. tensor_dict[key] = tensor
  474. continue
  475. if tensor.is_cpu:
  476. # use metadata_group for CPU tensors
  477. handle = torch.distributed.broadcast(
  478. tensor,
  479. src=self.ranks[src],
  480. group=metadata_group,
  481. async_op=True)
  482. else:
  483. # use group for GPU tensors
  484. handle = torch.distributed.broadcast(
  485. tensor,
  486. src=self.ranks[src],
  487. group=group,
  488. async_op=True)
  489. async_handles.append(handle)
  490. tensor_dict[key] = tensor
  491. else:
  492. tensor_dict[key] = value
  493. for async_handle in async_handles:
  494. async_handle.wait()
  495. return tensor_dict
  496. def send_tensor_dict(
  497. self,
  498. tensor_dict: Dict[str, Union[torch.Tensor, Any]],
  499. dst: Optional[int] = None,
  500. all_gather_group: Optional["GroupCoordinator"] = None,
  501. ) -> Optional[Dict[str, Union[torch.Tensor, Any]]]:
  502. """Send the input tensor dictionary.
  503. NOTE: `dst` is the local rank of the source rank.
  504. """
  505. # Bypass the function if we are using only 1 GPU.
  506. if not torch.distributed.is_initialized() or self.world_size == 1:
  507. return tensor_dict
  508. all_gather_size = (1 if all_gather_group is None else
  509. all_gather_group.world_size)
  510. all_gather_rank = (0 if all_gather_group is None else
  511. all_gather_group.rank_in_group)
  512. group = self.device_group
  513. metadata_group = self.cpu_group
  514. if dst is None:
  515. dst = (self.rank_in_group + 1) % self.world_size
  516. assert dst < self.world_size, f"Invalid dst rank ({dst})"
  517. metadata_list: List[Tuple[Any, Any]] = []
  518. assert isinstance(
  519. tensor_dict,
  520. dict), f"Expecting a dictionary, got {type(tensor_dict)}"
  521. metadata_list, tensor_list = _split_tensor_dict(tensor_dict)
  522. # `metadata_list` lives in CPU memory.
  523. # `send_object_list` has serialization & deserialization,
  524. # all happening on CPU. Therefore, we can use the CPU group.
  525. self.send_object(metadata_list, dst=dst)
  526. for tensor in tensor_list:
  527. if tensor.numel() == 0:
  528. # Skip sending empty tensors.
  529. continue
  530. # send-allgather: send only a slice, then do allgather.
  531. if (all_gather_group is not None
  532. and tensor.numel() % all_gather_size == 0):
  533. tensor = tensor.reshape(all_gather_size, -1)[all_gather_rank]
  534. if tensor.is_cpu:
  535. # use metadata_group for CPU tensors
  536. torch.distributed.send(tensor,
  537. dst=self.ranks[dst],
  538. group=metadata_group)
  539. else:
  540. # use group for GPU tensors
  541. torch.distributed.send(tensor,
  542. dst=self.ranks[dst],
  543. group=group)
  544. return None
  545. def recv_tensor_dict(
  546. self,
  547. src: Optional[int] = None,
  548. all_gather_group: Optional["GroupCoordinator"] = None,
  549. ) -> Optional[Dict[str, Union[torch.Tensor, Any]]]:
  550. """Recv the input tensor dictionary.
  551. NOTE: `src` is the local rank of the source rank.
  552. """
  553. # Bypass the function if we are using only 1 GPU.
  554. if not torch.distributed.is_initialized() or self.world_size == 1:
  555. return None
  556. all_gather_size = (1 if all_gather_group is None else
  557. all_gather_group.world_size)
  558. all_gather_rank = (0 if all_gather_group is None else
  559. all_gather_group.rank_in_group)
  560. group = self.device_group
  561. metadata_group = self.cpu_group
  562. if src is None:
  563. src = (self.rank_in_group - 1) % self.world_size
  564. assert src < self.world_size, f"Invalid src rank ({src})"
  565. recv_metadata_list = self.recv_object(src=src)
  566. tensor_dict: Dict[str, Any] = {}
  567. for key, value in recv_metadata_list:
  568. if isinstance(value, TensorMetadata):
  569. tensor = torch.empty(value.size,
  570. dtype=value.dtype,
  571. device=value.device)
  572. if tensor.numel() == 0:
  573. # Skip broadcasting empty tensors.
  574. tensor_dict[key] = tensor
  575. continue
  576. # send-allgather: send only a slice, then do allgather.
  577. use_all_gather = (all_gather_group is not None
  578. and tensor.numel() % all_gather_size == 0)
  579. if use_all_gather:
  580. orig_shape = tensor.shape
  581. tensor = tensor.reshape(all_gather_size,
  582. -1)[all_gather_rank]
  583. if tensor.is_cpu:
  584. # use metadata_group for CPU tensors
  585. torch.distributed.recv(tensor,
  586. src=self.ranks[src],
  587. group=metadata_group)
  588. else:
  589. # use group for GPU tensors
  590. torch.distributed.recv(tensor,
  591. src=self.ranks[src],
  592. group=group)
  593. if use_all_gather:
  594. # do the allgather
  595. tensor = all_gather_group.all_gather( # type: ignore
  596. tensor, dim=0)
  597. tensor = tensor.reshape(orig_shape)
  598. tensor_dict[key] = tensor
  599. else:
  600. tensor_dict[key] = value
  601. return tensor_dict
  602. def barrier(self):
  603. """Barrier synchronization among the group.
  604. NOTE: don't use `device_group` here! `barrier` in NCCL is
  605. terrible because it is internally a broadcast operation with
  606. secretly created GPU tensors. It is easy to mess up the current
  607. device. Use the CPU group instead.
  608. """
  609. torch.distributed.barrier(group=self.cpu_group)
  610. def send(self, tensor: torch.Tensor, dst: Optional[int] = None) -> None:
  611. """Sends a tensor to the destination rank in a non-blocking way"""
  612. """NOTE: `dst` is the local rank of the destination rank."""
  613. if dst is None:
  614. dst = (self.rank_in_group + 1) % self.world_size
  615. pynccl_comm = self.pynccl_comm
  616. if pynccl_comm is not None and not pynccl_comm.disabled:
  617. pynccl_comm.send(tensor, dst)
  618. else:
  619. torch.distributed.send(tensor, self.ranks[dst], self.device_group)
  620. def recv(self,
  621. size: torch.Size,
  622. dtype: torch.dtype,
  623. src: Optional[int] = None) -> torch.Tensor:
  624. """Receives a tensor from the src rank."""
  625. """NOTE: `src` is the local rank of the destination rank."""
  626. if src is None:
  627. src = (self.rank_in_group - 1) % self.world_size
  628. tensor = torch.empty(size, dtype=dtype, device=self.device)
  629. pynccl_comm = self.pynccl_comm
  630. if pynccl_comm is not None and not pynccl_comm.disabled:
  631. pynccl_comm.recv(tensor, src)
  632. else:
  633. torch.distributed.recv(tensor, self.ranks[src], self.device_group)
  634. return tensor
  635. def destroy(self):
  636. if self.device_group is not None:
  637. torch.distributed.destroy_process_group(self.device_group)
  638. self.device_group = None
  639. if self.cpu_group is not None:
  640. torch.distributed.destroy_process_group(self.cpu_group)
  641. self.cpu_group = None
  642. if self.pynccl_comm is not None:
  643. self.pynccl_comm = None
  644. if self.ca_comm is not None:
  645. self.ca_comm = None
  646. if self.mq_broadcaster is not None:
  647. self.mq_broadcaster = None
  648. _WORLD: Optional[GroupCoordinator] = None
  649. def get_world_group() -> GroupCoordinator:
  650. assert _WORLD is not None, ("world group is not initialized")
  651. return _WORLD
  652. def init_world_group(ranks: List[int], local_rank: int,
  653. backend: str) -> GroupCoordinator:
  654. return GroupCoordinator(
  655. group_ranks=[ranks],
  656. local_rank=local_rank,
  657. torch_distributed_backend=backend,
  658. use_pynccl=False,
  659. use_custom_allreduce=False,
  660. use_tpu_communicator=False,
  661. )
  662. def init_model_parallel_group(
  663. group_ranks: List[List[int]],
  664. local_rank: int,
  665. backend: str,
  666. use_custom_allreduce: Optional[bool] = None,
  667. use_message_queue_broadcaster: bool = False,
  668. ) -> GroupCoordinator:
  669. if use_custom_allreduce is None:
  670. use_custom_allreduce = _ENABLE_CUSTOM_ALL_REDUCE
  671. return GroupCoordinator(
  672. group_ranks=group_ranks,
  673. local_rank=local_rank,
  674. torch_distributed_backend=backend,
  675. use_pynccl=True,
  676. use_custom_allreduce=use_custom_allreduce,
  677. use_tpu_communicator=True,
  678. use_message_queue_broadcaster=use_message_queue_broadcaster,
  679. )
  680. _TP: Optional[GroupCoordinator] = None
  681. def get_tp_group() -> GroupCoordinator:
  682. assert _TP is not None, ("tensor model parallel group is not initialized")
  683. return _TP
  684. # kept for backward compatibility
  685. get_tensor_model_parallel_group = get_tp_group
  686. _PP: Optional[GroupCoordinator] = None
  687. def get_pp_group() -> GroupCoordinator:
  688. assert _PP is not None, (
  689. "pipeline model parallel group is not initialized")
  690. return _PP
  691. # kept for backward compatibility
  692. get_pipeline_model_parallel_group = get_pp_group
  693. @contextmanager
  694. def graph_capture():
  695. """
  696. `graph_capture` is a context manager which should surround the code that
  697. is capturing the CUDA graph. Its main purpose is to ensure that the
  698. some operations will be run after the graph is captured, before the graph
  699. is replayed. It returns a `GraphCaptureContext` object which contains the
  700. necessary data for the graph capture. Currently, it only contains the
  701. stream that the graph capture is running on. This stream is set to the
  702. current CUDA stream when the context manager is entered and reset to the
  703. default stream when the context manager is exited. This is to ensure that
  704. the graph capture is running on a separate stream from the default stream,
  705. in order to explicitly distinguish the kernels to capture
  706. from other kernels possibly launched on background in the default stream.
  707. """
  708. with get_tp_group().graph_capture() as context, get_pp_group(
  709. ).graph_capture(context):
  710. yield context
  711. _ENABLE_CUSTOM_ALL_REDUCE = True
  712. def set_custom_all_reduce(enable: bool):
  713. global _ENABLE_CUSTOM_ALL_REDUCE
  714. _ENABLE_CUSTOM_ALL_REDUCE = enable
  715. def init_distributed_environment(
  716. world_size: int = -1,
  717. rank: int = -1,
  718. distributed_init_method: str = "env://",
  719. local_rank: int = -1,
  720. backend: str = "nccl",
  721. ):
  722. logger.debug(
  723. f"world_size={world_size} rank={rank} local_rank={local_rank} "
  724. f"distributed_init_method={distributed_init_method} backend={backend}")
  725. if not torch.distributed.is_initialized():
  726. assert distributed_init_method is not None, (
  727. "distributed_init_method must be provided when initializing "
  728. "distributed environment")
  729. # this backend is used for WORLD
  730. torch.distributed.init_process_group(
  731. backend=backend,
  732. init_method=distributed_init_method,
  733. world_size=world_size,
  734. rank=rank)
  735. # set the local rank
  736. # local_rank is not available in torch ProcessGroup,
  737. # see https://github.com/pytorch/pytorch/issues/122816
  738. if local_rank == -1:
  739. # local rank not set, this usually happens in single-node
  740. # setting, where we can use rank as local rank
  741. if distributed_init_method == "env://":
  742. local_rank = os.getenv("LOCAL_RANK", rank)
  743. else:
  744. local_rank = rank
  745. global _WORLD
  746. if _WORLD is None:
  747. ranks = list(range(torch.distributed.get_world_size()))
  748. _WORLD = init_world_group(ranks, local_rank, backend)
  749. else:
  750. assert _WORLD.world_size == torch.distributed.get_world_size(), (
  751. "world group already initialized with a different world size")
  752. def initialize_model_parallel(
  753. tensor_model_parallel_size: int = 1,
  754. pipeline_model_parallel_size: int = 1,
  755. backend: Optional[str] = None,
  756. ) -> None:
  757. """
  758. Initialize model parallel groups.
  759. Arguments:
  760. tensor_model_parallel_size: number of GPUs used for tensor model
  761. parallelism.
  762. pipeline_model_parallel_size: number of GPUs used for pipeline model
  763. parallelism.
  764. Let's say we have a total of 8 GPUs denoted by g0 ... g7 and we
  765. use 2 GPUs to parallelize the model tensor, and 4 GPUs to parallelize
  766. the model pipeline. The present function will
  767. create 4 tensor model-parallel groups and 2 pipeline model-parallel groups:
  768. 4 tensor model-parallel groups:
  769. [g0, g1], [g2, g3], [g4, g5], [g6, g7]
  770. 2 pipeline model-parallel groups:
  771. [g0, g2, g4, g6], [g1, g3, g5, g7]
  772. Note that for efficiency, the caller should make sure adjacent ranks
  773. are on the same DGX box. For example if we are using 2 DGX-1 boxes
  774. with a total of 16 GPUs, rank 0 to 7 belong to the first box and
  775. ranks 8 to 15 belong to the second box.
  776. """
  777. # Get world size and rank. Ensure some consistencies.
  778. assert torch.distributed.is_initialized()
  779. world_size: int = torch.distributed.get_world_size()
  780. backend = backend or torch.distributed.get_backend(
  781. get_world_group().device_group)
  782. if (world_size !=
  783. tensor_model_parallel_size * pipeline_model_parallel_size):
  784. raise RuntimeError(
  785. f"world_size ({world_size}) is not equal to "
  786. f"tensor_model_parallel_size ({tensor_model_parallel_size}) x "
  787. f"pipeline_model_parallel_size ({pipeline_model_parallel_size})")
  788. # Build the tensor model-parallel groups.
  789. num_tensor_model_parallel_groups: int = (world_size //
  790. tensor_model_parallel_size)
  791. global _TP
  792. assert _TP is None, ("tensor model parallel group is already initialized")
  793. group_ranks = []
  794. for i in range(num_tensor_model_parallel_groups):
  795. ranks = list(
  796. range(i * tensor_model_parallel_size,
  797. (i + 1) * tensor_model_parallel_size))
  798. group_ranks.append(ranks)
  799. # message queue broadcaster is only used in tensor model parallel group
  800. _TP = init_model_parallel_group(group_ranks,
  801. get_world_group().local_rank,
  802. backend,
  803. use_message_queue_broadcaster=True)
  804. # Build the pipeline model-parallel groups.
  805. num_pipeline_model_parallel_groups: int = (world_size //
  806. pipeline_model_parallel_size)
  807. global _PP
  808. assert _PP is None, (
  809. "pipeline model parallel group is already initialized")
  810. group_ranks = []
  811. for i in range(num_pipeline_model_parallel_groups):
  812. ranks = list(range(i, world_size, num_pipeline_model_parallel_groups))
  813. group_ranks.append(ranks)
  814. # pipeline parallel does not need custom allreduce
  815. _PP = init_model_parallel_group(group_ranks,
  816. get_world_group().local_rank,
  817. backend,
  818. use_custom_allreduce=False)
  819. def ensure_model_parallel_initialized(
  820. tensor_model_parallel_size: int,
  821. pipeline_model_parallel_size: int,
  822. backend: Optional[str] = None,
  823. ) -> None:
  824. """Helper to initialize model parallel groups if they are not initialized,
  825. or ensure tensor-parallel and pipeline-parallel sizes are equal to expected
  826. values if the model parallel groups are initialized.
  827. """
  828. backend = backend or torch.distributed.get_backend(
  829. get_world_group().device_group)
  830. if not model_parallel_is_initialized():
  831. initialize_model_parallel(tensor_model_parallel_size,
  832. pipeline_model_parallel_size, backend)
  833. return
  834. assert (
  835. get_tensor_model_parallel_world_size() == tensor_model_parallel_size
  836. ), ("tensor parallel group already initialized, but of unexpected size: "
  837. f"{get_tensor_model_parallel_world_size()=} vs. "
  838. f"{tensor_model_parallel_size=}")
  839. pp_world_size = get_pp_group().world_size
  840. assert (pp_world_size == pipeline_model_parallel_size), (
  841. "pipeline parallel group already initialized, but of unexpected size: "
  842. f"{pp_world_size=} vs. "
  843. f"{pipeline_model_parallel_size=}")
  844. def model_parallel_is_initialized():
  845. """Check if tensor and pipeline parallel groups are initialized."""
  846. return (_TP is not None and _PP is not None)
  847. _TP_STATE_PATCHED = False
  848. @contextmanager
  849. def patch_tensor_parallel_group(tp_group: GroupCoordinator):
  850. """Patch the tp group temporarily until this function ends.
  851. This method is for draft workers of speculative decoding to run draft model
  852. with different tp degree from that of target model workers.
  853. Args:
  854. tp_group (GroupCoordinator): the tp group coordinator
  855. """
  856. global _TP_STATE_PATCHED
  857. assert not _TP_STATE_PATCHED, "Should not call when it's already patched"
  858. _TP_STATE_PATCHED = True
  859. old_tp_group = get_tp_group()
  860. global _TP
  861. _TP = tp_group
  862. try:
  863. yield
  864. finally:
  865. # restore the original state
  866. _TP_STATE_PATCHED = False
  867. _TP = old_tp_group
  868. def get_tensor_model_parallel_world_size():
  869. """Return world size for the tensor model parallel group."""
  870. return get_tp_group().world_size
  871. def get_tensor_model_parallel_rank():
  872. """Return my rank for the tensor model parallel group."""
  873. return get_tp_group().rank_in_group
  874. def destroy_model_parallel():
  875. """Set the groups to none and destroy them."""
  876. global _TP
  877. if _TP:
  878. _TP.destroy()
  879. _TP = None
  880. global _PP
  881. if _PP:
  882. _PP.destroy()
  883. _PP = None
  884. def destroy_distributed_environment():
  885. global _WORLD
  886. if _WORLD:
  887. _WORLD.destroy()
  888. _WORLD = None
  889. if torch.distributed.is_initialized():
  890. torch.distributed.destroy_process_group()
  891. def in_the_same_node_as(pg: ProcessGroup, source_rank: int = 0) -> List[bool]:
  892. """
  893. This is a collective operation that returns if each rank is in the same node
  894. as the source rank. It tests if processes are attached to the same
  895. memory system (shared access to shared memory).
  896. """
  897. assert torch.distributed.get_backend(
  898. pg) != torch.distributed.Backend.NCCL, (
  899. "in_the_same_node_as should be tested with a non-NCCL group.")
  900. # local rank inside the group
  901. rank = torch.distributed.get_rank(group=pg)
  902. world_size = torch.distributed.get_world_size(group=pg)
  903. # local tensor in each process to store the result
  904. is_in_the_same_node = torch.tensor([0] * world_size, dtype=torch.int32)
  905. # global ranks of the processes in the group
  906. ranks = torch.distributed.get_process_group_ranks(pg)
  907. magic_message = b"magic_message"
  908. shm = None
  909. try:
  910. with contextlib.suppress(OSError):
  911. if rank == source_rank:
  912. # create a shared memory segment
  913. shm = shared_memory.SharedMemory(create=True, size=128)
  914. shm.buf[:len(magic_message)] = magic_message
  915. torch.distributed.broadcast_object_list([shm.name],
  916. src=ranks[source_rank],
  917. group=pg)
  918. is_in_the_same_node[rank] = 1
  919. else:
  920. # try to open the shared memory segment
  921. recv = [None]
  922. torch.distributed.broadcast_object_list(recv,
  923. src=ranks[source_rank],
  924. group=pg)
  925. name = recv[0]
  926. # fix to https://stackoverflow.com/q/62748654/9191338
  927. # Python incorrectly tracks shared memory even if it is not
  928. # created by the process. The following patch is a workaround.
  929. with patch("multiprocessing.resource_tracker.register",
  930. lambda *args, **kwargs: None):
  931. shm = shared_memory.SharedMemory(name=name)
  932. if shm.buf[:len(magic_message)] == magic_message:
  933. is_in_the_same_node[rank] = 1
  934. except Exception as e:
  935. logger.error(f"Error ignored in is_in_the_same_node: {e}")
  936. finally:
  937. if shm:
  938. shm.close()
  939. torch.distributed.barrier(group=pg)
  940. # clean up the shared memory segment
  941. with contextlib.suppress(OSError):
  942. if rank == source_rank and shm:
  943. shm.unlink()
  944. torch.distributed.all_reduce(is_in_the_same_node, group=pg)
  945. return [x == 1 for x in is_in_the_same_node.tolist()]
  946. def get_current_tp_rank_partition_offset(total_size: int,
  947. tp_rank: Optional[int] = None,
  948. tp_size: Optional[int] = None,
  949. multiple_of: int = 1) -> int:
  950. if tp_rank is None:
  951. tp_rank = get_tensor_model_parallel_rank()
  952. if tp_size is None:
  953. tp_size = get_tensor_model_parallel_world_size()
  954. assert total_size % multiple_of == 0
  955. total_size = total_size // multiple_of
  956. return ((total_size // tp_size) * tp_rank +
  957. min(total_size % tp_size, tp_rank)) * multiple_of
  958. def get_current_tp_rank_partition_size(total_size: int,
  959. tp_rank: Optional[int] = None,
  960. tp_size: Optional[int] = None,
  961. multiple_of: int = 1) -> int:
  962. if tp_rank is None:
  963. tp_rank = get_tensor_model_parallel_rank()
  964. if tp_size is None:
  965. tp_size = get_tensor_model_parallel_world_size()
  966. assert total_size % multiple_of == 0
  967. total_size = total_size // multiple_of
  968. return ((total_size // tp_size) +
  969. (total_size % tp_size > tp_rank)) * multiple_of