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

197 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# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang 

16 

17# Keep the validated kernel adapter close to its upstream implementation. 

18# pylint: disable=line-too-long,missing-public-type-hints,missing-public-docstring 

19# pylint: disable=non-google-docstring,disallowed-name,unused-argument,invalid-name 

20# pylint: disable=missing-module-docstring,missing-function-docstring 

21# pylint: disable=abstract-method,arguments-differ 

22 

23import warnings 

24from typing import Any, Optional 

25 

26import torch 

27import triton 

28 

29from ._triton.gated_delta_net.state_summary import ( 

30 gdn_packed_state_summary_kernel, gdn_state_grad_ext_kernel, 

31) 

32from ._triton.gated_delta_net.chunk_delta_h import chunk_gated_delta_rule_bwd_dhu, chunk_gated_delta_rule_fwd_h 

33from ._triton.gated_delta_net.chunk_o import chunk_bwd_dqkwg, chunk_bwd_dv_local, chunk_fwd_o 

34from ._triton.gated_delta_net.chunk_scaled_dot_kkt import chunk_scaled_dot_kkt_fwd 

35from ._triton.gated_delta_net.cumsum import chunk_local_cumsum 

36from ._triton.gated_delta_net.solve_tril import solve_tril 

37from ._triton.gated_delta_net.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard 

38from ._triton.gated_delta_net.wy_fast import prepare_wy_repr_bwd, recompute_w_u_fwd 

39 

40 

41def _l2norm(x: torch.Tensor, eps: float = 1e-6) -> tuple[torch.Tensor, torch.Tensor]: 

42 inv_norm = torch.rsqrt((x * x).sum(dim=-1, keepdim=True) + eps) 

43 return (x * inv_norm).to(x.dtype), inv_norm 

44 

45 

46def chunk_gated_delta_rule_fwd_prepare( 

47 k: torch.Tensor, 

48 v: torch.Tensor, 

49 g: torch.Tensor, 

50 beta: torch.Tensor, 

51 cu_seqlens: Optional[torch.LongTensor] = None, 

52 chunk_size: int = 64, 

53) -> tuple: 

54 """Compute forward intermediates that do not depend on the initial state. 

55 

56 Args: 

57 k: Key activations in token-major layout. 

58 v: Value activations in token-major layout. 

59 g: Log-decay gates, cumulative when supplied by prepare. 

60 beta: Activated delta-rule update weights. 

61 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

62 chunk_size: Tokens per recurrence chunk. 

63 """ 

64 g = chunk_local_cumsum(g, chunk_size=chunk_size, cu_seqlens=cu_seqlens, head_first=False) 

65 matrix_a = chunk_scaled_dot_kkt_fwd( 

66 k=k, 

67 g=g, 

68 beta=beta, 

69 cu_seqlens=cu_seqlens, 

70 chunk_size=chunk_size, 

71 output_dtype=torch.float32, 

72 ) 

73 matrix_a = solve_tril(A=matrix_a, cu_seqlens=cu_seqlens, output_dtype=k.dtype) 

74 w, u = recompute_w_u_fwd( 

75 k=k, 

76 v=v, 

77 beta=beta, 

78 A=matrix_a, 

79 g=g, 

80 cu_seqlens=cu_seqlens, 

81 ) 

82 return g, matrix_a, w, u 

83 

84 

85def chunk_gated_delta_rule_fwd_apply_state( 

86 k: torch.Tensor, 

87 g: torch.Tensor, 

88 w: torch.Tensor, 

89 u: torch.Tensor, 

90 initial_state: Optional[torch.Tensor], 

91 output_final_state: bool, 

92 cu_seqlens: Optional[torch.LongTensor] = None, 

93 chunk_size: int = 64, 

94) -> tuple: 

95 """Apply the recurrent initial state and return local state intermediates. 

96 

97 Args: 

98 k: Key activations in token-major layout. 

99 g: Log-decay gates, cumulative when supplied by prepare. 

100 w: Prepared key/update projection for the recurrent state. 

101 u: Prepared value/update projection. 

102 initial_state: Optional state entering the local sequence. 

103 output_final_state: Whether to return the terminal state. 

104 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

105 chunk_size: Tokens per recurrence chunk. 

106 """ 

107 return chunk_gated_delta_rule_fwd_h( 

108 k=k, 

109 w=w, 

110 u=u, 

111 g=g, 

112 initial_state=initial_state, 

113 output_final_state=output_final_state, 

114 chunk_size=chunk_size, 

115 cu_seqlens=cu_seqlens, 

116 ) 

117 

118 

119def chunk_gated_delta_rule_fwd_output( 

120 q: torch.Tensor, 

121 k: torch.Tensor, 

122 v_new: torch.Tensor, 

123 h: torch.Tensor, 

124 g: torch.Tensor, 

125 scale: float, 

126 cu_seqlens: Optional[torch.LongTensor] = None, 

127 chunk_size: int = 64, 

128) -> torch.Tensor: 

129 """Compute local outputs after recurrent states have been applied. 

130 

131 Args: 

132 q: Query activations in token-major layout. 

133 k: Key activations in token-major layout. 

134 v_new: Values corrected by their incoming chunk states. 

135 h: Saved chunk-entry recurrent states. 

136 g: Log-decay gates, cumulative when supplied by prepare. 

137 scale: Attention output scaling factor. 

138 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

139 chunk_size: Tokens per recurrence chunk. 

140 """ 

141 return chunk_fwd_o( 

142 q=q, 

143 k=k, 

144 v=v_new, 

145 h=h, 

146 g=g, 

147 scale=scale, 

148 cu_seqlens=cu_seqlens, 

149 chunk_size=chunk_size, 

150 ) 

151 

152 

153def chunk_gated_delta_rule_fwd( 

154 q: torch.Tensor, 

155 k: torch.Tensor, 

156 v: torch.Tensor, 

157 g: torch.Tensor, 

158 beta: torch.Tensor, 

159 scale: float, 

160 initial_state: torch.Tensor, 

161 output_final_state: bool, 

162 cu_seqlens: Optional[torch.LongTensor] = None, 

163 chunk_size: int = 64, 

164) -> tuple: 

165 """Prepare chunks, apply their incoming state and finalize token outputs. 

166 

167 Args: 

168 q: Query activations in token-major layout. 

169 k: Key activations in token-major layout. 

170 v: Value activations in token-major layout. 

171 g: Log-decay gates, cumulative when supplied by prepare. 

172 beta: Activated delta-rule update weights. 

173 scale: Attention output scaling factor. 

174 initial_state: Optional state entering the local sequence. 

175 output_final_state: Whether to return the terminal state. 

176 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

177 chunk_size: Tokens per recurrence chunk. 

178 """ 

179 g, matrix_a, w, u = chunk_gated_delta_rule_fwd_prepare( 

180 k=k, 

181 v=v, 

182 g=g, 

183 beta=beta, 

184 cu_seqlens=cu_seqlens, 

185 chunk_size=chunk_size, 

186 ) 

187 h, v_new, final_state = chunk_gated_delta_rule_fwd_apply_state( 

188 k=k, 

189 g=g, 

190 w=w, 

191 u=u, 

192 initial_state=initial_state, 

193 output_final_state=output_final_state, 

194 cu_seqlens=cu_seqlens, 

195 chunk_size=chunk_size, 

196 ) 

197 output = chunk_gated_delta_rule_fwd_output( 

198 q=q, 

199 k=k, 

200 v_new=v_new, 

201 h=h, 

202 g=g, 

203 scale=scale, 

204 cu_seqlens=cu_seqlens, 

205 chunk_size=chunk_size, 

206 ) 

207 return g, output, matrix_a, final_state 

208 

209 

210def chunk_gated_delta_rule_bwd_prepare( 

211 q: torch.Tensor, 

212 k: torch.Tensor, 

213 v: torch.Tensor, 

214 g: torch.Tensor, 

215 beta: torch.Tensor, 

216 A: torch.Tensor, 

217 scale: float, 

218 initial_state: Optional[torch.Tensor], 

219 do: torch.Tensor, 

220 cu_seqlens: Optional[torch.LongTensor] = None, 

221 chunk_size: int = 64, 

222) -> tuple: 

223 """Compute backward intermediates that do not depend on final-state grad. 

224 

225 Args: 

226 q: Query activations in token-major layout. 

227 k: Key activations in token-major layout. 

228 v: Value activations in token-major layout. 

229 g: Log-decay gates, cumulative when supplied by prepare. 

230 beta: Activated delta-rule update weights. 

231 A: Solved per-chunk WY representation. 

232 scale: Attention output scaling factor. 

233 initial_state: Optional state entering the local sequence. 

234 do: Gradient of the local output. 

235 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

236 chunk_size: Tokens per recurrence chunk. 

237 """ 

238 w, u = recompute_w_u_fwd( 

239 k=k, 

240 v=v, 

241 beta=beta, 

242 A=A, 

243 g=g, 

244 cu_seqlens=cu_seqlens, 

245 ) 

246 h, v_new, _ = chunk_gated_delta_rule_fwd_apply_state( 

247 k=k, 

248 g=g, 

249 w=w, 

250 u=u, 

251 initial_state=initial_state, 

252 output_final_state=False, 

253 cu_seqlens=cu_seqlens, 

254 chunk_size=chunk_size, 

255 ) 

256 dv = chunk_bwd_dv_local( 

257 q=q, 

258 k=k, 

259 g=g, 

260 do=do, 

261 scale=scale, 

262 cu_seqlens=cu_seqlens, 

263 chunk_size=chunk_size, 

264 ) 

265 return w, h, v_new, dv 

266 

267 

268def chunk_gated_delta_rule_bwd_state( 

269 q: torch.Tensor, 

270 k: torch.Tensor, 

271 w: torch.Tensor, 

272 g: torch.Tensor, 

273 initial_state: Optional[torch.Tensor], 

274 dht: Optional[torch.Tensor], 

275 do: torch.Tensor, 

276 dv: torch.Tensor, 

277 scale: float, 

278 cu_seqlens: Optional[torch.LongTensor] = None, 

279 chunk_size: int = 64, 

280) -> tuple: 

281 """Apply the final-state gradient and produce the initial-state gradient. 

282 

283 Args: 

284 q: Query activations in token-major layout. 

285 k: Key activations in token-major layout. 

286 w: Prepared key/update projection for the recurrent state. 

287 g: Log-decay gates, cumulative when supplied by prepare. 

288 initial_state: Optional state entering the local sequence. 

289 dht: Optional gradient of the terminal recurrent state. 

290 do: Gradient of the local output. 

291 dv: Value gradient to propagate through the next local stage. 

292 scale: Attention output scaling factor. 

293 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

294 chunk_size: Tokens per recurrence chunk. 

295 """ 

296 return chunk_gated_delta_rule_bwd_dhu( 

297 q=q, 

298 k=k, 

299 w=w, 

300 g=g, 

301 h0=initial_state, 

302 dht=dht, 

303 do=do, 

304 dv=dv, 

305 scale=scale, 

306 cu_seqlens=cu_seqlens, 

307 chunk_size=chunk_size, 

308 ) 

309 

310 

311def chunk_gated_delta_rule_bwd_finish( 

312 q: torch.Tensor, 

313 k: torch.Tensor, 

314 v: torch.Tensor, 

315 g: torch.Tensor, 

316 beta: torch.Tensor, 

317 A: torch.Tensor, 

318 w: torch.Tensor, 

319 h: torch.Tensor, 

320 v_new: torch.Tensor, 

321 dv: torch.Tensor, 

322 do: torch.Tensor, 

323 dh: torch.Tensor, 

324 scale: float, 

325 cu_seqlens: Optional[torch.LongTensor] = None, 

326 chunk_size: int = 64, 

327) -> tuple: 

328 """Finish local tensor gradients after the state-gradient handoff. 

329 

330 Args: 

331 q: Query activations in token-major layout. 

332 k: Key activations in token-major layout. 

333 v: Value activations in token-major layout. 

334 g: Log-decay gates, cumulative when supplied by prepare. 

335 beta: Activated delta-rule update weights. 

336 A: Solved per-chunk WY representation. 

337 w: Prepared key/update projection for the recurrent state. 

338 h: Saved chunk-entry recurrent states. 

339 v_new: Values corrected by their incoming chunk states. 

340 dv: Value gradient to propagate through the next local stage. 

341 do: Gradient of the local output. 

342 dh: Gradients of chunk-entry recurrent states. 

343 scale: Attention output scaling factor. 

344 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

345 chunk_size: Tokens per recurrence chunk. 

346 """ 

347 dq, dk, dw, dg = chunk_bwd_dqkwg( 

348 q=q, 

349 k=k, 

350 v=v_new, 

351 w=w, 

352 g=g, 

353 h=h, 

354 dv=dv, 

355 do=do, 

356 dh=dh, 

357 chunk_size=chunk_size, 

358 scale=scale, 

359 cu_seqlens=cu_seqlens, 

360 ) 

361 dk2, dv, db, dg2 = prepare_wy_repr_bwd( 

362 k=k, 

363 v=v, 

364 beta=beta, 

365 g=g, 

366 A=A, 

367 dw=dw, 

368 du=dv, 

369 cu_seqlens=cu_seqlens, 

370 chunk_size=chunk_size, 

371 ) 

372 dk.add_(dk2) 

373 dg.add_(dg2) 

374 if dg.dtype != torch.float32: 

375 raise ValueError(f"dg current type is {dg.dtype} , should be float32") 

376 dg = chunk_local_cumsum( 

377 dg, 

378 chunk_size=chunk_size, 

379 reverse=True, 

380 cu_seqlens=cu_seqlens, 

381 head_first=False, 

382 ) 

383 return dq, dk, dv, db, dg 

384 

385 

386def chunk_gated_delta_rule_bwd( 

387 q: torch.Tensor, 

388 k: torch.Tensor, 

389 v: torch.Tensor, 

390 g: torch.Tensor, 

391 beta: torch.Tensor, 

392 A: torch.Tensor, 

393 scale: float, 

394 initial_state: torch.Tensor, 

395 do: torch.Tensor, 

396 dht: torch.Tensor, 

397 cu_seqlens: Optional[torch.LongTensor] = None, 

398 chunk_size: int = 64, 

399) -> tuple: 

400 """Reconstruct local intermediates and return raw input gradients. 

401 

402 Args: 

403 q: Query activations in token-major layout. 

404 k: Key activations in token-major layout. 

405 v: Value activations in token-major layout. 

406 g: Log-decay gates, cumulative when supplied by prepare. 

407 beta: Activated delta-rule update weights. 

408 A: Solved per-chunk WY representation. 

409 scale: Attention output scaling factor. 

410 initial_state: Optional state entering the local sequence. 

411 do: Gradient of the local output. 

412 dht: Optional gradient of the terminal recurrent state. 

413 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

414 chunk_size: Tokens per recurrence chunk. 

415 """ 

416 w, h, v_new, dv = chunk_gated_delta_rule_bwd_prepare( 

417 q=q, 

418 k=k, 

419 v=v, 

420 g=g, 

421 beta=beta, 

422 A=A, 

423 scale=scale, 

424 initial_state=initial_state, 

425 do=do, 

426 cu_seqlens=cu_seqlens, 

427 chunk_size=chunk_size, 

428 ) 

429 dh, dh0, dv = chunk_gated_delta_rule_bwd_state( 

430 q=q, 

431 k=k, 

432 w=w, 

433 g=g, 

434 initial_state=initial_state, 

435 dht=dht, 

436 do=do, 

437 dv=dv, 

438 scale=scale, 

439 cu_seqlens=cu_seqlens, 

440 chunk_size=chunk_size, 

441 ) 

442 dq, dk, dv, db, dg = chunk_gated_delta_rule_bwd_finish( 

443 q=q, 

444 k=k, 

445 v=v, 

446 g=g, 

447 beta=beta, 

448 A=A, 

449 w=w, 

450 h=h, 

451 v_new=v_new, 

452 dv=dv, 

453 do=do, 

454 dh=dh, 

455 scale=scale, 

456 cu_seqlens=cu_seqlens, 

457 chunk_size=chunk_size, 

458 ) 

459 return dq, dk, dv, db, dg, dh0 

460 

461 

462@torch.compiler.disable 

463@input_guard 

464def chunk_gated_delta_rule_fwd_prepare_saved( 

465 q: torch.Tensor, 

466 k: torch.Tensor, 

467 v: torch.Tensor, 

468 g: torch.Tensor, 

469 beta: torch.Tensor, 

470 scale: float = None, 

471 use_qk_l2norm_in_kernel: bool = False, 

472 chunk_size: int = 64, 

473 cu_seqlens: torch.Tensor = None, 

474) -> tuple: 

475 """Prepare fused GDN forward tensors without consuming the initial state. 

476 

477 Args: 

478 q: Query activations in token-major layout. 

479 k: Key activations in token-major layout. 

480 v: Value activations in token-major layout. 

481 g: Log-decay gates, cumulative when supplied by prepare. 

482 beta: Activated delta-rule update weights. 

483 scale: Attention output scaling factor. 

484 use_qk_l2norm_in_kernel: Whether local stages normalize Q/K and differentiate that normalization. 

485 chunk_size: Tokens per recurrence chunk. 

486 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

487 """ 

488 if scale is None: 

489 scale = k.shape[-1] ** -0.5 

490 

491 q_norm, q_inv_norm = q, q.new_empty(0) 

492 k_norm, k_inv_norm = k, k.new_empty(0) 

493 if use_qk_l2norm_in_kernel: 

494 q_norm, q_inv_norm = _l2norm(q) 

495 k_norm, k_inv_norm = _l2norm(k) 

496 

497 g_cumsum, matrix_a, w, u = chunk_gated_delta_rule_fwd_prepare( 

498 k=k_norm, 

499 v=v, 

500 g=g, 

501 beta=beta, 

502 chunk_size=chunk_size, 

503 cu_seqlens=cu_seqlens, 

504 ) 

505 return ( 

506 q_norm, 

507 k_norm, 

508 q_inv_norm, 

509 k_inv_norm, 

510 g_cumsum, 

511 matrix_a, 

512 w, 

513 u, 

514 scale, 

515 ) 

516 

517 

518@torch.compiler.disable 

519@input_guard 

520def chunk_gated_delta_rule_fwd_apply_state_saved( 

521 k_norm: torch.Tensor, 

522 g_cumsum: torch.Tensor, 

523 w: torch.Tensor, 

524 u: torch.Tensor, 

525 initial_state: torch.Tensor = None, 

526 output_final_state: bool = True, 

527 chunk_size: int = 64, 

528 cu_seqlens: torch.Tensor = None, 

529) -> tuple: 

530 """Apply an initial state to fused prepared forward tensors. 

531 

532 Args: 

533 k_norm: Normalized key activations. 

534 g_cumsum: Per-chunk cumulative log-decay gates. 

535 w: Prepared key/update projection for the recurrent state. 

536 u: Prepared value/update projection. 

537 initial_state: Optional state entering the local sequence. 

538 output_final_state: Whether to return the terminal state. 

539 chunk_size: Tokens per recurrence chunk. 

540 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

541 """ 

542 return chunk_gated_delta_rule_fwd_apply_state( 

543 k=k_norm, 

544 g=g_cumsum, 

545 w=w, 

546 u=u, 

547 initial_state=initial_state, 

548 output_final_state=output_final_state, 

549 chunk_size=chunk_size, 

550 cu_seqlens=cu_seqlens, 

551 ) 

552 

553 

554@torch.compiler.disable 

555@input_guard 

556def chunk_gated_delta_rule_fwd_output_saved( 

557 q_norm: torch.Tensor, 

558 k_norm: torch.Tensor, 

559 g_cumsum: torch.Tensor, 

560 h: torch.Tensor, 

561 v_new: torch.Tensor, 

562 scale: float, 

563 chunk_size: int = 64, 

564 cu_seqlens: torch.Tensor = None, 

565) -> torch.Tensor: 

566 """Compute fused GDN output from prepared, state-applied tensors. 

567 

568 Args: 

569 q_norm: Normalized query activations. 

570 k_norm: Normalized key activations. 

571 g_cumsum: Per-chunk cumulative log-decay gates. 

572 h: Saved chunk-entry recurrent states. 

573 v_new: Values corrected by their incoming chunk states. 

574 scale: Attention output scaling factor. 

575 chunk_size: Tokens per recurrence chunk. 

576 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

577 """ 

578 return chunk_gated_delta_rule_fwd_output( 

579 q=q_norm, 

580 k=k_norm, 

581 v_new=v_new, 

582 h=h, 

583 g=g_cumsum, 

584 scale=scale, 

585 chunk_size=chunk_size, 

586 cu_seqlens=cu_seqlens, 

587 ) 

588 

589 

590@torch.compiler.disable 

591@input_guard 

592def chunk_gated_delta_rule_fwd_saved( 

593 q: torch.Tensor, 

594 k: torch.Tensor, 

595 v: torch.Tensor, 

596 g: torch.Tensor, 

597 beta: torch.Tensor, 

598 scale: float = None, 

599 initial_state: torch.Tensor = None, 

600 use_qk_l2norm_in_kernel: bool = False, 

601 chunk_size: int = 64, 

602 cu_seqlens: torch.Tensor = None, 

603) -> tuple: 

604 """Run fused GDN forward and return the tensors required by its backward. 

605 

606 Args: 

607 q: Query activations in token-major layout. 

608 k: Key activations in token-major layout. 

609 v: Value activations in token-major layout. 

610 g: Log-decay gates, cumulative when supplied by prepare. 

611 beta: Activated delta-rule update weights. 

612 scale: Attention output scaling factor. 

613 initial_state: Optional state entering the local sequence. 

614 use_qk_l2norm_in_kernel: Whether local stages normalize Q/K and differentiate that normalization. 

615 chunk_size: Tokens per recurrence chunk. 

616 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

617 """ 

618 ( 

619 q_norm, 

620 k_norm, 

621 q_inv_norm, 

622 k_inv_norm, 

623 g_cumsum, 

624 matrix_a, 

625 w, 

626 u, 

627 scale, 

628 ) = chunk_gated_delta_rule_fwd_prepare_saved( 

629 q, 

630 k, 

631 v, 

632 g, 

633 beta, 

634 scale=scale, 

635 use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, 

636 chunk_size=chunk_size, 

637 cu_seqlens=cu_seqlens, 

638 ) 

639 h, v_new, final_state = chunk_gated_delta_rule_fwd_apply_state_saved( 

640 k_norm, 

641 g_cumsum, 

642 w, 

643 u, 

644 initial_state=initial_state, 

645 output_final_state=True, 

646 chunk_size=chunk_size, 

647 cu_seqlens=cu_seqlens, 

648 ) 

649 output = chunk_gated_delta_rule_fwd_output_saved( 

650 q_norm, 

651 k_norm, 

652 g_cumsum, 

653 h, 

654 v_new, 

655 scale, 

656 chunk_size=chunk_size, 

657 cu_seqlens=cu_seqlens, 

658 ) 

659 return ( 

660 output.to(q.dtype), 

661 final_state, 

662 q_norm, 

663 k_norm, 

664 q_inv_norm, 

665 k_inv_norm, 

666 g_cumsum, 

667 matrix_a, 

668 scale, 

669 ) 

670 

671 

672@torch.compiler.disable 

673@input_guard 

674def chunk_gated_delta_rule_bwd_prepare_saved( 

675 q_norm: torch.Tensor, 

676 k_norm: torch.Tensor, 

677 v: torch.Tensor, 

678 g_cumsum: torch.Tensor, 

679 beta: torch.Tensor, 

680 A: torch.Tensor, 

681 initial_state: torch.Tensor, 

682 grad_output: torch.Tensor, 

683 scale: float, 

684 chunk_size: int = 64, 

685 cu_seqlens: torch.Tensor = None, 

686) -> tuple: 

687 """Prepare fused backward tensors before the final-state grad arrives. 

688 

689 Args: 

690 q_norm: Normalized query activations. 

691 k_norm: Normalized key activations. 

692 v: Value activations in token-major layout. 

693 g_cumsum: Per-chunk cumulative log-decay gates. 

694 beta: Activated delta-rule update weights. 

695 A: Solved per-chunk WY representation. 

696 initial_state: Optional state entering the local sequence. 

697 grad_output: Gradient of the local output. 

698 scale: Attention output scaling factor. 

699 chunk_size: Tokens per recurrence chunk. 

700 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

701 """ 

702 return chunk_gated_delta_rule_bwd_prepare( 

703 q=q_norm, 

704 k=k_norm, 

705 v=v, 

706 g=g_cumsum, 

707 beta=beta, 

708 A=A, 

709 scale=scale, 

710 initial_state=initial_state, 

711 do=grad_output, 

712 chunk_size=chunk_size, 

713 cu_seqlens=cu_seqlens, 

714 ) 

715 

716 

717@torch.compiler.disable 

718@input_guard 

719def chunk_gated_delta_rule_bwd_state_saved( 

720 q_norm: torch.Tensor, 

721 k_norm: torch.Tensor, 

722 g_cumsum: torch.Tensor, 

723 w: torch.Tensor, 

724 initial_state: torch.Tensor, 

725 grad_final_state: torch.Tensor, 

726 grad_output: torch.Tensor, 

727 dv_local: torch.Tensor, 

728 scale: float, 

729 chunk_size: int = 64, 

730 cu_seqlens: torch.Tensor = None, 

731) -> tuple: 

732 """Consume the final-state grad and produce the initial-state grad. 

733 

734 Args: 

735 q_norm: Normalized query activations. 

736 k_norm: Normalized key activations. 

737 g_cumsum: Per-chunk cumulative log-decay gates. 

738 w: Prepared key/update projection for the recurrent state. 

739 initial_state: Optional state entering the local sequence. 

740 grad_final_state: Optional gradient of the terminal recurrent state. 

741 grad_output: Gradient of the local output. 

742 dv_local: Output-stage value gradient before recurrent correction. 

743 scale: Attention output scaling factor. 

744 chunk_size: Tokens per recurrence chunk. 

745 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

746 """ 

747 return chunk_gated_delta_rule_bwd_state( 

748 q=q_norm, 

749 k=k_norm, 

750 w=w, 

751 g=g_cumsum, 

752 initial_state=initial_state, 

753 dht=grad_final_state, 

754 do=grad_output, 

755 dv=dv_local, 

756 scale=scale, 

757 chunk_size=chunk_size, 

758 cu_seqlens=cu_seqlens, 

759 ) 

760 

761 

762@torch.compiler.disable 

763@input_guard 

764def chunk_gated_delta_rule_bwd_finish_saved( 

765 q: torch.Tensor, 

766 k: torch.Tensor, 

767 q_norm: torch.Tensor, 

768 k_norm: torch.Tensor, 

769 v: torch.Tensor, 

770 g_cumsum: torch.Tensor, 

771 beta: torch.Tensor, 

772 A: torch.Tensor, 

773 w: torch.Tensor, 

774 h: torch.Tensor, 

775 v_new: torch.Tensor, 

776 dv: torch.Tensor, 

777 grad_output: torch.Tensor, 

778 dh: torch.Tensor, 

779 q_inv_norm: torch.Tensor, 

780 k_inv_norm: torch.Tensor, 

781 scale: float, 

782 use_qk_l2norm_in_kernel: bool = False, 

783 chunk_size: int = 64, 

784 cu_seqlens: torch.Tensor = None, 

785) -> tuple: 

786 """Finish local fused gradients after the P2P state-gradient handoff. 

787 

788 Args: 

789 q: Query activations in token-major layout. 

790 k: Key activations in token-major layout. 

791 q_norm: Normalized query activations. 

792 k_norm: Normalized key activations. 

793 v: Value activations in token-major layout. 

794 g_cumsum: Per-chunk cumulative log-decay gates. 

795 beta: Activated delta-rule update weights. 

796 A: Solved per-chunk WY representation. 

797 w: Prepared key/update projection for the recurrent state. 

798 h: Saved chunk-entry recurrent states. 

799 v_new: Values corrected by their incoming chunk states. 

800 dv: Value gradient to propagate through the next local stage. 

801 grad_output: Gradient of the local output. 

802 dh: Gradients of chunk-entry recurrent states. 

803 q_inv_norm: Saved query inverse L2 norms. 

804 k_inv_norm: Saved key inverse L2 norms. 

805 scale: Attention output scaling factor. 

806 use_qk_l2norm_in_kernel: Whether local stages normalize Q/K and differentiate that normalization. 

807 chunk_size: Tokens per recurrence chunk. 

808 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

809 """ 

810 dq, dk, dv, dbeta, dg = chunk_gated_delta_rule_bwd_finish( 

811 q=q_norm, 

812 k=k_norm, 

813 v=v, 

814 g=g_cumsum, 

815 beta=beta, 

816 A=A, 

817 w=w, 

818 h=h, 

819 v_new=v_new, 

820 dv=dv, 

821 do=grad_output, 

822 dh=dh, 

823 scale=scale, 

824 chunk_size=chunk_size, 

825 cu_seqlens=cu_seqlens, 

826 ) 

827 if use_qk_l2norm_in_kernel: 

828 with torch.enable_grad(): 

829 q_leaf = q.detach().requires_grad_(True) 

830 k_leaf = k.detach().requires_grad_(True) 

831 q_recomputed, _ = _l2norm(q_leaf) 

832 k_recomputed, _ = _l2norm(k_leaf) 

833 dq, dk = torch.autograd.grad( 

834 (q_recomputed, k_recomputed), 

835 (q_leaf, k_leaf), 

836 grad_outputs=(dq, dk), 

837 ) 

838 del q_inv_norm, k_inv_norm 

839 return dq, dk, dv, dg, dbeta 

840 

841 

842@torch.compiler.disable 

843@input_guard 

844def chunk_gated_delta_rule_bwd_saved( 

845 q: torch.Tensor, 

846 k: torch.Tensor, 

847 q_norm: torch.Tensor, 

848 k_norm: torch.Tensor, 

849 v: torch.Tensor, 

850 g_cumsum: torch.Tensor, 

851 beta: torch.Tensor, 

852 A: torch.Tensor, 

853 initial_state: torch.Tensor, 

854 grad_output: torch.Tensor, 

855 grad_final_state: torch.Tensor, 

856 q_inv_norm: torch.Tensor, 

857 k_inv_norm: torch.Tensor, 

858 scale: float, 

859 use_qk_l2norm_in_kernel: bool = False, 

860 chunk_size: int = 64, 

861 cu_seqlens: torch.Tensor = None, 

862) -> tuple: 

863 """Run fused GDN backward from a context saved by the forward helper. 

864 

865 Args: 

866 q: Query activations in token-major layout. 

867 k: Key activations in token-major layout. 

868 q_norm: Normalized query activations. 

869 k_norm: Normalized key activations. 

870 v: Value activations in token-major layout. 

871 g_cumsum: Per-chunk cumulative log-decay gates. 

872 beta: Activated delta-rule update weights. 

873 A: Solved per-chunk WY representation. 

874 initial_state: Optional state entering the local sequence. 

875 grad_output: Gradient of the local output. 

876 grad_final_state: Optional gradient of the terminal recurrent state. 

877 q_inv_norm: Saved query inverse L2 norms. 

878 k_inv_norm: Saved key inverse L2 norms. 

879 scale: Attention output scaling factor. 

880 use_qk_l2norm_in_kernel: Whether local stages normalize Q/K and differentiate that normalization. 

881 chunk_size: Tokens per recurrence chunk. 

882 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

883 """ 

884 w, h, v_new, dv = chunk_gated_delta_rule_bwd_prepare_saved( 

885 q_norm, 

886 k_norm, 

887 v, 

888 g_cumsum, 

889 beta, 

890 A, 

891 initial_state, 

892 grad_output, 

893 scale, 

894 chunk_size=chunk_size, 

895 cu_seqlens=cu_seqlens, 

896 ) 

897 dh, dh0, dv = chunk_gated_delta_rule_bwd_state_saved( 

898 q_norm, 

899 k_norm, 

900 g_cumsum, 

901 w, 

902 initial_state, 

903 grad_final_state, 

904 grad_output, 

905 dv, 

906 scale, 

907 chunk_size=chunk_size, 

908 cu_seqlens=cu_seqlens, 

909 ) 

910 dq, dk, dv, dg, dbeta = chunk_gated_delta_rule_bwd_finish_saved( 

911 q, 

912 k, 

913 q_norm, 

914 k_norm, 

915 v, 

916 g_cumsum, 

917 beta, 

918 A, 

919 w, 

920 h, 

921 v_new, 

922 dv, 

923 grad_output, 

924 dh, 

925 q_inv_norm, 

926 k_inv_norm, 

927 scale, 

928 use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, 

929 chunk_size=chunk_size, 

930 cu_seqlens=cu_seqlens, 

931 ) 

932 return dq, dk, dv, dg, dbeta, dh0 

933 

934 

935class ChunkGatedDeltaRuleFunction(torch.autograd.Function): 

936 """Autograd wrapper for the Triton-Ascend chunk Gated Delta Rule.""" 

937 

938 @staticmethod 

939 @input_guard 

940 @autocast_custom_fwd 

941 def forward( 

942 ctx: Any, 

943 q: torch.Tensor, 

944 k: torch.Tensor, 

945 v: torch.Tensor, 

946 g: torch.Tensor, 

947 beta: torch.Tensor, 

948 scale: float, 

949 initial_state: torch.Tensor, 

950 output_final_state: bool, 

951 cu_seqlens: Optional[torch.LongTensor] = None, 

952 use_qk_l2norm_in_kernel: bool = False, 

953 chunk_size: int = 64, 

954 ) -> tuple: 

955 """Save the local recurrence inputs and normalization auxiliaries. 

956 

957 Args: 

958 ctx: Autograd context owned by this invocation. 

959 q: Query activations in token-major layout. 

960 k: Key activations in token-major layout. 

961 v: Value activations in token-major layout. 

962 g: Log-decay gates, cumulative when supplied by prepare. 

963 beta: Activated delta-rule update weights. 

964 scale: Attention output scaling factor. 

965 initial_state: Optional state entering the local sequence. 

966 output_final_state: Whether to return the terminal state. 

967 cu_seqlens: Optional cumulative offsets delimiting packed documents. 

968 use_qk_l2norm_in_kernel: Whether local stages normalize Q/K and differentiate that normalization. 

969 chunk_size: Tokens per recurrence chunk. 

970 """ 

971 g, output, matrix_a, final_state = chunk_gated_delta_rule_fwd( 

972 q=q, 

973 k=k, 

974 v=v, 

975 g=g, 

976 beta=beta, 

977 scale=scale, 

978 initial_state=initial_state, 

979 output_final_state=output_final_state, 

980 cu_seqlens=cu_seqlens, 

981 chunk_size=chunk_size, 

982 ) 

983 

984 saved_initial_state = initial_state if initial_state is not None else q.new_empty(0) 

985 saved_cu_seqlens = cu_seqlens if cu_seqlens is not None else q.new_empty(0, dtype=torch.long) 

986 ctx.save_for_backward(q, k, v, g, beta, matrix_a, saved_initial_state, saved_cu_seqlens) 

987 ctx.has_initial_state = initial_state is not None 

988 ctx.has_cu_seqlens = cu_seqlens is not None 

989 ctx.scale = scale 

990 ctx.chunk_size = chunk_size 

991 return output.to(q.dtype), final_state 

992 

993 @staticmethod 

994 @input_guard 

995 @autocast_custom_bwd 

996 def backward( 

997 ctx: Any, 

998 do: torch.Tensor, 

999 dht: torch.Tensor 

1000 ) -> tuple: 

1001 """Differentiate the local recurrence and restore input normalization gradients. 

1002 

1003 Args: 

1004 ctx: Autograd context owned by this invocation. 

1005 do: Gradient of the local output. 

1006 dht: Optional gradient of the terminal recurrent state. 

1007 """ 

1008 q, k, v, g, beta, matrix_a, initial_state, cu_seqlens = ctx.saved_tensors 

1009 if not ctx.has_initial_state: 

1010 initial_state = None 

1011 if not ctx.has_cu_seqlens: 

1012 cu_seqlens = None 

1013 dq, dk, dv, db, dg, dh0 = chunk_gated_delta_rule_bwd( 

1014 q=q, 

1015 k=k, 

1016 v=v, 

1017 g=g, 

1018 beta=beta, 

1019 A=matrix_a, 

1020 scale=ctx.scale, 

1021 initial_state=initial_state, 

1022 do=do, 

1023 dht=dht, 

1024 cu_seqlens=cu_seqlens, 

1025 chunk_size=ctx.chunk_size, 

1026 ) 

1027 return dq.to(q), dk.to(k), dv.to(v), dg.to(g), db.to(beta), None, dh0, None, None, None, None 

1028 

1029 

1030@torch.compiler.disable 

1031def chunk_gated_delta_rule( 

1032 q: torch.Tensor, 

1033 k: torch.Tensor, 

1034 v: torch.Tensor, 

1035 g: torch.Tensor, 

1036 beta: torch.Tensor, 

1037 scale: float = None, 

1038 initial_state: torch.Tensor = None, 

1039 output_final_state: bool = False, 

1040 use_qk_l2norm_in_kernel: bool = False, 

1041 cu_seqlens: Optional[torch.LongTensor] = None, 

1042 chunk_size: int = 64, 

1043 head_first: bool = False, 

1044) -> tuple: 

1045 """Execute the local fused GDN recurrence and its paired backward. 

1046 

1047 Args: 

1048 q (Tensor): 

1049 queries of shape `[B, T, H, K]`. 

1050 k (Tensor): 

1051 keys of shape `[B, T, H, K]`. 

1052 v (Tensor): 

1053 values of shape `[B, T, H, V]`. 

1054 g (Tensor): 

1055 (forget) gating tensor (in log space!) of shape `[B, T, H]`. 

1056 beta (Tensor): 

1057 betas of shape `[B, T, H]`. 

1058 scale (Optional[float]): 

1059 Scale factor for the RetNet attention scores. 

1060 If not provided, it will default to `1 / sqrt(K)`. Default: `None`. 

1061 initial_state (Optional[Tensor]): 

1062 Initial state of shape `[N, H, K, V]` for `N` input sequences. 

1063 For equal-length input sequences, `N` equals the batch size `B`. 

1064 Default: `None`. 

1065 output_final_state (Optional[bool]): 

1066 Whether to output the final state of shape `[N, H, K, V]`. Default: `False`. 

1067 use_qk_l2norm_in_kernel (bool): 

1068 Whether to apply L2norm to the q/k tensor internally. Default: `False`. 

1069 cu_seqlens (Tensor): 

1070 Cumulative sequence lengths of shape `[N+1]` used for variable-length training, 

1071 consistent with the FlashAttention API. 

1072 head_first (Optional[bool]): 

1073 Whether the inputs are in the head-first format. Default: `False`. 

1074 This argument has been deprecated. 

1075 Returns: 

1076 o (Tensor): 

1077 Outputs of shape `[B, T, H, V]`. 

1078 final_state (Tensor): 

1079 Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`. 

1080 """ 

1081 if q.dtype != k.dtype or k.dtype != v.dtype: 

1082 raise ValueError( 

1083 f"q current type is {q.dtype}, k current type is {k.dtype}, " 

1084 f"v current type is {v.dtype}, they should be equal" 

1085 ) 

1086 if q.dtype == torch.float32: 

1087 raise ValueError( 

1088 "ChunkGatedDeltaRuleFunction does not support float32. Please use bfloat16." 

1089 ) 

1090 if len(beta.shape) != 3: 

1091 raise ValueError( 

1092 f"beta current shape len is {len(beta.shape)}, beta must be of shape [B, T, H] if head_first=False, or [B, H, T] otherwise." 

1093 ) 

1094 

1095 if head_first: 

1096 warnings.warn( 

1097 "head_first is deprecated and will be removed in a future version. " 

1098 "Please use head_first=False for now instead." 

1099 ) 

1100 if not head_first and q.shape[1] < q.shape[2]: 

1101 warnings.warn( 

1102 f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). " 

1103 "This may indicate the inputs were passed in head-first format [B, H, T, ...] " 

1104 "when head_first=False was specified. " 

1105 "Please verify your input tensor format matches the expected shape [B, T, H, ...]." 

1106 ) 

1107 if cu_seqlens is not None: 

1108 if q.shape[0] != 1: 

1109 raise ValueError( 

1110 f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`." 

1111 f"Please flatten variable-length inputs before processing." 

1112 ) 

1113 if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1: 

1114 raise ValueError( 

1115 f"The number of initial states is expected to be equal to the number of input sequences, " 

1116 f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}." 

1117 ) 

1118 if scale is None: 

1119 scale = k.shape[-1] ** -0.5 

1120 

1121 if use_qk_l2norm_in_kernel: 

1122 q, _ = _l2norm(q) 

1123 k, _ = _l2norm(k) 

1124 

1125 output, final_state = ChunkGatedDeltaRuleFunction.apply( 

1126 q, k, v, g, beta, scale, initial_state, output_final_state, cu_seqlens, False, chunk_size, 

1127 ) 

1128 return output, final_state 

1129 

1130 

1131def _validate_fixed_summary_shape( 

1132 key_dim: int, 

1133 value_dim: int, 

1134 chunk_size: int, 

1135) -> None: 

1136 if key_dim != 128 or value_dim != 128 or chunk_size != 64: 

1137 raise NotImplementedError( 

1138 "Triton GDN state summary requires key_dim=value_dim=128 and " 

1139 "chunk_size=64." 

1140 ) 

1141 

1142 

1143@torch.compiler.disable 

1144def chunk_gated_delta_rule_state_summary_fwd( 

1145 key: torch.Tensor, 

1146 w: torch.Tensor, 

1147 u: torch.Tensor, 

1148 g: torch.Tensor, 

1149 *, 

1150 chunk_size: int = 64, 

1151 block_size: int = 128, 

1152 output_transition: bool = True, 

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

1154 """Return S and optionally M of ``state_out = M @ state_in + S``. 

1155 

1156 Set output_transition=False only when the caller has no consumer for M. 

1157 Both modes retain the same packed kernel; omitting M avoids its output 

1158 copy and saved-state lifetime, not its arithmetic. 

1159 

1160 Args: 

1161 key: Prepared key with shape [B,T,H,K]. 

1162 w: WY correction with the same shape as key. 

1163 u: Prepared value with shape [B,T,H,V]. 

1164 g: Chunk cumulative log-decay with shape [B,T,H]. 

1165 chunk_size: Number of tokens in each recurrent chunk. 

1166 block_size: Width of each output tile. 

1167 output_transition: Whether the caller consumes the transition M. 

1168 

1169 Returns: 

1170 FP32 additive state S and transition M, or None when M is omitted. 

1171 """ 

1172 if (key.ndim, w.ndim, u.ndim, g.ndim) != (4, 4, 4, 3): 

1173 raise ValueError("GDN state summary expects key/w/u [B,T,H,D] and g [B,T,H].") 

1174 batch, seq_len, heads, key_dim = key.shape 

1175 value_dim = u.shape[-1] 

1176 _validate_fixed_summary_shape(key_dim, value_dim, chunk_size) 

1177 if block_size not in (64, 128): 

1178 raise ValueError(f"GDN state-summary block_size must be 64 or 128, got {block_size}.") 

1179 if seq_len <= 0: 

1180 raise ValueError("State summary requires a nonempty sample fragment.") 

1181 if w.shape != key.shape or u.shape[:3] != key.shape[:3] or g.shape != key.shape[:3]: 

1182 raise ValueError( 

1183 "Incompatible GDN state-summary shapes: " 

1184 f"key={tuple(key.shape)}, w={tuple(w.shape)}, " 

1185 f"u={tuple(u.shape)}, g={tuple(g.shape)}." 

1186 ) 

1187 

1188 key, w, u, g = (tensor.contiguous() for tensor in (key, w, u, g)) 

1189 packed_summary = torch.empty( 

1190 batch, 

1191 heads, 

1192 key_dim, 

1193 value_dim + key_dim, 

1194 device=key.device, 

1195 dtype=torch.float32, 

1196 ) 

1197 gdn_packed_state_summary_kernel[ 

1198 (triton.cdiv(value_dim + key_dim, block_size), batch * heads) 

1199 ]( 

1200 key, 

1201 w, 

1202 u, 

1203 g, 

1204 packed_summary, 

1205 seq_len, 

1206 H=heads, 

1207 K=key_dim, 

1208 V=value_dim, 

1209 BT=chunk_size, 

1210 BV=block_size, 

1211 NT=triton.cdiv(seq_len, chunk_size), 

1212 ) 

1213 state_ext = packed_summary[..., :value_dim].contiguous() 

1214 if not output_transition: 

1215 return state_ext, None 

1216 transition = packed_summary[..., value_dim:].contiguous() 

1217 return state_ext, transition 

1218 

1219 

1220def _validate_gdn_gradient_summary_inputs( 

1221 query: torch.Tensor, 

1222 key: torch.Tensor, 

1223 w: torch.Tensor, 

1224 g: torch.Tensor, 

1225 grad_output: torch.Tensor, 

1226 dv: torch.Tensor, 

1227 chunk_size: int, 

1228) -> tuple[int, int, int, int, int]: 

1229 """Validate the reverse summary inputs before launching its kernel.""" 

1230 batch, seq_len, heads, key_dim = query.shape 

1231 value_dim = grad_output.shape[-1] 

1232 _validate_fixed_summary_shape(key_dim, value_dim, chunk_size) 

1233 if seq_len <= 0: 

1234 raise ValueError("State summary requires a nonempty sample fragment.") 

1235 qk_shape = (batch, seq_len, heads, key_dim) 

1236 value_shape = (batch, seq_len, heads, value_dim) 

1237 if (key.shape, w.shape, g.shape, grad_output.shape, dv.shape) != ( 

1238 qk_shape, qk_shape, qk_shape[:3], value_shape, value_shape 

1239 ): 

1240 raise ValueError( 

1241 "Incompatible GDN state-gradient summary shapes: " 

1242 f"query={tuple(query.shape)}, key={tuple(key.shape)}, " 

1243 f"w={tuple(w.shape)}, g={tuple(g.shape)}, " 

1244 f"grad_output={tuple(grad_output.shape)}, dv={tuple(dv.shape)}." 

1245 ) 

1246 return batch, seq_len, heads, key_dim, value_dim 

1247 

1248 

1249@torch.compiler.disable 

1250def chunk_gated_delta_rule_state_gradient_summary_bwd( 

1251 query: torch.Tensor, 

1252 key: torch.Tensor, 

1253 w: torch.Tensor, 

1254 g: torch.Tensor, 

1255 grad_output: torch.Tensor, 

1256 dv: torch.Tensor, 

1257 scale: float, 

1258 *, 

1259 chunk_size: int = 64, 

1260) -> torch.Tensor: 

1261 """Return the local-loss contribution to the incoming state gradient. 

1262 

1263 Args: 

1264 query: Prepared query with shape [B,T,H,K]. 

1265 key: Prepared key with the same shape as query. 

1266 w: WY correction with the same shape as query. 

1267 g: Chunk cumulative log-decay with shape [B,T,H]. 

1268 grad_output: Attention output gradient with shape [B,T,H,V]. 

1269 dv: Local value-gradient contribution with the same shape as grad_output. 

1270 scale: Attention scaling factor. 

1271 chunk_size: Number of tokens in each recurrent chunk. 

1272 

1273 Returns: 

1274 FP32 incoming-state gradient with zero outgoing-state gradient. 

1275 """ 

1276 batch, seq_len, heads, key_dim, value_dim = _validate_gdn_gradient_summary_inputs( 

1277 query, key, w, g, grad_output, dv, chunk_size 

1278 ) 

1279 

1280 query, key, w, g, grad_output, dv = ( 

1281 tensor.contiguous() for tensor in (query, key, w, g, grad_output, dv) 

1282 ) 

1283 grad_state_ext = torch.empty( 

1284 batch, 

1285 heads, 

1286 key_dim, 

1287 value_dim, 

1288 device=query.device, 

1289 dtype=torch.float32, 

1290 ) 

1291 gdn_state_grad_ext_kernel[(1, batch * heads)]( 

1292 query, 

1293 key, 

1294 w, 

1295 g, 

1296 grad_output, 

1297 dv, 

1298 grad_state_ext, 

1299 scale, 

1300 seq_len, 

1301 H=heads, 

1302 K=key_dim, 

1303 V=value_dim, 

1304 BT=chunk_size, 

1305 BV=128, 

1306 NT=triton.cdiv(seq_len, chunk_size), 

1307 ) 

1308 return grad_state_ext