Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / _builder / tp_collective_lowering.py: 89%

81 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"""Lower TP placement transitions to differentiable local-tensor collectives.""" 

16 

17import logging 

18from dataclasses import dataclass 

19from typing import Any, Optional, Sequence 

20 

21import torch 

22import torch.distributed as dist 

23 

24from hyper_parallel.core.dtensor.placement_types import Partial, Placement, Replicate, Shard 

25from hyper_parallel.core.utils import communication 

26 

27logger = logging.getLogger(__name__) 

28 

29 

30def classify_tp_transition( 

31 src: Sequence[Placement], 

32 dst: Sequence[Placement], 

33 mesh_dim_names: Sequence[str], 

34) -> Optional[dict]: 

35 """Classify one placement transition for the TP collective path. 

36 

37 Single source of truth shared by the runtime lowerer 

38 (``TPCollectiveLowerer``) and the codegen boundary-form classifier 

39 (``hyper_parallel.codegen.plan.boundary_forms``), so the emit-time form 

40 decision and the install-time lowering can never disagree about what a 

41 transition means. 

42 

43 Args: 

44 src: Source placements aligned to ``mesh_dim_names``. 

45 dst: Target placements aligned to ``mesh_dim_names``. 

46 mesh_dim_names: Axis names the placements resolve against. 

47 

48 Returns: 

49 ``{"kind": "identity"}`` when no communication is needed; 

50 ``{"kind": "all_gather", "tensor_dim": d}`` for Shard -> Replicate on 

51 the tp axis; ``{"kind": "all_reduce", "reduce_op": "sum"}`` for 

52 Partial -> Replicate; ``{"kind": "local_shard", "tensor_dim": d}`` 

53 for Replicate -> Shard; ``{"kind": "reduce_scatter", "tensor_dim": d, 

54 "reduce_op": "sum"}`` for Partial -> Shard; ``None`` when the 

55 transition is not lowerable on this path (a non-tp axis differs, the 

56 placement pair is unsupported, or the reduce op is not ``sum``). 

57 """ 

58 if tuple(src) == tuple(dst): 

59 return {"kind": "identity"} 

60 if "tp" not in mesh_dim_names: 

61 return None 

62 tp_axis = tuple(mesh_dim_names).index("tp") 

63 if any( 

64 axis != tp_axis and src_placement != dst_placement 

65 for axis, (src_placement, dst_placement) in enumerate(zip(src, dst)) 

66 ): 

67 return None 

68 

69 src_tp = src[tp_axis] 

70 dst_tp = dst[tp_axis] 

71 if isinstance(src_tp, Replicate) and isinstance(dst_tp, Shard): 

72 return {"kind": "local_shard", "tensor_dim": dst_tp.dim} 

73 if isinstance(src_tp, Shard) and isinstance(dst_tp, Replicate): 

74 return {"kind": "all_gather", "tensor_dim": src_tp.dim} 

75 if isinstance(src_tp, Partial): 

76 if src_tp.reduce_op != "sum": 

77 return None 

78 if isinstance(dst_tp, Replicate): 

79 return {"kind": "all_reduce", "reduce_op": "sum"} 

80 if isinstance(dst_tp, Shard): 

81 return { 

82 "kind": "reduce_scatter", 

83 "tensor_dim": dst_tp.dim, 

84 "reduce_op": "sum", 

85 } 

86 return None 

87 

88 

89@dataclass 

90class TPExecutionOp: 

91 """Executable local-tensor operation for one TP placement transition.""" 

92 

93 kind: str 

94 group: object 

95 group_size: int 

96 group_rank: int 

97 tensor_dim: Optional[int] = None 

98 reduce_op: str = "sum" 

99 

100 def execute(self, tensor: Any) -> Any: 

101 """Execute the differentiable operation selected during lowering. 

102 

103 Args: 

104 tensor: Local input tensor before the TP layout transition. 

105 

106 Returns: 

107 Local tensor in the destination placement. 

108 """ 

109 if self.kind == "local_shard": 

110 # Preserve DTensor local slicing and its zero-padded backward. 

111 return torch.chunk(tensor, self.group_size, dim=self.tensor_dim)[self.group_rank] 

112 if self.kind == "all_gather": 

113 return communication.differentiable_all_gather_concat( 

114 tensor, 

115 self.group, 

116 self.group_size, 

117 self.tensor_dim, 

118 ) 

119 if self.kind == "all_reduce": 

120 return communication.differentiable_all_reduce( 

121 tensor, 

122 self.reduce_op, 

123 self.group, 

124 ) 

125 if self.kind == "reduce_scatter": 

126 return communication.differentiable_reduce_scatter( 

127 tensor, 

128 self.group_size, 

129 self.tensor_dim, 

130 self.reduce_op, 

131 self.group, 

132 ) 

133 if self.kind == "all_reduce_shard": 

134 reduced = communication.differentiable_all_reduce( 

135 tensor, 

136 self.reduce_op, 

137 self.group, 

138 ) 

139 return torch.chunk( 

140 reduced, 

141 self.group_size, 

142 dim=self.tensor_dim, 

143 )[self.group_rank] 

144 raise ValueError(f"Unsupported TP execution operation: {self.kind!r}") 

145 

146 

147@dataclass(frozen=True) 

148class TPCollectiveLowerer: 

149 """Lower supported TP-only placement differences to execution operations.""" 

150 

151 mesh_dim_names: tuple[str, ...] 

152 group: object 

153 group_size: int 

154 group_rank: int 

155 backend: str 

156 

157 def __call__( 

158 self, 

159 src: Sequence[Placement], 

160 dst: Sequence[Placement], 

161 ) -> Optional[TPExecutionOp]: 

162 """Return an execution operation or ``None`` for the generic fallback.""" 

163 result = classify_tp_transition(src, dst, self.mesh_dim_names) 

164 if result is None or result["kind"] == "identity": 

165 return None 

166 return self.execution_op( 

167 result["kind"], 

168 tensor_dim=result.get("tensor_dim"), 

169 reduce_op=result.get("reduce_op", "sum"), 

170 ) 

171 

172 def execution_op( 

173 self, 

174 kind: str, 

175 tensor_dim: Optional[int] = None, 

176 reduce_op: str = "sum", 

177 ) -> TPExecutionOp: 

178 """Build an execution operation using the native backend's lowering.""" 

179 # Gloo has no reduce_scatter: lower to all_reduce + local chunk, the 

180 # same remap is used by placement-driven and explicit operation callers. 

181 if kind == "reduce_scatter" and "gloo" in self.backend: 

182 kind = "all_reduce_shard" 

183 return TPExecutionOp( 

184 kind=kind, 

185 group=self.group, 

186 group_size=self.group_size, 

187 group_rank=self.group_rank, 

188 tensor_dim=tensor_dim, 

189 reduce_op=reduce_op, 

190 ) 

191 

192 

193def create_tp_collective_lowerer( 

194 mesh: Any, 

195 mesh_dim_names: Sequence[str], 

196 *, 

197 collective_backend: Optional[str] = None, 

198) -> Optional[TPCollectiveLowerer]: 

199 """Resolve immutable TP runtime metadata and create the boundary lowerer.""" 

200 mesh_dim_names = tuple(mesh_dim_names) 

201 if "tp" not in mesh_dim_names: 

202 return None 

203 

204 tp_mesh = mesh if mesh_dim_names == ("tp",) else mesh["tp"] 

205 group = tp_mesh.get_group() 

206 mesh_ranks = tuple(tp_mesh.rank_list) 

207 group_ranks = tuple(dist.get_process_group_ranks(group)) 

208 if mesh_ranks != group_ranks: 

209 logger.warning( 

210 "TP mesh rank order %s differs from process group rank order %s; " 

211 "falling back to DTensor redistribution.", 

212 mesh_ranks, 

213 group_ranks, 

214 ) 

215 return None 

216 

217 backend = collective_backend or dist.get_backend(group) 

218 return TPCollectiveLowerer( 

219 mesh_dim_names=mesh_dim_names, 

220 group=group, 

221 group_size=tp_mesh.size(), 

222 group_rank=tp_mesh.get_local_rank(), 

223 backend=str(backend).lower(), 

224 ) 

225 

226 

227__all__ = [ 

228 "TPCollectiveLowerer", 

229 "TPExecutionOp", 

230 "classify_tp_transition", 

231 "create_tp_collective_lowerer", 

232]