Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / expert_parallel / collectives.py: 34%

86 statements  

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

1# Copyright 2025-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 

16"""expert_parallel.collectives: backend-dispatched EP all_to_all. 

17 

18NCCL/HCCL use the ragged a2a (``_EPAllToAllUneven``). Gloo and 

19other backends that do not support ragged a2a use pad-to-max + 

20``all_to_all_single`` (``_EPAllToAllPadded``). Both paths are numerically 

21equivalent (padding only adds filler rows that do not participate in 

22computation). 

23 

24Split out of components/distributed/ep_utils.py in stage 4e. 

25""" 

26 

27from typing import Any, Optional 

28import torch 

29import torch.distributed as dist 

30from torch import _check, _check_is_size 

31from torch.distributed import _functional_collectives 

32 

33from hyper_parallel.core.dtensor._utils import differentiable_all_to_all_single_async 

34from hyper_parallel.core.utils.communication import _is_tracing_or_compiling 

35 

36_UNEVEN_A2A_BACKENDS = ("nccl", "hccl") 

37 

38 

39 

40def ep_exchange_counts(counts: torch.Tensor, group: Any) -> torch.Tensor: 

41 """Exchange integer count rows per peer, waiting before reading the result. 

42 

43 Args: 

44 counts: Non-differentiable send counts in process-group rank order. 

45 Shape [EP] exchanges one count per peer; [EP, fields] may include 

46 per-peer protocol metadata alongside each count. 

47 group: Expert-parallel process group. 

48 

49 Returns: 

50 Counts received from each peer in the same rank order. 

51 """ 

52 if _is_tracing_or_compiling(): 

53 return _functional_collectives.wait_tensor( 

54 _functional_collectives.all_to_all_single(counts, None, None, group) 

55 ) 

56 received = torch.empty_like(counts) 

57 dist.all_to_all_single(received, counts, group=group) 

58 return received 

59 

60 

61def ep_split_sizes(counts: torch.Tensor, total: Optional[int] = None) -> list[int]: 

62 """Read per-call segment sizes, retaining data dependencies during capture. 

63 

64 Args: 

65 counts: One-dimensional integer tensor of segment lengths. 

66 total: Expected number of rows, when known from a payload's shape. 

67 

68 Returns: 

69 Concrete eager sizes or symbolic sizes evaluated by the captured graph. 

70 """ 

71 if not _is_tracing_or_compiling(): 

72 return counts.tolist() 

73 sizes = counts.cpu().tolist() 

74 for size in sizes: 

75 _check_is_size(size) 

76 if total is not None: 

77 _check(sum(sizes) == total) 

78 return sizes 

79 

80 

81def _backend_supports_uneven_a2a(group) -> bool: 

82 return dist.get_backend(group) in _UNEVEN_A2A_BACKENDS 

83 

84 

85class _EPAllToAllUneven(torch.autograd.Function): # pylint: disable=abstract-method 

86 """Ragged all_to_all (NCCL/HCCL production path): split by send/recv counts. 

87 

88 forward: split(x, send_counts) -> dist.all_to_all(out_list, in_list) -> cat 

89 backward: swap send/recv counts and run the ragged all_to_all again 

90 (a2a is self-inverse). 

91 """ 

92 

93 @staticmethod 

94 def forward( 

95 ctx: Any, 

96 x: torch.Tensor, 

97 send_counts: list[int], 

98 recv_counts: list[int], 

99 group: Any, 

100 ) -> torch.Tensor: # pylint: disable=arguments-differ 

101 """Run the ragged all_to_all and retain the counts for backward. 

102 

103 Args: 

104 ctx: Autograd context retaining the exchange plan. 

105 x: Peer-major payload, split along dimension zero. 

106 send_counts: Rows sent to each peer. 

107 recv_counts: Rows received from each peer. 

108 group: Existing expert-parallel process group. 

109 """ 

110 ctx.send_counts = send_counts 

111 ctx.recv_counts = recv_counts 

112 ctx.group = group 

113 out = x.new_empty((sum(recv_counts),) + tuple(x.shape[1:])) 

114 dist.all_to_all(list(out.split(recv_counts)), list(x.split(send_counts)), group=group) 

115 return out 

116 

117 @staticmethod 

118 def backward( 

119 ctx: Any, 

120 grad_output: torch.Tensor, 

121 ) -> tuple[torch.Tensor, None, None, None]: # pylint: disable=arguments-differ 

122 """Swap send/recv counts and re-run the self-inverse ragged all_to_all. 

123 

124 Args: 

125 ctx: Saved forward exchange plan. 

126 grad_output: Gradients in received peer-major order. 

127 """ 

128 grad = _EPAllToAllUneven.apply( 

129 grad_output.contiguous(), ctx.recv_counts, ctx.send_counts, ctx.group) 

130 return grad, None, None, None 

131 

132 

133class _EPAllToAllPadded(torch.autograd.Function): # pylint: disable=abstract-method 

134 """pad-to-max + all_to_all_single (gloo test path). 

135 

136 forward: pad each dest chunk to the global max(counts) (a2a_single 

137 requires equal-length chunks per rank -> pad_to must be 

138 globally consistent, obtained via all_reduce MAX) 

139 -> a2a_single -> unpad by recv_counts; 

140 backward: pad by recv_counts -> a2a_single (equal-length self-inverse) 

141 -> unpad by send_counts. 

142 """ 

143 

144 @staticmethod 

145 def _pad_and_exchange(x, counts, pad_to, group): 

146 """Pad each chunk to pad_to, run equal-length a2a_single, return [ep*pad_to, ...].""" 

147 chunks = [] 

148 for chunk, n in zip(x.split(counts), counts): 

149 if n < pad_to: 

150 pad = x.new_zeros((pad_to - n,) + tuple(x.shape[1:])) 

151 chunk = torch.cat([chunk, pad]) 

152 chunks.append(chunk) 

153 send = torch.cat(chunks).contiguous() 

154 recv = torch.empty_like(send) 

155 dist.all_to_all_single(recv, send, group=group) 

156 return recv 

157 

158 @staticmethod 

159 def _unpad(recv, counts, pad_to): 

160 """Take the valid rows from the equal-length buffer per counts and cat.""" 

161 pieces = [] 

162 for i, n in enumerate(counts): 

163 if n > 0: 

164 pieces.append(recv[i * pad_to: i * pad_to + n]) 

165 if not pieces: 

166 return recv.new_zeros((0,) + tuple(recv.shape[1:])) 

167 return torch.cat(pieces) 

168 

169 @staticmethod 

170 def forward( 

171 ctx: Any, 

172 x: torch.Tensor, 

173 send_counts: list[int], 

174 recv_counts: list[int], 

175 group: Any, 

176 ) -> torch.Tensor: # pylint: disable=arguments-differ 

177 """Exchange padded expert-token chunks and retain counts for backward. 

178 

179 Args: 

180 ctx: Autograd context retaining counts and padding size. 

181 x: Peer-major payload, split along dimension zero. 

182 send_counts: Valid rows sent to each peer. 

183 recv_counts: Valid rows received from each peer. 

184 group: Existing expert-parallel process group. 

185 """ 

186 ctx.send_counts = send_counts 

187 ctx.recv_counts = recv_counts 

188 ctx.group = group 

189 local_max = max([*send_counts, *recv_counts, 1]) 

190 pad_to = x.new_tensor([local_max], dtype=torch.int64) 

191 dist.all_reduce(pad_to, op=dist.ReduceOp.MAX, group=group) 

192 ctx.pad_to = pad_to = int(pad_to.item()) 

193 recv = _EPAllToAllPadded._pad_and_exchange(x, send_counts, pad_to, group) 

194 return _EPAllToAllPadded._unpad(recv, recv_counts, pad_to) 

195 

196 @staticmethod 

197 def backward( 

198 ctx: Any, 

199 grad_output: torch.Tensor, 

200 ) -> tuple[torch.Tensor, None, None, None]: # pylint: disable=arguments-differ 

201 """Reverse the exchange: pad by recv_counts, a2a_single, unpad by send_counts. 

202 

203 Args: 

204 ctx: Saved forward counts and padding size. 

205 grad_output: Gradients in received peer-major order. 

206 """ 

207 # backward = reversed a2a: pad by recv_counts -> a2a_single -> unpad by send_counts 

208 recv = _EPAllToAllPadded._pad_and_exchange( 

209 grad_output.contiguous(), ctx.recv_counts, ctx.pad_to, ctx.group) 

210 grad = _EPAllToAllPadded._unpad(recv, ctx.send_counts, ctx.pad_to) 

211 return grad, None, None, None 

212 

213 

214def ep_all_to_all( 

215 x: torch.Tensor, 

216 send_counts: list[int], 

217 recv_counts: list[int], 

218 group: Any, 

219) -> torch.Tensor: 

220 """Unified entry for EP token exchange (autograd-differentiable). 

221 

222 NCCL/HCCL use variable splits. Other backends pad each segment for the exchange. 

223 The eager entry returns a materialized tensor. Graph capture records the 

224 functional exchange and its consumer wait. 

225 

226 Args: 

227 x: Payload split along dimension zero. 

228 send_counts: Rows sent to each peer, in process-group rank order. 

229 recv_counts: Rows received from each peer, in process-group rank order. 

230 group: Existing expert-parallel process group. 

231 

232 Returns: 

233 Received payload with sum(recv_counts) rows. 

234 """ 

235 if _is_tracing_or_compiling(): 

236 # Keep the autograd wrapper; its first consumer inserts the stream wait. 

237 return _functional_collectives.all_to_all_single_autograd(x, recv_counts, send_counts, group) 

238 if not _backend_supports_uneven_a2a(group): 

239 return _EPAllToAllPadded.apply(x, send_counts, recv_counts, group) 

240 return _EPAllToAllUneven.apply(x, send_counts, recv_counts, group) 

241 

242 

243def ep_all_to_all_async( 

244 x: torch.Tensor, 

245 send_counts: list[int], 

246 recv_counts: list[int], 

247 group: Any, 

248) -> torch.Tensor: 

249 """Non-blocking variant of :func:`ep_all_to_all` (lazy wait). 

250 

251 On backends whose ``all_to_all_single`` accepts unequal splits the exchange 

252 is issued through ``differentiable_all_to_all_single_async``, which returns 

253 an ``AsyncCollectiveTensor``: the ``wait_tensor`` op is only enqueued when a 

254 non-view op first consumes the result. Issuing independent work between the 

255 exchange and that first read therefore overlaps with the in-flight transfer 

256 (forward and backward alike). 

257 

258 Backends without that support use the padded blocking exchange. 

259 

260 Args: 

261 x: Input tensor, split along dim 0 by ``send_counts``. 

262 send_counts: Rows sent to each EP rank. 

263 recv_counts: Rows received from each EP rank. 

264 group: EP process group. 

265 Returns: 

266 The exchanged rows, materialized lazily on the async path. 

267 """ 

268 if not _backend_supports_uneven_a2a(group): 

269 return _EPAllToAllPadded.apply(x, send_counts, recv_counts, group) 

270 return differentiable_all_to_all_single_async(x, send_counts, recv_counts, group)