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

118 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"""Async context parallel styles for DeepSeek Sparse Attention (DSA).""" 

16from typing import Any, Optional 

17 

18from hyper_parallel.core.context_parallel.async_context_parallel import ( 

19 _allgather_reconstruct, 

20 _launch_async_allgather_seq, 

21 _make_async_cp_slot, 

22 _slot_comm, 

23 _wrap_async_cp_result, 

24) 

25from hyper_parallel.core.context_parallel.context_parallel import _ensure_1d, _localize_foreign_dtensor 

26from hyper_parallel.core.context_parallel.dsa_context_parallel import ( 

27 DSAIndexerContextParallel, 

28 DSAIndexerLossContextParallel, 

29 DSASparseAttentionContextParallel, 

30 _apply_sparse_attention_boundary, 

31 _is_tensor_or_dtensor, 

32 _to_sequence_replicate, 

33) 

34from hyper_parallel.core.dtensor.device_mesh import DeviceMesh 

35from hyper_parallel.core.dtensor.dtensor import DTensor 

36from hyper_parallel.core.dtensor.placement_types import Replicate 

37from hyper_parallel.core.context_parallel import utils 

38from hyper_parallel.core.context_parallel.utils import Module 

39 

40 

41 

42class _AsyncSequenceReplicateSlot: 

43 """Per-boundary async sequence-replicate state. 

44 

45 Producer hooks append pre-launched all-gather handles here. Consumer 

46 pre-hooks pop and wait on them. If no producer hook ran, the consumer falls 

47 back to the synchronous sequence-gather path so async DSA styles remain 

48 compatible with the synchronous DSA module shape. 

49 """ 

50 

51 def __init__(self, device_mesh: DeviceMesh, seq_dim: int) -> None: 

52 self.device_mesh = device_mesh 

53 self.seq_dim = seq_dim 

54 self.world_size = device_mesh.mesh.numel() 

55 self.group = device_mesh.get_group() if self.world_size > 1 else None 

56 self._slots = {} 

57 self._bwd_slots = {} 

58 

59 def reset_after_device_restart(self) -> None: 

60 """Drop failed queues after communication has quiesced, preserving hook references.""" 

61 for slots in self._slots.values(): 

62 slots.clear() 

63 for slots in self._bwd_slots.values(): 

64 slots.clear() 

65 

66 @staticmethod 

67 def _extract_tensor_output(output: Any) -> Any: 

68 if _is_tensor_or_dtensor(output): 

69 return output 

70 if isinstance(output, (tuple, list)) and len(output) == 1 and _is_tensor_or_dtensor(output[0]): 

71 return output[0] 

72 return None 

73 

74 def _local_tensor(self, value: Any) -> Any: 

75 value = _localize_foreign_dtensor(value, self.device_mesh, self.seq_dim) 

76 return value.to_local() if isinstance(value, DTensor) else value 

77 

78 def _make_slot(self, value: Any, local: Any, work, out_perm) -> dict: 

79 """Create an async sequence-replicate slot with layout metadata.""" 

80 slot = _make_async_cp_slot( 

81 work, 

82 out_perm, 

83 value, 

84 self.device_mesh, 

85 (Replicate(),), 

86 self.seq_dim, 

87 ) 

88 slot["local"] = local 

89 return slot 

90 

91 def _wrap_gathered(self, gathered: Any, slot) -> Any: 

92 return _wrap_async_cp_result(gathered, slot, self.device_mesh, (Replicate(),)) 

93 

94 def register_launch_hook(self, module: Optional[Module], slot_name: str) -> None: 

95 """Register a producer-side launch hook when a handoff module exists.""" 

96 if module is None: 

97 return 

98 bwd_slot = self._bwd_slots.setdefault(slot_name, []) 

99 

100 def _post_hook(hook_module, hook_inputs, output): 

101 del hook_module, hook_inputs 

102 tensor = self._extract_tensor_output(output) 

103 if tensor is not None: 

104 self.launch(slot_name, tensor) 

105 return output 

106 

107 def _backward_pre_hook(hook_module, grad_output): 

108 del hook_module 

109 return self._producer_bwd_pre_hook(grad_output, bwd_slot) 

110 

111 module.register_forward_hook(_post_hook) 

112 utils.register_full_backward_pre_hook(module, _backward_pre_hook) 

113 

114 def _producer_bwd_pre_hook(self, grad_output: Any, bwd_slot: list) -> Any: 

115 """Wait deferred reduce-scatter before gradients cross the producer boundary.""" 

116 if not bwd_slot: 

117 return grad_output 

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

119 work.wait() 

120 d_local = _allgather_reconstruct(out_perm, gather_dim) 

121 if isinstance(grad_output, tuple): 

122 return (d_local,) + grad_output[1:] 

123 return (d_local,) 

124 

125 def launch(self, slot_name: str, value: Any) -> None: 

126 """Launch all-gather for ``value`` and enqueue its handle.""" 

127 if not _is_tensor_or_dtensor(value): 

128 return 

129 local = self._local_tensor(value) 

130 if not utils.is_tensor(local): 

131 return 

132 if self.world_size <= 1: 

133 self._slots.setdefault(slot_name, []).append(self._make_slot(value, local, None, None)) 

134 return 

135 work, out_perm = _launch_async_allgather_seq(local, self.group, self.world_size, self.seq_dim) 

136 self._slots.setdefault(slot_name, []).append(self._make_slot(value, local, work, out_perm)) 

137 

138 def wait(self, slot_name: str, value: Any) -> Any: 

139 """Wait on a pre-launched gather, or fall back to consumer-local launch.""" 

140 if not _is_tensor_or_dtensor(value): 

141 return value 

142 slot = self._slots.get(slot_name) 

143 if slot: 

144 item = slot.pop(0) 

145 if isinstance(item, dict): 

146 local = item["local"] 

147 work, out_perm = _slot_comm(item) 

148 else: 

149 local, work, out_perm = item 

150 if work is None: 

151 return self._wrap_gathered(local, item) 

152 graph_local = self._local_tensor(value) 

153 if not utils.is_tensor(graph_local): 

154 graph_local = local 

155 gathered = utils.differentiable_async_allgather_wait( 

156 graph_local, 

157 work, 

158 out_perm, 

159 self.group, 

160 self.world_size, 

161 self.seq_dim, 

162 self._bwd_slots.setdefault(slot_name, []), 

163 ) 

164 return self._wrap_gathered(gathered, item) 

165 return _to_sequence_replicate(value, self.device_mesh, self.seq_dim) 

166 

167 

168class AsyncDSAIndexerContextParallel(DSAIndexerContextParallel): 

169 """Async-first DSA indexer CP. 

170 

171 When ``key_handoff`` is provided, its forward hook launches key-side 

172 all-gather and the indexer boundary pre-hook waits on it. Without a 

173 handoff, this style falls back to the synchronous key-side gather. 

174 """ 

175 

176 def apply(self, module: Module, device_mesh: DeviceMesh, *, key_handoff: Optional[Module] = None) -> Module: 

177 """Register async DSA indexer CP hooks on ``module`` and optional producer.""" 

178 cp_mesh = _ensure_1d(device_mesh) 

179 async_state = _AsyncSequenceReplicateSlot(cp_mesh, self.seq_dim) 

180 setattr(module, "_context_parallel_async_state", async_state) 

181 async_state.register_launch_hook(key_handoff, "key") 

182 specs = self._build_specs( 

183 cp_mesh, 

184 key_fn=lambda value: async_state.wait("key", value), 

185 ) 

186 return self._apply_with_specs(module, specs, cp_mesh) 

187 

188 

189class AsyncDSASparseAttentionContextParallel(DSASparseAttentionContextParallel): 

190 """Async-first DSA sparse-attention CP.""" 

191 

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

193 self, 

194 module: Module, 

195 device_mesh: DeviceMesh, 

196 *, 

197 key_handoff: Optional[Module] = None, 

198 value_handoff: Optional[Module] = None, 

199 key_rope_handoff: Optional[Module] = None, 

200 ) -> Module: 

201 """Register async DSA sparse-attention CP hooks on ``module`` and producers.""" 

202 cp_mesh = _ensure_1d(device_mesh) 

203 async_state = _AsyncSequenceReplicateSlot(cp_mesh, self.seq_dim) 

204 setattr(module, "_context_parallel_async_state", async_state) 

205 async_state.register_launch_hook(key_handoff, "key") 

206 async_state.register_launch_hook(value_handoff, "value") 

207 async_state.register_launch_hook(key_rope_handoff, "key_rope") 

208 return _apply_sparse_attention_boundary(self, module, device_mesh, async_state=async_state) 

209 

210 

211class AsyncDSAIndexerLossContextParallel(DSAIndexerLossContextParallel): 

212 """Async-first DSA indexer-loss CP.""" 

213 

214 def apply( # pylint: disable=arguments-differ,too-many-arguments 

215 self, 

216 module: Module, 

217 device_mesh: DeviceMesh, 

218 *, 

219 key_handoff: Optional[Module] = None, 

220 key_indexer_handoff: Optional[Module] = None, 

221 key_rope_handoff: Optional[Module] = None, 

222 ) -> Module: 

223 """Register async DSA indexer-loss CP hooks on ``module`` and producers.""" 

224 cp_mesh = _ensure_1d(device_mesh) 

225 async_state = _AsyncSequenceReplicateSlot(cp_mesh, self.seq_dim) 

226 setattr(module, "_context_parallel_async_state", async_state) 

227 async_state.register_launch_hook(key_handoff, "key") 

228 async_state.register_launch_hook(key_indexer_handoff, "key_indexer") 

229 async_state.register_launch_hook(key_rope_handoff, "key_rope") 

230 specs = self._build_loss_specs( 

231 cp_mesh, 

232 replicate_fn_map={ 

233 "key": lambda value: async_state.wait("key", value), 

234 "key_indexer": lambda value: async_state.wait("key_indexer", value), 

235 "key_rope": lambda value: async_state.wait("key_rope", value), 

236 }, 

237 ) 

238 return self._apply_with_loss_specs(module, specs, self._get_local_idx(cp_mesh), cp_mesh)