Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / distributed / locality.py: 94%

63 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

1# Copyright 2026 Huawei Technologies Co., Ltd 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14# ============================================================================ 

15"""Create independent node-local data exchange groups.""" 

16# This distributed-data package is intentionally PyTorch-only. 

17 

18from __future__ import annotations 

19 

20import os 

21import socket 

22from typing import Any 

23 

24import torch.distributed as dist 

25 

26from hyper_parallel.data.distributed.topology import DataTopology 

27from hyper_parallel.data.distributed.transport import ( 

28 DataGroups, _create_data_plane_process_groups, all_gather_control_object, 

29) 

30 

31 

32def _node_rank_groups( 

33 topology: DataTopology, 

34 node_ids: dict[int, str], 

35) -> tuple[tuple[int, ...], ...]: 

36 buckets: dict[str, list[int]] = {} 

37 for rank in topology.rank_list: 

38 buckets.setdefault(node_ids[rank], []).append(rank) 

39 return tuple(sorted(tuple(sorted(ranks)) for ranks in buckets.values())) 

40 

41 

42def _fixed_rank_groups( 

43 topology: DataTopology, 

44 group_size: int, 

45) -> tuple[tuple[int, ...], ...]: 

46 """Partition the root mesh rank order into fixed-size balancing groups. 

47 

48 Args: 

49 topology: Root mesh topology whose rank order defines the groups. 

50 group_size: Number of ranks in every balancing group. 

51 

52 Returns: 

53 Fixed-size rank groups in root mesh order. 

54 

55 Raises: 

56 ValueError: If the mesh size is not divisible by ``group_size``. 

57 """ 

58 rank_list = topology.rank_list 

59 if len(rank_list) % group_size: 

60 raise ValueError( 

61 f"balance_group_size={group_size} must divide the root mesh size {len(rank_list)}." 

62 ) 

63 return tuple( 

64 tuple(rank_list[start:start + group_size]) 

65 for start in range(0, len(rank_list), group_size) 

66 ) 

67 

68 

69def _resolve_local_topology( 

70 mesh: Any, 

71 rank: int, 

72 world_size: int, 

73 dp_dim_names: tuple[str, ...] | None, 

74) -> DataTopology: 

75 """Resolve the WORLD-covering topology for independent DP readers.""" 

76 topology = DataTopology.from_mesh(mesh, global_rank=rank, dp_dim_names=dp_dim_names) 

77 if set(topology.rank_list) != set(range(world_size)): 

78 raise ValueError("Local balancing requires a root mesh containing every WORLD rank.") 

79 if any(len(group) != 1 for group in topology.model_parallel_rank_groups): 

80 raise ValueError("Local balancing currently requires CP/TP/PP/Ulysses and other model parallel sizes = 1.") 

81 return topology 

82 

83 

84def _validate_communication_config(backend: str, device: Any, distributed: bool) -> None: 

85 """Validate the node-local collective backend and its rank-local device.""" 

86 if backend not in ("gloo", "hccl"): 

87 raise ValueError("communication_backend must be 'gloo' or 'hccl'.") 

88 if backend != "hccl": 

89 return 

90 if distributed and (device is None or getattr(device, "type", None) != "npu"): 

91 raise ValueError("communication_backend='hccl' requires an NPU communication_device.") 

92 

93 

94def _gather_startup_statuses( 

95 status: Any, 

96 *, 

97 distributed: bool, 

98 backend: str, 

99 device: Any, 

100) -> list[Any]: 

101 """Gather startup state on an explicit Gloo group or HCCL WORLD.""" 

102 if not distributed: 

103 return [status] 

104 startup_group = None 

105 if backend == "gloo": 

106 startup_group = dist.new_group(ranks=list(range(dist.get_world_size())), backend="gloo") 

107 try: 

108 return list(all_gather_control_object(status, group=startup_group, device=device, backend=backend)) 

109 finally: 

110 if startup_group is not None: 

111 dist.destroy_process_group(startup_group) 

112 

113 

114def _create_locality_groups( 

115 mesh: Any, 

116 *, 

117 dp_dim_names: tuple[str, ...] | None = None, 

118 balance_group_size: int | None = None, 

119 communication_backend: str = "hccl", 

120 communication_device: Any = None, 

121) -> tuple[DataTopology, DataGroups]: 

122 """Resolve locality once and create all process groups in WORLD rank order. 

123 

124 Args: 

125 mesh: Named root mesh covering WORLD, with no nontrivial model parallelism. 

126 dp_dim_names: Root mesh data-parallel dimensions. 

127 balance_group_size: Optional fixed number of ranks per balancing group. 

128 

129 Returns: 

130 Training topology and this rank's independent data exchange groups. 

131 

132 Note: 

133 WORLD communication is used only during startup. No training mesh or 

134 FSDP process group is modified. All ranks must call this factory together. 

135 """ 

136 distributed = dist.is_available() and dist.is_initialized() 

137 _validate_communication_config(communication_backend, communication_device, distributed) 

138 rank = dist.get_rank() if distributed else 0 

139 world_size = dist.get_world_size() if distributed else 1 

140 topology = _resolve_local_topology(mesh, rank, world_size, dp_dim_names) 

141 if balance_group_size is None: 

142 selected_node = os.environ.get("GROUP_RANK") or socket.gethostname() 

143 statuses = _gather_startup_statuses( 

144 (rank, selected_node), 

145 distributed=distributed, 

146 backend=communication_backend, 

147 device=communication_device, 

148 ) 

149 rank_groups = _node_rank_groups(topology, dict(statuses)) 

150 else: 

151 rank_groups = _fixed_rank_groups(topology, balance_group_size) 

152 own_ranks = next(ranks for ranks in rank_groups if rank in ranks) 

153 own_groups = DataGroups(own_ranks, None, None, None, min(own_ranks), distributed) 

154 if not distributed: 

155 return topology, own_groups 

156 with own_groups.close_on_error(): 

157 for ranks in rank_groups: 

158 control, payload = _create_data_plane_process_groups( 

159 groups=own_groups, topology=topology, data_plane_ranks=ranks, 

160 cpu_backend=communication_backend, payload_backend=communication_backend, 

161 reuse_control_group=communication_backend == "gloo", enable_payload_exchange=True, 

162 ) 

163 if rank in ranks: 

164 own_groups.control_group = control 

165 own_groups.payload_group = payload 

166 return topology, own_groups