Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / kda.py: 81%

124 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 zero-state Kimi Delta Attention with raw gate and beta logits.""" 

16 

17from __future__ import annotations 

18 

19from importlib import import_module 

20from typing import Protocol 

21 

22import torch 

23from torch.nn import functional as F 

24 

25from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import PackedSequenceInfo 

26 

27from .._dependency import require_package, require_symbol 

28from ..registry import ImplementationUnavailable, OpRegistry 

29from ..spec import OpSpec 

30 

31 

32class KdaFn(Protocol): 

33 """Compute KDA with normalized Q/K and a lower-bounded gate.""" 

34 

35 def __call__( 

36 self, x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, gate: torch.Tensor, beta: torch.Tensor, 

37 *, a_log: torch.Tensor, dt_bias: torch.Tensor, lower_bound: float | None, 

38 chunk_size: int = 64, scale: float | None = None, info: PackedSequenceInfo | None = None, 

39 ) -> torch.Tensor: 

40 """Interpret gate and beta as logits and reset recurrence between packed documents.""" 

41 

42 

43KDA = OpSpec[KdaFn](config_key="kda", variant="zero_state") 

44 

45 

46def _inverse_unit_lower_triangular(strict_lower: torch.Tensor) -> torch.Tensor: 

47 """Invert ``I + strict_lower`` using differentiable forward substitution.""" 

48 chunk_size = strict_lower.shape[-1] 

49 rows = [] 

50 for row_idx in range(chunk_size): 

51 base = -strict_lower[..., row_idx, :] 

52 if rows: 

53 previous = torch.stack(rows, dim=-2) 

54 row = torch.einsum( 

55 "...i,...ij->...j", 

56 base[..., :row_idx], 

57 previous, 

58 ) 

59 else: 

60 row = torch.zeros_like(base) 

61 diagonal = F.one_hot( # pylint: disable=not-callable 

62 torch.tensor(row_idx, device=strict_lower.device), 

63 num_classes=chunk_size, 

64 ).to(strict_lower.dtype) 

65 rows.append(row + diagonal) 

66 return torch.stack(rows, dim=-2) 

67 

68 

69def _prepare_kda_wy( 

70 query: torch.Tensor, 

71 key: torch.Tensor, 

72 value: torch.Tensor, 

73 gate: torch.Tensor, 

74 beta: torch.Tensor, 

75 chunk_size: int, 

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

77 """Build the cumulative gate, causal mask, and chunkwise WY factors.""" 

78 gate = gate.cumsum(dim=-2) 

79 causal = torch.ones( 

80 chunk_size, 

81 chunk_size, 

82 dtype=torch.bool, 

83 device=query.device, 

84 ).tril() 

85 strict_causal = causal.logical_xor( 

86 torch.eye(chunk_size, dtype=torch.bool, device=query.device) 

87 ) 

88 

89 # Future-position differences can overflow before the final causal mask, 

90 # leaving NaNs in backward even when the forward result is finite. 

91 gate_pair = (gate.unsqueeze(-2) - gate.unsqueeze(-3)).masked_fill(~causal.unsqueeze(-1), -torch.inf) 

92 key_pair = torch.einsum( 

93 "...ik,...jk,...ijk->...ij", 

94 key, 

95 key, 

96 gate_pair.exp(), 

97 ) 

98 strict_lower = ( 

99 key_pair * beta.unsqueeze(-1) 

100 ).masked_fill(~strict_causal, 0) 

101 inverse = _inverse_unit_lower_triangular(strict_lower) 

102 transform = inverse * beta.unsqueeze(-2) 

103 w = transform @ (key * gate.exp()) 

104 u = transform @ value 

105 

106 return gate, causal, w, u 

107 

108 

109def _run_kda_chunks( 

110 query: torch.Tensor, 

111 key: torch.Tensor, 

112 gate: torch.Tensor, 

113 w: torch.Tensor, 

114 u: torch.Tensor, 

115 state: torch.Tensor, 

116 causal: torch.Tensor, 

117 scale: float, 

118 num_chunks: int, 

119) -> tuple[list[torch.Tensor], torch.Tensor]: 

120 """Apply chunk WY factors to the recurrent state in sequence order.""" 

121 output_chunks = [] 

122 for chunk_idx in range(num_chunks): 

123 query_i = query[:, :, chunk_idx] 

124 key_i = key[:, :, chunk_idx] 

125 gate_i = gate[:, :, chunk_idx] 

126 w_i = w[:, :, chunk_idx] 

127 u_i = u[:, :, chunk_idx] 

128 

129 relative_gate = (gate_i.unsqueeze(-2) - gate_i.unsqueeze(-3)).masked_fill(~causal.unsqueeze(-1), -torch.inf) 

130 qk = torch.einsum( 

131 "bhik,bhjk,bhijk->bhij", 

132 query_i, 

133 key_i, 

134 relative_gate.exp(), 

135 ).masked_fill(~causal, 0) 

136 value_new = u_i - w_i @ state 

137 output_inter = (query_i * gate_i.exp()) @ state 

138 output_chunks.append(output_inter * scale + qk @ value_new * scale) 

139 

140 last_gate = gate_i[:, :, -1] 

141 key_decay = key_i * (last_gate.unsqueeze(-2) - gate_i).exp() 

142 state = state * last_gate.exp().unsqueeze(-1) 

143 state = state + key_decay.transpose(-1, -2) @ value_new 

144 

145 return output_chunks, state 

146 

147 

148def _chunk_view(tensor: torch.Tensor, chunk_size: int) -> torch.Tensor: 

149 padding = (-tensor.shape[1]) % chunk_size 

150 tensor = F.pad(tensor, (0, 0) * (tensor.ndim - 2) + (0, padding)) 

151 chunks = tensor.shape[1] // chunk_size 

152 return tensor.reshape(tensor.shape[0], chunks, chunk_size, *tensor.shape[2:]).permute( 

153 0, 3, 1, 2, *range(4, tensor.ndim + 1), 

154 ) 

155 

156 

157def _validate_kda_shapes( 

158 x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, gate: torch.Tensor, beta: torch.Tensor, 

159) -> None: 

160 """Validate token alignment, grouped heads and gate shapes for native KDA.""" 

161 if x.ndim != 4 or x.shape != key.shape or value.ndim != 4 or value.shape[:2] != x.shape[:2]: 

162 raise ValueError("KDA requires matching [B,T,H,D] query/key and token-aligned values") 

163 key_heads, key_dim = x.shape[-2:] 

164 value_heads = value.shape[-2] 

165 if value_heads % key_heads or gate.shape != (*x.shape[:2], value_heads, key_dim): 

166 raise ValueError("KDA requires grouped value heads and a per-key-dimension gate") 

167 if beta.shape != (*x.shape[:2], value_heads): 

168 raise ValueError("KDA beta must have shape [B,T,value_heads]") 

169 

170 

171def _validate_kda_gate_parameters( 

172 a_log: torch.Tensor, dt_bias: torch.Tensor, lower_bound: float | None, gate_shape: tuple[int, int], 

173) -> None: 

174 """Validate the trainable gate dimensions and optional negative lower bound.""" 

175 value_heads, key_dim = gate_shape 

176 if a_log.numel() != value_heads or dt_bias.numel() != value_heads * key_dim: 

177 raise ValueError("KDA gate parameters must match value heads and key dimensions") 

178 if lower_bound is not None and lower_bound >= 0: 

179 raise ValueError("lower_bound must be negative") 

180 

181 

182def _native( 

183 x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, gate: torch.Tensor, beta: torch.Tensor, 

184 *, a_log: torch.Tensor, dt_bias: torch.Tensor, lower_bound: float | None, 

185 chunk_size: int = 64, scale: float | None = None, info: PackedSequenceInfo | None = None, 

186) -> torch.Tensor: 

187 """Evaluate the zero-state chunked WY reference without importing model modules.""" 

188 if chunk_size <= 0: 

189 raise ValueError("chunk_size must be positive") 

190 _validate_kda_shapes(x, key, value, gate, beta) 

191 batch, length, key_heads, key_dim = x.shape 

192 value_heads, value_dim = value.shape[-2:] 

193 _validate_kda_gate_parameters(a_log, dt_bias, lower_bound, (value_heads, key_dim)) 

194 if info is not None: 

195 if batch != 1 or length != info.length: 

196 raise ValueError("Packed KDA requires [1,T,H,D] matching the local token interval") 

197 outputs = [ 

198 _native(*(tensor[:, start:end] for tensor in (x, key, value, gate, beta)), 

199 a_log=a_log, dt_bias=dt_bias, lower_bound=lower_bound, chunk_size=chunk_size, scale=scale) 

200 for start, end in zip(info.local_offsets, info.local_offsets[1:]) 

201 ] 

202 return torch.cat(outputs, dim=1) 

203 output_dtype = value.dtype 

204 normalized = [ 

205 tensor * (tensor.float().square().sum(-1, keepdim=True) + 1e-6).rsqrt().to(tensor.dtype) 

206 for tensor in (x, key) 

207 ] 

208 x, key = (tensor.float().repeat_interleave(value_heads // key_heads, dim=2) for tensor in normalized) 

209 shifted = gate.float() + dt_bias.float().reshape(1, 1, value_heads, key_dim) 

210 coefficient = a_log.float().exp().reshape(1, 1, value_heads, 1) 

211 gate = (-coefficient * F.softplus(shifted) if lower_bound is None # pylint: disable=not-callable 

212 else lower_bound * (coefficient * shifted).sigmoid()) 

213 tensors = (x, key, value.float(), gate, beta.float().sigmoid()) 

214 x, key, value, gate, beta = (_chunk_view(tensor, chunk_size) for tensor in tensors) 

215 gate, causal, w, u = _prepare_kda_wy(x, key, value, gate, beta, chunk_size) 

216 state = x.new_zeros((batch, value_heads, key_dim, value_dim)) 

217 effective_scale = key_dim ** -0.5 if scale is None else scale 

218 outputs, _ = _run_kda_chunks(x, key, gate, w, u, state, causal, effective_scale, x.shape[2]) 

219 return torch.stack(outputs, dim=2).permute(0, 2, 3, 1, 4).reshape( 

220 batch, -1, value_heads, value_dim, 

221 )[:, :length].to(output_dtype) 

222 

223 

224def _implementation(backend: str) -> KdaFn: 

225 # Existing fused adapters remain optional and are loaded only for a selected backend. 

226 """Bind the fused KDA backend and translate per-document sequence offsets.""" 

227 chunk_kda = import_module("hyper_parallel.components.functional.kimi_delta_attention").chunk_kda 

228 

229 def run( 

230 x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, gate: torch.Tensor, beta: torch.Tensor, 

231 *, a_log: torch.Tensor, dt_bias: torch.Tensor, lower_bound: float | None, 

232 chunk_size: int = 64, scale: float | None = None, info: PackedSequenceInfo | None = None, 

233 ) -> torch.Tensor: 

234 """Run the selected fused KDA kernel with per-call document boundaries.""" 

235 offsets = None 

236 if info is not None: 

237 offsets = (info.materialize(x.device, chunk_size).cu_seqlens if backend == "triton" else info.local_offsets) 

238 output, _ = chunk_kda( 

239 x, key, value, gate, beta, a_log=a_log, dt_bias=dt_bias, scale=scale, lower_bound=lower_bound, 

240 chunk_size=chunk_size, use_qk_l2norm_in_kernel=True, use_gate_in_kernel=True, 

241 use_beta_sigmoid_in_kernel=True, backend=backend, cu_seqlens=offsets, 

242 ) 

243 return output 

244 return run 

245 

246 

247def _load_triton() -> KdaFn: 

248 require_package("triton") 

249 adapter = require_package("hyper_parallel.components.functional.kimi_delta_attention_triton") 

250 if not adapter.is_fla_triton_kda_available(): 

251 raise ImplementationUnavailable("requires the FLA Triton-Ascend KDA kernel") 

252 return _implementation("triton") 

253 

254 

255def _load_ascendc() -> KdaFn: 

256 kernels = require_package("fla_npu.ops.ascendc") 

257 for name in ( 

258 "chunk_kda_fwd_prepare", "chunk_fwd_h", "chunk_kda_fwd_finalize", "chunk_kda_bwd_prepare", 

259 "chunk_gated_delta_rule_bwd_dhu", "chunk_kda_bwd_finalize", 

260 ): 

261 require_symbol(kernels, name) 

262 return _implementation("ascendc") 

263 

264 

265def register_kda(registry: OpRegistry) -> None: 

266 """Register the local KDA contract and its optional NPU kernels.""" 

267 registry.register_family("kda", specs=(KDA,)) 

268 registry.register_impl(KDA, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _native) 

269 registry.register_impl(KDA, name="triton_ascend", devices=("npu",), load=_load_triton) 

270 registry.register_impl(KDA, name="ascendc", devices=("npu",), load=_load_ascendc)