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

72 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"""Paired Ulysses input transfers shared by attention modules. 

16 

17Inputs use [batch, local_sequence, heads, head_dim] and are exchanged into 

18[batch, global_sequence, local_heads, head_dim]. Every forward or checkpoint 

19replay owns separate state; handles and buffers must not be shared across calls. 

20 

21Paired launch/wait nodes require a complete first-order training backward. 

22Partial autograd.grad calls can prune the consumer and are not supported. 

23Model projections, rotary math and parameter management remain caller-owned. 

24""" 

25 

26from __future__ import annotations 

27 

28from dataclasses import dataclass 

29from typing import Any 

30 

31import torch 

32from torch.autograd.function import once_differentiable 

33 

34from hyper_parallel.distributed.context_parallel.collectives import ( 

35 AsyncCPCollective, async_ulysses_seq_to_head_launch, 

36) 

37 

38 

39@dataclass 

40class UlyssesInputA2AState: 

41 """Own one input A2A and its inverse for a single forward invocation. 

42 

43 Attributes: 

44 mesh: Ulysses device mesh. 

45 forward_a2a_handle: Q/K/V transfer from token-local to head-local layout. 

46 backward_a2a_handle: Gradient transfer from head-local to token-local layout. 

47 needs_send_grad: Whether the original input requires its inverse transfer. 

48 

49 Each handle owns the communication work and its buffers. The paired consumer 

50 waits for it exactly once before reading the result, then clears the field. 

51 This shared state passes directly between autograd nodes, not through the 

52 managed projection's forward arguments and FSDP input conversion. 

53 """ 

54 

55 mesh: Any 

56 forward_a2a_handle: AsyncCPCollective | None = None 

57 backward_a2a_handle: AsyncCPCollective | None = None 

58 needs_send_grad: bool = False 

59 

60 

61class _InputA2ALaunch(torch.autograd.Function): 

62 """Keep independent native compute between a send and its gradient wait.""" 

63 

64 @staticmethod 

65 def forward(ctx: Any, send_tensor: torch.Tensor, compute_input: torch.Tensor, 

66 state: UlyssesInputA2AState) -> torch.Tensor: 

67 """Launch token-to-head A2A and attach the intervening compute edge. 

68 

69 Args: 

70 ctx: Autograd context holding this invocation's A2A state. 

71 send_tensor: Token-local tensor ready for communication. 

72 compute_input: Input of the independent projection branch. 

73 state: Forward and backward handles shared with the paired wait. 

74 

75 Returns: 

76 A view of compute_input retaining both gradient dependencies. 

77 """ 

78 ctx.state = state 

79 state.needs_send_grad = ctx.needs_input_grad[0] 

80 state.forward_a2a_handle = async_ulysses_seq_to_head_launch(send_tensor, 1, 2, state.mesh) 

81 # Pass through the value without a copy while the paired nodes bracket 

82 # the independent projection's native backward graph. 

83 return compute_input.view_as(compute_input) 

84 

85 @staticmethod 

86 @once_differentiable 

87 def backward(ctx: Any, compute_gradient: torch.Tensor) -> tuple: 

88 """Consume the inverse A2A after the independent branch backward. 

89 

90 Args: 

91 ctx: Autograd context containing the paired A2A state. 

92 compute_gradient: Gradient returned by the independent branch. 

93 

94 Returns: 

95 Exchanged source gradient, compute gradient and no state gradient. 

96 """ 

97 state = ctx.state 

98 send_gradient = None 

99 if state.needs_send_grad: 

100 if state.backward_a2a_handle is None: 

101 raise RuntimeError("Ulysses input consumer did not submit its inverse A2A") 

102 send_gradient = state.backward_a2a_handle.wait() 

103 state.backward_a2a_handle = None 

104 return send_gradient, compute_gradient, None 

105 

106 

107@dataclass 

108class UlyssesQKVA2AState: 

109 """Own the Q/K/V transfers for one Ulysses forward invocation.""" 

110 

111 query: UlyssesInputA2AState 

112 key: UlyssesInputA2AState 

113 value: UlyssesInputA2AState 

114 

115 def wait(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

116 """Consume Q/K/V in attention order after all forward work is submitted.""" 

117 results = [] 

118 for a2a_state in (self.query, self.key, self.value): 

119 results.append(a2a_state.forward_a2a_handle.wait()) 

120 a2a_state.forward_a2a_handle = None 

121 return results[0], results[1], results[2] 

122 

123 def launch_backward(self, grad_query: torch.Tensor, grad_key: torch.Tensor, 

124 grad_value: torch.Tensor) -> None: 

125 """Submit each required inverse before releasing the independent compute. 

126 

127 Args: 

128 grad_query: Head-local query gradient from attention. 

129 grad_key: Head-local key gradient from attention. 

130 grad_value: Head-local value gradient from attention. 

131 """ 

132 for a2a_state, gradient in ((self.query, grad_query), (self.key, grad_key), (self.value, grad_value)): 

133 if a2a_state.needs_send_grad: 

134 a2a_state.backward_a2a_handle = async_ulysses_seq_to_head_launch(gradient, 2, 1, a2a_state.mesh) 

135 

136 

137class _QKVInputA2AWait(torch.autograd.Function): 

138 """Finish Q/K/V inputs and release Q backward before waiting for K/V.""" 

139 

140 @staticmethod 

141 def forward(ctx: Any, query: torch.Tensor, state: UlyssesQKVA2AState) -> tuple: 

142 """Submit Q after the shared V/K launches, then consume all three inputs. 

143 

144 Args: 

145 ctx: Autograd context holding the three input transfers. 

146 query: Final token-local query, with no following gate computation. 

147 state: Per-forward Q/K/V communication state. 

148 

149 Returns: 

150 Completed attention inputs in query, key, value order. 

151 """ 

152 ctx.state = state 

153 state.query.needs_send_grad = ctx.needs_input_grad[0] 

154 state.query.forward_a2a_handle = async_ulysses_seq_to_head_launch(query, 1, 2, state.query.mesh) 

155 return state.wait() 

156 

157 @staticmethod 

158 @once_differentiable 

159 def backward(ctx: Any, grad_query: torch.Tensor, grad_key: torch.Tensor, 

160 grad_value: torch.Tensor) -> tuple: 

161 """Submit dQ/dK/dV and release Q backward after dQ has arrived. 

162 

163 Args: 

164 ctx: Autograd context holding the three paired input transfers. 

165 grad_query: Attention gradient for head-local queries. 

166 grad_key: Attention gradient for head-local keys. 

167 grad_value: Attention gradient for head-local values. 

168 

169 Returns: 

170 Token-local Q gradient and no communication-state gradient. 

171 """ 

172 state = ctx.state 

173 state.launch_backward(grad_query, grad_key, grad_value) 

174 query_gradient = None 

175 if state.query.needs_send_grad: 

176 query_gradient = state.query.backward_a2a_handle.wait() 

177 state.query.backward_a2a_handle = None 

178 return query_gradient, None 

179 

180 

181def launch_input_a2a(send_tensor: torch.Tensor, compute_input: torch.Tensor, 

182 a2a_state: UlyssesInputA2AState, *, overlap_backward: bool = False) -> torch.Tensor: 

183 """Submit an input A2A with either native or paired collective backward. 

184 

185 Args: 

186 send_tensor: Final token-local Q, K or V ready to send. 

187 compute_input: Input of the independent branch to execute next. 

188 a2a_state: State receiving this forward communication handle. 

189 overlap_backward: Attach a paired gradient dependency. The caller must 

190 finish these inputs with the matching paired wait and execute a 

191 complete first-order backward, as in ``finish_qkv_inputs``. 

192 

193 Returns: 

194 compute_input, with the paired dependency when requested. 

195 """ 

196 if overlap_backward: 

197 return _InputA2ALaunch.apply(send_tensor, compute_input, a2a_state) 

198 a2a_state.forward_a2a_handle = async_ulysses_seq_to_head_launch(send_tensor, 1, 2, a2a_state.mesh) 

199 return compute_input 

200 

201 

202def finish_qkv_inputs(query: torch.Tensor, state: UlyssesQKVA2AState, 

203 overlap_backward: bool) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

204 """Finish Q/K/V inputs using paired or native collective gradients. 

205 

206 Args: 

207 query: Final token-local query, after V and K have been submitted. 

208 state: This invocation's Q/K/V communication state. 

209 overlap_backward: Pair input autograd nodes for the pure-Ulysses backward. 

210 

211 Returns: 

212 Completed query, key and value tensors in head-local layout. 

213 """ 

214 if overlap_backward: 

215 return _QKVInputA2AWait.apply(query, state) 

216 state.query.forward_a2a_handle = async_ulysses_seq_to_head_launch(query, 1, 2, state.query.mesh) 

217 return state.wait()