fla-core 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. fla/__init__.py +4 -0
  2. fla/modules/__init__.py +33 -0
  3. fla/modules/activations.py +548 -0
  4. fla/modules/convolution.py +1143 -0
  5. fla/modules/feature_map.py +300 -0
  6. fla/modules/fused_bitlinear.py +632 -0
  7. fla/modules/fused_cross_entropy.py +419 -0
  8. fla/modules/fused_kl_div.py +324 -0
  9. fla/modules/fused_linear_cross_entropy.py +620 -0
  10. fla/modules/fused_norm_gate.py +1253 -0
  11. fla/modules/grpo.py +411 -0
  12. fla/modules/l2norm.py +285 -0
  13. fla/modules/l2warp.py +38 -0
  14. fla/modules/layernorm.py +1433 -0
  15. fla/modules/layernorm_gated.py +528 -0
  16. fla/modules/mlp.py +132 -0
  17. fla/modules/parallel.py +42 -0
  18. fla/modules/rotary.py +500 -0
  19. fla/modules/token_shift.py +543 -0
  20. fla/ops/__init__.py +53 -0
  21. fla/ops/abc/__init__.py +7 -0
  22. fla/ops/abc/chunk.py +1117 -0
  23. fla/ops/abc/naive.py +96 -0
  24. fla/ops/attn/__init__.py +7 -0
  25. fla/ops/attn/decoding.py +182 -0
  26. fla/ops/attn/parallel.py +730 -0
  27. fla/ops/based/__init__.py +9 -0
  28. fla/ops/based/fused_chunk.py +373 -0
  29. fla/ops/based/naive.py +72 -0
  30. fla/ops/based/parallel.py +408 -0
  31. fla/ops/comba/__init__.py +7 -0
  32. fla/ops/comba/chunk.py +342 -0
  33. fla/ops/comba/fused_recurrent.py +332 -0
  34. fla/ops/comba/utils.py +172 -0
  35. fla/ops/comba/wy_fast.py +423 -0
  36. fla/ops/common/__init__.py +1 -0
  37. fla/ops/common/chunk_delta_h.py +527 -0
  38. fla/ops/common/chunk_h.py +384 -0
  39. fla/ops/common/chunk_h_parallel.py +551 -0
  40. fla/ops/common/chunk_h_split.py +596 -0
  41. fla/ops/common/chunk_o.py +681 -0
  42. fla/ops/common/chunk_scaled_dot_kkt.py +305 -0
  43. fla/ops/common/fused_chunk.py +629 -0
  44. fla/ops/common/fused_recurrent.py +567 -0
  45. fla/ops/delta_rule/__init__.py +11 -0
  46. fla/ops/delta_rule/chunk.py +311 -0
  47. fla/ops/delta_rule/fused_chunk.py +6 -0
  48. fla/ops/delta_rule/fused_recurrent.py +535 -0
  49. fla/ops/delta_rule/naive.py +120 -0
  50. fla/ops/delta_rule/parallel.py +403 -0
  51. fla/ops/delta_rule/wy_fast.py +294 -0
  52. fla/ops/forgetting_attn/__init__.py +7 -0
  53. fla/ops/forgetting_attn/parallel.py +64 -0
  54. fla/ops/gated_delta_product/__init__.py +5 -0
  55. fla/ops/gated_delta_product/chunk.py +305 -0
  56. fla/ops/gated_delta_product/chunk_deltaproduct_h.py +502 -0
  57. fla/ops/gated_delta_product/chunk_deltaproduct_o.py +154 -0
  58. fla/ops/gated_delta_product/chunk_ref.py +68 -0
  59. fla/ops/gated_delta_product/naive.py +36 -0
  60. fla/ops/gated_delta_rule/__init__.py +7 -0
  61. fla/ops/gated_delta_rule/chunk.py +340 -0
  62. fla/ops/gated_delta_rule/fused_recurrent.py +351 -0
  63. fla/ops/gated_delta_rule/wy_fast.py +296 -0
  64. fla/ops/generalized_delta_rule/__init__.py +9 -0
  65. fla/ops/generalized_delta_rule/dplr/__init__.py +7 -0
  66. fla/ops/generalized_delta_rule/dplr/chunk.py +362 -0
  67. fla/ops/generalized_delta_rule/dplr/chunk_A_bwd.py +367 -0
  68. fla/ops/generalized_delta_rule/dplr/chunk_A_fwd.py +198 -0
  69. fla/ops/generalized_delta_rule/dplr/chunk_h_bwd.py +175 -0
  70. fla/ops/generalized_delta_rule/dplr/chunk_h_fwd.py +175 -0
  71. fla/ops/generalized_delta_rule/dplr/chunk_o_bwd.py +430 -0
  72. fla/ops/generalized_delta_rule/dplr/chunk_o_fwd.py +125 -0
  73. fla/ops/generalized_delta_rule/dplr/fused_recurrent.py +268 -0
  74. fla/ops/generalized_delta_rule/dplr/naive.py +96 -0
  75. fla/ops/generalized_delta_rule/dplr/wy_fast_bwd.py +164 -0
  76. fla/ops/generalized_delta_rule/dplr/wy_fast_fwd.py +284 -0
  77. fla/ops/generalized_delta_rule/iplr/__init__.py +7 -0
  78. fla/ops/generalized_delta_rule/iplr/chunk.py +492 -0
  79. fla/ops/generalized_delta_rule/iplr/fused_recurrent.py +452 -0
  80. fla/ops/generalized_delta_rule/iplr/naive.py +69 -0
  81. fla/ops/generalized_delta_rule/iplr/wy_fast.py +300 -0
  82. fla/ops/gla/__init__.py +11 -0
  83. fla/ops/gla/chunk.py +1298 -0
  84. fla/ops/gla/fused_chunk.py +642 -0
  85. fla/ops/gla/fused_recurrent.py +111 -0
  86. fla/ops/gla/naive.py +41 -0
  87. fla/ops/gsa/__init__.py +9 -0
  88. fla/ops/gsa/chunk.py +1133 -0
  89. fla/ops/gsa/fused_recurrent.py +536 -0
  90. fla/ops/gsa/naive.py +69 -0
  91. fla/ops/hgrn/__init__.py +9 -0
  92. fla/ops/hgrn/chunk.py +282 -0
  93. fla/ops/hgrn/fused_recurrent.py +308 -0
  94. fla/ops/hgrn/naive.py +63 -0
  95. fla/ops/lightning_attn/__init__.py +9 -0
  96. fla/ops/lightning_attn/chunk.py +84 -0
  97. fla/ops/lightning_attn/fused_recurrent.py +84 -0
  98. fla/ops/linear_attn/__init__.py +11 -0
  99. fla/ops/linear_attn/chunk.py +76 -0
  100. fla/ops/linear_attn/fused_chunk.py +61 -0
  101. fla/ops/linear_attn/fused_recurrent.py +35 -0
  102. fla/ops/linear_attn/naive.py +64 -0
  103. fla/ops/linear_attn/utils.py +10 -0
  104. fla/ops/log_linear_attn/__init__.py +7 -0
  105. fla/ops/log_linear_attn/chunk.py +1904 -0
  106. fla/ops/log_linear_attn/naive.py +50 -0
  107. fla/ops/mesa_net/__init__.py +5 -0
  108. fla/ops/mesa_net/chunk.py +371 -0
  109. fla/ops/mesa_net/chunk_cg_solver_bwd.py +162 -0
  110. fla/ops/mesa_net/chunk_cg_solver_fwd.py +186 -0
  111. fla/ops/mesa_net/chunk_h_fwd.py +170 -0
  112. fla/ops/mesa_net/chunk_h_kk_intra_bwd.py +191 -0
  113. fla/ops/mesa_net/chunk_h_kv_intra_bwd.py +209 -0
  114. fla/ops/mesa_net/chunk_h_kv_intra_bwd_separate.py +300 -0
  115. fla/ops/mesa_net/decoding_one_step.py +175 -0
  116. fla/ops/mesa_net/naive.py +131 -0
  117. fla/ops/nsa/__init__.py +9 -0
  118. fla/ops/nsa/compression.py +536 -0
  119. fla/ops/nsa/naive.py +103 -0
  120. fla/ops/nsa/parallel.py +879 -0
  121. fla/ops/nsa/utils.py +92 -0
  122. fla/ops/path_attn/__init__.py +7 -0
  123. fla/ops/path_attn/cumprod_householder_bwd.py +140 -0
  124. fla/ops/path_attn/cumprod_householder_fwd.py +119 -0
  125. fla/ops/path_attn/intra_chunk_preprocess_bwd.py +140 -0
  126. fla/ops/path_attn/intra_chunk_preprocess_bwd_prepare.py +208 -0
  127. fla/ops/path_attn/intra_chunk_preprocess_fwd.py +168 -0
  128. fla/ops/path_attn/parallel.py +270 -0
  129. fla/ops/path_attn/parallel_path_bwd_inter_dkv.py +189 -0
  130. fla/ops/path_attn/parallel_path_bwd_inter_dqh.py +200 -0
  131. fla/ops/path_attn/parallel_path_bwd_intra.py +172 -0
  132. fla/ops/path_attn/parallel_path_fwd.py +195 -0
  133. fla/ops/path_attn/prepare_k_cache.py +74 -0
  134. fla/ops/path_attn/transform_q.py +108 -0
  135. fla/ops/rebased/__init__.py +7 -0
  136. fla/ops/rebased/naive.py +27 -0
  137. fla/ops/rebased/parallel.py +464 -0
  138. fla/ops/retention/__init__.py +13 -0
  139. fla/ops/retention/chunk.py +77 -0
  140. fla/ops/retention/fused_chunk.py +78 -0
  141. fla/ops/retention/fused_recurrent.py +33 -0
  142. fla/ops/retention/naive.py +15 -0
  143. fla/ops/retention/parallel.py +71 -0
  144. fla/ops/rwkv4/__init__.py +7 -0
  145. fla/ops/rwkv4/fused_recurrent.py +472 -0
  146. fla/ops/rwkv6/__init__.py +9 -0
  147. fla/ops/rwkv6/chunk.py +1300 -0
  148. fla/ops/rwkv6/chunk_naive.py +43 -0
  149. fla/ops/rwkv6/fused_recurrent.py +673 -0
  150. fla/ops/rwkv6/recurrent_naive.py +103 -0
  151. fla/ops/rwkv7/__init__.py +10 -0
  152. fla/ops/rwkv7/channel_mixing.py +323 -0
  153. fla/ops/rwkv7/chunk.py +78 -0
  154. fla/ops/rwkv7/fused_addcmul.py +293 -0
  155. fla/ops/rwkv7/fused_k_update.py +346 -0
  156. fla/ops/rwkv7/fused_recurrent.py +334 -0
  157. fla/ops/rwkv7/gate_output_correction.py +244 -0
  158. fla/ops/simple_gla/__init__.py +13 -0
  159. fla/ops/simple_gla/chunk.py +303 -0
  160. fla/ops/simple_gla/fused_chunk.py +108 -0
  161. fla/ops/simple_gla/fused_recurrent.py +112 -0
  162. fla/ops/simple_gla/naive.py +114 -0
  163. fla/ops/simple_gla/parallel.py +722 -0
  164. fla/ops/titans/__init__.py +7 -0
  165. fla/ops/titans/log_impl.py +153 -0
  166. fla/ops/titans/naive.py +375 -0
  167. fla/ops/ttt/__init__.py +9 -0
  168. fla/ops/ttt/chunk.py +1441 -0
  169. fla/ops/ttt/fused_chunk.py +831 -0
  170. fla/ops/ttt/naive.py +126 -0
  171. fla/ops/utils/__init__.py +58 -0
  172. fla/ops/utils/constant.py +6 -0
  173. fla/ops/utils/cumsum.py +465 -0
  174. fla/ops/utils/index.py +133 -0
  175. fla/ops/utils/logcumsumexp.py +52 -0
  176. fla/ops/utils/logsumexp.py +80 -0
  177. fla/ops/utils/matmul.py +245 -0
  178. fla/ops/utils/op.py +62 -0
  179. fla/ops/utils/pack.py +208 -0
  180. fla/ops/utils/pooling.py +207 -0
  181. fla/ops/utils/softmax.py +106 -0
  182. fla/ops/utils/solve_tril.py +381 -0
  183. fla/utils.py +462 -0
  184. fla_core-0.3.2.dist-info/METADATA +575 -0
  185. fla_core-0.3.2.dist-info/RECORD +188 -0
  186. fla_core-0.3.2.dist-info/WHEEL +5 -0
  187. fla_core-0.3.2.dist-info/licenses/LICENSE +21 -0
  188. fla_core-0.3.2.dist-info/top_level.txt +1 -0
fla/ops/gsa/chunk.py ADDED
@@ -0,0 +1,1133 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ import warnings
5
+ from typing import Optional, Tuple
6
+
7
+ import torch
8
+ import triton
9
+ import triton.language as tl
10
+ from einops import reduce
11
+
12
+ from fla.ops.common.chunk_h import chunk_bwd_dh, chunk_fwd_h
13
+ from fla.ops.gla.chunk import chunk_gla_bwd, chunk_gla_fwd
14
+ from fla.ops.utils import prepare_chunk_indices
15
+ from fla.ops.utils.cumsum import chunk_local_cumsum
16
+ from fla.ops.utils.op import exp
17
+ from fla.ops.utils.softmax import softmax_bwd, softmax_fwd
18
+ from fla.utils import input_guard
19
+
20
+
21
+ @triton.heuristics({
22
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
23
+ })
24
+ @triton.autotune(
25
+ configs=[
26
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps, num_stages=num_stages)
27
+ for BK in [32, 64]
28
+ for BV in [32, 64]
29
+ for num_warps in [2, 4, 8]
30
+ for num_stages in [2, 3, 4]
31
+ ],
32
+ key=['BT']
33
+ )
34
+ @triton.jit(do_not_specialize=['T'])
35
+ def chunk_gsa_fwd_k_kernel_inter(
36
+ q,
37
+ k,
38
+ h,
39
+ g,
40
+ o,
41
+ A,
42
+ cu_seqlens,
43
+ chunk_indices,
44
+ scale,
45
+ T,
46
+ HQ: tl.constexpr,
47
+ H: tl.constexpr,
48
+ K: tl.constexpr,
49
+ V: tl.constexpr,
50
+ BT: tl.constexpr,
51
+ BK: tl.constexpr,
52
+ BV: tl.constexpr,
53
+ NG: tl.constexpr,
54
+ IS_VARLEN: tl.constexpr,
55
+ ):
56
+ i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
57
+ i_b, i_hq = i_bh // HQ, i_bh % HQ
58
+ i_h = i_hq // NG
59
+ if IS_VARLEN:
60
+ i_tg = i_t
61
+ i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
62
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
63
+ T = eos - bos
64
+ NT = tl.cdiv(T, BT)
65
+ else:
66
+ NT = tl.cdiv(T, BT)
67
+ i_tg = i_b * NT + i_t
68
+ bos, eos = i_b * T, i_b * T + T
69
+
70
+ o_i = tl.arange(0, BT)
71
+ m_s = o_i[:, None] >= o_i[None, :]
72
+
73
+ b_o = tl.zeros([BT, BV], dtype=tl.float32)
74
+ b_A = tl.zeros([BT, BT], dtype=tl.float32)
75
+ for i_k in range(tl.cdiv(K, BK)):
76
+ p_q = tl.make_block_ptr(q + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
77
+ p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
78
+ p_h = tl.make_block_ptr(h + (i_tg * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
79
+
80
+ # [BT, BK]
81
+ b_q = tl.load(p_q, boundary_check=(0, 1))
82
+ b_q = (b_q * scale).to(b_q.dtype)
83
+ # [BK, BT]
84
+ b_k = tl.load(p_k, boundary_check=(0, 1))
85
+ # [BK, BV]
86
+ b_h = tl.load(p_h, boundary_check=(0, 1))
87
+ # [BT, BV]
88
+ b_o += tl.dot(b_q, b_h)
89
+ # [BT, BT]
90
+ b_A += tl.dot(b_q, b_k)
91
+ p_g = tl.make_block_ptr(g + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
92
+ p_o = tl.make_block_ptr(o + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
93
+ p_A = tl.make_block_ptr(A + (bos * HQ + i_hq) * BT, (T, BT), (HQ*BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
94
+ # [BT, BV]
95
+ b_g = tl.load(p_g, boundary_check=(0, 1))
96
+ b_o = b_o * exp(b_g)
97
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
98
+
99
+ # [BT, BT]
100
+ b_A = tl.where(m_s, b_A, 0.)
101
+ if i_v == 0:
102
+ tl.store(p_A, b_A.to(p_A.dtype.element_ty), boundary_check=(0, 1))
103
+
104
+
105
+ @triton.heuristics({
106
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
107
+ })
108
+ @triton.jit(do_not_specialize=['T'])
109
+ def chunk_gsa_fwd_k_kernel_intra(
110
+ v,
111
+ g,
112
+ o,
113
+ A,
114
+ cu_seqlens,
115
+ chunk_indices,
116
+ T,
117
+ HQ: tl.constexpr,
118
+ H: tl.constexpr,
119
+ V: tl.constexpr,
120
+ BT: tl.constexpr,
121
+ BC: tl.constexpr,
122
+ BV: tl.constexpr,
123
+ NC: tl.constexpr,
124
+ NG: tl.constexpr,
125
+ IS_VARLEN: tl.constexpr,
126
+ ):
127
+ i_v, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
128
+ i_b, i_hq = i_bh // HQ, i_bh % HQ
129
+ i_h = i_hq // NG
130
+ i_t, i_i = i_c // NC, i_c % NC
131
+ if IS_VARLEN:
132
+ i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
133
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
134
+ T = eos - bos
135
+ else:
136
+ bos, eos = i_b * T, i_b * T + T
137
+
138
+ o_v = i_v * BV + tl.arange(0, BV)
139
+ m_v = o_v < V
140
+
141
+ if i_t * BT + i_i * BC >= T:
142
+ return
143
+
144
+ p_g = tl.make_block_ptr(g + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
145
+ p_gn = g + (bos + min(i_t * BT + i_i * BC, T)) * H*V + i_h * V + o_v
146
+ # [BV,]
147
+ b_gn = tl.load(p_gn, mask=m_v, other=0)
148
+ # [BC, BV]
149
+ b_o = tl.zeros([BC, BV], dtype=tl.float32)
150
+ for i_j in range(0, i_i):
151
+ p_A = tl.make_block_ptr(A + (bos*HQ+i_hq) * BT, (T, BT), (HQ*BT, 1), (i_t*BT+i_i*BC, i_j * BC), (BC, BC), (1, 0))
152
+ p_v = tl.make_block_ptr(v + (bos*H+i_h) * V, (T, V), (H*V, 1), (i_t * BT + i_j * BC, i_v * BV), (BC, BV), (1, 0))
153
+ p_gv = tl.make_block_ptr(g + (bos*H+i_h) * V, (T, V), (H*V, 1), (i_t * BT + i_j * BC, i_v * BV), (BC, BV), (1, 0))
154
+ # [BC, BV]
155
+ b_v = tl.load(p_v, boundary_check=(0, 1))
156
+ b_gv = tl.load(p_gv, boundary_check=(0, 1))
157
+ b_vg = (b_v * exp(b_gn[None, :] - b_gv)).to(b_v.dtype)
158
+ # [BC, BC]
159
+ b_A = tl.load(p_A, boundary_check=(0, 1))
160
+ b_o += tl.dot(b_A, b_vg)
161
+ # [BC, BV]
162
+ b_g = tl.load(p_g, boundary_check=(0, 1))
163
+ b_o *= exp(b_g - b_gn[None, :])
164
+
165
+ o_i = tl.arange(0, BC)
166
+ o_A = (bos + i_t * BT + i_i * BC + tl.arange(0, BC)) * HQ*BT + i_hq * BT + i_i * BC
167
+ m_A = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
168
+ for j in range(0, min(BC, T - i_t * BT - i_i * BC)):
169
+ p_v = v + (bos + i_t * BT + i_i * BC + j) * H*V + i_h * V + o_v
170
+ p_gv = g + (bos + i_t * BT + i_i * BC + j) * H*V + i_h * V + o_v
171
+ # [BC,]
172
+ b_A = tl.load(A + o_A + j, mask=m_A, other=0)
173
+ # [BV,]
174
+ b_v = tl.load(p_v, mask=m_v, other=0).to(tl.float32)
175
+ b_gv = tl.load(p_gv, mask=m_v, other=0).to(tl.float32)
176
+ # [BC, BV]
177
+ b_vg = b_v[None, :] * exp(b_g - b_gv[None, :])
178
+ # avoid 0 * inf = inf
179
+ b_o += tl.where(o_i[:, None] >= j, b_A[:, None] * b_vg, 0.)
180
+ p_o = tl.make_block_ptr(o + (bos*HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
181
+ b_o += tl.load(p_o, boundary_check=(0, 1))
182
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
183
+
184
+
185
+ @triton.heuristics({
186
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
187
+ })
188
+ @triton.autotune(
189
+ configs=[
190
+ triton.Config({}, num_warps=num_warps)
191
+ for num_warps in [2, 4, 8]
192
+ ],
193
+ key=["BT"]
194
+ )
195
+ @triton.jit(do_not_specialize=['T'])
196
+ def chunk_gsa_bwd_k_kernel_dA(
197
+ v,
198
+ g,
199
+ do,
200
+ dA,
201
+ chunk_indices,
202
+ cu_seqlens,
203
+ scale,
204
+ T,
205
+ B: tl.constexpr,
206
+ HQ: tl.constexpr,
207
+ H: tl.constexpr,
208
+ V: tl.constexpr,
209
+ BT: tl.constexpr,
210
+ BC: tl.constexpr,
211
+ BV: tl.constexpr,
212
+ NC: tl.constexpr,
213
+ NG: tl.constexpr,
214
+ IS_VARLEN: tl.constexpr,
215
+ ):
216
+ i_v, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
217
+ i_b, i_hq = i_bh // HQ, i_bh % HQ
218
+ i_h = i_hq // NG
219
+ i_t, i_i, i_j = i_c // (NC * NC), (i_c % (NC * NC)) // NC, (i_c % (NC * NC)) % NC
220
+ if IS_VARLEN:
221
+ i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
222
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
223
+ all = T
224
+ T = eos - bos
225
+ else:
226
+ bos, eos = i_b * T, i_b * T + T
227
+ all = B * T
228
+
229
+ o_v = i_v * BV + tl.arange(0, BV)
230
+ m_v = o_v < V
231
+
232
+ if i_t * BT + i_i * BC >= T:
233
+ return
234
+
235
+ p_dA = tl.make_block_ptr(dA+((i_v*all+bos)*HQ+i_hq)*BT, (T, BT), (HQ*BT, 1), (i_t*BT+i_i*BC, i_j*BC), (BC, BC), (1, 0))
236
+
237
+ # [BC, BC]
238
+ b_dA = tl.zeros([BC, BC], dtype=tl.float32)
239
+ if i_i > i_j:
240
+ p_v = tl.make_block_ptr(v + (bos*H+i_h) * V, (V, T), (1, H*V), (i_v * BV, i_t*BT + i_j*BC), (BV, BC), (0, 1))
241
+ p_gv = tl.make_block_ptr(g + (bos*H+i_h) * V, (V, T), (1, H*V), (i_v * BV, i_t*BT + i_j*BC), (BV, BC), (0, 1))
242
+ p_gn = g + (bos + i_t*BT + i_i*BC) * H*V + i_h * V + o_v
243
+ p_g = tl.make_block_ptr(g + (bos*H+i_h) * V, (T, V), (H*V, 1), (i_t*BT + i_i*BC, i_v*BV), (BC, BV), (1, 0))
244
+ p_do = tl.make_block_ptr(do + (bos*HQ+i_hq) * V, (T, V), (HQ*V, 1), (i_t*BT + i_i*BC, i_v*BV), (BC, BV), (1, 0))
245
+ # [BV,]
246
+ b_gn = tl.load(p_gn, mask=m_v, other=0.)
247
+ # [BC, BV]
248
+ b_g = tl.load(p_g, boundary_check=(0, 1))
249
+ b_do = tl.load(p_do, boundary_check=(0, 1))
250
+ b_do = (b_do * exp(b_g - b_gn[None, :]) * scale).to(b_do.dtype)
251
+ # [BV, BC]
252
+ b_v = tl.load(p_v, boundary_check=(0, 1))
253
+ b_gv = tl.load(p_gv, boundary_check=(0, 1))
254
+ b_vg = (b_v * exp(b_gn[:, None] - b_gv)).to(b_v.dtype)
255
+ # [BC, BC]
256
+ b_dA = tl.dot(b_do, b_vg)
257
+ elif i_i == i_j:
258
+ p_g = tl.make_block_ptr(g + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t*BT + i_i*BC, i_v*BV), (BC, BV), (1, 0))
259
+ p_do = tl.make_block_ptr(do + (bos*HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_t*BT + i_i*BC, i_v*BV), (BC, BV), (1, 0))
260
+ p_v = v + (bos + i_t*BT + i_j*BC) * H*V + i_h * V + o_v
261
+ p_gv = g + (bos + i_t*BT + i_j*BC) * H*V + i_h * V + o_v
262
+ # [BC, BV]
263
+ b_g = tl.load(p_g, boundary_check=(0, 1))
264
+ b_do = tl.load(p_do, boundary_check=(0, 1)) * scale
265
+ m_v = o_v < V
266
+
267
+ o_i = tl.arange(0, BC)
268
+ # [BC, BC]
269
+ m_dA = o_i[:, None] >= o_i[None, :]
270
+ for j in range(0, min(BC, T - i_t * BT - i_j * BC)):
271
+ # [BV,]
272
+ b_v = tl.load(p_v, mask=m_v, other=0).to(tl.float32)
273
+ b_gv = tl.load(p_gv, mask=m_v, other=0).to(tl.float32)
274
+ # [BC,]
275
+ b_dAj = tl.sum(b_do * b_v[None, :] * exp(b_g - b_gv[None, :]), 1)
276
+ b_dA = tl.where((o_i == j)[None, :], b_dAj[:, None], b_dA)
277
+
278
+ p_v += H*V
279
+ p_gv += H*V
280
+ b_dA = tl.where(m_dA, b_dA, 0.)
281
+ tl.store(p_dA, b_dA.to(dA.dtype.element_ty), boundary_check=(0, 1))
282
+
283
+
284
+ @triton.heuristics({
285
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
286
+ })
287
+ @triton.autotune(
288
+ configs=[
289
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
290
+ for num_warps in [2, 4]
291
+ for num_stages in [2, 3, 4]
292
+ ],
293
+ key=['BT']
294
+ )
295
+ @triton.jit(do_not_specialize=['T'])
296
+ def chunk_gsa_bwd_k_kernel_dqkvg(
297
+ q,
298
+ k,
299
+ v,
300
+ h,
301
+ g,
302
+ A,
303
+ do,
304
+ dh,
305
+ dq,
306
+ dk,
307
+ dv,
308
+ dg,
309
+ dgv,
310
+ dA,
311
+ cu_seqlens,
312
+ chunk_indices,
313
+ scale,
314
+ T,
315
+ B: tl.constexpr,
316
+ HQ: tl.constexpr,
317
+ H: tl.constexpr,
318
+ K: tl.constexpr,
319
+ V: tl.constexpr,
320
+ BT: tl.constexpr,
321
+ BK: tl.constexpr,
322
+ BV: tl.constexpr,
323
+ NG: tl.constexpr,
324
+ IS_VARLEN: tl.constexpr,
325
+ ):
326
+ i_k, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
327
+ i_b, i_hq = i_bh // HQ, i_bh % HQ
328
+ i_h = i_hq // NG
329
+ if IS_VARLEN:
330
+ i_tg = i_t
331
+ i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
332
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
333
+ all = T
334
+ T = eos - bos
335
+ NT = tl.cdiv(T, BT)
336
+ else:
337
+ NT = tl.cdiv(T, BT)
338
+ i_tg = i_b * NT + i_t
339
+ bos, eos = i_b * T, i_b * T + T
340
+ all = B * T
341
+
342
+ o_i = tl.arange(0, BT)
343
+ o_t = min(i_t * BT + BT, T)
344
+ m_s = o_i[:, None] >= o_i[None, :]
345
+
346
+ p_q = tl.make_block_ptr(q + (bos*HQ+i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
347
+ p_k = tl.make_block_ptr(k + (bos*H+i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
348
+ p_A = tl.make_block_ptr(A + ((i_k*all+bos)*HQ+i_hq)*BT, (T, BT), (HQ*BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
349
+
350
+ # [BT, BK]
351
+ b_q = tl.load(p_q, boundary_check=(0, 1))
352
+ b_k = tl.load(p_k, boundary_check=(0, 1))
353
+ # [BT, BT]
354
+ b_A = tl.dot((b_q * scale).to(b_q.dtype), tl.trans(b_k))
355
+ b_A = tl.where(m_s, b_A, 0.)
356
+ tl.store(p_A, b_A.to(p_A.dtype.element_ty), boundary_check=(0, 1))
357
+
358
+ b_dq = tl.zeros([BT, BK], dtype=tl.float32)
359
+ b_dk = tl.zeros([BT, BK], dtype=tl.float32)
360
+ for i_v in range(tl.cdiv(V, BV)):
361
+ o_v = i_v * BV + tl.arange(0, BV)
362
+ p_v = tl.make_block_ptr(v + (bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
363
+ p_g = tl.make_block_ptr(g + (bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
364
+ p_gn = g + (bos + o_t - 1) * H*V + i_h * V + o_v
365
+ p_do = tl.make_block_ptr(do + (bos*HQ+i_hq)*V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
366
+ p_dv = tl.make_block_ptr(dv + ((i_k*all+bos)*HQ+i_hq)*V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
367
+ p_dg = tl.make_block_ptr(dg + (bos*HQ+i_hq)*V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
368
+ p_dgv = tl.make_block_ptr(dgv+((i_k*all+bos)*HQ+i_hq)*V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
369
+ p_h = tl.make_block_ptr(h + (i_tg * H + i_h) * K*V, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
370
+ p_dh = tl.make_block_ptr(dh + (i_tg * HQ + i_hq) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
371
+ m_v = o_v < V
372
+
373
+ # [BV,]
374
+ b_gn = tl.load(p_gn, mask=m_v, other=0)
375
+ # [BT, BV]
376
+ b_v = tl.load(p_v, boundary_check=(0, 1))
377
+ b_g = tl.load(p_g, boundary_check=(0, 1))
378
+ b_gv = exp(b_gn[None, :] - b_g)
379
+ # [BV, BK]
380
+ b_h = tl.load(p_h, boundary_check=(0, 1))
381
+ # [BT, BV]
382
+ b_do = tl.load(p_do, boundary_check=(0, 1))
383
+ b_do = (b_do * exp(b_g) * scale).to(b_do.dtype)
384
+ # [BK, BV]
385
+ b_dh = tl.load(p_dh, boundary_check=(0, 1))
386
+ # [BV]
387
+ b_dg = tl.sum(tl.trans(b_h) * b_dh, 0) * exp(b_gn)
388
+
389
+ b_dh = b_dh.to(b_k.dtype)
390
+ # [BT, BK]
391
+ b_dq += tl.dot(b_do, b_h.to(b_k.dtype))
392
+ b_dk += tl.dot((b_v * b_gv).to(b_v.dtype), tl.trans(b_dh))
393
+ # [BT, BV]
394
+ b_dv = tl.dot(b_k, b_dh) * b_gv
395
+ # [BV]
396
+ b_dg += tl.sum(b_dv * b_v, 0)
397
+
398
+ if i_k == 0:
399
+ b_dgv = tl.load(p_dg, boundary_check=(0, 1)) + b_dg[None, :]
400
+ else:
401
+ b_dgv = tl.zeros([BT, BV], dtype=tl.float32) + b_dg[None, :]
402
+
403
+ tl.store(p_dgv, b_dgv.to(p_dgv.dtype.element_ty), boundary_check=(0, 1))
404
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
405
+ p_dA = tl.make_block_ptr(dA + (bos*HQ + i_hq) * BT, (T, BT), (HQ*BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
406
+ p_dq = tl.make_block_ptr(dq + (bos*HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
407
+ p_dk = tl.make_block_ptr(dk + (bos*HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
408
+ # [BT, BT]
409
+ b_dA = tl.load(p_dA, boundary_check=(0, 1))
410
+ # [BT, BK]
411
+ b_dq += tl.dot(b_dA, b_k)
412
+ b_dk += tl.dot(tl.trans(b_dA).to(b_k.dtype), b_q)
413
+
414
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
415
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
416
+
417
+
418
+ @triton.heuristics({
419
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
420
+ })
421
+ @triton.jit(do_not_specialize=['T'])
422
+ def chunk_gsa_bwd_k_kernel_intra_dvg(
423
+ v,
424
+ g,
425
+ o,
426
+ A,
427
+ do,
428
+ dv,
429
+ dg,
430
+ cu_seqlens,
431
+ chunk_indices,
432
+ T,
433
+ HQ: tl.constexpr,
434
+ H: tl.constexpr,
435
+ V: tl.constexpr,
436
+ BT: tl.constexpr,
437
+ BC: tl.constexpr,
438
+ BV: tl.constexpr,
439
+ NC: tl.constexpr,
440
+ NG: tl.constexpr,
441
+ IS_VARLEN: tl.constexpr,
442
+ ):
443
+ i_v, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
444
+ i_b, i_hq = i_bh // HQ, i_bh % HQ
445
+ i_h = i_hq // NG
446
+ i_t, i_i = i_c // NC, i_c % NC
447
+ if IS_VARLEN:
448
+ i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
449
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
450
+ T = eos - bos
451
+ else:
452
+ bos, eos = i_b * T, i_b * T + T
453
+
454
+ o_v = i_v * BV + tl.arange(0, BV)
455
+ m_v = o_v < V
456
+
457
+ if i_t * BT + i_i * BC >= T:
458
+ return
459
+
460
+ p_gv = tl.make_block_ptr(g + (bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
461
+ p_gn = g + (bos + min(i_t * BT + i_i * BC + BC, T)-1)*H*V + i_h*V + o_v
462
+ # [BV,]
463
+ b_gn = tl.load(p_gn, mask=m_v, other=0)
464
+ # [BC, BV]
465
+ b_gv = tl.load(p_gv, boundary_check=(0, 1))
466
+ b_dv = tl.zeros([BC, BV], dtype=tl.float32)
467
+ for i_j in range(i_i + 1, NC):
468
+ p_g = tl.make_block_ptr(g + (bos*H+i_h) * V, (T, V), (H*V, 1), (i_t * BT + i_j * BC, i_v * BV), (BC, BV), (1, 0))
469
+ p_A = tl.make_block_ptr(A + (bos*HQ+i_hq) * BT, (BT, T), (1, HQ*BT), (i_i*BC, i_t*BT + i_j*BC), (BC, BC), (0, 1))
470
+ p_do = tl.make_block_ptr(do + (bos*HQ+i_hq) * V, (T, V), (HQ*V, 1), (i_t*BT + i_j*BC, i_v*BV), (BC, BV), (1, 0))
471
+ # [BC, BV]
472
+ b_g = tl.load(p_g, boundary_check=(0, 1))
473
+ b_do = tl.load(p_do, boundary_check=(0, 1)) * exp(b_g - b_gn[None, :])
474
+ # [BC, BC]
475
+ b_A = tl.load(p_A, boundary_check=(0, 1))
476
+ # [BC, BV]
477
+ b_dv += tl.dot(b_A, b_do.to(b_A.dtype))
478
+ b_dv *= exp(b_gn[None, :] - b_gv)
479
+
480
+ o_i = tl.arange(0, BC)
481
+ o_c = i_i * BC + tl.arange(0, BC)
482
+
483
+ p_g = g + (bos + i_t * BT + i_i * BC) * H*V + i_h * V + o_v
484
+ p_A = A + (bos + i_t*BT + i_i*BC) * HQ*BT + i_hq * BT + o_c
485
+ p_do = do + (bos + i_t*BT + i_i*BC) * HQ*V + i_hq * V + o_v
486
+ for j in range(0, min(BC, T - i_t * BT - i_i * BC)):
487
+ # [BC,]
488
+ b_A = tl.load(p_A)
489
+ # [BV,]
490
+ b_g = tl.load(p_g, mask=m_v, other=0)
491
+ b_do = tl.load(p_do, mask=m_v, other=0)
492
+ # [BC, BV]
493
+ m_i = o_i[:, None] <= j
494
+ b_dv += tl.where(m_i, exp(b_g[None, :] - b_gv) * b_A[:, None] * b_do[None, :], 0.)
495
+
496
+ p_g += H * V
497
+ p_A += HQ * BT
498
+ p_do += HQ * V
499
+ p_o = tl.make_block_ptr(o + (bos*HQ+i_hq)*V, (T, V), (HQ*V, 1), (i_t*BT + i_i*BC, i_v*BV), (BC, BV), (1, 0))
500
+ p_v = tl.make_block_ptr(v + (bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT + i_i*BC, i_v*BV), (BC, BV), (1, 0))
501
+ p_do = tl.make_block_ptr(do + (bos*HQ+i_hq)*V, (T, V), (HQ*V, 1), (i_t*BT + i_i*BC, i_v*BV), (BC, BV), (1, 0))
502
+ p_dv = tl.make_block_ptr(dv + (bos*HQ+i_hq)*V, (T, V), (HQ*V, 1), (i_t*BT + i_i*BC, i_v*BV), (BC, BV), (1, 0))
503
+ p_dg = tl.make_block_ptr(dg + (bos*HQ+i_hq)*V, (T, V), (HQ*V, 1), (i_t*BT + i_i*BC, i_v*BV), (BC, BV), (1, 0))
504
+
505
+ b_o = tl.load(p_o, boundary_check=(0, 1)).to(tl.float32)
506
+ b_v = tl.load(p_v, boundary_check=(0, 1)).to(tl.float32)
507
+ b_do = tl.load(p_do, boundary_check=(0, 1)).to(tl.float32)
508
+ b_dv = b_dv + tl.load(p_dv, boundary_check=(0, 1)).to(tl.float32)
509
+ b_dg = b_o * b_do - b_v * b_dv
510
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
511
+ tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0, 1))
512
+
513
+
514
+ def chunk_gsa_fwd_v(
515
+ q: torch.Tensor,
516
+ k: torch.Tensor,
517
+ v: torch.Tensor,
518
+ g: torch.Tensor,
519
+ scale: float = 1.,
520
+ initial_state: Optional[torch.Tensor] = None,
521
+ output_final_state: bool = False,
522
+ cu_seqlens: Optional[torch.LongTensor] = None,
523
+ chunk_size: int = 64
524
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
525
+ _, A, h, ht, o = chunk_gla_fwd(
526
+ q=q,
527
+ k=k,
528
+ v=v,
529
+ g=None,
530
+ g_cumsum=g,
531
+ scale=scale,
532
+ initial_state=initial_state,
533
+ output_final_state=output_final_state,
534
+ cu_seqlens=cu_seqlens,
535
+ chunk_size=chunk_size
536
+ )
537
+ return A, h, ht, o
538
+
539
+
540
+ def chunk_gsa_fwd_k(
541
+ q: torch.Tensor,
542
+ k: torch.Tensor,
543
+ v: torch.Tensor,
544
+ g: torch.Tensor,
545
+ h0: Optional[torch.Tensor] = None,
546
+ output_final_state: bool = False,
547
+ scale: float = 1.,
548
+ cu_seqlens: Optional[torch.LongTensor] = None,
549
+ chunk_size: int = 64
550
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
551
+ B, T, H, K, V = *k.shape, v.shape[-1]
552
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
553
+ BC = min(16, BT)
554
+ BV = min(64, triton.next_power_of_2(V))
555
+ HQ = q.shape[2]
556
+
557
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
558
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
559
+ NC = triton.cdiv(BT, BC)
560
+ NG = HQ // H
561
+
562
+ h, ht = chunk_fwd_h(
563
+ k=k,
564
+ v=v,
565
+ g=None,
566
+ gk=None,
567
+ gv=g,
568
+ h0=h0,
569
+ output_final_state=output_final_state,
570
+ cu_seqlens=cu_seqlens,
571
+ chunk_size=BT,
572
+ states_in_fp32=False
573
+ )
574
+ o = v.new_empty(B, T, HQ, V)
575
+ A = q.new_empty(B, T, HQ, BT)
576
+ def grid(meta): return (triton.cdiv(V, meta['BV']), NT, B * HQ)
577
+ chunk_gsa_fwd_k_kernel_inter[grid](
578
+ q,
579
+ k,
580
+ h,
581
+ g,
582
+ o,
583
+ A,
584
+ cu_seqlens=cu_seqlens,
585
+ chunk_indices=chunk_indices,
586
+ scale=scale,
587
+ T=T,
588
+ HQ=HQ,
589
+ H=H,
590
+ K=K,
591
+ V=V,
592
+ BT=BT,
593
+ NG=NG,
594
+ )
595
+
596
+ def grid(meta): return (triton.cdiv(V, meta['BV']), NT * NC, B * HQ)
597
+ chunk_gsa_fwd_k_kernel_intra[grid](
598
+ v,
599
+ g,
600
+ o,
601
+ A,
602
+ cu_seqlens=cu_seqlens,
603
+ chunk_indices=chunk_indices,
604
+ T=T,
605
+ HQ=HQ,
606
+ H=H,
607
+ V=V,
608
+ BT=BT,
609
+ BC=BC,
610
+ BV=BV,
611
+ NC=NC,
612
+ NG=NG,
613
+ num_warps=4,
614
+ num_stages=2
615
+ )
616
+ return A, h, ht, o
617
+
618
+
619
+ def chunk_gsa_bwd_v(
620
+ q: torch.Tensor,
621
+ k: torch.Tensor,
622
+ v: torch.Tensor,
623
+ g: torch.Tensor,
624
+ h0: torch.Tensor,
625
+ h: torch.Tensor,
626
+ A: torch.Tensor,
627
+ do: torch.Tensor,
628
+ dht: torch.Tensor,
629
+ dg: torch.Tensor,
630
+ scale: float = 1.,
631
+ cu_seqlens: Optional[torch.LongTensor] = None,
632
+ chunk_size: int = 64
633
+ ):
634
+ dq, dk, dv, dg, dh0 = chunk_gla_bwd(
635
+ q=q,
636
+ k=k,
637
+ v=v,
638
+ g=None,
639
+ g_cumsum=g,
640
+ scale=scale,
641
+ initial_state=h0,
642
+ h=h,
643
+ A=A,
644
+ do=do,
645
+ dht=dht,
646
+ cu_seqlens=cu_seqlens,
647
+ chunk_size=chunk_size
648
+ )
649
+ return dq, dk, dv, dg, dh0
650
+
651
+
652
+ def chunk_gsa_bwd_k(
653
+ q: torch.Tensor,
654
+ k: torch.Tensor,
655
+ v: torch.Tensor,
656
+ g: torch.Tensor,
657
+ h: torch.Tensor,
658
+ h0: torch.Tensor,
659
+ o: torch.Tensor,
660
+ do: torch.Tensor,
661
+ dht: torch.Tensor,
662
+ dg: torch.Tensor,
663
+ scale: float = 1.,
664
+ cu_seqlens: Optional[torch.LongTensor] = None,
665
+ chunk_size: int = 64
666
+ ):
667
+ B, T, H, K, V = *k.shape, v.shape[-1]
668
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
669
+ BC = min(16, BT)
670
+ BK = min(64, triton.next_power_of_2(K))
671
+ BV = min(64, triton.next_power_of_2(V))
672
+ HQ = q.shape[2]
673
+
674
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
675
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
676
+ NC = triton.cdiv(BT, BC)
677
+ NK = triton.cdiv(K, BK)
678
+ NV = triton.cdiv(V, BV)
679
+ NG = HQ // H
680
+
681
+ if h is None:
682
+ h, _ = chunk_fwd_h(
683
+ k=k,
684
+ v=v,
685
+ g=None,
686
+ gk=None,
687
+ gv=g,
688
+ h0=h0,
689
+ output_final_state=False,
690
+ cu_seqlens=cu_seqlens,
691
+ chunk_size=BT,
692
+ states_in_fp32=False
693
+ )
694
+ dh, dh0 = chunk_bwd_dh(
695
+ q=q,
696
+ k=k,
697
+ v=v,
698
+ g=None,
699
+ gk=None,
700
+ gv=g,
701
+ do=do,
702
+ h0=h0,
703
+ dht=dht,
704
+ scale=scale,
705
+ cu_seqlens=cu_seqlens,
706
+ chunk_size=BT,
707
+ states_in_fp32=True
708
+ )
709
+ dA = q.new_empty(NV, B, T, HQ, BT)
710
+ grid = (NV, NT * NC * NC, B * HQ)
711
+ chunk_gsa_bwd_k_kernel_dA[grid](
712
+ v,
713
+ g,
714
+ do,
715
+ dA,
716
+ cu_seqlens=cu_seqlens,
717
+ chunk_indices=chunk_indices,
718
+ scale=scale,
719
+ T=T,
720
+ B=B,
721
+ HQ=HQ,
722
+ H=H,
723
+ V=V,
724
+ BT=BT,
725
+ BC=BC,
726
+ BV=BV,
727
+ NC=NC,
728
+ NG=NG,
729
+ )
730
+ dA = dA.sum(0, dtype=dA.dtype)
731
+
732
+ A = do.new_empty(NK, B, T, HQ, BT)
733
+ dq = torch.empty_like(q)
734
+ dk = k.new_empty(B, T, HQ, K)
735
+ dv = v.new_empty(NK, B, T, HQ, V)
736
+ dgv = g.new_empty(NK, B, T, HQ, V, dtype=torch.float)
737
+ grid = (NK, NT, B * HQ)
738
+ chunk_gsa_bwd_k_kernel_dqkvg[grid](
739
+ q,
740
+ k,
741
+ v,
742
+ h,
743
+ g,
744
+ A,
745
+ do,
746
+ dh,
747
+ dq,
748
+ dk,
749
+ dv,
750
+ dg,
751
+ dgv,
752
+ dA,
753
+ cu_seqlens=cu_seqlens,
754
+ chunk_indices=chunk_indices,
755
+ scale=scale,
756
+ T=T,
757
+ B=B,
758
+ HQ=HQ,
759
+ H=H,
760
+ K=K,
761
+ V=V,
762
+ BT=BT,
763
+ BK=BK,
764
+ BV=BV,
765
+ NG=NG,
766
+ )
767
+ A = A.sum(0, dtype=A.dtype)
768
+ dv = dv.sum(0, dtype=dv.dtype)
769
+ dgv = dgv.sum(0, dtype=dgv.dtype)
770
+
771
+ def grid(meta): return (triton.cdiv(V, meta['BV']), NT * NC, B * HQ)
772
+ chunk_gsa_bwd_k_kernel_intra_dvg[grid](
773
+ v,
774
+ g,
775
+ o,
776
+ A,
777
+ do,
778
+ dv,
779
+ dg,
780
+ cu_seqlens=cu_seqlens,
781
+ chunk_indices=chunk_indices,
782
+ T=T,
783
+ HQ=HQ,
784
+ H=H,
785
+ V=V,
786
+ BT=BT,
787
+ BC=BC,
788
+ BV=BV,
789
+ NC=NC,
790
+ NG=NG,
791
+ num_warps=4,
792
+ num_stages=2
793
+ )
794
+ dg = dgv.add_(chunk_local_cumsum(dg, chunk_size=BT, reverse=True, cu_seqlens=cu_seqlens))
795
+
796
+ return dq, dk, dv, dg, dh0
797
+
798
+
799
+ def chunk_gsa_fwd(
800
+ q: torch.Tensor,
801
+ k: torch.Tensor,
802
+ v: torch.Tensor,
803
+ s: torch.Tensor,
804
+ g: torch.Tensor,
805
+ initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
806
+ output_final_state: bool = False,
807
+ scale: float = 1.,
808
+ cu_seqlens: Optional[torch.LongTensor] = None,
809
+ chunk_size: int = 64
810
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
811
+ hk0, hv0 = None, None
812
+ if initial_state is not None:
813
+ hk0, hv0 = initial_state
814
+ Ak, hk, hkt, ok = chunk_gsa_fwd_k(
815
+ q=q,
816
+ k=k,
817
+ v=s,
818
+ g=g,
819
+ h0=hk0,
820
+ output_final_state=output_final_state,
821
+ scale=scale,
822
+ cu_seqlens=cu_seqlens,
823
+ chunk_size=chunk_size
824
+ )
825
+
826
+ # p is kept in fp32 for safe softmax backward
827
+ p = softmax_fwd(ok, dtype=torch.float)
828
+
829
+ qv = p.to(q.dtype)
830
+ Av, hv, hvt, ov = chunk_gsa_fwd_v(
831
+ q=qv,
832
+ k=s,
833
+ v=v,
834
+ g=g,
835
+ scale=1.,
836
+ initial_state=hv0,
837
+ output_final_state=output_final_state,
838
+ cu_seqlens=cu_seqlens,
839
+ chunk_size=chunk_size
840
+ )
841
+ return Ak, hk, hkt, ok, p, Av, hv, hvt, ov
842
+
843
+
844
+ def chunk_gsa_bwd(
845
+ q: torch.Tensor,
846
+ k: torch.Tensor,
847
+ v: torch.Tensor,
848
+ s: torch.Tensor,
849
+ g: torch.Tensor,
850
+ ok: torch.Tensor,
851
+ p: torch.Tensor,
852
+ A: Tuple[torch.Tensor, torch.Tensor],
853
+ h: Tuple[torch.Tensor, torch.Tensor],
854
+ initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]],
855
+ scale: float,
856
+ do: torch.Tensor,
857
+ dht: Tuple[torch.Tensor, torch.Tensor],
858
+ cu_seqlens: Optional[torch.LongTensor] = None,
859
+ chunk_size: int = 64
860
+ ):
861
+ hk0, hv0 = None, None
862
+ if initial_state is not None:
863
+ hk0, hv0 = initial_state
864
+
865
+ _, Av = A
866
+ hk, hv = h
867
+ dhkt, dhvt = dht
868
+
869
+ qv = p.to(q.dtype)
870
+ dqv, dsv, dv, dg, dhv0 = chunk_gsa_bwd_v(
871
+ q=qv,
872
+ k=s,
873
+ v=v,
874
+ g=g,
875
+ h0=hv0,
876
+ h=hv,
877
+ A=Av,
878
+ do=do,
879
+ dht=dhvt,
880
+ dg=None,
881
+ scale=1.,
882
+ cu_seqlens=cu_seqlens,
883
+ chunk_size=chunk_size
884
+ )
885
+
886
+ # softmax gradient, equivalent to:
887
+ # dok = qv * (dqv - (qv * dqv).sum(-1, True))
888
+ dok = softmax_bwd(p, dqv, dtype=ok.dtype)
889
+
890
+ dq, dk, dsk, dg, dhk0 = chunk_gsa_bwd_k(
891
+ q=q,
892
+ k=k,
893
+ v=s,
894
+ g=g,
895
+ h0=hk0,
896
+ h=hk,
897
+ o=ok,
898
+ do=dok,
899
+ dht=dhkt,
900
+ dg=dg,
901
+ scale=scale,
902
+ cu_seqlens=cu_seqlens,
903
+ chunk_size=chunk_size
904
+ )
905
+
906
+ ds = dsv.add_(dsk)
907
+ if q.shape[1] != k.shape[1]:
908
+ dk, dv, ds, dg = map(lambda x: reduce(x, 'b (h g) ... -> b h ...', 'sum', h=k.shape[1]), (dk, dv, ds, dg))
909
+ dg = dg.to(s.dtype)
910
+ return dq, dk, dv, ds, dg, dhk0, dhv0
911
+
912
+
913
+ class ChunkGSAFunction(torch.autograd.Function):
914
+
915
+ @staticmethod
916
+ @input_guard
917
+ def forward(
918
+ ctx,
919
+ q: torch.Tensor,
920
+ k: torch.Tensor,
921
+ v: torch.Tensor,
922
+ s: torch.Tensor,
923
+ g: torch.Tensor,
924
+ scale: float,
925
+ hk0: Optional[torch.Tensor],
926
+ hv0: Optional[torch.Tensor],
927
+ output_final_state: bool,
928
+ checkpoint_level: int,
929
+ cu_seqlens: Optional[torch.LongTensor],
930
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
931
+ T = q.shape[1]
932
+ chunk_size = min(64, max(16, triton.next_power_of_2(T)))
933
+
934
+ g_org, g = g, chunk_local_cumsum(g, chunk_size, cu_seqlens=cu_seqlens)
935
+ Ak, hk, hkt, ok, p, Av, hv, hvt, ov = chunk_gsa_fwd(
936
+ q=q,
937
+ k=k,
938
+ v=v,
939
+ s=s,
940
+ g=g,
941
+ initial_state=(hk0, hv0),
942
+ output_final_state=output_final_state,
943
+ scale=scale,
944
+ cu_seqlens=cu_seqlens,
945
+ chunk_size=chunk_size
946
+ )
947
+
948
+ if checkpoint_level >= 1:
949
+ del g
950
+ g = g_org
951
+ if checkpoint_level > 1:
952
+ del hk
953
+ del hv
954
+ hk, hv = None, None
955
+ else:
956
+ hk0, hv0 = None, None
957
+
958
+ ctx.save_for_backward(q, k, v, s, g, ok, p, Av, hk0, hv0, hk, hv)
959
+ ctx.checkpoint_level = checkpoint_level
960
+ ctx.scale = scale
961
+ ctx.cu_seqlens = cu_seqlens
962
+ ctx.chunk_size = chunk_size
963
+ return ov, hkt, hvt
964
+
965
+ @staticmethod
966
+ @input_guard
967
+ def backward(ctx, dov, dhkt=None, dhvt=None):
968
+ q, k, v, s, g, ok, p, Av, hk0, hv0, hk, hv = ctx.saved_tensors
969
+ scale = ctx.scale
970
+ cu_seqlens = ctx.cu_seqlens
971
+ chunk_size = ctx.chunk_size
972
+
973
+ if ctx.checkpoint_level >= 1:
974
+ g = chunk_local_cumsum(g, chunk_size, cu_seqlens=cu_seqlens)
975
+ dq, dk, dv, ds, dg, dhk0, dhv0 = chunk_gsa_bwd(
976
+ q=q,
977
+ k=k,
978
+ v=v,
979
+ s=s,
980
+ g=g,
981
+ ok=ok,
982
+ p=p,
983
+ A=(None, Av),
984
+ h=(hk, hv),
985
+ initial_state=(hk0, hv0),
986
+ scale=scale,
987
+ do=dov,
988
+ dht=(dhkt, dhvt),
989
+ cu_seqlens=cu_seqlens,
990
+ chunk_size=chunk_size
991
+ )
992
+ return dq, dk, dv, ds, dg, None, dhk0, dhv0, None, None, None, None
993
+
994
+
995
+ @torch.compiler.disable
996
+ def chunk_gsa(
997
+ q: torch.Tensor,
998
+ k: torch.Tensor,
999
+ v: torch.Tensor,
1000
+ s: torch.Tensor,
1001
+ g: Optional[torch.Tensor] = None,
1002
+ scale: Optional[int] = None,
1003
+ initial_state: Optional[Tuple[torch.Tensor]] = None,
1004
+ output_final_state: Optional[bool] = False,
1005
+ checkpoint_level: Optional[int] = 2,
1006
+ cu_seqlens: Optional[torch.LongTensor] = None,
1007
+ head_first: Optional[bool] = False
1008
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
1009
+ r"""
1010
+ Args:
1011
+ q (torch.Tensor):
1012
+ queries of shape `[B, T, HQ, K]`..
1013
+ k (torch.Tensor):
1014
+ keys of shape `[B, T, H, K]`.
1015
+ GQA is performed if `H` is not equal to `HQ`.
1016
+ v (torch.Tensor):
1017
+ values of shape `[B, T, H, V]`.
1018
+ s (torch.Tensor):
1019
+ slot representations of shape `[B, T, H, M]`..
1020
+ g (torch.Tensor):
1021
+ Forget gates of shape `[B, T, H, M]` applied to keys.
1022
+ If not provided, this function is equivalent to vanilla ABC.
1023
+ scale (Optional[float]):
1024
+ Scale factor for attention scores.
1025
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
1026
+ initial_state (Optional[Tuple[torch.Tensor]]):
1027
+ Initial state tuple having tensors of shape `[N, H, K, M]` and `[N, H, M, V]` for `N` input sequences.
1028
+ For equal-length input sequences, `N` equals the batch size `B`.
1029
+ Default: `None`.
1030
+ output_final_state (Optional[bool]):
1031
+ Whether to output the final state tuple, having tensors of shape `[N, H, K, M]` and `[N, H, M, V]`.
1032
+ Default: `False`.
1033
+ checkpoint_level (Optional[int]):
1034
+ Checkpointing level; higher values will save more memories and do more recomputations during backward.
1035
+ Default: `2`:
1036
+ - Level `0`: no memory saved, no recomputation.
1037
+ - Level `1`: recompute the fp32 cumulative values during backward.
1038
+ - Level `2`: recompute the fp32 cumulative values and forward hidden states during backward.
1039
+ cu_seqlens (torch.LongTensor):
1040
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
1041
+ consistent with the FlashAttention API.
1042
+ head_first (Optional[bool]):
1043
+ Whether the inputs are in the head-first format. Default: `False`.
1044
+ This argument has been deprecated.
1045
+
1046
+ Returns:
1047
+ o (torch.Tensor):
1048
+ Outputs of shape `[B, T, H, V]`.
1049
+ final_state (Tuple[torch.Tensor]):
1050
+ Final state tuple having tensors of shape `[N, H, K, M]` and `[N, H, M, V]` if `output_final_state=True`.
1051
+ `None` otherwise.
1052
+
1053
+ Examples::
1054
+ >>> import torch
1055
+ >>> import torch.nn.functional as F
1056
+ >>> from einops import rearrange
1057
+ >>> from fla.ops.gsa import fused_recurrent_gsa
1058
+ # inputs with equal lengths
1059
+ >>> B, T, H, K, V, M = 4, 2048, 4, 512, 512, 64
1060
+ >>> q = torch.randn(B, T, H, K, device='cuda')
1061
+ >>> k = torch.randn(B, T, H, K, device='cuda')
1062
+ >>> v = torch.randn(B, T, H, V, device='cuda')
1063
+ >>> s = torch.randn(B, T, H, M, device='cuda')
1064
+ >>> g = F.logsigmoid(torch.randn(B, T, H, M, device='cuda'))
1065
+ >>> h0 = (torch.randn(B, H, K, M, device='cuda'), torch.randn(B, H, M, V, device='cuda'))
1066
+ >>> o, (hk, hv) = chunk_gsa(
1067
+ q, k, v, s, g,
1068
+ initial_state=h0,
1069
+ output_final_state=True
1070
+ )
1071
+ # for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
1072
+ >>> q, k, v, s, g = map(lambda x: rearrange(x, 'b t h d -> 1 (b t) h d'), (q, k, v, s, g))
1073
+ # for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
1074
+ >>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
1075
+ >>> o_var, (hk_var, hv_var) = chunk_gsa(
1076
+ q, k, v, s, g,
1077
+ initial_state=h0,
1078
+ output_final_state=True,
1079
+ cu_seqlens=cu_seqlens
1080
+ )
1081
+ >>> assert o.allclose(o_var.view(o.shape))
1082
+ >>> assert hk.allclose(hk_var)
1083
+ >>> assert hv.allclose(hv_var)
1084
+ """
1085
+ if head_first:
1086
+ raise DeprecationWarning(
1087
+ "head_first is deprecated and will be removed in a future version. "
1088
+ "Please use head_first=False for now instead."
1089
+ )
1090
+ if not head_first and q.shape[1] < q.shape[2]:
1091
+ warnings.warn(
1092
+ f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
1093
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
1094
+ "when head_first=False was specified. "
1095
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
1096
+ )
1097
+ if cu_seqlens is not None:
1098
+ if q.shape[0] != 1:
1099
+ raise ValueError(
1100
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
1101
+ f"Please flatten variable-length inputs before processing."
1102
+ )
1103
+ if initial_state is not None and initial_state[0].shape[0] != len(cu_seqlens) - 1:
1104
+ raise ValueError(
1105
+ f"The number of initial states is expected to be equal to the number of input sequences, "
1106
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state[0].shape[0]}."
1107
+ )
1108
+ assert checkpoint_level in [0, 1, 2]
1109
+ if g is None:
1110
+ # TODO: this 3 steps took huge amount of time, ought to be optimized
1111
+ z = s.float().logcumsumexp(2)
1112
+ g = torch.cat((z[:, :, :1], z[:, :, :-1]), 1) - z
1113
+ s = torch.exp(s - z).to(k.dtype)
1114
+ if scale is None:
1115
+ scale = q.shape[-1] ** -0.5
1116
+
1117
+ hk0, hv0 = None, None
1118
+ if initial_state is not None:
1119
+ hk0, hv0 = initial_state
1120
+ o, *final_state = ChunkGSAFunction.apply(
1121
+ q,
1122
+ k,
1123
+ v,
1124
+ s,
1125
+ g,
1126
+ scale,
1127
+ hk0,
1128
+ hv0,
1129
+ output_final_state,
1130
+ checkpoint_level,
1131
+ cu_seqlens
1132
+ )
1133
+ return o, final_state