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

125 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"""Local GDN math, state application and explicit backend selection.""" 

16from __future__ import annotations 

17import importlib 

18import importlib.metadata 

19import importlib.util 

20import re 

21from typing import Optional 

22 

23import torch 

24from torch.nn import functional as F 

25 

26from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import packed_eager 

27from .gated_delta_net_ascendc import chunk_gated_delta_rule_ascendc 

28 

29 

30def _l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-6) -> torch.Tensor: 

31 """L2-normalize along ``dim``.""" 

32 # ``(x * x).sum`` (MulBackward) instead of ``x.pow(2).sum`` (PowBackward): 

33 # equal math, NPU yields ULP-different gradients across the two ops. 

34 # NPU autocast promotes the reduction; the native core still consumes x.dtype. 

35 return (x * torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)).to(x.dtype) 

36 

37 

38def torch_chunk_gated_delta_rule( 

39 query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, 

40 g: torch.Tensor, beta: torch.Tensor, 

41 chunk_size: int = 64, 

42 initial_state: Optional[torch.Tensor] = None, 

43 output_final_state: bool = False, 

44 normalize_qk: bool = False, 

45 cu_seqlens: Optional[torch.Tensor] = None, 

46) -> tuple[torch.Tensor, Optional[torch.Tensor]]: 

47 """Chunked gated delta-rule linear attention (eager reference). 

48 

49 fp32 internal compute, output cast back to input dtype. 

50 

51 Shapes 

52 ------ 

53 query / key: ``(B, S, num_k_heads, head_k_dim)`` 

54 value: ``(B, S, num_v_heads, head_v_dim)`` (here num_k_heads == num_v_heads) 

55 g: ``(B, S, num_v_heads)`` 

56 beta: ``(B, S, num_v_heads)`` 

57 

58 Args: 

59 query: Query tensor in batch, token, head, key-dimension order. 

60 key: Key tensor with the same token and key-head axes as query. 

61 value: Value tensor in batch, token, head, value-dimension order. 

62 g: Log decay values for the recurrence. 

63 beta: Delta-rule update strengths, or logits when sigmoid fusion is enabled. 

64 chunk_size: Number of tokens in a recurrence chunk. 

65 initial_state: Optional state entering the first local chunk. 

66 output_final_state: Whether to return the state after the final chunk. 

67 normalize_qk: Whether this operator normalizes query and key. 

68 cu_seqlens: Cumulative document boundaries for packed tokens. 

69 """ 

70 if cu_seqlens is not None: 

71 return packed_eager( 

72 torch_chunk_gated_delta_rule, (query, key, value, g, beta), cu_seqlens, 

73 initial_state=initial_state, output_final_state=output_final_state, 

74 normalize_qk=normalize_qk, chunk_size=chunk_size, 

75 ) 

76 initial_dtype = query.dtype 

77 if normalize_qk: 

78 query = _l2norm(query, dim=-1, eps=1e-6) 

79 key = _l2norm(key, dim=-1, eps=1e-6) 

80 # (B, S, H, D) → (B, H, S, D), fp32 

81 query, key, value, beta, g = [ 

82 x.transpose(1, 2).contiguous().to(torch.float32) 

83 for x in (query, key, value, beta, g) 

84 ] 

85 

86 batch_size, num_heads, sequence_length, k_head_dim = key.shape 

87 v_head_dim = value.shape[-1] 

88 pad_size = (chunk_size - sequence_length % chunk_size) % chunk_size 

89 query = F.pad(query, (0, 0, 0, pad_size)) 

90 key = F.pad(key, (0, 0, 0, pad_size)) 

91 value = F.pad(value, (0, 0, 0, pad_size)) 

92 beta = F.pad(beta, (0, pad_size)) 

93 g = F.pad(g, (0, pad_size)) 

94 total_sequence_length = sequence_length + pad_size 

95 scale = 1 / (query.shape[-1] ** 0.5) 

96 query = query * scale 

97 

98 v_beta = value * beta.unsqueeze(-1) 

99 k_beta = key * beta.unsqueeze(-1) 

100 # (B, H, S, D) → (B, H, n_chunks, chunk_size, D) 

101 query, key, value, k_beta, v_beta = [ 

102 x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) 

103 for x in (query, key, value, k_beta, v_beta) 

104 ] 

105 g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size) 

106 mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=0) 

107 

108 # chunk decay 

109 g = g.cumsum(dim=-1) 

110 decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril() 

111 attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0) 

112 for i in range(1, chunk_size): 

113 row = attn[..., i, :i].clone() 

114 sub = attn[..., :i, :i].clone() 

115 attn[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2) 

116 attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device) 

117 value = attn @ v_beta 

118 k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1)) 

119 last_recurrent_state = ( 

120 torch.zeros(batch_size, num_heads, k_head_dim, v_head_dim).to(value) 

121 if initial_state is None 

122 else initial_state.to(value) 

123 ) 

124 core_attn_out = torch.zeros_like(value) 

125 

126 # for each chunk 

127 for i in range(0, total_sequence_length // chunk_size): 

128 q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i] 

129 attn = q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i] 

130 v_prime = k_cumdecay[:, :, i] @ last_recurrent_state 

131 v_new = v_i - v_prime 

132 attn_inter = (q_i * g[:, :, i, :, None].exp()) @ last_recurrent_state 

133 core_attn_out[:, :, i] = attn_inter + attn @ v_new 

134 last_recurrent_state = ( 

135 last_recurrent_state * g[:, :, i, -1, None, None].exp() 

136 + (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new 

137 ) 

138 

139 if not output_final_state: 

140 last_recurrent_state = None 

141 core_attn_out = core_attn_out.reshape( 

142 core_attn_out.shape[0], core_attn_out.shape[1], -1, core_attn_out.shape[-1]) 

143 core_attn_out = core_attn_out[:, :, :sequence_length] 

144 core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype) 

145 return core_attn_out, last_recurrent_state 

146 

147 

148def apply_gdn_state_summary( 

149 state_ext: torch.Tensor, 

150 transition: Optional[torch.Tensor], 

151 initial_state: Optional[torch.Tensor], 

152) -> torch.Tensor: 

153 """Apply GDN's existing local affine state program. 

154 

155 Args: 

156 state_ext: Local zero-entry state S. 

157 transition: Local transfer M, omitted only for a zero entry. 

158 initial_state: Incoming state, or None for a zero entry. 

159 """ 

160 if initial_state is None: 

161 return state_ext 

162 return torch.matmul(transition, initial_state.float()) + state_ext 

163 

164 

165def apply_gdn_state_gradient_summary( 

166 grad_state_ext: torch.Tensor, 

167 transition: Optional[torch.Tensor], 

168 grad_final_state: Optional[torch.Tensor], 

169) -> torch.Tensor: 

170 """Apply the adjoint summary to a gradient from the next rank. 

171 

172 Args: 

173 grad_state_ext: Local gradient contribution G. 

174 transition: Forward transfer M used by this backend's existing adjoint. 

175 grad_final_state: Incoming terminal-state gradient, or None for zero exit. 

176 """ 

177 if grad_final_state is None: 

178 return grad_state_ext 

179 return ( 

180 torch.matmul(transition.transpose(-2, -1), grad_final_state.float()) 

181 + grad_state_ext 

182 ) 

183 

184 

185_GDN_BACKENDS = frozenset({"eager", "triton", "ascendc"}) 

186_MIN_TRITON_ASCEND_VERSION = (3, 2, 1) 

187_TRITON_GDN_HEAD_DIM = 128 

188_TRITON_GDN_CHUNK_SIZE = 64 

189 

190 

191def _parse_version(version_text: str) -> tuple[int, int, int]: 

192 """Return a three-component numeric version tuple.""" 

193 parts = [] 

194 for part in version_text.split("+")[0].split(".")[:3]: 

195 match = re.match(r"\d+", part) 

196 if match is not None: 

197 parts.append(int(match.group())) 

198 return tuple((parts + [0, 0, 0])[:3]) 

199 

200 

201def _is_triton_gdn_input_supported( 

202 query: torch.Tensor, 

203 key: Optional[torch.Tensor], 

204 value: Optional[torch.Tensor], 

205 g: Optional[torch.Tensor], 

206 beta: Optional[torch.Tensor], 

207) -> bool: 

208 """Check the fixed Qwen3.5 GDN contract validated by this backend.""" 

209 if any(tensor is None for tensor in (key, value, g, beta)): 

210 return False 

211 if not ( 

212 query.device.type == "npu" 

213 and query.dtype == key.dtype == value.dtype == beta.dtype == torch.bfloat16 

214 and g.dtype == torch.float32 

215 and query.ndim == key.ndim == value.ndim == 4 

216 and g.ndim == beta.ndim == 3 

217 and query.shape == key.shape 

218 and query.shape[:3] == value.shape[:3] == g.shape == beta.shape 

219 and query.shape[-1] == value.shape[-1] == _TRITON_GDN_HEAD_DIM 

220 ): 

221 return False 

222 return all( 

223 tensor.device == query.device 

224 for tensor in (key, value, g, beta) 

225 ) 

226 

227 

228def is_triton_gdn_available( 

229 query: Optional[torch.Tensor] = None, 

230 key: Optional[torch.Tensor] = None, 

231 value: Optional[torch.Tensor] = None, 

232 g: Optional[torch.Tensor] = None, 

233 beta: Optional[torch.Tensor] = None, 

234 chunk_size: int = _TRITON_GDN_CHUNK_SIZE, 

235) -> bool: 

236 """Return whether the validated Triton-Ascend GDN backend is available. 

237 

238 Args: 

239 query: Query tensor in batch, token, head, key-dimension order. 

240 key: Key tensor with the same token and key-head axes as query. 

241 value: Value tensor in batch, token, head, value-dimension order. 

242 g: Log decay values for the recurrence. 

243 beta: Delta-rule update strengths, or logits when sigmoid fusion is enabled. 

244 chunk_size: Number of tokens in a recurrence chunk. 

245 """ 

246 if chunk_size != _TRITON_GDN_CHUNK_SIZE: 

247 return False 

248 if query is not None and not _is_triton_gdn_input_supported( 

249 query, key, value, g, beta, 

250 ): 

251 return False 

252 try: 

253 version_text = importlib.metadata.version("triton-ascend") 

254 except importlib.metadata.PackageNotFoundError: 

255 return False 

256 version = _parse_version(version_text) 

257 if version < _MIN_TRITON_ASCEND_VERSION: 

258 return False 

259 try: 

260 importlib.import_module("triton") 

261 return importlib.util.find_spec("triton.backends.ascend") is not None 

262 except (AttributeError, ImportError, ModuleNotFoundError): 

263 return False 

264 

265 

266def chunk_gated_delta_rule( 

267 query: torch.Tensor, 

268 key: torch.Tensor, 

269 value: torch.Tensor, 

270 g: torch.Tensor, 

271 beta: torch.Tensor, 

272 chunk_size: int = 64, 

273 initial_state: Optional[torch.Tensor] = None, 

274 output_final_state: bool = False, 

275 use_qk_l2norm_in_kernel: bool = False, 

276 backend: str = "eager", 

277 cu_seqlens: Optional[torch.Tensor] = None, 

278 use_beta_sigmoid_in_kernel: bool = False, 

279) -> tuple[torch.Tensor, Optional[torch.Tensor]]: 

280 """Dispatch GDN to an explicitly selected eager, Triton or Ascend C backend. 

281 

282 Args: 

283 query: Query tensor in batch, token, head, key-dimension order. 

284 key: Key tensor with the same token and key-head axes as query. 

285 value: Value tensor in batch, token, head, value-dimension order. 

286 g: Log decay values for the recurrence. 

287 beta: Delta-rule update strengths, or logits when sigmoid fusion is enabled. 

288 chunk_size: Number of tokens in a recurrence chunk. 

289 initial_state: Optional state entering the first local chunk. 

290 output_final_state: Whether to return the state after the final chunk. 

291 use_qk_l2norm_in_kernel: Whether this operator normalizes query and key. 

292 backend: Explicit local operator implementation to dispatch. 

293 cu_seqlens: Cumulative document boundaries for packed tokens. 

294 use_beta_sigmoid_in_kernel: Interpret beta as raw logits and fuse when supported. 

295 """ 

296 if query.ndim == 3: 

297 output, final = chunk_gated_delta_rule( 

298 *(tensor.unsqueeze(0) for tensor in (query, key, value, g, beta)), 

299 initial_state=initial_state, output_final_state=output_final_state, 

300 use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, chunk_size=chunk_size, 

301 backend=backend, cu_seqlens=cu_seqlens, 

302 use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel) 

303 return output.squeeze(0), final 

304 backend = backend.lower() 

305 if backend not in _GDN_BACKENDS: 

306 raise ValueError( 

307 f"unsupported GDN backend {backend!r}; " 

308 f"expected one of {sorted(_GDN_BACKENDS)}." 

309 ) 

310 if use_beta_sigmoid_in_kernel and backend != "ascendc": 

311 beta = beta.sigmoid() 

312 if backend == "eager": 

313 return torch_chunk_gated_delta_rule( 

314 query, 

315 key, 

316 value, 

317 g=g, 

318 beta=beta, 

319 chunk_size=chunk_size, 

320 initial_state=initial_state, 

321 output_final_state=output_final_state, 

322 normalize_qk=use_qk_l2norm_in_kernel, 

323 cu_seqlens=cu_seqlens, 

324 ) 

325 if backend == "ascendc": 

326 if initial_state is not None or output_final_state: 

327 raise NotImplementedError( 

328 "The local GDN Ascend C entry does not expose recurrent states; state CP uses its staged adapter.") 

329 if chunk_size != 64: 

330 raise ValueError("GDN Ascend C requires chunk_size=64.") 

331 return chunk_gated_delta_rule_ascendc( 

332 query, key, value, g, beta, cu_seqlens=cu_seqlens, 

333 use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, 

334 use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel) 

335 if not is_triton_gdn_available( 

336 query, key, value, g, beta, chunk_size=chunk_size, 

337 ): 

338 raise RuntimeError( 

339 "GDN backend='triton' requires triton-ascend >= 3.2.1 " 

340 "installation with the Ascend backend and NPU inputs " 

341 "q/k/v/beta=bf16, g=fp32, head_k_dim=head_v_dim=128, " 

342 "and chunk_size=64." 

343 ) 

344 

345 # The vendored Triton kernels are an optional NPU dependency. 

346 from hyper_parallel.components.functional.gated_delta_net_triton import ( # pylint: disable=import-outside-toplevel 

347 chunk_gated_delta_rule as triton_chunk_gated_delta_rule, 

348 ) 

349 

350 return triton_chunk_gated_delta_rule( 

351 query, 

352 key, 

353 value, 

354 g, 

355 beta, 

356 initial_state=initial_state, 

357 output_final_state=output_final_state, 

358 use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, 

359 chunk_size=chunk_size, 

360 cu_seqlens=cu_seqlens, 

361 )