Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / attention / kimi_delta_attention / cp_kimi_delta_attention.py: 22%

551 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"""KDA layer CP scheduling, state protocols and backend-specific state autograd.""" 

16from __future__ import annotations 

17from functools import lru_cache 

18from typing import Any, Optional 

19 

20import torch 

21import torch.distributed as dist 

22from torch.nn import functional as F 

23from torch.autograd.function import once_differentiable 

24 

25from hyper_parallel.components.functional.kimi_delta_attention import ( 

26 apply_kda_state_gradient_summary, apply_kda_state_summary, 

27) 

28from hyper_parallel.components.functional.kimi_delta_attention_ascendc import ( 

29 load_kda_native_ops, prepare_kda_native, finish_kda_native_forward, restore_kda_native_backward, 

30 prepare_kda_native_backward, finish_kda_native_backward, 

31) 

32from hyper_parallel.components.functional.kimi_delta_attention_triton import ( 

33 get_fla_kda_staged_ops, validate_triton_kda_inputs, validate_kda_state_summary, 

34 kda_state_gradient_summary_from_prepared, kda_state_summary_forward_from_prepared, 

35) 

36from hyper_parallel.components.functional.linear_attention_convolution import fused_causal_conv1d, packed_causal_conv1d 

37from hyper_parallel.components.modules.attention.linear_attention_utils.cp_state_exchange import ( 

38 NativeStateAllGather, NativeStateExchange as _NativeStateExchange, 

39 native_state_intervals as _native_ag_intervals, 

40) 

41from hyper_parallel.components.modules.attention.linear_attention_utils.layer_adapter import ( 

42 prepare_linear_attention_input, 

43) 

44from hyper_parallel.components.modules.attention.linear_attention_utils.cp_convolution import ( 

45 causal_convolutions_with_halo, 

46) 

47from hyper_parallel.components.modules.attention.linear_attention_utils.parallel_layout import ( 

48 validate_linear_attention_layout, split_linear_attention_mesh as split_kda_mesh, 

49) 

50from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import ( 

51 PackedSequenceInfo, resolve_packed_sequence, plan_packed_summary_exchange, local_chunk_metadata, 

52) 

53from hyper_parallel.core.dtensor.device_mesh import DeviceMesh 

54from hyper_parallel.distributed.context_parallel.collectives import exchange_sequence_heads 

55from hyper_parallel.distributed.module_binding import ParallelModuleSpec 

56from .kimi_delta_attention import KimiDeltaAttentionModule 

57from .cp_recursive_doubling import KDAStateRecursiveDoubling 

58 

59 

60class CPKimiDeltaAttentionModule(KimiDeltaAttentionModule): 

61 """KDA pure Ulysses or Ulysses plus a state protocol, sharing local layer math.""" 

62 

63 def __init__(self, *, config: Any = None, module: torch.nn.Module | None = None, 

64 module_fqn: str = "", context: Any = None, backend: str = "eager", 

65 conv_backend: str | None = None, chunk_size: int = 64, input_layout: str = "BSH", 

66 ulysses_degree: int | None = 1, state_cp_method: str = "p2p", 

67 allgather_group_size: int = 1, p2p_head_chunks: int = 1, 

68 reuse_cp_state_on_recompute: bool = False) -> None: 

69 """Record scheduling choices; do not construct groups or retain an active invocation.""" 

70 del module_fqn, context 

71 # Preserve the established post-A2A convolution for the degree=None request. 

72 # Topology is tracked separately as CP = ulysses_size * state_size. 

73 self.convolve_after_exchange = ulysses_degree is None 

74 if conv_backend is None and not self.convolve_after_exchange: 

75 conv_backend = "ascendc" if backend == "ascendc" else "eager" 

76 super().__init__(config=config, module=module, 

77 backend=backend, conv_backend=conv_backend, chunk_size=chunk_size, input_layout=input_layout) 

78 self.ulysses_degree = ulysses_degree 

79 self.state_cp_method = state_cp_method 

80 self.allgather_group_size = allgather_group_size 

81 self.p2p_head_chunks = p2p_head_chunks 

82 if reuse_cp_state_on_recompute and backend != "ascendc": 

83 raise NotImplementedError("Checkpoint entry caching currently requires the Ascend C state backend.") 

84 self.reuse_cp_state_on_recompute, self._cp_entry_key = reuse_cp_state_on_recompute, object() 

85 self.cp_rank, self.cp_size = 0, 1 

86 self.cp_context = None 

87 self.state_mesh = None 

88 self.state_cp = None 

89 self.ulysses_mesh = None 

90 self.ulysses_rank = 0 

91 self.ulysses_size, self.state_size = 1, 1 

92 

93 def prepare_input(self, hidden_states: torch.Tensor, options: dict) -> tuple: 

94 """Resolve real document boundaries against this CP rank's physical shard. 

95 

96 Args: 

97 hidden_states: Local dense or flat hidden activations. 

98 options: Explicit backend options or invocation document metadata. 

99 """ 

100 return prepare_linear_attention_input(hidden_states, options, self.cp_rank, self.cp_size) 

101 

102 def parallel_module_spec(self) -> ParallelModuleSpec: 

103 """Declare the stage containing both token exchange and nested state exchange.""" 

104 return ParallelModuleSpec("attention.kda.cp", "cp", 

105 {"execute_attention_pipeline": ("hidden_states", "info")}, 

106 validate=validate_linear_attention_layout) 

107 

108 def bind_parallel(self, binding: Any) -> None: 

109 """Borrow the chronological mesh and prebuild the selected U/state groups. 

110 

111 Args: 

112 binding: Resolved parallel binding containing the CP context. 

113 """ 

114 if binding.cp_context is None: 

115 raise ValueError("KDA CP requires CPContext") 

116 self.cp_context = binding.cp_context 

117 self.cp_rank, self.cp_size = self.cp_context.rank, self.cp_context.size 

118 degree = self.cp_size if self.convolve_after_exchange else self.ulysses_degree 

119 if (not isinstance(degree, int) or isinstance(degree, bool)) or degree < 1 or self.cp_size % degree: 

120 raise ValueError("KDA Ulysses degree must divide CP size") 

121 if self.num_heads % degree or self.num_v_heads % degree: 

122 raise ValueError("KDA Ulysses degree must divide query and value heads") 

123 self.ulysses_size, self.state_size = degree, self.cp_size // degree 

124 if self.state_size == 1: 

125 # Pure U has no state exchange. Preserve the requested convolution position. 

126 self.ulysses_mesh = self.cp_context.mesh if degree > 1 else None 

127 self.ulysses_rank = self.cp_rank 

128 return 

129 self.state_mesh = self.cp_context.mesh 

130 if degree > 1: 

131 hybrid = split_kda_mesh(self.state_mesh, degree, ("kda_state", "kda_ulysses")) 

132 self.ulysses_mesh = hybrid["kda_ulysses"] 

133 self.ulysses_rank = self.ulysses_mesh.get_local_rank() 

134 self.state_mesh = hybrid["kda_state"] 

135 self.state_cp = build_kda_state_cp(self.state_mesh, self.state_cp_method, self.allgather_group_size) 

136 

137 def _run_state_backend(self, operands: tuple, info: PackedSequenceInfo | None, 

138 a_log: torch.Tensor, dt_bias: torch.Tensor) -> torch.Tensor: 

139 """Inject states inside backend autograd, reusing the local path at state degree one.""" 

140 if self.state_size == 1: 

141 return self.run_local_core(operands, info, a_log, dt_bias) 

142 size, rank = self.state_size, self.state_mesh.get_local_rank() 

143 if self.backend == "ascendc": 

144 # FSDP may expose BF16 compute weights; native gates require FP32, as in the local core. 

145 return ascendc_state_kda( 

146 *operands, a_log=a_log.float(), dt_bias=dt_bias.float(), lower_bound=self.lower_bound, 

147 state_cp=self.state_cp, cp_mesh=self.state_mesh, sequence_info=info, 

148 p2p_head_chunks=self.p2p_head_chunks, 

149 reuse_cp_state_on_recompute=self.reuse_cp_state_on_recompute, cache_key=self._cp_entry_key) 

150 if self.backend != "triton": 

151 raise NotImplementedError("KDA state CP requires Triton or Ascend C; eager supports local/pure Ulysses") 

152 ranks = self.state_mesh.rank_list 

153 return triton_state_kda( 

154 *operands, a_log=a_log.float(), dt_bias=dt_bias.float(), lower_bound=self.lower_bound, 

155 chunk_size=self.chunk_size, safe_gate=self.safe_gate, 

156 cp_group=self.state_mesh.get_group(), cp_rank=rank, cp_size=size, 

157 prev_rank=int(ranks[max(rank - 1, 0)]), next_rank=int(ranks[min(rank + 1, size - 1)]), 

158 state_cp=self.state_cp, sequence_info=info) 

159 

160 def run_state_core(self, operands: tuple, info: PackedSequenceInfo | None, 

161 a_log: torch.Tensor | None = None, dt_bias: torch.Tensor | None = None) -> torch.Tensor: 

162 """Apply optional Ulysses to projected inputs and restore their external token layout. 

163 

164 Args: 

165 operands: Projected and convolved Q/K/V plus raw gate and beta. 

166 info: Real document boundaries for this rank's physical token interval. 

167 a_log: Optional parameter view used by the projected-stage caller. 

168 dt_bias: Optional parameter view used by the projected-stage caller. 

169 """ 

170 a_log = self.A_log if a_log is None else a_log 

171 dt_bias = self.dt_bias if dt_bias is None else dt_bias 

172 if self.ulysses_mesh is None: 

173 return self._run_state_backend(operands, info, a_log, dt_bias) 

174 inputs = tuple(exchange_sequence_heads(tensor, self.ulysses_mesh, split_dim=2, concat_dim=1) 

175 for tensor in operands) 

176 heads = self.num_v_heads // self.ulysses_size 

177 a_log = a_log.reshape(self.num_v_heads).narrow(0, self.ulysses_rank * heads, heads).contiguous() 

178 dt_bias = dt_bias.reshape(self.num_v_heads, self.head_k_dim).narrow( 

179 0, self.ulysses_rank * heads, heads).contiguous() 

180 info = None if info is None else info.ulysses(self.ulysses_size, self.ulysses_rank) 

181 output = self._run_state_backend(inputs, info, a_log, dt_bias) 

182 return exchange_sequence_heads(output, self.ulysses_mesh, split_dim=1, concat_dim=2) 

183 

184 def _exchange_raw_inputs(self, operands: tuple) -> tuple: 

185 if self.cp_size == 1: 

186 return operands 

187 widths = (self.key_dim, self.key_dim, self.value_dim, 

188 self.num_v_heads * self.head_k_dim, self.num_v_heads) 

189 widths = tuple(width // self.cp_size for width in widths) 

190 chunks = [tensor.split(width, dim=-1) for tensor, width in zip(operands, widths)] 

191 packed = torch.cat([torch.cat(parts, dim=-1) for parts in zip(*chunks)], dim=-1).contiguous() 

192 packed = exchange_sequence_heads(packed, self.cp_context.mesh, split_dim=2, concat_dim=1) 

193 return packed.split(widths, dim=-1) 

194 

195 def _convolve_local_heads(self, operands: tuple, info: PackedSequenceInfo | None) -> tuple: 

196 """Convolve each local head shard with its matching source weight slice.""" 

197 query, key, value, gate, beta = operands 

198 if not self.use_short_conv: 

199 return *(F.silu(tensor) for tensor in (query, key, value)), gate, beta 

200 convolved = [] 

201 for tensor, conv in zip((query, key, value), (self.q_conv1d, self.k_conv1d, self.v_conv1d)): 

202 channels = tensor.shape[-1] 

203 start = self.cp_rank * channels 

204 weight = conv.weight.narrow(0, start, channels) 

205 bias = None if conv.bias is None else conv.bias.narrow(0, start, channels) 

206 if info is not None: 

207 output = packed_causal_conv1d(tensor, conv, info, weight=weight, bias=bias, backend=self.conv_backend) 

208 elif self.conv_backend != "eager": 

209 output = fused_causal_conv1d(tensor, weight, bias, backend=self.conv_backend, 

210 dilation=conv.dilation[0]) 

211 else: 

212 output = torch.conv1d(tensor.transpose(1, 2), weight, bias, stride=conv.stride, 

213 padding=conv.padding, dilation=conv.dilation, groups=channels) 

214 output = F.silu(output[:, :, :tensor.shape[1]].transpose(1, 2)) 

215 convolved.append(output) 

216 return *convolved, gate, beta 

217 

218 def execute_attention_pipeline(self, hidden_states: torch.Tensor, info: PackedSequenceInfo | None) -> tuple: 

219 """Preserve pure-U post-exchange convolution and state-CP pre-exchange halos. 

220 

221 Args: 

222 hidden_states: Local hidden activations in BSH or flat TH layout. 

223 info: Immutable packed-sequence metadata, or None for dense input. 

224 """ 

225 if self.cp_context is None: 

226 raise RuntimeError("Bind KDA CP resources before forward") 

227 if not self.training: 

228 raise NotImplementedError("KDA CP currently supports training only") 

229 projected = self.project_inputs(hidden_states) 

230 if self.convolve_after_exchange: 

231 gate, beta = self.project_state_gates(hidden_states) 

232 output_gate = self.project_output_gate(hidden_states) 

233 operands = (*projected, gate, beta) 

234 exchanged_info = None if info is None else info.ulysses(self.cp_size, self.cp_rank) 

235 operands = self._exchange_raw_inputs(operands) 

236 operands = self.shape_inputs(self._convolve_local_heads(operands, exchanged_info), self.cp_size) 

237 heads = self.num_v_heads // self.cp_size 

238 a_log = self.A_log.reshape(self.num_v_heads).narrow(0, self.cp_rank * heads, heads) 

239 dt_bias = self.dt_bias.reshape(self.num_v_heads, self.head_k_dim).narrow(0, self.cp_rank * heads, heads) 

240 output = self._run_state_backend(operands, exchanged_info, a_log, dt_bias) 

241 return exchange_sequence_heads(output, self.cp_context.mesh, split_dim=1, concat_dim=2), output_gate 

242 query, key, value = projected 

243 if self.use_short_conv: 

244 query, key, value = causal_convolutions_with_halo( 

245 (query, key, value), (self.q_conv1d, self.k_conv1d, self.v_conv1d), 

246 self.cp_context.mesh, self.cp_rank, self.cp_size, sequence_info=info, backend=self.conv_backend) 

247 else: 

248 query, key, value = (F.silu(tensor) for tensor in (query, key, value)) 

249 gate, beta = self.project_state_gates(hidden_states) 

250 output_gate = self.project_output_gate(hidden_states) 

251 output = self.run_state_core(self.shape_inputs((query, key, value, gate, beta)), info) 

252 return output, output_gate 

253 

254 

255def _validate_mesh_order(mesh: DeviceMesh) -> None: 

256 """Prevent collective slots from being mistaken for chronological positions.""" 

257 group_ranks = tuple(dist.get_process_group_ranks(mesh.get_group())) 

258 if tuple(mesh.rank_list) != group_ranks: 

259 raise ValueError("KDA mesh sequence order must match its communication group order.") 

260 

261 

262def build_kda_state_cp(mesh: DeviceMesh, protocol: str, allgather_group_size: int) -> object | None: 

263 """Construct a state-CP executor holding only communication metadata. 

264 

265 Args: 

266 mesh: One-dimensional mesh ordered along the state sequence. 

267 protocol: p2p, allgather, alltoallv, grouped_allgather_p2p, or recursive_doubling. 

268 allgather_group_size: Consecutive ranks per local gather, only for the grouped protocol. 

269 

270 Returns: 

271 State executor with an invocation-owned cache, or None for the P2P/local path. 

272 """ 

273 if protocol not in ("p2p", "allgather", "alltoallv", "grouped_allgather_p2p", "recursive_doubling"): 

274 raise ValueError(f"Unknown KDA state_cp_method: {protocol!r}.") 

275 if not isinstance(allgather_group_size, int) or isinstance(allgather_group_size, bool) or allgather_group_size < 1: 

276 raise ValueError("KDA allgather_group_size must be a positive integer.") 

277 if protocol != "grouped_allgather_p2p" and allgather_group_size != 1: 

278 raise ValueError("KDA allgather_group_size is only valid for grouped_allgather_p2p.") 

279 if protocol == "p2p": 

280 return None 

281 ranks = tuple(mesh.rank_list) 

282 rank, size = mesh.get_local_rank(), mesh.size() 

283 if protocol == "recursive_doubling": 

284 return KDAStateRecursiveDoubling(mesh.get_group(), rank, ranks) if size > 1 else None 

285 if protocol in ("allgather", "alltoallv"): 

286 _validate_mesh_order(mesh) 

287 executor = KDAStateAllToAllV if protocol == "alltoallv" else KDAStateAllGather 

288 return executor(mesh.get_group(), rank, size) 

289 if size % allgather_group_size: 

290 raise ValueError("KDA allgather_group_size must divide the state CP size.") 

291 if allgather_group_size == 1: 

292 return None 

293 if allgather_group_size == size: 

294 _validate_mesh_order(mesh) 

295 return KDAStateAllGather(mesh.get_group(), rank, size) 

296 split = split_kda_mesh(mesh, allgather_group_size, ("kda_outer", "kda_group")) 

297 return KDAStateAllGatherP2P( 

298 mesh.get_group(), split["kda_group"].get_group(), rank, ranks, allgather_group_size) 

299 

300 

301def _gather_maps(state: torch.Tensor, matrix: torch.Tensor, group: Any, size: int) -> torch.Tensor: 

302 """Pack validated local summaries for one invocation; the caller owns the gathered storage.""" 

303 packed = torch.cat((state, matrix), dim=-1) 

304 output = packed.new_empty((size * packed.shape[0], *packed.shape[1:])) 

305 dist.all_gather_into_tensor(output, packed, group=group) 

306 return output.view(size, *packed.shape) 

307 

308 

309class KDAStateAllGather(NativeStateAllGather): 

310 """Gather S/M forward and G/M backward; only local M survives forward.""" 

311 

312 def forward(self, state: torch.Tensor, matrix: torch.Tensor) -> tuple[torch.Tensor, tuple[torch.Tensor, ...]]: 

313 """Return the incoming state and this invocation's original local M. 

314 

315 Args: 

316 state: Local FP32 offset S [B,H,128,128]. 

317 matrix: Local forward transfer M of the same shape. 

318 

319 Returns: 

320 This rank's incoming recurrent state and a one-tensor local M cache. 

321 """ 

322 validate_kda_state_summary(state, matrix) 

323 # The native driver uses transport only and must not import Triton. 

324 from hyper_parallel.components.functional.kimi_delta_attention_triton import ( # pylint: disable=import-outside-toplevel 

325 merge_affine_summaries, 

326 ) 

327 maps = _gather_maps(state, matrix, self.group, self.size) 

328 return merge_affine_summaries(maps[..., :128], maps[..., 128:], self.rank, True), (matrix,) 

329 

330 def backward(self, gradient: torch.Tensor, cache: tuple[torch.Tensor, ...]) -> torch.Tensor: 

331 """Collect new G with the saved local M and recover the outgoing gradient. 

332 

333 Args: 

334 gradient: Local FP32 offset G [B,H,128,128]. 

335 cache: One-tensor tuple containing this invocation's local forward M. 

336 

337 Returns: 

338 This rank's outgoing recurrent-state gradient. 

339 """ 

340 matrix, = cache 

341 validate_kda_state_summary(gradient, matrix) 

342 # Load optional Triton math only for this protocol implementation. 

343 from hyper_parallel.components.functional.kimi_delta_attention_triton import ( # pylint: disable=import-outside-toplevel 

344 merge_affine_summaries, 

345 ) 

346 maps = _gather_maps(gradient, matrix, self.group, self.size) 

347 return merge_affine_summaries(maps[..., :128], maps[..., 128:], self.rank, False) 

348 

349 

350class KDAStateAllToAllV(KDAStateAllGather): 

351 """Collect only packed-document dependencies; dense calls retain AllGather.""" 

352 

353 protocol = "alltoallv" 

354 

355 def bind_sequence(self, info: PackedSequenceInfo, *, state_shape: tuple) -> object: 

356 """Bind an immutable sparse plan to this invocation, not the shared executor. 

357 

358 Args: 

359 info: Real document offsets and this state rank's local interval. 

360 state_shape: Local state shape, with physical packed batch size one. 

361 """ 

362 if state_shape[0] != 1: 

363 raise ValueError("Sparse packed summaries require physical batch size one.") 

364 plan = plan_packed_summary_exchange(info, self.rank, self.size) 

365 return _SparseAllGatherInvocation(self.group, plan) 

366 

367 

368class _SparseAllGatherInvocation: 

369 """Own only a plan; transport buffers remain local to each forward/backward.""" 

370 

371 def __init__(self, group: Any, plan: Any) -> None: 

372 self.group, self.plan = group, plan 

373 

374 def exchange_maps(self, packed: torch.Tensor, forward: bool) -> tuple[torch.Tensor, int]: 

375 """Receive compact chronological maps and one unused local-rank slot. 

376 

377 The sentinel preserves existing merge-kernel rank semantics without a 

378 full-group restore copy. Raw collectives are inside the attention's 

379 custom autograd, whose reverse summary exchange owns differentiation. 

380 

381 Args: 

382 packed: One rank's [B,H,128,256] S/M or reverse G/M (native G/N). 

383 forward: Select forward edges; backward uses the exact transposed edges. 

384 """ 

385 sends, receives = self.plan.send_counts, self.plan.recv_counts 

386 if not forward: 

387 sends, receives = receives, sends 

388 send_count, recv_count = sum(sends), sum(receives) 

389 maps = packed.new_empty((recv_count + 1, *packed.shape)) 

390 rank = recv_count if forward else 0 

391 if self.plan.active: 

392 outgoing = packed.unsqueeze(0).expand(send_count, *packed.shape).contiguous() 

393 incoming = maps[:recv_count] if forward else maps[1:] 

394 dist.all_to_all_single(incoming, outgoing, output_split_sizes=list(receives), 

395 input_split_sizes=list(sends), group=self.group) 

396 return maps, rank 

397 

398 def forward(self, state: torch.Tensor, matrix: torch.Tensor) -> tuple[torch.Tensor, tuple]: 

399 """Merge only the head document's earlier fragments and cache local M.""" 

400 validate_kda_state_summary(state, matrix) 

401 # Triton math is optional for native transport-only users. 

402 from hyper_parallel.components.functional.kimi_delta_attention_triton import ( # pylint: disable=import-outside-toplevel 

403 merge_affine_summaries, 

404 ) 

405 maps, rank = self.exchange_maps(torch.cat((state, matrix), dim=-1), True) 

406 initial = merge_affine_summaries(maps[..., :128], maps[..., 128:], rank, True) 

407 return initial, (matrix,) 

408 

409 def backward(self, gradient: torch.Tensor, cache: tuple) -> torch.Tensor: 

410 """Send head gradients backward and merge only the tail document's suffix.""" 

411 matrix, = cache 

412 validate_kda_state_summary(gradient, matrix) 

413 # Keep the native path free of an optional Triton import. 

414 from hyper_parallel.components.functional.kimi_delta_attention_triton import ( # pylint: disable=import-outside-toplevel 

415 merge_affine_summaries, 

416 ) 

417 maps, rank = self.exchange_maps(torch.cat((gradient, matrix), dim=-1), False) 

418 return merge_affine_summaries(maps[..., :128], maps[..., 128:], rank, False) 

419 

420 

421class KDAStateAllGatherP2P: 

422 """Use group-local gathers and an owner chain, retaining only each local M.""" 

423 

424 def __init__(self, group: Any, intra_group: Any, rank: int, 

425 ranks: tuple[int, ...], width: int) -> None: 

426 """Bind ranks already validated against the process-group order by the factory.""" 

427 size = len(ranks) 

428 if not isinstance(width, int) or isinstance(width, bool) or width < 2 or size % width: 

429 raise ValueError("Grouped AllGather width must be >= 2 and divide the CP size.") 

430 if not 0 <= rank < size or len(set(ranks)) != size: 

431 raise ValueError("Grouped AllGather requires unique global ranks and a valid local rank.") 

432 self.group, self.intra, self.rank, self.width = group, intra_group, rank, width 

433 self.ranks = tuple(ranks) 

434 self.block, self.local = divmod(rank, width) 

435 self.blocks = size // width 

436 self.owner = self.block * width + width - 1 

437 

438 def _receive(self, state: torch.Tensor, forward: bool) -> tuple[torch.Tensor, Any]: 

439 """Post the owner receive before gathering local summaries.""" 

440 incoming = torch.zeros_like(state) 

441 recv_handle = None 

442 peer = self.owner - self.width if forward else self.owner + self.width 

443 if self.rank == self.owner and 0 <= peer < len(self.ranks): 

444 recv_handle = dist.irecv(incoming, src=self.ranks[peer], group=self.group) 

445 return incoming, recv_handle 

446 

447 def forward(self, state: torch.Tensor, matrix: torch.Tensor) -> tuple[torch.Tensor, tuple[torch.Tensor, ...]]: 

448 """Relay ordered group scans and restore this rank's incoming state. 

449 

450 Args: 

451 state: Local FP32 offset S [B,H,128,128]. 

452 matrix: Local forward transfer M of the same shape. 

453 

454 Returns: 

455 This rank's incoming recurrent state and a one-tensor local M cache. 

456 """ 

457 validate_kda_state_summary(state, matrix) 

458 # The native driver borrows groups without loading these Triton scans. 

459 from hyper_parallel.components.functional.kimi_delta_attention_triton import ( # pylint: disable=import-outside-toplevel 

460 scan_kda_affine_maps, 

461 ) 

462 incoming, recv_handle = self._receive(state, True) 

463 maps = _gather_maps(state, matrix, self.intra, self.width) 

464 send_handle, send_state = None, None 

465 result = None 

466 if self.rank == self.owner: 

467 if recv_handle is not None: 

468 recv_handle.wait() 

469 if self.block + 1 < self.blocks: 

470 send_state, result = scan_kda_affine_maps(maps, incoming, range(self.width), True, 

471 prefix_count=self.local) 

472 send_handle = dist.isend(send_state, dst=self.ranks[self.owner + self.width], group=self.group) 

473 if self.block > 0: 

474 dist.broadcast(incoming, src=self.ranks[self.owner], group=self.intra) 

475 if result is None: 

476 result, _ = scan_kda_affine_maps(maps, incoming, range(self.local), True) 

477 if send_handle is not None: 

478 send_handle.wait() 

479 return result, (matrix,) 

480 

481 def backward(self, gradient: torch.Tensor, cache: tuple[torch.Tensor, ...]) -> torch.Tensor: 

482 """Regather G/M and reverse the owner chain with ordered state feedback. 

483 

484 Args: 

485 gradient: Local FP32 offset G [B,H,128,128]. 

486 cache: One-tensor tuple containing this invocation's local forward M. 

487 

488 Returns: 

489 This rank's outgoing recurrent-state gradient. 

490 """ 

491 matrix, = cache 

492 validate_kda_state_summary(gradient, matrix) 

493 # Keep the optional Triton implementation local to the selected path. 

494 from hyper_parallel.components.functional.kimi_delta_attention_triton import ( # pylint: disable=import-outside-toplevel 

495 scan_kda_affine_maps, 

496 ) 

497 incoming, recv_handle = self._receive(gradient, False) 

498 maps = _gather_maps(gradient, matrix, self.intra, self.width) 

499 send_handle, send_state = None, None 

500 if self.rank == self.owner: 

501 if recv_handle is not None: 

502 recv_handle.wait() 

503 if self.block > 0: 

504 send_state, _ = scan_kda_affine_maps(maps, incoming, range(self.width - 1, -1, -1), False) 

505 send_handle = dist.isend(send_state, dst=self.ranks[self.owner - self.width], group=self.group) 

506 if self.block + 1 < self.blocks: 

507 dist.broadcast(incoming, src=self.ranks[self.owner], group=self.intra) 

508 result, _ = scan_kda_affine_maps(maps, incoming, range(self.width - 1, self.local, -1), False) 

509 if send_handle is not None: 

510 send_handle.wait() 

511 return result 

512 

513 

514def _validate_state_cp_inputs( 

515 query: torch.Tensor, 

516 key: torch.Tensor, 

517 value: torch.Tensor, 

518 gate: torch.Tensor, 

519 beta: torch.Tensor, 

520 a_log: torch.Tensor, 

521 dt_bias: torch.Tensor, 

522 *, 

523 chunk_size: int, 

524 lower_bound: float, 

525 cp_rank: int, 

526 cp_size: int, 

527) -> None: 

528 """Validate the fixed-shape KDA state CP backend before communication starts.""" 

529 validate_triton_kda_inputs( 

530 query, 

531 key, 

532 value, 

533 gate, 

534 beta, 

535 a_log, 

536 dt_bias, 

537 chunk_size=chunk_size, 

538 lower_bound=lower_bound, 

539 ) 

540 if cp_size <= 0 or not 0 <= cp_rank < cp_size: 

541 raise ValueError(f"Invalid KDA state CP rank {cp_rank} for cp_size {cp_size}.") 

542 

543 

544def _prepare_packed_kda_summary(kg, w, u, gate, sequence_info, state_cp, send_next, chunk_size): 

545 """Skip summaries with no consumer when the invocation supports absent tensors.""" 

546 if state_cp is None and not send_next: 

547 return None, None 

548 state_shape = (kg.shape[0], u.shape[2], kg.shape[-1], u.shape[-1]) 

549 transition = None 

550 if getattr(state_cp, "needs_state_summary", True): 

551 tail = sequence_info.tail 

552 state, transition = kda_state_summary_forward_from_prepared( 

553 kg[:, tail], w[:, tail], u[:, tail], gate[:, tail], chunk_size=chunk_size, 

554 output_transition=(sequence_info.transfer_active 

555 and getattr(state_cp, "needs_transition_summary", True)), 

556 ) 

557 elif getattr(state_cp, "allows_absent_summaries", False): 

558 return None, None 

559 else: 

560 state = kg.new_zeros(state_shape, dtype=torch.float32) 

561 if state_cp is not None and transition is None: 

562 # Shape placeholders preserve existing collective validation; no M kernel runs. 

563 transition = kg.new_zeros((*state_shape[:-1], kg.shape[-1]), dtype=torch.float32) 

564 return state, transition 

565 

566 

567def _sequence_metadata(sequence_info, device, chunk_size): 

568 """Materialize one immutable packed plan for both intra-chunk and recurrent stages.""" 

569 if sequence_info is None: 

570 return None, {}, {} 

571 plan = sequence_info.materialize(device, chunk_size) 

572 varlen = plan.kwargs() 

573 return plan, varlen, dict(varlen, chunk_offsets=plan.chunk_offsets) 

574 

575 

576def _exchange_forward(kg, w, u, gate, sequence_info, state_cp, send_next, chunk_size, 

577 cp_rank, cp_size, initial_state, recv_handle, next_rank, cp_group): 

578 """Produce only consumed summaries and keep an outgoing buffer alive until its send completes.""" 

579 state_ext = None 

580 transition = None 

581 if sequence_info is not None: 

582 state_ext, transition = _prepare_packed_kda_summary( 

583 kg, w, u, gate, sequence_info, state_cp, send_next, chunk_size, 

584 ) 

585 else: 

586 if state_cp is None and cp_rank == 0 and cp_size > 1: 

587 # Zero entry uses S directly, and rank 0 has no reverse-state recipient. 

588 state_ext, transition = kda_state_summary_forward_from_prepared( 

589 kg, w, u, gate, chunk_size=chunk_size, output_transition=False, 

590 ) 

591 elif state_cp is not None or cp_rank < cp_size - 1: 

592 state_ext, transition = kda_state_summary_forward_from_prepared(kg, w, u, gate, chunk_size=chunk_size) 

593 # A reset makes the outgoing summary independent of the incoming state. 

594 # Wait before apply only when it actually reads that state; local h still waits below. 

595 if recv_handle is not None and (sequence_info is None or sequence_info.transfer_active): 

596 recv_handle.wait() 

597 recv_handle = None 

598 

599 send_handle = None 

600 send_state = None 

601 state_cache = (transition,) if transition is not None else () 

602 if state_cp is not None: 

603 initial_state, state_cache = state_cp.forward(state_ext, transition) 

604 transition = None 

605 elif send_next: 

606 summary_initial = initial_state if transition is not None else None 

607 final_state = apply_kda_state_summary(state_ext, transition, summary_initial) 

608 send_state = final_state.contiguous() 

609 send_handle = dist.isend(send_state, dst=next_rank, group=cp_group) 

610 

611 if recv_handle is not None: 

612 recv_handle.wait() 

613 return initial_state, state_cache, send_handle, send_state 

614 

615 

616def _exchange_backward(ctx, query_gated, key_gated, w, gate, grad_output, grad_value_local, 

617 state_shape, state_cache, grad_final_state, recv_handle): 

618 """Produce G and reverse the state exchange without changing local backward arithmetic.""" 

619 sequence_info = ctx.sequence_info 

620 grad_state_ext = None 

621 if ctx.state_cp is not None or ctx.receive_previous: 

622 if sequence_info is not None and not sequence_info.continues_previous: 

623 if not getattr(ctx.state_cp, "allows_absent_summaries", False): 

624 grad_state_ext = query_gated.new_zeros(state_shape, dtype=torch.float32) 

625 else: 

626 head = slice(None) if sequence_info is None else sequence_info.head 

627 grad_state_ext = kda_state_gradient_summary_from_prepared( 

628 query_gated[:, head], key_gated[:, head], w[:, head], gate[:, head], 

629 grad_output[:, head], grad_value_local[:, head], ctx.scale, chunk_size=ctx.chunk_size, 

630 ) 

631 if recv_handle is not None and (sequence_info is None or sequence_info.transfer_active): 

632 recv_handle.wait() 

633 recv_handle = None 

634 send_handle = None 

635 send_state_gradient = None 

636 if ctx.state_cp is not None: 

637 grad_final_state = ctx.state_cp.backward(grad_state_ext, state_cache) 

638 elif ctx.receive_previous: 

639 transition = state_cache[0] if state_cache else None 

640 summary_final_gradient = grad_final_state if transition is not None else None 

641 grad_initial_state = apply_kda_state_gradient_summary(grad_state_ext, transition, summary_final_gradient) 

642 send_state_gradient = grad_initial_state.contiguous() 

643 send_handle = dist.isend(send_state_gradient, dst=ctx.prev_rank, group=ctx.cp_group) 

644 

645 if recv_handle is not None: 

646 recv_handle.wait() 

647 return grad_final_state, send_handle, send_state_gradient 

648 

649 

650class _KDAStateCPFunction(torch.autograd.Function): 

651 """Run shared local KDA and autograd with the selected state exchange.""" 

652 

653 @staticmethod 

654 def forward( # pylint: disable=arguments-differ,too-many-arguments,too-many-locals 

655 ctx: Any, 

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

657 gate_raw: torch.Tensor, beta_raw: torch.Tensor, 

658 a_log: torch.Tensor, dt_bias: torch.Tensor, 

659 scale: float, lower_bound: float, chunk_size: int, safe_gate: bool, 

660 cp_group: Any, prev_rank: int, next_rank: int, cp_rank: int, cp_size: int, 

661 state_cp: Any, 

662 sequence_info: Optional[PackedSequenceInfo], 

663 ) -> torch.Tensor: 

664 """Prepare local KDA, propagate its state, and produce token outputs. 

665 

666 Args: 

667 ctx: Autograd context holding tensors and communication metadata. 

668 query: Local query tensor [B,T,H,K]. 

669 key: Matching local key tensor. 

670 value: Local value tensor [B,T,HV,V]. 

671 gate_raw: Unactivated per-token gate logits. 

672 beta_raw: Unactivated per-token beta logits. 

673 a_log: Decay parameter with one value per value head. 

674 dt_bias: Learned bias with one value per gate channel. 

675 scale: Optional attention scaling factor. 

676 lower_bound: Lower bound for the activated gate. 

677 chunk_size: Tokens per local recurrence chunk. 

678 safe_gate: Use the staged lower-bounded gate implementation. 

679 cp_group: Precreated chronological CP process group. 

680 prev_rank: Global rank of the preceding sequence partition. 

681 next_rank: Global rank of the following sequence partition. 

682 cp_rank: Chronological index within the CP group. 

683 cp_size: Number of state partitions. 

684 state_cp: Executor returning an invocation cache; None selects P2P. 

685 """ 

686 ops = get_fla_kda_staged_ops() 

687 bind_sequence = getattr(state_cp, "bind_sequence", None) 

688 if sequence_info is not None and bind_sequence is not None: 

689 state_cp = bind_sequence( 

690 sequence_info, state_shape=(query.shape[0], value.shape[2], query.shape[-1], value.shape[-1])) 

691 plan, varlen, recurrent_varlen = _sequence_metadata(sequence_info, query.device, chunk_size) 

692 

693 # FLA consumes base-2 log gates: exp(x) = exp2(x / ln(2)). 

694 # Use the same conversion when recomputing gates in backward. 

695 rcp_ln2 = 1.4426950408889634 

696 

697 query, key, value, gate_raw, beta_raw = ( 

698 tensor.contiguous() for tensor in (query, key, value, gate_raw, beta_raw)) 

699 query, query_rstd = ops.l2norm_fwd(query) 

700 key, key_rstd = ops.l2norm_fwd(key) 

701 beta = ops.fused_beta_sigmoid(beta_raw) 

702 gate = ops.kda_gate_chunk_cumsum( 

703 g=gate_raw, A_log=a_log, dt_bias=dt_bias, scale=rcp_ln2, chunk_size=chunk_size, 

704 lower_bound=lower_bound, **varlen, 

705 ) 

706 

707 state_shape = (query.shape[0], value.shape[2], query.shape[-1], value.shape[-1]) 

708 receive_previous = cp_rank > 0 and (sequence_info is None or sequence_info.continues_previous) 

709 send_next = cp_rank < cp_size - 1 and (sequence_info is None or sequence_info.continues_next) 

710 initial_state = None 

711 recv_handle = None 

712 if state_cp is None and receive_previous: 

713 initial_state = torch.empty(state_shape, device=query.device, dtype=torch.float32) 

714 recv_handle = dist.irecv(initial_state, src=prev_rank, group=cp_group) 

715 

716 w, u, _, kg, attention_qk, attention_kk = ops.chunk_kda_fwd_intra( 

717 q=query, k=key, v=value, gk=gate, beta=beta, scale=scale, chunk_size=chunk_size, safe_gate=safe_gate, 

718 disable_recompute=True, **varlen, 

719 ) 

720 # The gated query is unused here and is recomputed in backward. 

721 del _ 

722 initial_state, state_cache, send_handle, send_state = _exchange_forward( 

723 kg, w, u, gate, sequence_info, state_cp, send_next, chunk_size, 

724 cp_rank, cp_size, initial_state, recv_handle, next_rank, cp_group) 

725 kernel_initial_state = initial_state if sequence_info is None else sequence_info.first_state(initial_state) 

726 states, value_new, _ = ops.chunk_gated_delta_rule_fwd_h( 

727 k=kg, w=w, u=u, gk=gate, initial_state=kernel_initial_state, 

728 output_final_state=False, chunk_size=chunk_size, **recurrent_varlen, 

729 ) 

730 # Local h was their last forward consumer on this stream. 

731 del w, u, kg, _ 

732 output = ops.chunk_gla_fwd_o_gk( 

733 q=query, v=value_new, g=gate, A=attention_qk, h=states, scale=scale, chunk_size=chunk_size, **varlen, 

734 ) 

735 if send_handle is not None: 

736 send_handle.wait() 

737 del send_state 

738 

739 saved_initial_state = initial_state 

740 if saved_initial_state is None: 

741 saved_initial_state = query.new_empty(0, dtype=torch.float32) 

742 packed_tensors = () if plan is None else ( 

743 plan.cu_seqlens, plan.chunk_indices, plan.chunk_offsets) 

744 ctx.save_for_backward( 

745 query, query_rstd, key, key_rstd, value, gate_raw, beta_raw, a_log, dt_bias, attention_qk, 

746 attention_kk, saved_initial_state, *state_cache, *packed_tensors, 

747 ) 

748 ctx.scale = scale 

749 ctx.lower_bound = lower_bound 

750 ctx.chunk_size = chunk_size 

751 ctx.safe_gate = safe_gate 

752 ctx.cp_group = cp_group 

753 ctx.prev_rank = prev_rank 

754 ctx.next_rank = next_rank 

755 ctx.cp_rank = cp_rank 

756 ctx.cp_size = cp_size 

757 ctx.state_cp = state_cp 

758 ctx.state_cache_count = len(state_cache) 

759 ctx.receive_previous = receive_previous 

760 ctx.send_next = send_next 

761 ctx.sequence_info = sequence_info 

762 return output.to(value.dtype) 

763 

764 @staticmethod 

765 def backward( # pylint: disable=arguments-differ,too-many-locals 

766 ctx: Any, 

767 grad_output: torch.Tensor, 

768 ) -> tuple[Any, ...]: 

769 """Reverse the state wavefront, then finish the fused local backward. 

770 

771 Args: 

772 ctx: Autograd context holding tensors and communication metadata. 

773 grad_output: Upstream gradient for the local token output. 

774 """ 

775 ops = get_fla_kda_staged_ops() 

776 

777 # FLA consumes base-2 log gates: exp(x) = exp2(x / ln(2)). 

778 # Use the same conversion when recomputing gates in backward. 

779 rcp_ln2 = 1.4426950408889634 

780 

781 ( 

782 query, query_rstd, key, key_rstd, value, gate_raw, beta_raw, a_log, dt_bias, 

783 attention_qk, attention_kk, saved_initial_state, *saved_tail, 

784 ) = ctx.saved_tensors 

785 state_cache = tuple(saved_tail[:ctx.state_cache_count]) 

786 packed_tensors = saved_tail[ctx.state_cache_count:] 

787 sequence_info = ctx.sequence_info 

788 cu_seqlens = chunk_indices = chunk_offsets = None 

789 if sequence_info is not None: 

790 cu_seqlens, chunk_indices, chunk_offsets = packed_tensors 

791 varlen = {} if sequence_info is None else {"cu_seqlens": cu_seqlens, "chunk_indices": chunk_indices} 

792 recurrent_varlen = dict(varlen) 

793 if sequence_info is not None: 

794 recurrent_varlen["chunk_offsets"] = chunk_offsets 

795 initial_state = saved_initial_state if saved_initial_state.numel() else None 

796 kernel_initial_state = initial_state if sequence_info is None else sequence_info.first_state(initial_state) 

797 grad_output = grad_output.contiguous() 

798 

799 grad_final_state = None 

800 recv_handle = None 

801 if ctx.state_cp is None and ctx.send_next: 

802 grad_final_state = torch.empty( 

803 (query.shape[0], value.shape[2], query.shape[-1], value.shape[-1]), device=query.device, 

804 dtype=torch.float32, 

805 ) 

806 recv_handle = dist.irecv(grad_final_state, src=ctx.next_rank, group=ctx.cp_group) 

807 

808 beta = ops.fused_beta_sigmoid(beta_raw) 

809 gate = ops.kda_gate_chunk_cumsum( 

810 g=gate_raw, A_log=a_log, dt_bias=dt_bias, scale=rcp_ln2, chunk_size=ctx.chunk_size, 

811 lower_bound=ctx.lower_bound, **varlen, 

812 ) 

813 w, u, query_gated, key_gated = ops.recompute_w_u_fwd( 

814 q=query, k=key, v=value, beta=beta, A=attention_kk, gk=gate, **varlen, 

815 ) 

816 states, value_new, _ = ops.chunk_gated_delta_rule_fwd_h( 

817 k=key_gated, w=w, u=u, gk=gate, initial_state=kernel_initial_state, output_final_state=False, 

818 chunk_size=ctx.chunk_size, **recurrent_varlen, 

819 ) 

820 grad_attention_qk, grad_value_local = ops.chunk_kda_bwd_dav( 

821 q=query, k=key, v=value_new, do=grad_output, A=attention_qk, scale=ctx.scale, 

822 chunk_size=ctx.chunk_size, **varlen, 

823 ) 

824 grad_final_state, send_handle, send_state_gradient = _exchange_backward( 

825 ctx, query_gated, key_gated, w, gate, grad_output, grad_value_local, 

826 (query.shape[0], value.shape[2], query.shape[-1], value.shape[-1]), 

827 state_cache, grad_final_state, recv_handle) 

828 kernel_grad_final = grad_final_state if sequence_info is None else sequence_info.last_state(grad_final_state) 

829 grad_states, _, grad_value = ops.chunk_gated_delta_rule_bwd_dhu( 

830 q=query_gated, k=key_gated, w=w, gk=gate, h0=kernel_initial_state, dht=kernel_grad_final, do=grad_output, 

831 dv=grad_value_local, scale=ctx.scale, chunk_size=ctx.chunk_size, **recurrent_varlen, 

832 ) 

833 # These recomputed tensors have no consumers after dhu. Dropping local 

834 # references lets the allocator reuse their storage on this stream. 

835 del query_gated, key_gated, w, u, grad_value_local, _ 

836 ( 

837 grad_query, grad_key, grad_value, grad_beta, grad_gate, grad_attention_kk, 

838 ) = ops.chunk_kda_bwd_wy_dqkg_fused( 

839 q=query, k=key, v=value, v_new=value_new, g=gate, beta=beta, A=attention_kk, h=states, do=grad_output, 

840 dh=grad_states, dv=grad_value, scale=ctx.scale, chunk_size=ctx.chunk_size, 

841 **varlen, 

842 ) 

843 # Release recomputed states before intra backward allocates its outputs. 

844 del states, grad_states, value_new 

845 grad_query, grad_key, grad_beta, grad_gate = ops.chunk_kda_bwd_intra( 

846 q=query, k=key, g=gate, beta=beta, dAqk=grad_attention_qk, dAkk=grad_attention_kk, dq=grad_query, 

847 dk=grad_key, db=grad_beta, dg=grad_gate, chunk_size=ctx.chunk_size, safe_gate=ctx.safe_gate, 

848 **varlen, 

849 ) 

850 

851 num_query_heads = query.shape[2] 

852 num_value_heads = value.shape[2] 

853 if num_value_heads > num_query_heads: 

854 groups = num_value_heads // num_query_heads 

855 grad_query = grad_query.view(*grad_query.shape[:2], num_query_heads, groups, grad_query.shape[-1]).sum( 

856 dim=3, 

857 ) 

858 grad_key = grad_key.view(*grad_key.shape[:2], num_query_heads, groups, grad_key.shape[-1]).sum(dim=3) 

859 

860 grad_gate = ops.chunk_local_cumsum(grad_gate, chunk_size=ctx.chunk_size, reverse=True, **varlen) 

861 grad_gate, grad_a_log, grad_dt_bias = ops.kda_gate_bwd( 

862 g=gate_raw, A_log=a_log, dt_bias=dt_bias, dyg=grad_gate, lower_bound=ctx.lower_bound, 

863 ) 

864 grad_beta = ops.fused_beta_sigmoid_bwd(beta_raw, grad_beta) 

865 grad_query = ops.l2norm_bwd(query, query_rstd, grad_query) 

866 grad_key = ops.l2norm_bwd(key, key_rstd, grad_key) 

867 if send_handle is not None: 

868 send_handle.wait() 

869 del send_state_gradient 

870 

871 return ( 

872 grad_query, grad_key, grad_value, grad_gate, grad_beta, grad_a_log, grad_dt_bias, None, None, None, 

873 None, None, None, None, None, None, None, None, 

874 ) 

875 

876 

877@torch.compiler.disable 

878def triton_state_kda( 

879 query: torch.Tensor, 

880 key: torch.Tensor, 

881 value: torch.Tensor, 

882 gate: torch.Tensor, 

883 beta: torch.Tensor, 

884 *, 

885 a_log: torch.Tensor, 

886 dt_bias: torch.Tensor, 

887 cp_group: Any, 

888 prev_rank: int, 

889 next_rank: int, 

890 cp_rank: int, 

891 cp_size: int, 

892 scale: Optional[float] = None, 

893 lower_bound: float = -5.0, 

894 chunk_size: int = 64, 

895 safe_gate: bool = True, 

896 state_cp: Any = None, 

897 sequence_info: Optional[PackedSequenceInfo] = None, 

898) -> torch.Tensor: 

899 """Run one sequence-sharded KDA segment with a selected state CP executor. 

900 

901 The historical P2P entry name is retained for existing callers; passing 

902 state_cp selects gathered or recursive state exchange with the same local ops. 

903 

904 Args: 

905 query: Query input [B,T,H,K]. 

906 key: Matching key input. 

907 value: Value input [B,T,HV,V]. 

908 gate: Per-token gate logits. 

909 beta: Per-token beta logits. 

910 a_log: FP32 decay parameter per value head. 

911 dt_bias: FP32 gate-channel bias. 

912 cp_group: Existing chronological state process group. 

913 prev_rank: Global predecessor rank for P2P. 

914 next_rank: Global successor rank for P2P. 

915 cp_rank: Chronological index within the state group. 

916 cp_size: Number of state partitions. 

917 scale: Optional attention scale. 

918 lower_bound: Lower bound for the activated gate. 

919 chunk_size: Tokens per local chunk. 

920 safe_gate: Enable the staged safe-gate path. 

921 state_cp: State executor returning an invocation cache; None selects existing P2P. 

922 

923 Returns: 

924 Output tokens in the local sequence layout. 

925 """ 

926 _validate_state_cp_inputs( 

927 query, 

928 key, 

929 value, 

930 gate, 

931 beta, 

932 a_log, 

933 dt_bias, 

934 chunk_size=chunk_size, 

935 lower_bound=lower_bound, 

936 cp_rank=cp_rank, 

937 cp_size=cp_size, 

938 ) 

939 if sequence_info is not None: 

940 if query.shape[0] != 1: 

941 raise ValueError("Packed state CP requires batch dimension one.") 

942 resolve_packed_sequence({"packed_sequence_info": sequence_info}, query.shape[1], 

943 cp_rank=cp_rank, cp_size=cp_size) 

944 effective_scale = query.shape[-1] ** -0.5 if scale is None else float(scale) 

945 return _KDAStateCPFunction.apply( 

946 query, 

947 key, 

948 value, 

949 gate, 

950 beta, 

951 a_log, 

952 dt_bias.reshape(-1), 

953 effective_scale, 

954 float(lower_bound), 

955 chunk_size, 

956 safe_gate, 

957 cp_group, 

958 prev_rank, 

959 next_rank, 

960 cp_rank, 

961 cp_size, 

962 state_cp, 

963 sequence_info, 

964 ) 

965 

966 

967@lru_cache(maxsize=1) 

968def _load_state_ops(): 

969 """Check every native stage before entering the first state collective.""" 

970 ops = load_kda_native_ops() 

971 required = ( 

972 "pre_process_fwd_kernel_merged", "pre_process_bwd_kernel_merged", 

973 "merge_fwd_bwd_kernel", 

974 ) 

975 missing = [name for name in required if not callable(getattr(ops, name, None))] 

976 if missing: 

977 raise RuntimeError(f"Native KDA state CP requires these fla-npu APIs: {', '.join(missing)}.") 

978 return ops 

979 

980 

981def _exchange_native_gradient(ctx, ops, inputs, reception): 

982 """Own G/N production, reset injection and the stock dHT dtype boundary.""" 

983 if ctx.exchange is None: 

984 return None, None, None 

985 gk, qg, kg, weights, grad, dv_local_head = inputs 

986 maps = None 

987 if ctx.exchange.needs_summary(False): 

988 # Only the stock G/N ABI rounds gk; local dhu/finalize retain FP32. 

989 summary_gate = gk.to(qg.dtype) 

990 # The public backward summary processes one window, unlike forward S/M. 

991 summaries = [ops.pre_process_bwd_kernel_merged( 

992 qg, kg, weights, grad, dv_local_head, ctx.scale, 64, 

993 gk=summary_gate, cu_seqlens=ctx.head[index:index + 2]) 

994 for index in range(len(ctx.head) - 1)] 

995 maps = summaries[0] if len(summaries) == 1 else torch.stack(summaries) 

996 del summaries, summary_gate 

997 terminal, send_handle, outgoing = ctx.exchange.exchange(ops, maps, reception, False, ctx.suffix) 

998 if ctx.exchange.info is not None: 

999 terminal = ctx.exchange.info.last_state(terminal) 

1000 # Communication and summary apply retain FP32; only stock dhu requires BF16. 

1001 terminal = None if terminal is None else terminal.to(qg.dtype) 

1002 return terminal, send_handle, outgoing 

1003 

1004 

1005class _AscendCKDAState(torch.autograd.Function): 

1006 """Share native local stages; state protocols optionally inject H and D.""" 

1007 

1008 @staticmethod 

1009 def forward(ctx: Any, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, 

1010 gate: torch.Tensor, beta: torch.Tensor, a_log: torch.Tensor, dt_bias: torch.Tensor, 

1011 scale: float, lower_bound: float, metadata: dict, 

1012 exchange: _NativeStateExchange | None) -> torch.Tensor: 

1013 """Share prepare with S/M and local FwdH, then release gathered maps. 

1014 

1015 Args: 

1016 ctx: Per-invocation autograd context. 

1017 query: Raw token-major queries. 

1018 key: Raw token-major keys. 

1019 value: Token-major values. 

1020 gate: Sequence-major gate logits. 

1021 beta: Sequence-major beta logits. 

1022 a_log: FP32 decay parameters. 

1023 dt_bias: FP32 gate bias. 

1024 scale: Attention scale. 

1025 lower_bound: Safe-gate lower bound. 

1026 metadata: Native packed offsets and chunk indices. 

1027 exchange: Optional state protocol for this invocation. 

1028 """ 

1029 ops = _load_state_ops() 

1030 inputs = (query, key, value, gate, beta, a_log, dt_bias) 

1031 reception = None if exchange is None else exchange.receive(query, True) 

1032 prepared = prepare_kda_native(inputs, scale, lower_bound, metadata) 

1033 initial = send_handle = outgoing = head = suffix = None 

1034 if exchange is not None: 

1035 tail, head, prefix, suffix = _native_ag_intervals( 

1036 exchange.info, exchange.local_length, exchange.rank, exchange.size) 

1037 if exchange.batch_size > 1: 

1038 tail = head = metadata["cu_seqlens"] 

1039 maps = None 

1040 if exchange.needs_summary(True): 

1041 maps = ops.pre_process_fwd_kernel_merged( 

1042 prepared.kg, prepared.w, prepared.u, gk=prepared.gk, cu_seqlens=tail) 

1043 initial, send_handle, outgoing = exchange.exchange(ops, maps, reception, True, prefix) 

1044 del maps, reception 

1045 if exchange.info is not None: 

1046 initial = exchange.info.first_state(initial) 

1047 output = finish_kda_native_forward( 

1048 ctx, inputs, prepared, initial, scale, lower_bound, metadata, 

1049 compress_entry=exchange is not None and exchange.info is not None) 

1050 if send_handle is not None: 

1051 send_handle.wait() 

1052 del outgoing 

1053 ctx.exchange, ctx.head, ctx.suffix = exchange, head, suffix 

1054 return output 

1055 

1056 @staticmethod 

1057 @once_differentiable 

1058 def backward(ctx: Any, grad_output: torch.Tensor) -> tuple: 

1059 """Collect G/N, inject nonzero dHT and finish raw-input gradients. 

1060 

1061 Args: 

1062 ctx: Forward-owned activations and communication metadata. 

1063 grad_output: Sequence-major output gradient. 

1064 """ 

1065 ops = _load_state_ops() 

1066 # Share one unpack across phases, including checkpoint recomputation. 

1067 saved = ctx.saved_tensors 

1068 reception = ctx.exchange.receive(saved[12], False) 

1069 saved = restore_kda_native_backward(ctx, saved) 

1070 gk, weights, qg, kg = saved[4], saved[7], saved[9], saved[10] 

1071 grad, d_aqk, dv_local_head, dq_raw = prepare_kda_native_backward(ctx, saved, grad_output) 

1072 terminal, send_handle, outgoing = _exchange_native_gradient( 

1073 ctx, ops, (gk, qg, kg, weights, grad, dv_local_head), reception) 

1074 del reception 

1075 gradients = finish_kda_native_backward(ctx, saved, grad, d_aqk, dv_local_head, dq_raw, terminal) 

1076 if send_handle is not None: 

1077 send_handle.wait() 

1078 del outgoing 

1079 return (*gradients, None, None, None, None) 

1080 

1081 

1082def ascendc_state_kda( 

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

1084 gate: torch.Tensor, beta: torch.Tensor, *, a_log: torch.Tensor, 

1085 dt_bias: torch.Tensor, state_cp: Any, cp_mesh: Any, sequence_info: Any = None, 

1086 scale: float | None = None, lower_bound: float = -5.0, 

1087 p2p_head_chunks: int = 1, reuse_cp_state_on_recompute: bool = False, cache_key: object = None, 

1088) -> torch.Tensor: 

1089 """Run native KDA with P2P, AllGather, grouped AllGather/P2P, or RD. 

1090 

1091 Args: 

1092 query: Raw BF16 queries [B,T,H,128]; packed sequences require B=1. 

1093 key: Matching raw keys. 

1094 value: BF16 values with the query shape. 

1095 gate: Raw gate logits with the query shape. 

1096 beta: Raw beta logits [B,T,H]. 

1097 a_log: Per-head FP32 decay parameters. 

1098 dt_bias: FP32 gate bias [H,128]. 

1099 state_cp: Existing gather/RD executor, or None for ordinary P2P. 

1100 cp_mesh: Ordered state mesh after any Ulysses redistribution. 

1101 sequence_info: Packed interval metadata after any Ulysses redistribution. 

1102 scale: Attention scale, default 1/sqrt(128). 

1103 lower_bound: Safe gate lower bound. 

1104 p2p_head_chunks: Number of state packets for ordinary P2P; keeps Prepare and summaries unsplit. 

1105 reuse_cp_state_on_recompute: Reuse this forward entry during a HyperParallel checkpoint replay. 

1106 cache_key: Stable caller identity; direct callers otherwise follow invocation order. 

1107 

1108 Returns: 

1109 Output with the query shape. Uses the unmodified native stage APIs: 

1110 backward summary gk and local dhu dHT are converted to model dtype. 

1111 Prepared gates, communicated states and summary apply remain FP32. 

1112 These ABI conversions introduce rounding relative to FP32-input kernels. 

1113 """ 

1114 if query.device.type != "npu" or query.dtype != torch.bfloat16: 

1115 raise ValueError("Native KDA state CP requires BF16 NPU inputs.") 

1116 if query.ndim != 4 or query.shape[0] < 1 or query.shape[-1] != 128: 

1117 raise ValueError("Native KDA state CP requires [B,T,H,128] inputs.") 

1118 if sequence_info is not None and query.shape[0] != 1: 

1119 raise ValueError("Packed native KDA state CP requires physical batch size 1.") 

1120 if any(tensor.shape != query.shape for tensor in (key, value, gate)) or beta.shape != query.shape[:-1]: 

1121 raise ValueError("Native KDA state CP requires matching Q/K/V/gate heads and beta [B,T,H].") 

1122 batch, tokens = query.shape[:2] 

1123 offsets = None if sequence_info is None else sequence_info.local_offsets 

1124 if batch > 1: 

1125 offsets = tuple(index * tokens for index in range(batch + 1)) 

1126 metadata = local_chunk_metadata(offsets, batch * tokens) 

1127 scale = query.shape[-1] ** -0.5 if scale is None else float(scale) 

1128 exchange = _NativeStateExchange(cp_mesh, state_cp, sequence_info, tokens, query.shape[2], 

1129 p2p_head_chunks, reuse_cp_state_on_recompute=reuse_cp_state_on_recompute, 

1130 cache_key=cache_key, algorithm="kda", batch_size=batch) 

1131 # Local packing preserves the state mesh: every sample still follows its 

1132 # own cross-rank chain. Parameters retain their original head dimensions. 

1133 inputs = tuple(tensor.reshape(1, batch * tokens, *tensor.shape[2:]).contiguous() 

1134 for tensor in (query, key, value, gate, beta)) 

1135 output = _AscendCKDAState.apply( 

1136 *inputs, a_log.reshape(-1).clone(), 

1137 dt_bias.reshape(-1, query.shape[-1]).clone(), scale, lower_bound, metadata, exchange) 

1138 return output.reshape_as(value)