Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / functional / mhc_pre.py: 84%

63 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"""Manifold hyper-connection pre-processing functions.""" 

16 

17import importlib 

18from typing import Any, Optional, Tuple 

19 

20import torch 

21 

22from hyper_parallel.components.functional.sinkhorn import sinkhorn 

23from hyper_parallel.tools.logging import get_logger 

24 

25logger = get_logger() 

26 

27 

28def _mhc_pre_backward(ctx, dh_in, dh_post, dh_res, dh_x): 

29 """Invoke the legacy omni MHC gradient operator with the saved forward state.""" 

30 x, phi, alpha, gamma, h_post, inv_rms, h_mix, h_pre = ctx.saved_tensors 

31 return torch.ops.custom.npu_manifold_constrained_hyper_connection_pre_grad( 

32 x, phi, alpha, dh_in, dh_post, dh_res, inv_rms, h_mix, h_pre, h_post, 

33 gamma=gamma, 

34 hc_eps=ctx.hc_eps, 

35 grad_x_post=dh_x, 

36 ) 

37 

38 

39class _MhcPre(torch.autograd.Function): 

40 """Autograd bridge for the legacy omni NPU MHC pre operator.""" 

41 

42 @staticmethod 

43 def forward( 

44 ctx: Any, 

45 x: torch.Tensor, 

46 phi: torch.Tensor, 

47 alpha: torch.Tensor, 

48 bias: torch.Tensor, 

49 gamma: Optional[torch.Tensor] = None, 

50 out_flag: bool = True, 

51 norm_eps: float = 1e-6, 

52 hc_eps: float = 1e-6, 

53 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: 

54 """Run the legacy omni NPU MHC pre forward operator.""" 

55 # The package is optional and is needed only for the legacy omni backend. 

56 # pylint: disable=import-outside-toplevel 

57 try: 

58 import omni_training_custom_ops # noqa: F401 # pylint: disable=unused-import 

59 except ImportError as error: 

60 raise ImportError("MHC backend='omni' requires omni_training_custom_ops") from error 

61 # pylint: enable=import-outside-toplevel 

62 hin, h_post, h_comb_before, inv_rms, h_mix, h_pre = ( 

63 torch.ops.custom.npu_manifold_constrained_hyper_connection_pre( 

64 x, 

65 phi, 

66 alpha, 

67 bias, 

68 gamma=gamma, 

69 out_flag=out_flag, 

70 norm_eps=norm_eps, 

71 hc_eps=hc_eps, 

72 ) 

73 ) 

74 ctx.save_for_backward(x, phi, alpha, gamma, h_post, inv_rms, h_mix, h_pre) 

75 ctx.hc_eps = hc_eps 

76 ctx.has_gamma = gamma is not None 

77 return hin, h_pre, h_post, h_comb_before, x 

78 

79 @staticmethod 

80 def backward( 

81 ctx: Any, 

82 dh_in: torch.Tensor, 

83 dh_pre: torch.Tensor, 

84 dh_post: torch.Tensor, 

85 dh_res: torch.Tensor, 

86 dh_x: torch.Tensor, 

87 ) -> tuple: 

88 """Run the legacy omni NPU MHC pre backward operator.""" 

89 del dh_pre 

90 dx, dphi, dalpha, dbias, dgamma = _mhc_pre_backward(ctx, dh_in, dh_post, dh_res, dh_x) 

91 if not ctx.has_gamma: 

92 dgamma = None 

93 grads = [dx, dphi, dalpha, dbias, dgamma, None, None, None] 

94 return tuple(grads) 

95 

96 

97class _CannMhcPre(torch.autograd.Function): 

98 """Autograd bridge routing CANN mhc_pre_sinkhorn through the PyTorch dispatcher.""" 

99 

100 @staticmethod 

101 def forward( 

102 ctx: Any, 

103 x: torch.Tensor, 

104 phi: torch.Tensor, 

105 alpha: torch.Tensor, 

106 bias: torch.Tensor, 

107 num_stream: int, 

108 sinkhorn_iters: int, 

109 hc_eps: float, 

110 norm_eps: float, 

111 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

112 """Invoke the registered CANN mhc_pre_sinkhorn dispatcher op.""" 

113 # Keep the optional CANN extension out of CPU/non-CANN imports. 

114 importlib.import_module("cann_ops_transformer.ops.mhc_pre_sinkhorn") 

115 

116 hin, h_post, h_res, h_pre, hc_before_norm, inv_rms, sum_out, norm_out = ( 

117 torch.ops.cann_ops_transformer.mhc_pre_sinkhorn( 

118 x, phi, alpha, bias, num_stream, sinkhorn_iters, hc_eps, norm_eps, True 

119 ) 

120 ) 

121 ctx.save_for_backward( 

122 x, phi, alpha, bias, h_pre, hc_before_norm, inv_rms, sum_out, norm_out 

123 ) 

124 ctx.hc_eps = hc_eps 

125 return hin, h_post, h_res 

126 

127 @staticmethod 

128 def backward( 

129 ctx: Any, 

130 grad_hin: torch.Tensor, 

131 grad_h_post: torch.Tensor, 

132 grad_h_res: torch.Tensor, 

133 ) -> tuple: 

134 """Invoke the registered CANN mhc_pre_sinkhorn_backward dispatcher op.""" 

135 # Keep the optional CANN extension out of CPU/non-CANN imports. 

136 importlib.import_module("cann_ops_transformer.ops.mhc_pre_sinkhorn_backward") 

137 

138 x, phi, alpha, bias, h_pre, hc_before_norm, inv_rms, sum_out, norm_out = ( 

139 ctx.saved_tensors 

140 ) 

141 grad_x, grad_phi, grad_alpha, grad_bias = ( 

142 torch.ops.cann_ops_transformer.mhc_pre_sinkhorn_backward( 

143 grad_hin, 

144 grad_h_post, 

145 grad_h_res, 

146 x, 

147 phi, 

148 alpha, 

149 bias, 

150 h_pre, 

151 hc_before_norm, 

152 inv_rms, 

153 sum_out, 

154 norm_out, 

155 ctx.hc_eps, 

156 ) 

157 ) 

158 return grad_x, grad_phi, grad_alpha, grad_bias, None, None, None, None 

159 

160 

161def _cann_mhc_pre( 

162 x: torch.Tensor, 

163 phi: torch.Tensor, 

164 alpha: torch.Tensor, 

165 bias: torch.Tensor, 

166 num_stream: int, 

167 sinkhorn_iters: int, 

168 norm_eps: float, 

169 hc_eps: float, 

170 gamma: Optional[torch.Tensor], 

171) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

172 """Run the fused ops-transformer MHC pre and Sinkhorn operator. 

173 

174 The CANN operator has no RMS-scale input, so an optional gamma is folded 

175 into the projection as a differentiable ``phi * gamma`` product; autograd 

176 then keeps the phi and gamma gradients exact. 

177 """ 

178 if gamma is not None: 

179 phi = phi * gamma.reshape(1, -1).to(phi.dtype) 

180 hin, h_post, h_res = _CannMhcPre.apply( 

181 x, phi, alpha, bias, num_stream, sinkhorn_iters, hc_eps, norm_eps 

182 ) 

183 # The operator returns the flattened [.., N*N] residual matrix while the 

184 # shared post path consumes the square [.., N, N] layout. 

185 return hin, h_post, h_res.reshape(*h_res.shape[:-1], num_stream, num_stream) 

186 

187 

188def mhc_pre( 

189 x: torch.Tensor, 

190 phi: torch.Tensor, 

191 branch_alpha: torch.Tensor, 

192 branch_beta: torch.Tensor, 

193 num_stream: int, 

194 sinkhorn_iters: int = 20, 

195 norm_eps: float = 1e-6, 

196 hc_eps: float = 1e-6, 

197 gamma: Optional[torch.Tensor] = None, 

198 *, 

199 backend: str = "cann", 

200) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: 

201 """Prepare an input and its mixing coefficients for an MHC-wrapped block. 

202 

203 Args: 

204 x: Flattened residual streams. 

205 phi: MHC projection weight. 

206 branch_alpha: Learned scale for each coefficient group. 

207 branch_beta: Learned bias for each coefficient group. 

208 num_stream: Number of residual streams. 

209 sinkhorn_iters: Number of Sinkhorn iterations. 

210 norm_eps: RMS normalization epsilon. 

211 hc_eps: Hyper-connection numerical stability epsilon. 

212 gamma: Optional RMS normalization scale. 

213 backend: ``"cann"`` (default) calls the CANN ops-transformer 

214 ``mhc_pre_sinkhorn`` operator; the legacy ``"omni"`` backend is 

215 deprecated. CANN constraints: fp32 phi/alpha/beta, fp16/bf16 

216 ``x`` with a 128-aligned tail axis, and fixed N=4 streams with 20 

217 Sinkhorn iterations on Atlas A2/A3 series. 

218 

219 Returns: 

220 Block input, post coefficients, residual coefficients, and residual buffer. 

221 """ 

222 if backend not in ("cann", "omni"): 

223 raise ValueError(f"backend must be 'cann' or 'omni', got {backend!r}") 

224 shape = x.size() 

225 x = x.reshape(shape[0], shape[1], num_stream, -1) 

226 if gamma is not None: 

227 gamma = gamma.reshape(num_stream, -1).float() 

228 if backend == "cann": 

229 hin, h_post, h_res = _cann_mhc_pre( 

230 x, 

231 phi.float(), 

232 branch_alpha.float(), 

233 branch_beta.float(), 

234 num_stream, 

235 sinkhorn_iters, 

236 norm_eps, 

237 hc_eps, 

238 gamma, 

239 ) 

240 return hin, h_post, h_res, x.reshape(shape[0], shape[1], -1) 

241 logger.warning( 

242 "mhc_pre backend='omni' is deprecated and will be removed in a future release; " 

243 "use backend='cann'." 

244 ) 

245 y, _, h_post, h_comb_before, residual = _MhcPre.apply( 

246 x, 

247 phi.float(), 

248 branch_alpha.float(), 

249 branch_beta.float(), 

250 gamma, 

251 True, 

252 norm_eps, 

253 hc_eps, 

254 ) 

255 h_res = sinkhorn(h_comb_before, sinkhorn_iters, hc_eps) 

256 residual = residual.reshape(shape[0], shape[1], -1) 

257 return y, h_post, h_res, residual