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

36 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"""Reusable sequence transport over an existing HyperParallel CP mesh.""" 

16 

17from __future__ import annotations 

18 

19from typing import Any 

20 

21from torch import Tensor 

22 

23from hyper_parallel.distributed.context_parallel.collectives import ( 

24 AsyncCPCollective, _build_hybrid_cp_submeshes, async_cp_allgather_launch, 

25 async_ulysses_seq_to_head_launch, ulysses_head_to_seq, ulysses_seq_to_head, 

26) 

27from hyper_parallel.distributed.context_parallel.cp_types import PendingSequence, SequencePartition 

28 

29 

30class CPContext: 

31 """Transport only: model families retain projection, mask and attention math.""" 

32 

33 def __init__(self, mesh: Any) -> None: 

34 """Borrow a one-dimensional CP mesh without creating process groups.""" 

35 if mesh is None or getattr(mesh, "ndim", 1) != 1: 

36 raise ValueError("CPContext requires an existing one-dimensional HP mesh") 

37 self.mesh = mesh 

38 self.size = mesh.size() 

39 self.rank = mesh.get_local_rank() 

40 

41 def partition(self, local_length: int) -> SequencePartition: 

42 """Describe equal contiguous source shards without reading activations. 

43 

44 Args: 

45 local_length: Sequence length on each rank of the CP group. 

46 """ 

47 if local_length < 0: 

48 raise ValueError("local sequence length cannot be negative") 

49 return SequencePartition((local_length,) * self.size, self.rank) 

50 

51 def launch_gather_sequence(self, tensor: Tensor, *, dim: int = 1) -> PendingSequence: 

52 """Launch differentiable sequence gathering with explicit readiness. 

53 

54 Args: 

55 tensor: Local activation shard, with equal lengths on all CP ranks. 

56 dim: Sequence dimension; rank order defines global token coordinates. 

57 """ 

58 partition = self.partition(tensor.shape[dim]) 

59 return PendingSequence(async_cp_allgather_launch(tensor, dim, self.mesh), partition) 

60 

61 def gather_sequence(self, tensor: Tensor, *, dim: int = 1) -> tuple[Tensor, SequencePartition]: 

62 """Gather and wait synchronously; backward sums consumers into source shards. 

63 

64 Args: 

65 tensor: Local sequence shard. 

66 dim: Sequence dimension. 

67 """ 

68 return self.launch_gather_sequence(tensor, dim=dim).wait() 

69 

70 def sequence_to_head(self, tensor: Tensor, *, seq_dim: int = 1, head_dim: int = 2) -> Tensor: 

71 """Exchange sequence-sharded activations into head-sharded activations. 

72 

73 Args: 

74 tensor: Local sequence shard with divisible head count. 

75 seq_dim: Sequence dimension. 

76 head_dim: Head dimension. 

77 """ 

78 return ulysses_seq_to_head(tensor, seq_dim=seq_dim, head_dim=head_dim, cp_mesh=self.mesh) 

79 

80 def head_to_sequence(self, tensor: Tensor, *, seq_dim: int = 1, head_dim: int = 2) -> Tensor: 

81 """Apply the inverse head-to-sequence exchange. 

82 

83 Args: 

84 tensor: Local head shard with divisible sequence length. 

85 seq_dim: Sequence dimension. 

86 head_dim: Head dimension. 

87 """ 

88 return ulysses_head_to_seq(tensor, seq_dim=seq_dim, head_dim=head_dim, cp_mesh=self.mesh) 

89 

90 def launch_sequence_to_head(self, tensor: Tensor, *, seq_dim: int = 1, 

91 head_dim: int = 2) -> AsyncCPCollective: 

92 """Launch the existing differentiable A2A; wait before consuming its output. 

93 

94 Args: 

95 tensor: Input in sequence-partitioned layout. 

96 seq_dim: Sequence axis. 

97 head_dim: Head axis. 

98 """ 

99 return async_ulysses_seq_to_head_launch(tensor, seq_dim, head_dim, self.mesh) 

100 

101 def launch_head_to_sequence(self, tensor: Tensor, *, seq_dim: int = 1, 

102 head_dim: int = 2) -> AsyncCPCollective: 

103 """Launch the inverse A2A without changing its existing autograd contract. 

104 

105 Args: 

106 tensor: Input in head-partitioned layout. 

107 seq_dim: Sequence axis. 

108 head_dim: Head axis. 

109 """ 

110 return async_ulysses_seq_to_head_launch(tensor, head_dim, seq_dim, self.mesh) 

111 

112 def split(self, ulysses_degree: int) -> tuple[CPContext, CPContext]: 

113 """Borrow cached Ulysses/query-owner submeshes at bind time, never in forward. 

114 

115 Args: 

116 ulysses_degree: Number of CP ranks partitioning attention heads. 

117 """ 

118 if ulysses_degree < 1 or self.size % ulysses_degree: 

119 raise ValueError("Ulysses degree must divide the CP mesh size") 

120 if ulysses_degree in (1, self.size): 

121 return self, self 

122 heads, queries = _build_hybrid_cp_submeshes(self.mesh, ulysses_degree) 

123 return CPContext(heads), CPContext(queries)