parallel_state.py 44 KB

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