Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / encoder_parallel / projector_dispatch.py: 56%

142 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"""Route spatial projector inputs and outputs between their unique owners. 

16 

17Within an Encoder-CP bucket, each output row owns one spatial patch block. 

18The input plan gathers local patches and exchanges only missing remote patches; 

19negative bank indices represent spatial padding, not communication requests. 

20 

21After projection, a separate parent CP-times-TP exchange sends output rows to 

22their decoder token intervals. This routing may replicate rows for decoder TP 

23without sequence parallelism, but never repeats their projector computation. 

24""" 

25 

26from __future__ import annotations 

27 

28from dataclasses import dataclass, replace 

29from typing import Any, Mapping, Sequence 

30 

31import torch 

32 

33from hyper_parallel.core.utils.communication import differentiable_all_to_all_single 

34from hyper_parallel.distributed.encoder_parallel.contracts import EncoderFeature, EncoderWorkItem 

35from hyper_parallel.distributed.encoder_parallel.exchange import cat_or_empty 

36from hyper_parallel.distributed.encoder_parallel.planning import DecoderSequenceLayout 

37 

38 

39def _exchange_rows(value: torch.Tensor, input_splits: Sequence[int], 

40 output_splits: Sequence[int], group: Any) -> torch.Tensor: 

41 """Use the common variable-split exchange and its inverse gradient routing.""" 

42 return differentiable_all_to_all_single( 

43 value.contiguous(), input_splits=list(input_splits), output_splits=list(output_splits), group=group, 

44 ) 

45 

46 

47@dataclass(frozen=True) 

48class ProjectorShard: 

49 """One image's output-row interval and its offset in this producer's output. 

50 

51 ``start``/``stop`` are image-local; ``offset`` is rank-local across images. 

52 """ 

53 

54 item: EncoderWorkItem 

55 start: int 

56 stop: int 

57 offset: int 

58 

59 

60def projector_shards(items: Sequence[EncoderWorkItem], rank: int, size: int) -> tuple[ProjectorShard, ...]: 

61 """Assign equal-sized ranges of concatenated projector rows to ranks. 

62 

63 Args: 

64 items: Images in this Encoder-DP bucket. 

65 rank: Local producer coordinate. 

66 size: Number of producers in the bucket. 

67 """ 

68 if size < 1 or not 0 <= rank < size: 

69 raise ValueError("projector rank must lie in a nonempty producer group") 

70 width = (sum(item.output_rows for item in items) + size - 1) // size 

71 left, right = rank * width, (rank + 1) * width 

72 shards = [] 

73 begin = offset = 0 

74 for item in items: 

75 start, stop = max(left, begin), min(right, begin + item.output_rows) 

76 if start < stop: 

77 shards.append(ProjectorShard(item, start - begin, stop - begin, offset)) 

78 offset += stop - start 

79 begin += item.output_rows 

80 return tuple(shards) 

81 

82 

83def _cat_indices(parts: Sequence[torch.Tensor]) -> torch.Tensor: 

84 return torch.cat(tuple(parts)) if parts else torch.empty(0, dtype=torch.int64) 

85 

86 

87def _input_requests(items: Sequence[EncoderWorkItem], shards: Sequence[ProjectorShard], 

88 size: int, packed: bool, bridge: Any) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

89 """Map each block input to its full-bank row and unique sequence owner.""" 

90 total = sum(item.sequence_length for item in items) 

91 packed_width = max(1, (total + size - 1) // size) 

92 offsets = {} 

93 global_offset = local_offset = 0 

94 for item in items: 

95 local_width = (item.sequence_length + size - 1) // size 

96 offsets[item.item_id] = (global_offset, local_offset, local_width) 

97 global_offset += item.sequence_length 

98 local_offset += local_width 

99 bank_parts, owner_parts, local_parts = [], [], [] 

100 for shard in shards: 

101 indices = bridge.projector_input_indices(shard.item, shard.start, shard.stop).reshape(-1) 

102 global_start, local_start, local_width = offsets[shard.item.item_id] 

103 bank = indices + global_start 

104 if packed: 

105 owners = bank.clamp_min(0).div(packed_width, rounding_mode="floor") 

106 local = bank.remainder(packed_width) 

107 else: 

108 owners = indices.clamp_min(0).div(local_width, rounding_mode="floor") 

109 local = indices.remainder(local_width) + local_start 

110 bank_parts.append(bank.masked_fill(indices < 0, -1)) 

111 owner_parts.append(owners.masked_fill(indices < 0, -1)) 

112 local_parts.append(local) 

113 return _cat_indices(bank_parts), _cat_indices(owner_parts), _cat_indices(local_parts) 

114 

115 

116@dataclass(frozen=True) 

117class EncoderProjectorPlan: 

118 """CPU-only spatial input routing, fixed for one microbatch. 

119 

120 ``bank_indices`` maps flattened block slots to valid full-bucket patch rows 

121 or -1 for spatial padding. Send indices address this rank's ViT output. 

122 Local and receive positions address flattened block slots, in peer order. 

123 """ 

124 

125 shards: tuple[ProjectorShard, ...] 

126 patch_count: int 

127 bank_indices: torch.Tensor 

128 send_indices: torch.Tensor 

129 input_splits: tuple[int, ...] 

130 output_splits: tuple[int, ...] 

131 local_indices: torch.Tensor 

132 local_positions: torch.Tensor 

133 receive_positions: torch.Tensor 

134 has_images: bool 

135 

136 def dispatch_blocks(self, hidden: torch.Tensor, mesh: Any) -> torch.Tensor: 

137 """Move each remote patch once and bypass patches already held locally. 

138 

139 Args: 

140 hidden: This rank's packed ViT output, including local padding. 

141 mesh: Encoder-CP group that owns the bucket's patch shards. 

142 """ 

143 width = hidden.shape[-1] 

144 result = hidden.new_zeros((self.bank_indices.numel(), width)) 

145 local = hidden.index_select(0, self.local_indices.to(hidden.device)) 

146 result = result.index_copy(0, self.local_positions.to(hidden.device), local) 

147 if self.has_images and mesh.size() > 1: 

148 send = hidden.index_select(0, self.send_indices.to(hidden.device)) 

149 received = _exchange_rows( 

150 send, input_splits=list(self.input_splits), output_splits=list(self.output_splits), 

151 group=mesh.get_group(), 

152 ) 

153 if self.receive_positions.numel(): 

154 result = result.index_copy(0, self.receive_positions.to(hidden.device), received) 

155 else: 

156 # Empty index_copy is not an identity on every NPU backend. 

157 # Keep the exchange edge: send-only ranks still receive gradients. 

158 result = result + received.sum() * 0.0 

159 return result.reshape(-1, self.patch_count, width) 

160 

161 

162def build_projector_plan(items: Sequence[EncoderWorkItem], rank: int, size: int, 

163 *, packed: bool, bridge: Any) -> EncoderProjectorPlan: 

164 """Plan block inputs without inspecting any activation or model parameter. 

165 

166 Args: 

167 items: Images assigned to this Encoder-DP bucket. 

168 rank: Local Encoder-CP coordinate. 

169 size: Encoder-CP degree. 

170 packed: Whether the ViT shards the concatenated bucket sequence. 

171 bridge: Model-owned spatial block mapping. 

172 """ 

173 shards = [projector_shards(items, peer, size) for peer in range(size)] 

174 requests = [_input_requests(items, value, size, packed, bridge) for value in shards] 

175 bank, owners, local = requests[rank] 

176 sends = [indices[peer_owners == rank] if peer != rank else indices[:0] 

177 for peer, (_, peer_owners, indices) in enumerate(requests)] 

178 positions = [torch.nonzero(owners == peer, as_tuple=False).flatten() if peer != rank else owners[:0] 

179 for peer in range(size)] 

180 own_positions = torch.nonzero(owners == rank, as_tuple=False).flatten() 

181 return EncoderProjectorPlan( 

182 shards=shards[rank], patch_count=bridge.projector_patch_count, bank_indices=bank, 

183 send_indices=_cat_indices(sends), input_splits=tuple(part.numel() for part in sends), 

184 output_splits=tuple(part.numel() for part in positions), local_indices=local[own_positions], 

185 local_positions=own_positions, receive_positions=_cat_indices(positions), has_images=bool(items), 

186 ) 

187 

188 

189def project_spatial_blocks(plan: EncoderProjectorPlan, blocks: torch.Tensor, 

190 hidden: torch.Tensor, bridge: Any) -> tuple[torch.Tensor, torch.Tensor]: 

191 """Call the same FSDP projector once on every rank, including empty owners. 

192 

193 Args: 

194 plan: Spatial block ownership for this rank. 

195 blocks: Local block inputs, including zero spatial padding. 

196 hidden: Graph-connected local ViT output for empty work. 

197 bridge: Model-owned projector entry point. 

198 """ 

199 anchor = blocks.sum() * 0.0 + hidden.sum() * 0.0 

200 count = blocks.shape[0] 

201 if not count: 

202 blocks = hidden[:1].unsqueeze(1).expand(1, plan.patch_count, -1) * 0.0 + anchor 

203 projected = bridge.project_blocks(blocks) 

204 return projected[:count], anchor + projected.sum() * 0.0 

205 

206 

207def _needed_rows(bridge: Any, item: EncoderWorkItem, layout: DecoderSequenceLayout) -> tuple[int, int]: 

208 return bridge.feature_interval(item, layout.global_start, layout.global_stop) 

209 

210 

211def route_projected_rows(features: torch.Tensor, *, buckets: Sequence[Sequence[EncoderWorkItem]], 

212 layouts: Mapping[int, DecoderSequenceLayout], parent_rank: int, 

213 encoder_cp_size: int, mesh: Any, bridge: Any) -> tuple[list[EncoderFeature], torch.Tensor]: 

214 """Send contiguous feature intersections directly to their decoder owners. 

215 

216 Args: 

217 features: This producer's packed projector output rows. 

218 buckets: Images assigned to each Encoder-DP bucket. 

219 layouts: Decoder token intervals for every parent rank. 

220 parent_rank: Local coordinate in the CP-times-TP parent. 

221 encoder_cp_size: Number of projector producers in each bucket. 

222 mesh: Parent mesh, including TP replicas when decoder SP is disabled. 

223 bridge: Model-owned mapping from token intervals to feature rows. 

224 

225 Returns: 

226 One partial record per locally relevant image and a collective anchor. 

227 """ 

228 size = len(layouts) 

229 source_shards = [projector_shards(buckets[peer // encoder_cp_size], peer % encoder_cp_size, 

230 encoder_cp_size) for peer in range(size)] 

231 send_parts, input_splits = [], [] 

232 for destination in range(size): 

233 parts = [] 

234 for shard in source_shards[parent_rank]: 

235 first, last = _needed_rows(bridge, shard.item, layouts[destination]) 

236 start, stop = max(first, shard.start), min(last, shard.stop) 

237 if start < stop: 

238 begin = shard.offset + start - shard.start 

239 parts.append(features[begin:begin + stop - start]) 

240 input_splits.append(sum(part.shape[0] for part in parts)) 

241 send_parts.extend(parts) 

242 send = cat_or_empty(send_parts, anchor=features, feature_width=features.shape[-1]) 

243 output_splits, receipts = [], [] 

244 offset = 0 

245 layout = layouts[parent_rank] 

246 for shards in source_shards: 

247 count = 0 

248 for shard in shards: 

249 first, last = _needed_rows(bridge, shard.item, layout) 

250 start, stop = max(first, shard.start), min(last, shard.stop) 

251 if start < stop: 

252 receipts.append((shard.item.item_id, start, stop, offset + count)) 

253 count += stop - start 

254 output_splits.append(count) 

255 offset += count 

256 rows = _exchange_rows( 

257 send, input_splits=input_splits, output_splits=output_splits, group=mesh.get_group(), 

258 ) if size > 1 else send 

259 items = tuple(item for bucket in buckets for item in bucket) 

260 records = _received_projector_records(rows, receipts, items, layout, bridge) 

261 return records, rows.sum() * 0.0 

262 

263 

264def _received_projector_records(rows: torch.Tensor, receipts: Sequence[tuple[int, int, int, int]], 

265 items: Sequence[EncoderWorkItem], layout: DecoderSequenceLayout, 

266 bridge: Any) -> list[EncoderFeature]: 

267 """Restore each locally relevant image from its ordered producer intervals.""" 

268 records = [] 

269 for item in sorted(items, 

270 key=lambda value: (value.batch_index, value.decoder_token_start, value.item_id)): 

271 if max(item.decoder_token_start, layout.global_start) >= min( 

272 item.decoder_token_start + item.decoder_token_length, layout.global_stop): 

273 continue 

274 first, last = _needed_rows(bridge, item, layout) 

275 spans = sorted((start, stop, offset) for item_id, start, stop, offset in receipts if item_id == item.item_id) 

276 if sum(stop - start for start, stop, _ in spans) != last - first: 

277 raise RuntimeError(f"projector route does not cover image {item.item_id} rows [{first}, {last})") 

278 pieces = [rows[offset:offset + stop - start] for start, stop, offset in spans] 

279 feature = cat_or_empty(pieces, anchor=rows, feature_width=rows.shape[-1]) 

280 records.append((replace(item, feature_row_start=first), feature)) 

281 return records