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

194 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"""Per-batch visual encoder planning and packed execution.""" 

16 

17from __future__ import annotations 

18 

19import fnmatch 

20import hashlib 

21from dataclasses import dataclass 

22from typing import Any, Mapping 

23 

24import torch 

25import torch.distributed as dist 

26from torch import nn 

27 

28from hyper_parallel.core.dtensor._utils import differentiable_variable_all_gather 

29from hyper_parallel.distributed.encoder_parallel.attention import ( 

30 EncoderAttentionContext, 

31 activate_encoder_attention, 

32) 

33from hyper_parallel.distributed.encoder_parallel.config import EncoderParallelConfig 

34from hyper_parallel.distributed.encoder_parallel.contracts import ( 

35 EncoderFeature, 

36 EncoderLocalInputs, 

37 EncoderParallelAdapterSpec, 

38 EncoderSegment, 

39 EncoderWorkItem, 

40) 

41from hyper_parallel.distributed.encoder_parallel.exchange import ( 

42 FeatureExchangeMode, 

43 route_features, 

44 select_feature_exchange, 

45 unpack_records, 

46) 

47from hyper_parallel.distributed.encoder_parallel.mesh import derive_reshaped_submesh 

48from hyper_parallel.distributed.encoder_parallel.planning import ( 

49 DecoderSequenceLayout, 

50 assign_lpt, 

51 build_destinations, 

52 build_segments, 

53) 

54from hyper_parallel.distributed.encoder_parallel.projector_dispatch import ( 

55 EncoderProjectorPlan, 

56 build_projector_plan, 

57 project_spatial_blocks, 

58 route_projected_rows, 

59) 

60 

61 

62def _invalid_head_count(count: Any) -> bool: 

63 """Reject booleans, nonintegers, and zero-sized QKV head axes.""" 

64 return isinstance(count, bool) or not isinstance(count, int) or count < 1 

65 

66 

67def validate_ulysses_head_divisibility(*, encoder_cp_size: int, head_counts: Mapping[str, int], 

68 attention_pattern: str, model: nn.Module) -> None: 

69 """Check every Q/K/V head count before deriving any Encoder-CP group.""" 

70 required = ("query", "key", "value") 

71 missing = [name for name in required if name not in head_counts] 

72 invalid = {name: head_counts[name] for name in required if name in head_counts 

73 and _invalid_head_count(head_counts[name])} 

74 non_divisible = {name: head_counts[name] for name in required if name in head_counts 

75 and name not in invalid and head_counts[name] % encoder_cp_size} 

76 if missing or invalid or non_divisible: 

77 matched = sorted(name for name, _ in model.named_modules() 

78 if fnmatch.fnmatchcase(name, attention_pattern)) 

79 raise ValueError( 

80 "Encoder-CP/Ulysses head divisibility check failed; " 

81 "constraint=head_count % encoder_cp_size == 0 for every Q/K/V; " 

82 "config_path=accelerator.encoder_parallel.encoder_cp_size; " 

83 f"encoder_cp_size={encoder_cp_size}; head_counts={dict(head_counts)}; " 

84 f"missing={missing}; invalid_values={invalid}; non_divisible={non_divisible}; " 

85 f"attention_pattern={attention_pattern!r}; matched_modules={matched}" 

86 ) 

87 

88 

89def validate_attention_replacement(model: nn.Module, spec: EncoderParallelAdapterSpec) -> frozenset[str]: 

90 """Require an exact structural replacement for every visual attention. 

91 

92 Args: 

93 model: Final model after module replacements. 

94 spec: Model-owned attention matching and replacement contract. 

95 """ 

96 expected = frozenset(name for name, _ in model.named_modules() 

97 if fnmatch.fnmatchcase(name, spec.attention_pattern)) 

98 recorded = set(getattr(model, "_hp_replaced_module_fqns", ()) or ()) 

99 recorded_visual = {name for name in recorded if fnmatch.fnmatchcase(name, spec.attention_pattern)} 

100 missing = sorted(expected - recorded_visual) 

101 unexpected = sorted(recorded_visual - expected) 

102 wrong_type = sorted(name for name in expected 

103 if not isinstance(model.get_submodule(name), spec.replacement_attention_type)) 

104 if not expected or missing or unexpected or wrong_type: 

105 raise RuntimeError( 

106 "incomplete vision attention replacement: " 

107 f"expected={len(expected)}; missing={missing}; unexpected={unexpected}; wrong_type={wrong_type}" 

108 ) 

109 return expected 

110 

111 

112def validate_encoder_execution_options(options: Mapping[str, Any], bridge: Any) -> None: 

113 """Reject unsupported execution modes before creating Encoder groups. 

114 

115 Args: 

116 options: Trainer microbatch, compile, and placement settings. 

117 bridge: Model-bound validator for vision-specific restrictions. 

118 """ 

119 bridge.validate_training(options) 

120 if options.get("compile_enabled"): 

121 raise NotImplementedError("v1 requires compile.enabled=false") 

122 if options.get("validate_placement"): 

123 raise NotImplementedError("v1 requires model.validate_placement=false") 

124 

125 

126@dataclass 

127class EncoderParallelPlan: 

128 """One microbatch of derived visual work and feature routing.""" 

129 

130 runtime: "EncoderParallelRuntime" 

131 active: bool 

132 decoder_layout: DecoderSequenceLayout 

133 buckets: tuple[tuple[EncoderWorkItem, ...], ...] 

134 destinations: dict[int, tuple[int, ...]] 

135 local_segments: tuple[EncoderSegment, ...] 

136 k_fsdp_max: int 

137 projector_plan: EncoderProjectorPlan | None = None 

138 decoder_layouts: dict[int, DecoderSequenceLayout] | None = None 

139 

140 def _gather_features(self, hidden: torch.Tensor) -> tuple[torch.Tensor, ...]: 

141 """All-gather each local segment and trim dummy padding.""" 

142 if self.runtime.config.packed_attention: 

143 full = differentiable_variable_all_gather( 

144 hidden, output_splits=[hidden.shape[0]] * self.runtime.config.encoder_cp_size, 

145 group=self.runtime.encoder_cp_mesh.get_group(), 

146 ) if self.runtime.config.encoder_cp_size > 1 else hidden 

147 lengths = tuple(item.sequence_length for item in self.buckets[self.runtime.encoder_dp_rank]) 

148 return tuple(full[:sum(lengths)].split(lengths)) if lengths else (full,) 

149 gathered = [] 

150 offset = 0 

151 for segment in self.local_segments: 

152 local = hidden[offset:offset + segment.local_padded_length] 

153 offset += segment.local_padded_length 

154 full = differentiable_variable_all_gather( 

155 local, output_splits=[segment.local_padded_length] * self.runtime.config.encoder_cp_size, 

156 group=self.runtime.encoder_cp_mesh.get_group(), 

157 ) if self.runtime.config.encoder_cp_size > 1 else local 

158 gathered.append(full if segment.is_dummy else full[:segment.item.sequence_length]) 

159 return tuple(gathered) 

160 

161 def _encode_local(self, image_inputs: Mapping[str, Any] | EncoderLocalInputs) -> torch.Tensor: 

162 """Run one local ViT pass with its matching sequence plan.""" 

163 bridge = self.runtime.bridge 

164 context = EncoderAttentionContext( 

165 self.local_segments, 

166 self.runtime.encoder_cp_mesh, 

167 bridge.head_counts, 

168 self.runtime.expected, 

169 packed_sequence_lengths=( 

170 tuple(item.sequence_length for item in self.buckets[self.runtime.encoder_dp_rank]) 

171 or (self.runtime.config.encoder_cp_size,) 

172 ) if self.runtime.config.packed_attention else None, 

173 overlap=self.runtime.config.overlap, 

174 ) 

175 with activate_encoder_attention(context): 

176 hidden = bridge.encode_local(image_inputs, self.local_segments) 

177 context.assert_exactly_once() 

178 return hidden 

179 

180 def _execute_local(self, image_inputs: Mapping[str, Any] | EncoderLocalInputs 

181 ) -> tuple[tuple[EncoderFeature, ...], torch.Tensor, torch.Tensor]: 

182 """Run the local ViT pass and build routed feature records.""" 

183 bridge = self.runtime.bridge 

184 hidden = self._encode_local(image_inputs) 

185 full_features = self._gather_features(hidden) 

186 records = [] 

187 anchors = [feature.sum() * 0.0 for feature in full_features] 

188 prototype = None 

189 items = self.buckets[self.runtime.encoder_dp_rank] 

190 for slot in range(self.k_fsdp_max): 

191 item = items[slot] if slot < len(items) else None 

192 real = item is not None and self.runtime.encoder_cp_rank == 0 

193 if real: 

194 feature = bridge.project(full_features[slot], item) 

195 if feature.ndim != 2 or feature.shape[0] != item.output_rows: 

196 raise ValueError( 

197 "aligner output does not match planned rows; " 

198 f"item_id={item.item_id}; actual_shape={tuple(feature.shape)}; " 

199 f"expected_rows={item.output_rows}" 

200 ) 

201 records.append((item, feature)) 

202 else: 

203 feature = bridge.project(hidden, None) 

204 anchors.append(feature.sum() * 0.0) 

205 prototype = feature 

206 if prototype is None: 

207 raise RuntimeError("active plan must have an aligner slot") 

208 anchor = torch.stack(anchors).sum() if anchors else prototype.sum() * 0.0 

209 return tuple(records), prototype, anchor 

210 

211 def _execute_sharded_projector(self, image_inputs: Mapping[str, Any] | EncoderLocalInputs 

212 ) -> tuple[list[EncoderFeature], torch.Tensor]: 

213 """Project independently owned spatial blocks, then route only needed rows.""" 

214 if self.projector_plan is None or self.decoder_layouts is None: 

215 raise RuntimeError("sharded projector requires a complete input and output plan") 

216 runtime = self.runtime 

217 hidden = self._encode_local(image_inputs) 

218 blocks = self.projector_plan.dispatch_blocks(hidden, runtime.encoder_cp_mesh) 

219 projected, anchor = project_spatial_blocks(self.projector_plan, blocks, hidden, runtime.bridge) 

220 records, route_anchor = route_projected_rows( 

221 projected, buckets=self.buckets, layouts=self.decoder_layouts, 

222 parent_rank=runtime.parent_rank, encoder_cp_size=runtime.config.encoder_cp_size, 

223 mesh=runtime.parent_mesh, bridge=runtime.bridge, 

224 ) 

225 return records, anchor + route_anchor 

226 

227 def encode_and_route(self, image_inputs: Mapping[str, Any] | EncoderLocalInputs 

228 ) -> tuple[list[EncoderFeature], torch.Tensor | None]: 

229 """Run packed ViT and route aligned features to this decoder owner. 

230 

231 Args: 

232 image_inputs: Prepared local patches, or a native image bundle for direct callers. 

233 

234 Returns: 

235 Routed image records and a zero-valued gradient anchor, or no work. 

236 """ 

237 if not self.active: 

238 return [], None 

239 if self.runtime.config.projector_mode != "leader": 

240 return self._execute_sharded_projector(image_inputs) 

241 records, prototype, local_anchor = self._execute_local(image_inputs) 

242 mode = self.runtime.feature_exchange_mode 

243 exchange_mesh = self.runtime.tp_mesh if mode in ( 

244 FeatureExchangeMode.TP_VARIABLE_ALL_GATHER, FeatureExchangeMode.TP_VARIABLE_A2A 

245 ) else self.runtime.parent_mesh 

246 rows, received_items = route_features( 

247 mode=mode, producer_records=records, prototype=prototype, 

248 parent_rank=self.runtime.parent_rank, destinations=self.destinations, 

249 buckets=self.buckets, encoder_cp_size=self.runtime.config.encoder_cp_size, exchange_mesh=exchange_mesh, 

250 ) 

251 unpacked = unpack_records(rows, received_items) 

252 return list(unpacked), local_anchor + rows.sum() * 0.0 

253 

254 

255class EncoderParallelRuntime: 

256 """Own static topology and create one plan per Omni microbatch.""" 

257 

258 def __init__(self, *, config: EncoderParallelConfig, mesh_context: Any, 

259 model: nn.Module, spec: EncoderParallelAdapterSpec, 

260 execution_options: Mapping[str, Any]) -> None: 

261 """Validate the static contract and derive Encoder-CP groups.""" 

262 self.config = config 

263 self.mesh_context = mesh_context 

264 self.model = model 

265 self.spec = spec 

266 self.bridge = spec.bind(model) 

267 required = [] 

268 if config.projector_mode != "leader": 

269 required.extend(("projector_patch_count", "projector_input_indices", "project_blocks", "feature_interval")) 

270 if config.balance_cost == "encoder_flops": 

271 required.append("estimate_work_cost") 

272 missing = [name for name in required if not hasattr(self.bridge, name)] 

273 if missing: 

274 raise ValueError(f"encoder bridge does not support requested execution options: missing={missing}") 

275 validate_encoder_execution_options( 

276 {**execution_options, "loss_parallel": mesh_context.loss_parallel}, self.bridge, 

277 ) 

278 parent_size = mesh_context.cp_size * mesh_context.tp_size 

279 if mesh_context.pp_size != 1: 

280 raise NotImplementedError("v1 requires pp_size=1") 

281 if parent_size % config.encoder_cp_size: 

282 raise ValueError("encoder_cp_size must divide cp_size*tp_size") 

283 validate_ulysses_head_divisibility(encoder_cp_size=config.encoder_cp_size, 

284 head_counts=self.bridge.head_counts, 

285 attention_pattern=spec.attention_pattern, model=model) 

286 self.expected = validate_attention_replacement(model, spec) 

287 self.parent_rank = mesh_context.cp_rank * mesh_context.tp_size + mesh_context.tp_rank 

288 self.encoder_cp_rank = self.parent_rank % config.encoder_cp_size 

289 self.encoder_dp_rank = self.parent_rank // config.encoder_cp_size 

290 self.encoder_dp_size = parent_size // config.encoder_cp_size 

291 self.parent_mesh = mesh_context.device_mesh[("cp", "tp")].flatten("encoder_parent") 

292 encoder_mesh = derive_reshaped_submesh( 

293 mesh_context.device_mesh, source_dims=("cp", "tp"), 

294 target_sizes=(self.encoder_dp_size, config.encoder_cp_size), 

295 target_names=("encoder_dp", "encoder_cp"), 

296 ) 

297 self.encoder_cp_mesh = encoder_mesh["encoder_cp"] 

298 self.tp_mesh = mesh_context.device_mesh["tp"] 

299 self.global_mesh = mesh_context.device_mesh.flatten("encoder_global") 

300 self.feature_exchange_mode = select_feature_exchange(mesh_context) 

301 

302 def preflight_batch(self, batch: Mapping[str, Any] 

303 ) -> tuple[tuple[EncoderWorkItem, ...], DecoderSequenceLayout]: 

304 """Validate local metadata and SP geometry before control collectives. 

305 

306 Args: 

307 batch: Device batch with decoder tokens and optional image fields. 

308 """ 

309 layout = DecoderSequenceLayout.build( 

310 mesh_context=self.mesh_context, cp_local_length=int(batch["input_ids"].shape[1]) 

311 ) 

312 present = [batch.get(name) is not None for name in self.bridge.input_fields] 

313 if any(present) and not all(present): 

314 missing = [name for name in self.bridge.input_fields if batch.get(name) is None] 

315 raise ValueError(f"incomplete image metadata bundle: missing={missing}") 

316 return tuple(self.bridge.parse_images(batch)), layout 

317 

318 def finalize_plan(self, items: tuple[EncoderWorkItem, ...], 

319 layout: DecoderSequenceLayout) -> EncoderParallelPlan: 

320 """Agree on active mode, then assign images and exact decoder owners. 

321 

322 Args: 

323 items: Locally validated image jobs. 

324 layout: Locally validated decoder token ownership. 

325 """ 

326 marker = torch.tensor(int(bool(items)), device=self.model.device if hasattr(self.model, "device") 

327 else next(self.model.parameters()).device) 

328 if dist.is_initialized() and self.parent_mesh.size() > 1: 

329 signature = tuple( 

330 (item.item_id, item.batch_index, item.sequence_length, item.output_rows, 

331 item.decoder_token_start, item.decoder_token_length, item.payload_start, item.payload_stop, 

332 tuple(sorted(item.metadata.items()))) 

333 for item in items 

334 ) 

335 digest = hashlib.sha256(repr((layout.cp_local_length, signature)).encode()).digest() 

336 digest_value = int.from_bytes(digest[:8], "big") & ((1 << 63) - 1) 

337 local_digest = torch.tensor(digest_value, dtype=torch.int64, device=marker.device) 

338 peer_digests = [torch.empty_like(local_digest) for _ in range(self.parent_mesh.size())] 

339 dist.all_gather(peer_digests, local_digest, group=self.parent_mesh.get_group()) 

340 if any(int(peer.item()) != digest_value for peer in peer_digests): 

341 raise ValueError("image metadata differs across decoder parent ranks") 

342 if dist.is_initialized() and self.global_mesh.size() > 1: 

343 dist.all_reduce(marker, op=dist.ReduceOp.MAX, group=self.global_mesh.get_group()) 

344 active = bool(marker.item()) 

345 costs = (self.bridge.estimate_work_cost(items, self.config.encoder_cp_size) 

346 if self.config.balance_cost == "encoder_flops" else None) 

347 buckets = assign_lpt(items, self.encoder_dp_size, self.config.encoder_cp_size, costs=costs) 

348 layouts = {rank: DecoderSequenceLayout.build(mesh_context=self.mesh_context, 

349 cp_local_length=layout.cp_local_length, 

350 cp_rank=rank // self.mesh_context.tp_size, 

351 tp_rank=rank % self.mesh_context.tp_size) 

352 for rank in range(self.mesh_context.cp_size * self.mesh_context.tp_size)} 

353 destinations = build_destinations(items, layouts) 

354 segments = build_segments(buckets[self.encoder_dp_rank], self.encoder_cp_rank, 

355 self.config.encoder_cp_size, packed=self.config.packed_attention) 

356 k_fsdp_max = self._projector_call_count(buckets, marker.device) 

357 projector_plan = build_projector_plan( 

358 buckets[self.encoder_dp_rank], self.encoder_cp_rank, self.config.encoder_cp_size, 

359 packed=self.config.packed_attention, bridge=self.bridge, 

360 ) if self.config.projector_mode != "leader" else None 

361 return EncoderParallelPlan( 

362 runtime=self, 

363 active=active, decoder_layout=layout, buckets=buckets, 

364 destinations=destinations, local_segments=segments, 

365 k_fsdp_max=k_fsdp_max, 

366 projector_plan=projector_plan, decoder_layouts=layouts, 

367 ) 

368 

369 def _projector_call_count(self, buckets: tuple[tuple[EncoderWorkItem, ...], ...], 

370 device: torch.device) -> int: 

371 """Align leader-mode projector calls across the FSDP domain.""" 

372 if self.config.projector_mode != "leader": 

373 return 1 

374 slot_count = torch.tensor(len(buckets[self.encoder_dp_rank]), device=device) 

375 if dist.is_initialized() and self.global_mesh.size() > 1: 

376 dist.all_reduce(slot_count, op=dist.ReduceOp.MAX, group=self.global_mesh.get_group()) 

377 return max(1, int(slot_count.item())) 

378 

379 

380def build_encoder_parallel_runtime(*, config: EncoderParallelConfig, mesh_context: Any, 

381 model: nn.Module | None, model_adapter_spec: Any, 

382 execution_options: Mapping[str, Any] | None) -> EncoderParallelRuntime | None: 

383 """Create the model-neutral runtime only when the feature is enabled.""" 

384 if not config.enabled: 

385 return None 

386 if model is None or model_adapter_spec is None or model_adapter_spec.encoder_parallel is None: 

387 raise ValueError("enabled encoder parallel requires a model adapter provider") 

388 spec = model_adapter_spec.encoder_parallel() 

389 if not isinstance(spec, EncoderParallelAdapterSpec): 

390 raise TypeError("encoder_parallel provider returned an invalid spec") 

391 return EncoderParallelRuntime(config=config, mesh_context=mesh_context, model=model, 

392 spec=spec, execution_options=execution_options or {})