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

302 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"""context_parallel.collectives: CP collective primitives (05 §4.4.2 / §6.3.4). 

17 

18- ``flex_cp_allgather``: K/V all-gather along the CP dim (reuses 

19 cp_mesh.get_group(); new_group is forbidden); 

20- ``ulysses_seq_to_head`` / ``ulysses_head_to_seq``: differentiable Pure 

21 Ulysses all-to-all layout transforms; 

22- async collective launches (``AsyncCPCollective`` / 

23 ``async_cp_allgather_launch`` / ``async_ulysses_seq_to_head_launch``); 

24- hybrid (Ulysses + all-gather) CP sub-mesh construction and attention 

25 orchestration (``_build_hybrid_cp_submeshes`` / ``hybrid_cp_attention``). 

26 

27Note (G5): the seq_len % (2*cp) padding constraint originates from the 

28zigzag/ring load-balancing scheme; this design uses all-gather K/V + 

29contiguous chunk (D-01'' rejected ring), so each rank's Q chunk is 

30equal-length and FLOPs are naturally balanced -- the constraint is redundant 

31but harmless: the implementation is kept and documented here. 

32 

33Split out of components/distributed/cp_utils.py in stage 4e; the attention 

34adaptations live in context_parallel/attention.py and the batch sharding in 

35hyper_parallel/data/parallel/batch_parallel.py. 

36""" 

37 

38# The legacy header checker does not recognize the existing multi-year copyright. 

39# pylint: disable=missing-apache-license-header 

40 

41from dataclasses import dataclass 

42from typing import Any, Callable, Optional 

43import torch 

44import torch.distributed as dist 

45from torch import Tensor 

46from torch.distributed.nn.functional import all_gather as differentiable_all_gather 

47from hyper_parallel.core.dtensor.device_mesh import DeviceMesh 

48from hyper_parallel.core.utils import communication 

49 

50 

51_ULYSSES_WRAPPED_FLAG = "_hyper_ulysses_wrapped" 

52 

53 

54_HYBRID_MESH_CACHE = {} 

55 

56 

57class _SeqAllToAll(torch.autograd.Function): 

58 """Autograd-aware exchange from one tensor dimension to another.""" 

59 

60 @staticmethod 

61 def forward( 

62 ctx: Any, 

63 group: Any, 

64 tensor: Tensor, 

65 scatter_dim: int, 

66 gather_dim: int, 

67 ) -> Tensor: 

68 """Exchange tensor shards between the sequence and head dimensions. 

69 

70 Args: 

71 ctx: Autograd context for this collective invocation. 

72 group: Existing communication group; no group is created here. 

73 tensor: Input tensor whose autograd edge is preserved. 

74 scatter_dim: Tensor dimension divided across the group. 

75 gather_dim: Tensor dimension assembled across the group. 

76 

77 Returns: 

78 Tensor with shards concatenated along gather_dim. 

79 """ 

80 ctx.group = group 

81 ctx.scatter_dim = scatter_dim 

82 ctx.gather_dim = gather_dim 

83 world_size = dist.get_world_size(group) 

84 if tensor.size(scatter_dim) % world_size: 

85 raise ValueError( 

86 f"dimension {scatter_dim} size {tensor.size(scatter_dim)} " 

87 f"is not divisible by CP size {world_size}") 

88 inputs = [ 

89 part.contiguous() 

90 for part in tensor.chunk(world_size, dim=scatter_dim) 

91 ] 

92 outputs = [torch.empty_like(inputs[0]) for _ in range(world_size)] 

93 dist.all_to_all(outputs, inputs, group=group) 

94 return torch.cat(outputs, dim=gather_dim).contiguous() 

95 

96 @staticmethod 

97 def backward( 

98 ctx: Any, 

99 grad_output: Tensor, 

100 ) -> tuple[None, Tensor, None, None]: 

101 """Apply the inverse all-to-all to the output gradient. 

102 

103 Args: 

104 ctx: Autograd context for this collective invocation. 

105 grad_output: Gradient in the forward output layout. 

106 

107 Returns: 

108 Input gradient and None for the communication metadata. 

109 """ 

110 grad_input = _SeqAllToAll.apply( 

111 ctx.group, grad_output, ctx.gather_dim, ctx.scatter_dim) 

112 return None, grad_input, None, None 

113 

114 

115@dataclass(frozen=True) 

116class _UlyssesContext: 

117 """Communication context derived from the framework-owned CP mesh.""" 

118 

119 cp_mesh: Any 

120 

121 @property 

122 def group(self) -> Any: 

123 """Process group of the CP mesh.""" 

124 return self.cp_mesh.get_group() 

125 

126 @property 

127 def size(self) -> int: 

128 """Number of ranks in the CP mesh.""" 

129 return self.cp_mesh.size() 

130 

131 @property 

132 def rank(self) -> int: 

133 """Local rank of this process within the CP mesh.""" 

134 return self.cp_mesh.get_local_rank() 

135 

136 

137def _sequence_to_head(tensor, context): 

138 """[B, S/CP, H, D] -> [B, S, H/CP, D].""" 

139 return _SeqAllToAll.apply(context.group, tensor, 2, 1) 

140 

141 

142def _head_to_sequence(tensor, context): 

143 """[B, S, H/CP, D] -> [B, S/CP, H, D].""" 

144 return _SeqAllToAll.apply(context.group, tensor, 1, 2) 

145 

146 

147def _gather_sequence(tensor, context): 

148 """Gather sequence shards and sum their gradients during backward.""" 

149 return torch.cat( 

150 differentiable_all_gather( 

151 tensor.contiguous(), group=context.group), dim=1) 

152 

153 

154def _slice_sequence(tensor, dim, context): 

155 if tensor.size(dim) % context.size: 

156 raise ValueError( 

157 f"sequence length {tensor.size(dim)} is not divisible by " 

158 f"CP size {context.size}") 

159 length = tensor.size(dim) // context.size 

160 return tensor.narrow( 

161 dim, context.rank * length, length).contiguous() 

162 

163 

164def _global_seq_len(actual, length, device): 

165 if actual is None: 

166 return [length] 

167 if isinstance(actual, Tensor): 

168 return actual.to(device=device, dtype=torch.int32) 

169 return actual 

170 

171 

172def _slice_sink(tensor, context): 

173 if tensor is None or tensor.size(2) == 1: 

174 return tensor 

175 if tensor.size(2) % context.size: 

176 raise ValueError( 

177 f"parameter-sink heads {tensor.size(2)} are not divisible by " 

178 f"CP size {context.size}") 

179 count = tensor.size(2) // context.size 

180 start = context.rank * count 

181 return tensor[:, :, start:start + count].contiguous() 

182 

183 

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

185 """Normalize and validate a tensor dimension.""" 

186 normalized = dim + ndim if dim < 0 else dim 

187 if normalized < 0 or normalized >= ndim: 

188 raise ValueError(f"dimension {dim} is out of range for a {ndim}D tensor") 

189 return normalized 

190 

191 

192def _reconstruct_all_to_all(output: Tensor, concat_dim: int) -> Tensor: 

193 """Move the source-rank axis next to ``concat_dim`` and merge it.""" 

194 rank_axis_position = concat_dim + 1 

195 permutation = ( 

196 list(range(1, rank_axis_position)) 

197 + [0] 

198 + list(range(rank_axis_position, output.dim())) 

199 ) 

200 reconstructed = output.permute(permutation).contiguous() 

201 shape = list(reconstructed.shape) 

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

203 return reconstructed.reshape(shape[:concat_dim] + [merged] + shape[concat_dim + 2:]) 

204 

205 

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

207 """Move one dimension to the leading communication dimension.""" 

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

209 if dim == 0: 

210 return tensor.contiguous() 

211 return tensor.movedim(dim, 0).contiguous() 

212 

213 

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

215 """Restore a leading communication dimension to its original position.""" 

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

217 if dim == 0: 

218 return tensor.contiguous() 

219 return tensor.movedim(0, dim).contiguous() 

220 

221 

222def _prepare_ulysses_send( 

223 tensor: Tensor, 

224 scatter_dim: int, 

225 world_size: int, 

226) -> Tensor: 

227 """Split one tensor dimension and move the destination-rank axis first.""" 

228 ndim = tensor.dim() 

229 scatter_dim = _normalize_dim(scatter_dim, ndim) 

230 shape = list(tensor.shape) 

231 scatter_size = shape[scatter_dim] 

232 if scatter_size % world_size: 

233 raise ValueError( 

234 f"tensor dimension {scatter_dim} size ({scatter_size}) must be " 

235 f"divisible by Ulysses degree ({world_size})" 

236 ) 

237 split_shape = ( 

238 shape[:scatter_dim] 

239 + [world_size, scatter_size // world_size] 

240 + shape[scatter_dim + 1:] 

241 ) 

242 permutation = ( 

243 [scatter_dim] 

244 + list(range(scatter_dim)) 

245 + list(range(scatter_dim + 1, ndim + 1)) 

246 ) 

247 return tensor.contiguous().reshape(split_shape).permute(permutation).contiguous() 

248 

249 

250class _AsyncAllGatherWait(torch.autograd.Function): 

251 """Attach a pre-launched all-gather to autograd at its wait point.""" 

252 

253 @staticmethod 

254 def forward( 

255 ctx: Any, 

256 tensor: Tensor, 

257 work: Any, 

258 output: Tensor, 

259 group: Any, 

260 world_size: int, 

261 gather_dim: int, 

262 ) -> Tensor: 

263 """Wait for a launched all-gather and expose its autograd edge. 

264 

265 Args: 

266 ctx: Autograd context for this collective invocation. 

267 tensor: Input tensor whose autograd edge is preserved. 

268 work: Handle for the already launched asynchronous collective. 

269 output: Receive buffer owned by this invocation. 

270 group: Existing communication group; no group is created here. 

271 world_size: Number of participating ranks. 

272 gather_dim: Tensor dimension assembled across the group. 

273 

274 Returns: 

275 Gathered tensor after its communication completes. 

276 """ 

277 del tensor 

278 ctx.group = group 

279 ctx.world_size = world_size 

280 ctx.gather_dim = gather_dim 

281 work.wait() 

282 return _move_dim_from_front(output, gather_dim) 

283 

284 @staticmethod 

285 def backward( 

286 ctx: Any, 

287 grad_output: Tensor, 

288 ) -> tuple[Tensor, None, None, None, None, None]: 

289 """SUM consumer gradients directly into each owner's sequence shard. 

290 

291 Args: 

292 ctx: Autograd context for this collective invocation. 

293 grad_output: Gradient in the forward output layout. 

294 

295 Returns: 

296 Local summed gradient and None for non-tensor metadata. 

297 """ 

298 send = _move_dim_to_front(grad_output, ctx.gather_dim) 

299 output = grad_output.new_empty((send.shape[0] // ctx.world_size, *send.shape[1:])) 

300 work = dist.reduce_scatter_tensor( 

301 output, send, op=dist.ReduceOp.SUM, group=ctx.group, async_op=True, 

302 ) 

303 work.wait() 

304 local = _move_dim_from_front(output, ctx.gather_dim) 

305 return ( 

306 local, 

307 None, 

308 None, 

309 None, 

310 None, 

311 None, 

312 ) 

313 

314 

315class _AsyncUlyssesWait(torch.autograd.Function): 

316 """Attach a pre-launched sequence-to-head A2A to autograd.""" 

317 

318 @staticmethod 

319 def forward( 

320 ctx: Any, 

321 tensor: Tensor, 

322 work: Any, 

323 output: Tensor, 

324 group: Any, 

325 world_size: int, 

326 seq_dim: int, 

327 head_dim: int, 

328 ) -> Tensor: 

329 """Wait for a launched A2A and expose its autograd edge. 

330 

331 Args: 

332 ctx: Autograd context for this collective invocation. 

333 tensor: Input tensor whose autograd edge is preserved. 

334 work: Handle for the already launched asynchronous collective. 

335 output: Receive buffer owned by this invocation. 

336 group: Existing communication group; no group is created here. 

337 world_size: Number of participating ranks. 

338 seq_dim: Tensor dimension representing tokens. 

339 head_dim: Tensor dimension representing attention heads. 

340 

341 Returns: 

342 Exchanged tensor after its communication completes. 

343 """ 

344 del tensor 

345 ctx.group = group 

346 ctx.world_size = world_size 

347 ctx.seq_dim = seq_dim 

348 ctx.head_dim = head_dim 

349 work.wait() 

350 return _reconstruct_all_to_all(output, seq_dim) 

351 

352 @staticmethod 

353 def backward( 

354 ctx: Any, 

355 grad_output: Tensor, 

356 ) -> tuple[Tensor, None, None, None, None, None, None]: 

357 """Apply the inverse A2A to restore the input-gradient layout. 

358 

359 Args: 

360 ctx: Autograd context for this collective invocation. 

361 grad_output: Gradient in the forward output layout. 

362 

363 Returns: 

364 Input gradient and None for non-tensor metadata. 

365 """ 

366 send = _prepare_ulysses_send( 

367 grad_output, 

368 scatter_dim=ctx.seq_dim, 

369 world_size=ctx.world_size, 

370 ) 

371 output = torch.empty( 

372 list(send.shape), device=send.device, dtype=send.dtype 

373 ) 

374 work = dist.all_to_all_single( 

375 output, send, group=ctx.group, async_op=True 

376 ) 

377 work.wait() 

378 grad_input = _reconstruct_all_to_all(output, ctx.head_dim) 

379 return grad_input, None, None, None, None, None, None 

380 

381 

382@dataclass 

383class AsyncCPCollective: 

384 """A local-tensor CP collective launched before its consumer.""" 

385 

386 tensor: Tensor 

387 work: Any 

388 output: Tensor 

389 group: Any 

390 world_size: int 

391 kind: str 

392 seq_dim: int 

393 head_dim: Optional[int] = None 

394 waited: bool = False 

395 

396 def wait(self) -> Tensor: 

397 """Materialize the collective result exactly once.""" 

398 if self.waited: 

399 raise RuntimeError("an async CP collective handle cannot be waited twice") 

400 self.waited = True 

401 if self.work is None: 

402 return self.tensor 

403 if self.kind == "allgather": 

404 return _AsyncAllGatherWait.apply( 

405 self.tensor, 

406 self.work, 

407 self.output, 

408 self.group, 

409 self.world_size, 

410 self.seq_dim, 

411 ) 

412 if self.kind == "ulysses": 

413 return _AsyncUlyssesWait.apply( 

414 self.tensor, 

415 self.work, 

416 self.output, 

417 self.group, 

418 self.world_size, 

419 self.seq_dim, 

420 self.head_dim, 

421 ) 

422 raise RuntimeError(f"unknown async CP collective kind {self.kind!r}") 

423 

424 

425def async_cp_allgather_launch( 

426 tensor: Tensor, 

427 gather_dim: int, 

428 cp_mesh: DeviceMesh, 

429) -> AsyncCPCollective: 

430 """Launch an asynchronous all-gather along gather_dim. 

431 

432 Args: 

433 tensor: Input tensor whose autograd edge is preserved. 

434 gather_dim: Tensor dimension assembled across the group. 

435 cp_mesh: Context-parallel mesh owning the communication group. 

436 

437 Returns: 

438 Collective handle whose wait method exposes the gathered tensor. 

439 """ 

440 world_size = cp_mesh.size() 

441 if world_size <= 1: 

442 return AsyncCPCollective( 

443 tensor, None, tensor, None, world_size, "allgather", gather_dim 

444 ) 

445 gather_dim = _normalize_dim(gather_dim, tensor.dim()) 

446 send = _move_dim_to_front(tensor.detach(), gather_dim) 

447 output_shape = list(send.shape) 

448 output_shape[0] *= world_size 

449 group = cp_mesh.get_group() 

450 output = torch.empty( 

451 output_shape, device=send.device, dtype=send.dtype 

452 ) 

453 work = dist.all_gather_into_tensor( 

454 output, send, group=group, async_op=True 

455 ) 

456 return AsyncCPCollective( 

457 tensor, work, output, group, world_size, "allgather", gather_dim 

458 ) 

459 

460 

461def async_ulysses_seq_to_head_launch( 

462 tensor: Tensor, 

463 seq_dim: int, 

464 head_dim: int, 

465 cp_mesh: DeviceMesh, 

466) -> AsyncCPCollective: 

467 """Launch an asynchronous Ulysses sequence-to-head A2A. 

468 

469 Args: 

470 tensor: Input tensor whose autograd edge is preserved. 

471 seq_dim: Tensor dimension representing tokens. 

472 head_dim: Tensor dimension representing attention heads. 

473 cp_mesh: Context-parallel mesh owning the communication group. 

474 

475 Returns: 

476 Collective handle whose wait method exposes the exchanged tensor. 

477 """ 

478 world_size = cp_mesh.size() 

479 if world_size <= 1: 

480 return AsyncCPCollective( 

481 tensor, 

482 None, 

483 tensor, 

484 None, 

485 world_size, 

486 "ulysses", 

487 seq_dim, 

488 head_dim, 

489 ) 

490 seq_dim = _normalize_dim(seq_dim, tensor.dim()) 

491 head_dim = _normalize_dim(head_dim, tensor.dim()) 

492 if seq_dim == head_dim: 

493 raise ValueError("Ulysses seq_dim and head_dim must be different") 

494 send = _prepare_ulysses_send( 

495 tensor.detach(), scatter_dim=head_dim, world_size=world_size 

496 ) 

497 group = cp_mesh.get_group() 

498 output = torch.empty( 

499 list(send.shape), device=send.device, dtype=send.dtype 

500 ) 

501 work = dist.all_to_all_single( 

502 output, send, group=group, async_op=True 

503 ) 

504 return AsyncCPCollective( 

505 tensor, 

506 work, 

507 output, 

508 group, 

509 world_size, 

510 "ulysses", 

511 seq_dim, 

512 head_dim, 

513 ) 

514 

515 

516def _ulysses_all_to_all( 

517 tensor: Tensor, 

518 *, 

519 scatter_dim: int, 

520 gather_dim: int, 

521 cp_mesh: DeviceMesh, 

522) -> Tensor: 

523 """Split one tensor dimension and gather another through all-to-all.""" 

524 cp_size = cp_mesh.size() 

525 if cp_size <= 1: 

526 return tensor 

527 

528 ndim = tensor.dim() 

529 scatter_dim = _normalize_dim(scatter_dim, ndim) 

530 gather_dim = _normalize_dim(gather_dim, ndim) 

531 if scatter_dim == gather_dim: 

532 raise ValueError("Ulysses scatter_dim and gather_dim must be different") 

533 

534 shape = list(tensor.shape) 

535 scatter_size = shape[scatter_dim] 

536 if scatter_size % cp_size != 0: 

537 raise ValueError( 

538 f"tensor dimension {scatter_dim} size ({scatter_size}) must be " 

539 f"divisible by Ulysses degree ({cp_size})" 

540 ) 

541 

542 split_shape = ( 

543 shape[:scatter_dim] 

544 + [cp_size, scatter_size // cp_size] 

545 + shape[scatter_dim + 1:] 

546 ) 

547 split_ndim = ndim + 1 

548 permutation = ( 

549 [scatter_dim] 

550 + list(range(scatter_dim)) 

551 + list(range(scatter_dim + 1, split_ndim)) 

552 ) 

553 send = tensor.contiguous().reshape(split_shape).permute(permutation).contiguous() 

554 received = communication.differentiable_all_to_all( 

555 send, list(send.shape), cp_mesh.get_group()) 

556 return _reconstruct_all_to_all(received, gather_dim) 

557 

558 

559def ulysses_seq_to_head( 

560 tensor: Tensor, 

561 seq_dim: int, 

562 head_dim: int, 

563 cp_mesh: DeviceMesh, 

564) -> Tensor: 

565 """Convert a sequence shard into a full-sequence head shard. 

566 

567 Args: 

568 tensor: Local Q, K, or V tensor. 

569 seq_dim: Sequence dimension to gather across the CP group. 

570 head_dim: Head dimension to split across the CP group. 

571 cp_mesh: One-dimensional CP DeviceMesh. 

572 

573 Returns: 

574 Tensor with the sequence dimension gathered and head dimension sharded. 

575 """ 

576 return _ulysses_all_to_all( 

577 tensor, 

578 scatter_dim=head_dim, 

579 gather_dim=seq_dim, 

580 cp_mesh=cp_mesh, 

581 ) 

582 

583 

584def ulysses_head_to_seq( 

585 tensor: Tensor, 

586 seq_dim: int, 

587 head_dim: int, 

588 cp_mesh: DeviceMesh, 

589) -> Tensor: 

590 """Convert a full-sequence head shard back into a sequence shard. 

591 

592 Args: 

593 tensor: Local attention output in Ulysses head-sharded layout. 

594 seq_dim: Full sequence dimension to split across the CP group. 

595 head_dim: Head dimension to gather across the CP group. 

596 cp_mesh: One-dimensional CP DeviceMesh. 

597 

598 Returns: 

599 Tensor restored to the original local sequence-sharded layout. 

600 """ 

601 return _ulysses_all_to_all( 

602 tensor, 

603 scatter_dim=seq_dim, 

604 gather_dim=head_dim, 

605 cp_mesh=cp_mesh, 

606 ) 

607 

608 

609def _validate_ulysses_head_counts( 

610 query: Tensor, key: Tensor, value: Tensor, 

611 ulysses_degree: int, context: str) -> None: 

612 """Require every Q/K/V head dimension to be shardable by Ulysses.""" 

613 head_counts = { 

614 "query": query.shape[1], 

615 "key": key.shape[1], 

616 "value": value.shape[1], 

617 } 

618 invalid = { 

619 name: count 

620 for name, count in head_counts.items() 

621 if count % ulysses_degree 

622 } 

623 if invalid: 

624 details = ", ".join( 

625 f"{name}_heads={count}" for name, count in invalid.items() 

626 ) 

627 raise ValueError( 

628 f"{context} requires every Q/K/V head count to be divisible by " 

629 f"ulysses_degree ({ulysses_degree}), got {details}" 

630 ) 

631 

632 

633class _AllGatherAlongDim(torch.autograd.Function): 

634 """all-gather along cp_dim + backward reduce-scatter semantics (sum across 

635 ranks, then take this rank's chunk).""" 

636 

637 @staticmethod 

638 def forward( 

639 ctx: Any, 

640 t: Tensor, 

641 cp_dim: int, 

642 group: Any, 

643 cp_size: int, 

644 ) -> Tensor: 

645 """All-gather the tensor along cp_dim in CP-rank order. 

646 

647 Args: 

648 ctx: Autograd context for this collective invocation. 

649 t: Local input shard. 

650 cp_dim: Sequence dimension gathered across ranks. 

651 group: Existing communication group; no group is created here. 

652 cp_size: Number of ranks in the context-parallel group. 

653 

654 Returns: 

655 Tensor assembled in CP-rank order. 

656 """ 

657 ctx.cp_dim = cp_dim 

658 ctx.group = group 

659 ctx.cp_size = cp_size 

660 world_t = [torch.empty_like(t) for _ in range(cp_size)] 

661 dist.all_gather(world_t, t.contiguous(), group=group) 

662 # cat in cp_rank order: [chunk_rank0, chunk_rank1, ...] 

663 return torch.cat(world_t, dim=cp_dim) 

664 

665 @staticmethod 

666 def backward( 

667 ctx: Any, 

668 grad_output: Tensor, 

669 ) -> tuple[Tensor, None, None, None]: 

670 """Sum the gradient across ranks and take this rank's chunk. 

671 

672 Args: 

673 ctx: Autograd context for this collective invocation. 

674 grad_output: Gradient in the forward output layout. 

675 

676 Returns: 

677 This rank's summed gradient and None for metadata. 

678 """ 

679 # reduce-scatter: sum the gradient across ranks, take this rank's chunk 

680 grad = grad_output.contiguous().clone() 

681 dist.all_reduce(grad, group=ctx.group) 

682 rank = dist.get_rank(ctx.group) 

683 local = torch.chunk(grad, ctx.cp_size, dim=ctx.cp_dim)[rank] 

684 return local.contiguous(), None, None, None 

685 

686 

687def flex_cp_allgather( 

688 k: Tensor, 

689 v: Tensor, 

690 cp_dim: int, 

691 cp_mesh: DeviceMesh, 

692) -> tuple[Tensor, Tensor]: 

693 """All-gather K/V along CP dimension for context parallel attention. 

694 

695 Forward: all-gather K/V along cp_dim (each rank ends up holding the full K/V). 

696 Backward: reduce-scatter semantics (gradients summed across ranks, then this 

697 rank's chunk is taken -- implemented explicitly by the _AllGatherAlongDim 

698 autograd.Function, since plain ``dist.all_gather`` has no autograd kernel). 

699 

700 Args: 

701 k, v: [B, N, S_local, H] (cp_dim=2 is the sequence dim). 

702 cp_dim: the gather dimension. 

703 cp_mesh: DeviceMesh of the CP dim. The communication group is taken from 

704 ``cp_mesh.get_group()`` -- already created and cached at DeviceMesh 

705 construction; **dist.new_group must NOT be called here** (otherwise 

706 every forward leaks one process group, and the semantics would be 

707 misaligned). 

708 """ 

709 cp_size = cp_mesh.size() 

710 if cp_size <= 1: 

711 return k, v 

712 group = cp_mesh.get_group() 

713 return (_AllGatherAlongDim.apply(k, cp_dim, group, cp_size), 

714 _AllGatherAlongDim.apply(v, cp_dim, group, cp_size)) 

715 

716 

717def _build_hybrid_cp_submeshes(cp_mesh, ulysses_degree: int): 

718 """Build cached communication submeshes for local-tensor Hybrid CP.""" 

719 if cp_mesh is None or cp_mesh.size() <= 1: 

720 raise ValueError("Hybrid CP requires an active CP mesh") 

721 if isinstance(ulysses_degree, bool) or not isinstance(ulysses_degree, int): 

722 raise TypeError( 

723 "Hybrid CP requires integer ulysses_degree, got " 

724 f"{type(ulysses_degree).__name__}" 

725 ) 

726 cp_size = cp_mesh.size() 

727 if not 1 < ulysses_degree < cp_size: 

728 raise ValueError( 

729 "Hybrid CP requires 1 < ulysses_degree < cp_size, got " 

730 f"ulysses_degree={ulysses_degree}, cp_size={cp_size}" 

731 ) 

732 if cp_size % ulysses_degree: 

733 raise ValueError( 

734 f"cp_size ({cp_size}) must be divisible by ulysses_degree " 

735 f"({ulysses_degree})" 

736 ) 

737 

738 cache_key = (cp_mesh.to_hash(), ulysses_degree) 

739 cached = _HYBRID_MESH_CACHE.get(cache_key) 

740 if cached is not None: 

741 return cached 

742 

743 colossal_degree = cp_size // ulysses_degree 

744 if cp_mesh.ndim == 2: 

745 hybrid_mesh = cp_mesh 

746 elif (cp_mesh.root_mesh is not None 

747 and cp_mesh.mesh_dim_names == ("cp",)): 

748 hybrid_mesh = cp_mesh._unflatten( # pylint: disable=protected-access 

749 "cp", 

750 (colossal_degree, ulysses_degree), 

751 ("colossal", "ulysses"), 

752 ) 

753 else: 

754 ranks = list(cp_mesh.rank_list) 

755 hybrid_mesh = DeviceMesh( 

756 cp_mesh.device_type, 

757 [ 

758 ranks[index * ulysses_degree:(index + 1) * ulysses_degree] 

759 for index in range(colossal_degree) 

760 ], 

761 mesh_dim_names=("colossal", "ulysses"), 

762 ) 

763 dim_names = hybrid_mesh.mesh_dim_names 

764 if not dim_names or len(dim_names) != 2: 

765 raise ValueError("Hybrid CP requires a named two-dimensional submesh") 

766 colossal_mesh = hybrid_mesh[dim_names[0]] 

767 ulysses_mesh = hybrid_mesh[dim_names[1]] 

768 result = (ulysses_mesh, colossal_mesh) 

769 _HYBRID_MESH_CACHE[cache_key] = result 

770 return result 

771 

772 

773def hybrid_cp_attention( 

774 attention_fn: Callable[[Tensor, Tensor, Tensor, dict[str, Any]], Any], 

775 query: Tensor, key: Tensor, value: Tensor, 

776 attention_kwargs: dict[str, Any], cp_mesh: Any, 

777 ulysses_degree: int) -> Any: 

778 """Run local-tensor Hybrid communication around an attention callable. 

779 

780 ``attention_kwargs`` are forwarded unchanged. Mask construction and other 

781 model-input semantics belong to the caller's input-preparation contract. 

782 

783 Args: 

784 attention_fn: Local attention callable consuming exchanged Q/K/V. 

785 query: Query tensor with layout [B,H,T,D]. 

786 key: Key tensor with layout [B,H,T,D]. 

787 value: Value tensor with layout [B,H,T,D]. 

788 attention_kwargs: Model-prepared arguments forwarded to the attention callable. 

789 cp_mesh: Context-parallel mesh owning the communication group. 

790 ulysses_degree: Size of the head-exchange subgroup. 

791 

792 Returns: 

793 Attention output restored to the original local query layout. 

794 """ 

795 _validate_ulysses_head_counts( 

796 query, key, value, ulysses_degree, "Hybrid CP" 

797 ) 

798 ulysses_mesh, colossal_mesh = ( 

799 _build_hybrid_cp_submeshes(cp_mesh, ulysses_degree) 

800 ) 

801 local_shape = tuple(query.shape) 

802 query, key, value = ( 

803 ulysses_seq_to_head(tensor, 2, 1, ulysses_mesh) 

804 for tensor in (query, key, value) 

805 ) 

806 key, value = flex_cp_allgather(key, value, 2, colossal_mesh) 

807 output = attention_fn(query, key, value, attention_kwargs) 

808 output = ulysses_head_to_seq(output, 2, 1, ulysses_mesh) 

809 if tuple(output.shape) != local_shape: 

810 raise RuntimeError( 

811 f"Hybrid CP output shape {tuple(output.shape)} does not restore " 

812 f"the local query shape {local_shape}" 

813 ) 

814 return output 

815 

816 

817 

818def exchange_sequence_heads( 

819 tensor: torch.Tensor, 

820 device_mesh: DeviceMesh, 

821 *, 

822 split_dim: int, 

823 concat_dim: int, 

824) -> torch.Tensor: 

825 """Redistribute a local tensor from concat-dim shard to split-dim shard. 

826 

827 Args: 

828 tensor: Tensor to reshape or redistribute without changing token order. 

829 device_mesh: Device mesh used for sequence/head redistribution. 

830 split_dim: Tensor dimension divided across the participating ranks. 

831 concat_dim: Tensor dimension assembled from the participating ranks. 

832 """ 

833 split_count = device_mesh.size() 

834 if split_count == 1: 

835 return tensor 

836 

837 original_shape = tuple(tensor.shape) 

838 if original_shape[split_dim] % split_count != 0: 

839 raise ValueError( 

840 f"Linear-attention all-to-all split dimension {split_dim} with size " 

841 f"{original_shape[split_dim]} must be divisible by cp_size " 

842 f"{split_count}." 

843 ) 

844 split_size = original_shape[split_dim] // split_count 

845 final_shape = list(original_shape) 

846 final_shape[split_dim] = split_size 

847 final_shape[concat_dim] *= split_count 

848 

849 reshape_dims = list(original_shape) 

850 reshape_dims[split_dim] = split_count 

851 reshape_dims.insert(split_dim + 1, split_size) 

852 permutation = list(range(len(reshape_dims))) 

853 permutation.remove(split_dim) 

854 permutation.insert(0, split_dim) 

855 all_to_all_input = tensor.reshape(reshape_dims).permute(permutation).contiguous() 

856 all_to_all_input = all_to_all_input.flatten(0, 1) 

857 

858 split_length = all_to_all_input.shape[0] // split_count 

859 splits = [split_length] * split_count 

860 output = communication.differentiable_all_to_all_single( 

861 all_to_all_input, 

862 splits, 

863 splits, 

864 group=device_mesh.get_group(), 

865 ) 

866 

867 output_reshape = list(output.shape) 

868 output_reshape[0] = split_count 

869 output_reshape.insert(1, output.shape[0] // split_count) 

870 permutation = list(range(len(output_reshape))) 

871 rank_dimension = permutation.pop(0) 

872 permutation.insert(concat_dim, rank_dimension) 

873 output = output.reshape(output_reshape).permute(permutation).contiguous() 

874 

875 output_shape = list(output.shape) 

876 output_shape[concat_dim] *= output_shape[concat_dim + 1] 

877 output_shape.pop(concat_dim + 1) 

878 return output.reshape(output_shape).view(final_shape)