Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / context_parallel / async_context_parallel.py: 96%

282 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"""AsyncContextParallel: overlap projection GEMM with CP collectives. 

16 

17Supports async Pure Ulysses, async Pure Colossal AI, and Hybrid CP modes. 

18Hybrid keeps the original half-async path: async Ulysses A2A + sync Colossal 

19AllGather. Falls back to sync ContextParallel when q/k/v_proj are not provided. 

20 

21Forward: proj hooks launch async A2A → attn pre-hook waits Q/K/V → attn hook gathers output 

22Backward: autograd backward launches async A2A → proj pre-hooks wait before GEMMs 

23""" 

24from functools import partial 

25from typing import Any, Optional 

26 

27from hyper_parallel.core.context_parallel.context_parallel import ( 

28 ContextParallel, 

29 _build_hybrid_cp_mesh, 

30 _compose_cp_non_cp_placements, 

31 _ensure_1d, 

32 _finalize_ata_output, 

33 _gather_seq, 

34 _gather_head_to_seq, 

35 _is_cp_composed_dtensor, 

36 _localize_foreign_dtensor, 

37 _non_cp_dtensor_layout, 

38 _pop_output_layout, 

39 _to_cp_dtensor, 

40) 

41from hyper_parallel.core.dtensor.device_mesh import DeviceMesh 

42from hyper_parallel.core.dtensor.dtensor import DTensor 

43from hyper_parallel.core.dtensor.placement_types import Shard, Replicate 

44from hyper_parallel.core.context_parallel import utils 

45from hyper_parallel.core.context_parallel.utils import Module, Tensor 

46 

47 

48class _AsyncCPState: 

49 """Own the slot containers shared by projection and attention hooks.""" 

50 

51 def __init__(self, forward_slots: dict[str, Any], backward_slots: dict[str, list]) -> None: 

52 """Bind existing containers without changing the hook-owned identities.""" 

53 self.forward_slots = forward_slots 

54 self.backward_slots = backward_slots 

55 

56 def reset_after_device_restart(self) -> None: 

57 """Discard failed work after the caller has quiesced device communication. 

58 

59 Forward slots hold one task per key, with None representing no task. 

60 Keep the keys because consumers index them directly. Backward slots 

61 hold task lists captured by hook closures; clear each list in place 

62 because replacing it would leave the hook referencing the old tasks. 

63 Neither cleanup path waits on obsolete Work objects. 

64 """ 

65 for key in self.forward_slots: 

66 self.forward_slots[key] = None 

67 for slots in self.backward_slots.values(): 

68 slots.clear() 

69 

70 

71# --------------------------------------------------------------------------- 

72# All-to-all helpers 

73# --------------------------------------------------------------------------- 

74 

75def _detach_if_available(tensor: Tensor) -> Tensor: 

76 """Detach the communication buffer when the backend tensor exposes ``detach``.""" 

77 detach = getattr(tensor, "detach", None) 

78 return detach() if detach is not None else tensor 

79 

80 

81def _launch_async_a2a_seq_to_head( 

82 tensor: Tensor, 

83 group, 

84 world_size: int, 

85 head_dim: int, 

86) -> tuple: 

87 """Launch async seq→head A2A (forward).""" 

88 x = tensor.contiguous() 

89 shape = list(x.shape) 

90 num_heads = shape[head_dim] 

91 if num_heads % world_size != 0: 

92 raise ValueError(f"num_heads ({num_heads}) must be divisible by world_size ({world_size}).") 

93 ndim = len(shape) + 1 

94 x_perm = x.reshape( 

95 shape[:head_dim] + [world_size, num_heads // world_size] + shape[head_dim + 1:] 

96 ).permute( 

97 [head_dim] + list(range(head_dim)) + list(range(head_dim + 1, ndim)) 

98 ).contiguous() 

99 out_perm, work = utils.all_to_all_single( 

100 _detach_if_available(x_perm), list(x_perm.shape), group, async_op=True 

101 ) 

102 return work, out_perm 

103 

104 

105def _a2a_reconstruct(out_perm: Tensor, concat_dim: int) -> Tensor: 

106 """Reconstruct A2A result from raw out_perm.""" 

107 new_ndim = out_perm.dim() 

108 chunk_in_perm = concat_dim + 1 

109 recon_perm = list(range(1, chunk_in_perm)) + [0] + list(range(chunk_in_perm, new_ndim)) 

110 x_recon = out_perm.permute(recon_perm).contiguous() 

111 shape = list(x_recon.shape) 

112 merged = shape[concat_dim] * shape[concat_dim + 1] 

113 return x_recon.reshape(shape[:concat_dim] + [merged] + shape[concat_dim + 2:]) 

114 

115 

116def _normalize_dim(dim: int, ndim: int) -> int: 

117 """Normalize a possibly negative dimension index.""" 

118 return dim + ndim if dim < 0 else dim 

119 

120 

121def _move_dim_to_front(tensor: Tensor, dim: int) -> Tensor: 

122 """Move ``dim`` to the leading dimension before all-gather/reduce-scatter.""" 

123 dim = _normalize_dim(dim, tensor.dim()) 

124 if dim == 0: 

125 return tensor.contiguous() 

126 perm = [dim] + [i for i in range(tensor.dim()) if i != dim] 

127 return tensor.permute(perm).contiguous() 

128 

129 

130def _move_dim_from_front(tensor: Tensor, dim: int) -> Tensor: 

131 """Inverse of :func:`_move_dim_to_front`.""" 

132 dim = _normalize_dim(dim, tensor.dim()) 

133 if dim == 0: 

134 return tensor.contiguous() 

135 perm = [dim] + [i for i in range(tensor.dim()) if i != dim] 

136 inverse = [0] * len(perm) 

137 for idx, value in enumerate(perm): 

138 inverse[value] = idx 

139 return tensor.permute(inverse).contiguous() 

140 

141 

142def _launch_async_allgather_seq( 

143 tensor: Tensor, 

144 group, 

145 world_size: int, 

146 gather_dim: int, 

147) -> tuple: 

148 """Launch async all-gather along ``gather_dim``.""" 

149 x_perm = _move_dim_to_front(tensor.contiguous(), gather_dim) 

150 output_shape = list(x_perm.shape) 

151 output_shape[0] *= world_size 

152 out_perm, work = utils.all_gather_single( 

153 _detach_if_available(x_perm), output_shape, group, async_op=True 

154 ) 

155 return work, out_perm 

156 

157 

158def _allgather_reconstruct(out_perm: Tensor, gather_dim: int) -> Tensor: 

159 """Move the leading communication buffer dimension back to ``gather_dim``. 

160 

161 The input may be a forward all-gather output buffer or a backward 

162 reduce-scatter local buffer, as both are stored with ``gather_dim`` moved 

163 to dimension 0 before communication. 

164 """ 

165 return _move_dim_from_front(out_perm, gather_dim) 

166 

167 

168# --------------------------------------------------------------------------- 

169# Tensor helpers 

170# --------------------------------------------------------------------------- 

171 

172def _to_local(tensor: Tensor) -> Tensor: 

173 """Return the local Tensor from a DTensor, or the tensor itself.""" 

174 return tensor.to_local() if isinstance(tensor, DTensor) else tensor 

175 

176 

177def _to_cp_local(tensor: Tensor, submesh: DeviceMesh, seq_dim: int) -> Tensor: 

178 """Return the local tensor CP async collectives should consume.""" 

179 tensor = _localize_foreign_dtensor(tensor, submesh, seq_dim) 

180 return tensor.to_local() if isinstance(tensor, DTensor) else tensor 

181 

182 

183def _cp_execution_layout_from_input(tensor: Tensor, cp_mesh: DeviceMesh, cp_placements, seq_dim: int) -> tuple: 

184 """Return the DTensor layout to use after a raw async CP collective.""" 

185 cp_placements = tuple(cp_placements) 

186 layout = _non_cp_dtensor_layout(tensor, cp_mesh, seq_dim) 

187 if layout is None: 

188 return cp_mesh, cp_placements 

189 non_cp_mesh, non_cp_placements, composed_mesh = layout 

190 return composed_mesh, _compose_cp_non_cp_placements( 

191 composed_mesh, 

192 cp_mesh, 

193 cp_placements, 

194 non_cp_mesh, 

195 non_cp_placements, 

196 ) 

197 

198 

199def _make_async_cp_slot(work, out_perm, tensor: Tensor, cp_mesh: DeviceMesh, cp_placements, seq_dim: int) -> dict: 

200 """Store an async handle together with the layout needed after wait.""" 

201 return { 

202 "work": work, 

203 "out_perm": out_perm, 

204 "layout": _cp_execution_layout_from_input(tensor, cp_mesh, cp_placements, seq_dim), 

205 } 

206 

207 

208def _slot_comm(slot): 

209 """Return ``(work, out_perm)`` from a new metadata slot or a legacy tuple.""" 

210 if isinstance(slot, dict): 

211 return slot["work"], slot["out_perm"] 

212 return slot 

213 

214 

215def _slot_layout(slot, fallback_mesh: DeviceMesh, fallback_placements) -> tuple: 

216 """Return the post-collective layout recorded in *slot*.""" 

217 if isinstance(slot, dict) and "layout" in slot: 

218 return slot["layout"] 

219 return fallback_mesh, tuple(fallback_placements) 

220 

221 

222def _wrap_async_cp_result(local: Tensor, slot, fallback_mesh: DeviceMesh, fallback_placements) -> "DTensor": 

223 """Wrap a waited async result with the layout captured before communication.""" 

224 mesh, placements = _slot_layout(slot, fallback_mesh, fallback_placements) 

225 return DTensor.from_local(local, mesh, placements) 

226 

227 

228# --------------------------------------------------------------------------- 

229# AsyncContextParallel 

230# --------------------------------------------------------------------------- 

231 

232class AsyncContextParallel(ContextParallel): 

233 """Context Parallel with projection–collective compute overlap. 

234 

235 Requires ``q_proj``, ``k_proj``, ``v_proj`` in :meth:`apply`; otherwise 

236 falls back to synchronous :class:`ContextParallel`. 

237 

238 Pure Colossal AI (``ulysses_degree=1``) overlaps K/V AllGather when the 

239 backend exposes async all-gather handles. Hybrid CP overlaps Ulysses A2A and 

240 keeps the Colossal K/V AllGather synchronous for backward-ordering safety. 

241 

242 Args: 

243 seq_dim: Sequence dimension (1=BSHD, 2=BNSD). 

244 head_dim: Head dimension (2=BSHD, 1=BNSD). 

245 ulysses_degree: Ulysses sub-mesh size (see :class:`ContextParallel`). 

246 qkv_indices: Positional indices of (Q, K, V) in attention forward. 

247 qkv_kwarg_names: Keyword names for (Q, K, V). 

248 use_local_output: Return local tensors after CP when True. When False, 

249 keep CP DTensor outputs, or drop the CP axis from 

250 composed CP+TP outputs and keep the non-CP layout. 

251 load_balance: Load-balance flag forwarded to base class. 

252 """ 

253 

254 def __init__( 

255 self, 

256 seq_dim: int = 1, 

257 head_dim: int = 2, 

258 ulysses_degree: Optional[int] = None, 

259 qkv_indices: tuple = (0, 1, 2), 

260 qkv_kwarg_names: tuple = (), 

261 use_local_output: bool = False, 

262 load_balance: bool = False, 

263 ): 

264 super().__init__( 

265 seq_dim=seq_dim, 

266 head_dim=head_dim, 

267 ulysses_degree=ulysses_degree, 

268 qkv_indices=qkv_indices, 

269 qkv_kwarg_names=qkv_kwarg_names, 

270 use_local_output=use_local_output, 

271 load_balance=load_balance, 

272 ) 

273 

274 # ------------------------------------------------------------------ 

275 # Public entry point 

276 # ------------------------------------------------------------------ 

277 

278 def apply( # pylint: disable=arguments-differ 

279 self, 

280 module: Module, 

281 device_mesh: DeviceMesh, 

282 q_proj: Optional[Module] = None, 

283 k_proj: Optional[Module] = None, 

284 v_proj: Optional[Module] = None, 

285 ) -> Module: 

286 """Register async-overlap hooks and return *module*. 

287 

288 Falls back to synchronous :class:`ContextParallel` if any of 

289 ``q/k/v_proj`` is ``None``. 

290 

291 Args: 

292 module: Core-attention submodule. 

293 device_mesh: CP device mesh (1-D or 2-D). 

294 q_proj: The last module in the Q path whose output is passed 

295 directly to the attention module as Q. Its forward 

296 post-hook launches the async Q all-to-all. There 

297 must be **no** intermediate ops (view, transpose, …) 

298 between this module and attention; such ops would be 

299 bypassed by the pre-hook substitution and could cause 

300 shape mismatches. For models with QK normalization 

301 applied right before attention, pass ``qk_norm_q`` 

302 here instead of the raw projection. 

303 k_proj: Same semantics as ``q_proj``, for the K path. Pass 

304 ``qk_norm_k`` when the model applies QK-Norm before 

305 attention. 

306 v_proj: Value projection module (no norm variant needed). 

307 """ 

308 if q_proj is None or k_proj is None or v_proj is None: 

309 return super().apply(module, device_mesh) 

310 

311 cp_size = device_mesh.mesh.numel() 

312 ds = self.ulysses_degree if self.ulysses_degree is not None else cp_size 

313 if cp_size % ds != 0: 

314 raise ValueError( 

315 f"cp_size ({cp_size}) must be divisible by ulysses_degree ({ds})." 

316 ) 

317 co = cp_size // ds 

318 

319 if ds == 1: 

320 if self.load_balance: 

321 return super().apply(module, device_mesh) 

322 return self._apply_colossal_async(module, device_mesh, cp_size, k_proj, v_proj) 

323 

324 return self._apply_a2a_async(module, device_mesh, ds, co, q_proj, k_proj, v_proj) 

325 

326 def _apply_colossal_async( 

327 self, 

328 module: Module, 

329 device_mesh: DeviceMesh, 

330 cp_size: int, 

331 k_proj: Module, 

332 v_proj: Module, 

333 ) -> Module: 

334 """Register Pure Colossal async K/V AllGather hooks.""" 

335 co_submesh = _ensure_1d(device_mesh) 

336 group = co_submesh.get_group() 

337 fwd_ag_slots = {"k": None, "v": None} 

338 bwd_ag_slots = {"k": [], "v": []} 

339 setattr(module, "_context_parallel_async_state", _AsyncCPState(fwd_ag_slots, bwd_ag_slots)) 

340 self._register_ag_proj_hooks( 

341 k_proj, 

342 v_proj, 

343 submesh=co_submesh, 

344 group=group, 

345 world_size=cp_size, 

346 fwd_slots=fwd_ag_slots, 

347 bwd_slots=bwd_ag_slots, 

348 ) 

349 utils.register_forward_pre_hook( 

350 module, 

351 partial( 

352 self._attn_pre_hook_colossal, 

353 co_submesh=co_submesh, 

354 group=group, 

355 world_size=cp_size, 

356 fwd_slots=fwd_ag_slots, 

357 bwd_slots=bwd_ag_slots, 

358 ), 

359 with_kwargs=True, 

360 ) 

361 module.register_forward_hook( 

362 partial(self._post_hook_colossal, co_submesh=co_submesh) 

363 ) 

364 return module 

365 

366 def _apply_a2a_async( # pylint: disable=too-many-arguments 

367 self, 

368 module: Module, 

369 device_mesh: DeviceMesh, 

370 ds: int, 

371 co: int, 

372 q_proj: Module, 

373 k_proj: Module, 

374 v_proj: Module, 

375 ) -> Module: 

376 """Register Pure Ulysses or Hybrid async A2A hooks.""" 

377 fwd_slots = {"q": None, "k": None, "v": None} 

378 bwd_slots = {"q": [], "k": [], "v": []} 

379 setattr(module, "_context_parallel_async_state", _AsyncCPState(fwd_slots, bwd_slots)) 

380 

381 if co == 1: 

382 ds_submesh = _ensure_1d(device_mesh) 

383 group = ds_submesh.get_group() 

384 a2a_layout_mesh = ds_submesh 

385 a2a_layout_placements = (Shard(self.head_dim),) 

386 pre_hook = partial( 

387 self._attn_pre_hook_ulysses, 

388 ds_submesh=ds_submesh, 

389 group=group, 

390 world_size=ds, 

391 fwd_slots=fwd_slots, 

392 bwd_slots=bwd_slots, 

393 ) 

394 post_hook = partial(self._attn_post_hook_ata, ds_submesh=ds_submesh) 

395 else: 

396 hybrid_cp_mesh = _build_hybrid_cp_mesh(device_mesh, ds, co) 

397 dim_names = hybrid_cp_mesh.mesh_dim_names 

398 if dim_names is None: 

399 raise ValueError("2-D mesh must have mesh_dim_names (guaranteed by _build_2d_mesh)") 

400 ds_submesh = hybrid_cp_mesh[dim_names[1]] 

401 group = ds_submesh.get_group() 

402 a2a_layout_mesh = hybrid_cp_mesh 

403 a2a_layout_placements = (Shard(self.seq_dim), Shard(self.head_dim)) 

404 pre_hook = partial( 

405 self._attn_pre_hook_hybrid, 

406 ds_submesh=ds_submesh, 

407 group=group, 

408 world_size=ds, 

409 hybrid_cp_mesh=hybrid_cp_mesh, 

410 fwd_slots=fwd_slots, 

411 bwd_slots=bwd_slots, 

412 ) 

413 post_hook = partial( 

414 self._post_hook_hybrid, 

415 hybrid_cp_mesh=hybrid_cp_mesh, 

416 ds_submesh=ds_submesh, 

417 ) 

418 

419 self._register_proj_hooks( 

420 q_proj, 

421 k_proj, 

422 v_proj, 

423 submesh=ds_submesh, 

424 group=group, 

425 world_size=ds, 

426 fwd_slots=fwd_slots, 

427 bwd_slots=bwd_slots, 

428 layout_mesh=a2a_layout_mesh, 

429 layout_placements=a2a_layout_placements, 

430 ) 

431 utils.register_forward_pre_hook( 

432 module, 

433 pre_hook, 

434 with_kwargs=True, 

435 ) 

436 module.register_forward_hook(post_hook) 

437 return module 

438 

439 # ------------------------------------------------------------------ 

440 # Shared: projection hooks registration 

441 # ------------------------------------------------------------------ 

442 

443 def _register_proj_hooks( 

444 self, 

445 q_proj, 

446 k_proj, 

447 v_proj, 

448 submesh, 

449 group, 

450 world_size, 

451 fwd_slots, 

452 bwd_slots, 

453 layout_mesh, 

454 layout_placements, 

455 ): 

456 """Register forward and backward hooks on all three projection modules.""" 

457 for key, proj in [("q", q_proj), ("k", k_proj), ("v", v_proj)]: 

458 proj.register_forward_hook( 

459 partial(self._proj_post_hook, key=key, submesh=submesh, group=group, world_size=world_size, 

460 fwd_slots=fwd_slots, layout_mesh=layout_mesh, layout_placements=layout_placements) 

461 ) 

462 utils.register_full_backward_pre_hook( 

463 proj, 

464 partial(self._proj_bwd_pre_hook, bwd_slot=bwd_slots[key]) 

465 ) 

466 

467 def _proj_post_hook( # pylint: disable=unused-argument,too-many-arguments 

468 self, module, inputs, output, key, submesh, group, world_size, fwd_slots, layout_mesh, layout_placements 

469 ): 

470 """Launch async seq→head A2A after projection; return original output unchanged.""" 

471 tensor = _to_cp_local(output, submesh, self.seq_dim) 

472 work, out_perm = _launch_async_a2a_seq_to_head( 

473 tensor, group, world_size, self.head_dim 

474 ) 

475 fwd_slots[key] = _make_async_cp_slot( 

476 work, 

477 out_perm, 

478 output, 

479 layout_mesh, 

480 layout_placements, 

481 self.seq_dim, 

482 ) 

483 return output 

484 

485 def _register_ag_proj_hooks(self, k_proj, v_proj, submesh, group, world_size, fwd_slots, bwd_slots): 

486 """Register async AllGather hooks for K/V projection modules.""" 

487 for key, proj in [("k", k_proj), ("v", v_proj)]: 

488 proj.register_forward_hook( 

489 partial(self._proj_ag_post_hook, key=key, submesh=submesh, group=group, world_size=world_size, 

490 fwd_slots=fwd_slots) 

491 ) 

492 utils.register_full_backward_pre_hook( 

493 proj, 

494 partial(self._proj_ag_bwd_pre_hook, bwd_slot=bwd_slots[key]) 

495 ) 

496 

497 def _proj_ag_post_hook( # pylint: disable=unused-argument,too-many-arguments 

498 self, module, inputs, output, key, submesh, group, world_size, fwd_slots 

499 ): 

500 """Launch async K/V AllGather after projection; return original output.""" 

501 tensor = _to_cp_local(output, submesh, self.seq_dim) 

502 work, out_perm = _launch_async_allgather_seq( 

503 tensor, group, world_size, self.seq_dim 

504 ) 

505 fwd_slots[key] = _make_async_cp_slot( 

506 work, 

507 out_perm, 

508 output, 

509 submesh, 

510 (Replicate(),), 

511 self.seq_dim, 

512 ) 

513 return output 

514 

515 def _get_qkv_value(self, args, kwargs, qkv_pos: int): 

516 """Return Q/K/V value from positional args or configured kwargs.""" 

517 idx = self.qkv_indices[qkv_pos] 

518 if idx < len(args): 

519 return args[idx] 

520 if qkv_pos < len(self.qkv_kwarg_names): 

521 name = self.qkv_kwarg_names[qkv_pos] 

522 if name in kwargs: 

523 return kwargs[name] 

524 return None 

525 

526 def _set_qkv_value(self, args, kwargs, qkv_pos: int, value): 

527 """Set Q/K/V value in positional args or configured kwargs.""" 

528 idx = self.qkv_indices[qkv_pos] 

529 if idx < len(args): 

530 args[idx] = value 

531 return 

532 if qkv_pos < len(self.qkv_kwarg_names): 

533 name = self.qkv_kwarg_names[qkv_pos] 

534 if name in kwargs: 

535 kwargs[name] = value 

536 

537 # ------------------------------------------------------------------ 

538 # Internal: wait for pre-launched communication handles 

539 # ------------------------------------------------------------------ 

540 

541 def _wait_a2a(self, tensor, group, world_size, fwd_slots, key, bwd_slot): 

542 """Wait for pre-launched A2A; returns head-scattered tensor (differentiable).""" 

543 slot = fwd_slots[key] 

544 work, out_perm = _slot_comm(slot) 

545 fwd_slots[key] = None 

546 return utils.differentiable_async_a2a_wait( 

547 tensor, work, out_perm, group, world_size, 

548 self.seq_dim, self.head_dim, # concat_dim=seq_dim, split_dim=head_dim 

549 bwd_slot, 

550 ) 

551 

552 def _wait_a2a_dtensor( 

553 self, 

554 tensor, 

555 group, 

556 world_size, 

557 fwd_slots, 

558 key, 

559 bwd_slot, 

560 fallback_mesh, 

561 fallback_placements, 

562 ): 

563 """Wait for pre-launched A2A and wrap the result with captured CP+non-CP layout.""" 

564 slot = fwd_slots[key] 

565 local = self._wait_a2a( 

566 tensor, 

567 group, 

568 world_size, 

569 fwd_slots, 

570 key, 

571 bwd_slot, 

572 ) 

573 return _wrap_async_cp_result(local, slot, fallback_mesh, fallback_placements) 

574 

575 def _wait_allgather(self, tensor, group, world_size, work, out_perm, bwd_slot=None): 

576 """Wait for pre-launched AllGather and return gathered tensor.""" 

577 return utils.differentiable_async_allgather_wait( 

578 tensor, 

579 work, 

580 out_perm, 

581 group, 

582 world_size, 

583 self.seq_dim, 

584 bwd_slot, 

585 ) 

586 

587 # ------------------------------------------------------------------ 

588 # QKV transform helpers 

589 # ------------------------------------------------------------------ 

590 

591 def _apply_qkv_transforms( 

592 self, 

593 args, 

594 kwargs, 

595 submesh, 

596 transform_q, 

597 transform_k, 

598 transform_v, 

599 ): 

600 """Apply transforms to Q/K/V and return modified ``(args, kwargs)``. 

601 

602 Each transform receives ``(original, local)``. The local tensor is the 

603 raw communication buffer, while the original value carries any non-CP 

604 DTensor layout that must be restored after the async wait. 

605 """ 

606 new_args = list(args) 

607 new_kwargs = dict(kwargs) 

608 

609 transforms = (transform_q, transform_k, transform_v) 

610 for pos, transform in enumerate(transforms): 

611 value = self._get_qkv_value(new_args, new_kwargs, pos) 

612 if value is None: 

613 continue 

614 self._set_qkv_value( 

615 new_args, 

616 new_kwargs, 

617 pos, 

618 transform(value, _to_cp_local(value, submesh, self.seq_dim)), 

619 ) 

620 return tuple(new_args), new_kwargs 

621 

622 # ------------------------------------------------------------------ 

623 # Attention pre-hooks 

624 # ------------------------------------------------------------------ 

625 

626 def _attn_pre_hook_ulysses( # pylint: disable=unused-argument,too-many-arguments 

627 self, module, args, kwargs, group, world_size, fwd_slots, bwd_slots, ds_submesh=None 

628 ): 

629 """Wait Q/K/V A2A and return head-scattered args/kwargs.""" 

630 self._record_q_output_tp_layout(module, args, kwargs, ds_submesh) 

631 

632 def make_a2a(key): 

633 def transform(value, local_value): # pylint: disable=unused-argument 

634 if ds_submesh is None: 

635 return self._wait_a2a( 

636 local_value, 

637 group, 

638 world_size, 

639 fwd_slots, 

640 key, 

641 bwd_slots[key], 

642 ) 

643 return self._wait_a2a_dtensor( 

644 local_value, 

645 group, 

646 world_size, 

647 fwd_slots, 

648 key, 

649 bwd_slots[key], 

650 ds_submesh, 

651 (Shard(self.head_dim),), 

652 ) 

653 return transform 

654 

655 return self._apply_qkv_transforms( 

656 args, 

657 kwargs, 

658 ds_submesh, 

659 transform_q=make_a2a("q"), 

660 transform_k=make_a2a("k"), 

661 transform_v=make_a2a("v"), 

662 ) 

663 

664 def _ulysses_cp_layout_from_input(self, t, ds_submesh): 

665 """Return the pure-Ulysses execution mesh and placements for one input tensor.""" 

666 cp_placements = (Shard(self.head_dim),) 

667 layout = _non_cp_dtensor_layout(t, ds_submesh, self.seq_dim) 

668 if layout is None: 

669 return ds_submesh, cp_placements 

670 non_cp_mesh, non_cp_placements, composed_mesh = layout 

671 return composed_mesh, _compose_cp_non_cp_placements( 

672 composed_mesh, 

673 ds_submesh, 

674 cp_placements, 

675 non_cp_mesh, 

676 non_cp_placements, 

677 ) 

678 

679 def _attn_pre_hook_colossal( # pylint: disable=unused-argument,too-many-arguments 

680 self, module, args, kwargs, co_submesh, group, world_size, fwd_slots, bwd_slots 

681 ): 

682 """Wait K/V AllGather, wrap Q as local shard and return CP-ready args/kwargs.""" 

683 new_args = list(args) 

684 new_kwargs = dict(kwargs) 

685 

686 q_value = self._get_qkv_value(new_args, new_kwargs, 0) 

687 self._record_q_output_tp_layout(module, new_args, new_kwargs, co_submesh) 

688 if q_value is not None: 

689 self._set_qkv_value( 

690 new_args, 

691 new_kwargs, 

692 0, 

693 _to_cp_dtensor( 

694 q_value, 

695 co_submesh, 

696 (Shard(self.seq_dim),), 

697 (Shard(self.seq_dim),), 

698 self.seq_dim, 

699 ), 

700 ) 

701 

702 for pos, key in enumerate(("k", "v"), start=1): 

703 value = self._get_qkv_value(new_args, new_kwargs, pos) 

704 if value is None: 

705 continue 

706 local = _to_cp_local(value, co_submesh, self.seq_dim) 

707 slot = fwd_slots[key] 

708 work, out_perm = _slot_comm(slot) 

709 fwd_slots[key] = None 

710 gathered = self._wait_allgather( 

711 local, 

712 group, 

713 world_size, 

714 work, 

715 out_perm, 

716 bwd_slots[key], 

717 ) 

718 if isinstance(value, DTensor): 

719 layout = _non_cp_dtensor_layout(value, co_submesh, self.seq_dim) 

720 if layout is not None: 

721 non_cp_mesh, non_cp_placements, composed_mesh = layout 

722 composed_placements = _compose_cp_non_cp_placements( 

723 composed_mesh, 

724 co_submesh, 

725 (Replicate(),), 

726 non_cp_mesh, 

727 non_cp_placements, 

728 ) 

729 self._set_qkv_value( 

730 new_args, 

731 new_kwargs, 

732 pos, 

733 DTensor.from_local( 

734 gathered.to_local() if isinstance(gathered, DTensor) else gathered, 

735 composed_mesh, 

736 composed_placements, 

737 ), 

738 ) 

739 continue 

740 self._set_qkv_value( 

741 new_args, 

742 new_kwargs, 

743 pos, 

744 DTensor.from_local( 

745 _to_local(gathered), 

746 co_submesh, 

747 (Replicate(),), 

748 ), 

749 ) 

750 

751 return tuple(new_args), new_kwargs 

752 

753 def _attn_pre_hook_hybrid( # pylint: disable=too-many-locals,too-many-arguments 

754 self, module, args, kwargs, group, world_size, hybrid_cp_mesh, # pylint: disable=unused-argument 

755 fwd_slots, bwd_slots, ds_submesh=None 

756 ): 

757 """Wait Ulysses A2A for Q/K/V, then synchronously gather K/V on the co-submesh.""" 

758 new_args = list(args) 

759 new_kwargs = dict(kwargs) 

760 

761 co_submesh = hybrid_cp_mesh[hybrid_cp_mesh.mesh_dim_names[0]] 

762 if ds_submesh is None: 

763 ds_submesh = hybrid_cp_mesh[hybrid_cp_mesh.mesh_dim_names[1]] 

764 self._record_q_output_tp_layout(module, new_args, new_kwargs, hybrid_cp_mesh) 

765 

766 q_value = self._get_qkv_value(new_args, new_kwargs, 0) 

767 if q_value is not None: 

768 self._set_qkv_value( 

769 new_args, 

770 new_kwargs, 

771 0, 

772 self._wait_a2a_dtensor( 

773 _to_cp_local(q_value, ds_submesh, self.seq_dim), 

774 group, 

775 world_size, 

776 fwd_slots, 

777 "q", 

778 bwd_slots["q"], 

779 hybrid_cp_mesh, 

780 (Shard(self.seq_dim), Shard(self.head_dim)), 

781 ), 

782 ) 

783 

784 k_value = self._get_qkv_value(new_args, new_kwargs, 1) 

785 if k_value is not None: 

786 k_ul = self._wait_a2a_dtensor( 

787 _to_cp_local(k_value, ds_submesh, self.seq_dim), 

788 group, 

789 world_size, 

790 fwd_slots, 

791 "k", 

792 bwd_slots["k"], 

793 hybrid_cp_mesh, 

794 (Shard(self.seq_dim), Shard(self.head_dim)), 

795 ) 

796 k_full = _gather_seq(k_ul, co_submesh, self.seq_dim) 

797 k_mesh, k_placements = self._hybrid_kv_gather_placements( 

798 k_value, 

799 hybrid_cp_mesh, 

800 ) 

801 self._set_qkv_value( 

802 new_args, 

803 new_kwargs, 

804 1, 

805 DTensor.from_local( 

806 _to_local(k_full), 

807 k_mesh, 

808 k_placements, 

809 ), 

810 ) 

811 

812 v_value = self._get_qkv_value(new_args, new_kwargs, 2) 

813 if v_value is not None: 

814 v_ul = self._wait_a2a_dtensor( 

815 _to_cp_local(v_value, ds_submesh, self.seq_dim), 

816 group, 

817 world_size, 

818 fwd_slots, 

819 "v", 

820 bwd_slots["v"], 

821 hybrid_cp_mesh, 

822 (Shard(self.seq_dim), Shard(self.head_dim)), 

823 ) 

824 v_full = _gather_seq(v_ul, co_submesh, self.seq_dim) 

825 v_mesh, v_placements = self._hybrid_kv_gather_placements( 

826 v_value, 

827 hybrid_cp_mesh, 

828 ) 

829 self._set_qkv_value( 

830 new_args, 

831 new_kwargs, 

832 2, 

833 DTensor.from_local( 

834 _to_local(v_full), 

835 v_mesh, 

836 v_placements, 

837 ), 

838 ) 

839 

840 return tuple(new_args), new_kwargs 

841 

842 # ------------------------------------------------------------------ 

843 # Attention post-hook (Ulysses and Hybrid share the same reverse ATA) 

844 # ------------------------------------------------------------------ 

845 

846 def _attn_post_hook_ata(self, module, args, output, ds_submesh): # pylint: disable=unused-argument 

847 """Reverse head→seq gather on ds_submesh; returns local tensor.""" 

848 output_layout = _pop_output_layout(module) 

849 

850 def _process(output_item): 

851 if isinstance(output_item, (Tensor, DTensor)): 

852 if isinstance(output_item, DTensor) and not _is_cp_composed_dtensor(output_item, ds_submesh): 

853 output_item = output_item.to_local() 

854 seq_dtensor = _gather_head_to_seq( 

855 output_item, ds_submesh, self.seq_dim, self.head_dim 

856 ) 

857 return _finalize_ata_output( 

858 seq_dtensor, output_layout, ds_submesh, self.seq_dim, self.use_local_output 

859 ) 

860 return output_item 

861 

862 if isinstance(output, (tuple, list)): 

863 return type(output)(_process(item) for item in output) 

864 return _process(output) 

865 

866 # ------------------------------------------------------------------ 

867 # Backward: wait A2A handle (launched by autograd) before proj GEMM 

868 # ------------------------------------------------------------------ 

869 

870 def _proj_bwd_pre_hook(self, module, grad_output, bwd_slot): # pylint: disable=unused-argument 

871 """Wait backward A2A just before proj GEMM; replace grad with seq-form. 

872 

873 The async head→seq A2A is launched inside _TorchAsyncA2AFunction.backward 

874 and appended to ``bwd_slot``. Waiting here lets the A2A overlap with the 

875 preceding proj GEMM. 

876 """ 

877 work, out_perm = bwd_slot.pop() 

878 work.wait() 

879 d_seq = _a2a_reconstruct(out_perm, self.head_dim) 

880 return (d_seq,) + grad_output[1:] if isinstance(grad_output, tuple) else (d_seq,) 

881 

882 def _proj_ag_bwd_pre_hook(self, module, grad_output, bwd_slot): # pylint: disable=unused-argument 

883 """Wait backward reduce-scatter just before K/V projection GEMM.""" 

884 work, out_perm, gather_dim = bwd_slot.pop() 

885 work.wait() 

886 d_local = _allgather_reconstruct(out_perm, gather_dim) 

887 return (d_local,) + grad_output[1:] if isinstance(grad_output, tuple) else (d_local,)