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
@@ -0,0 +1,384 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Optional, Tuple
5
+
6
+ import torch
7
+ import triton
8
+ import triton.language as tl
9
+
10
+ from fla.ops.utils import prepare_chunk_offsets
11
+ from fla.ops.utils.op import exp
12
+ from fla.utils import check_shared_mem
13
+
14
+ BKV_LIST = [32, 64] if check_shared_mem() else [16, 32]
15
+
16
+
17
+ @triton.heuristics({
18
+ 'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
19
+ 'STORE_FINAL_STATE': lambda args: args['ht'] is not None,
20
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
21
+ })
22
+ @triton.autotune(
23
+ configs=[
24
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps, num_stages=num_stages)
25
+ for BK in BKV_LIST
26
+ for BV in BKV_LIST
27
+ for num_warps in [1, 2, 4, 8]
28
+ for num_stages in [2, 3, 4]
29
+ ],
30
+ key=['BT', 'USE_G', 'USE_GK', 'USE_GV']
31
+ )
32
+ @triton.jit(do_not_specialize=['T'])
33
+ def chunk_fwd_kernel_h(
34
+ k,
35
+ v,
36
+ h,
37
+ g,
38
+ g_gamma,
39
+ gk,
40
+ gv,
41
+ h0,
42
+ ht,
43
+ cu_seqlens,
44
+ split_offsets,
45
+ T,
46
+ H: tl.constexpr,
47
+ K: tl.constexpr,
48
+ V: tl.constexpr,
49
+ BT: tl.constexpr,
50
+ BS: tl.constexpr,
51
+ BK: tl.constexpr,
52
+ BV: tl.constexpr,
53
+ USE_G: tl.constexpr,
54
+ USE_G_GAMMA: tl.constexpr,
55
+ USE_GK: tl.constexpr,
56
+ USE_GV: tl.constexpr,
57
+ USE_INITIAL_STATE: tl.constexpr,
58
+ STORE_FINAL_STATE: tl.constexpr,
59
+ IS_VARLEN: tl.constexpr,
60
+ ):
61
+ i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
62
+ i_n, i_h = i_nh // H, i_nh % H
63
+ if IS_VARLEN:
64
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
65
+ T = eos - bos
66
+ NT, NS = tl.cdiv(T, BT), tl.cdiv(T, BS)
67
+ boh = tl.load(split_offsets + i_n).to(tl.int32)
68
+ else:
69
+ bos, eos = i_n * T, i_n * T + T
70
+ NT, NS = tl.cdiv(T, BT), tl.cdiv(T, BS)
71
+ boh = i_n * NS
72
+ NTS = BS // BT
73
+
74
+ if USE_G_GAMMA:
75
+ # decay rate given the head index
76
+ b_gamma = tl.load(g_gamma + i_h)
77
+ b_g = b_gamma * (tl.arange(0, BT) + 1)
78
+
79
+ # [BK, BV]
80
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
81
+ if USE_INITIAL_STATE:
82
+ p_h0 = tl.make_block_ptr(h0 + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
83
+ b_h = tl.load(p_h0, boundary_check=(0, 1)).to(tl.float32)
84
+
85
+ for i_t in range(NT):
86
+ i_s = i_t // NTS
87
+ 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))
88
+ 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))
89
+
90
+ o_h = ((boh + i_s) * H + i_h).to(tl.int64) * K*V
91
+ p_h = tl.make_block_ptr(h + o_h, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
92
+
93
+ if i_t % NTS == 0:
94
+ tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
95
+ # [BK, BT]
96
+ b_k = tl.load(p_k, boundary_check=(0, 1))
97
+ # [BT, BV]
98
+ b_v = tl.load(p_v, boundary_check=(0, 1))
99
+ last_idx = min((i_t + 1) * BT, T) - 1
100
+
101
+ # scalar decay
102
+ if USE_G:
103
+ b_g_last = tl.load(g + bos * H + last_idx * H + i_h)
104
+ p_g = g + bos*H + (i_t * BT + tl.arange(0, BT)) * H + i_h
105
+ b_g = tl.load(p_g, mask=(i_t * BT + tl.arange(0, BT) < T), other=0.)
106
+ b_h *= exp(b_g_last)
107
+ b_v = (b_v * exp(b_g_last - b_g)[:, None]).to(b_v.dtype)
108
+
109
+ if USE_G_GAMMA:
110
+ b_g_last = b_gamma * min(BT, T - i_t * BT)
111
+ b_h *= exp(b_g_last)
112
+ b_v = (b_v * exp(b_g_last - b_g)[:, None]).to(b_v.dtype)
113
+
114
+ # vector decay, h = Diag(gk) @ h
115
+ if USE_GK:
116
+ p_gk = tl.make_block_ptr(gk + (bos*H + i_h) * K, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
117
+ p_gk_last = gk + (bos + last_idx) * H*K + i_h * K + i_k * BK + tl.arange(0, BK)
118
+
119
+ b_gk_last = tl.load(p_gk_last, mask=(i_k * BK + tl.arange(0, BK) < K), other=0.)
120
+ b_h *= exp(b_gk_last)[:, None]
121
+
122
+ b_gk = tl.load(p_gk, boundary_check=(0, 1))
123
+ b_k = (b_k * exp(b_gk_last[:, None] - b_gk)).to(b_k.dtype)
124
+
125
+ # vector decay, h = h @ Diag(gv)
126
+ if USE_GV:
127
+ p_gv = tl.make_block_ptr(gv + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
128
+ p_gv_last = gv + (bos + last_idx) * H*V + i_h * V + i_v * BV + tl.arange(0, BV)
129
+
130
+ b_gv_last = tl.load(p_gv_last, mask=(i_v * BV + tl.arange(0, BV) < V), other=0.)
131
+ b_h *= exp(b_gv_last)[None, :]
132
+
133
+ b_gv = tl.load(p_gv, boundary_check=(0, 1))
134
+ b_v = (b_v * exp(b_gv_last[None, :] - b_gv)).to(b_v.dtype)
135
+
136
+ b_h += tl.dot(b_k, b_v)
137
+
138
+ if STORE_FINAL_STATE:
139
+ p_ht = tl.make_block_ptr(ht + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
140
+ tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
141
+
142
+
143
+ @triton.heuristics({
144
+ 'STORE_INITIAL_STATE_GRADIENT': lambda args: args['dh0'] is not None,
145
+ 'USE_FINAL_STATE_GRADIENT': lambda args: args['dht'] is not None,
146
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
147
+ })
148
+ @triton.autotune(
149
+ configs=[
150
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps, num_stages=num_stages)
151
+ for BK in BKV_LIST
152
+ for BV in BKV_LIST
153
+ for num_warps in [1, 2, 4, 8]
154
+ for num_stages in [2, 3, 4]
155
+ ],
156
+ key=['BT', 'USE_G', 'USE_GK', 'USE_GV']
157
+ )
158
+ @triton.jit(do_not_specialize=['T'])
159
+ def chunk_bwd_kernel_dh(
160
+ q,
161
+ g,
162
+ g_gamma,
163
+ gk,
164
+ gv,
165
+ do,
166
+ dh,
167
+ dht,
168
+ dh0,
169
+ cu_seqlens,
170
+ split_offsets,
171
+ scale,
172
+ T,
173
+ HQ: tl.constexpr,
174
+ H: tl.constexpr,
175
+ K: tl.constexpr,
176
+ V: tl.constexpr,
177
+ BT: tl.constexpr,
178
+ BS: tl.constexpr,
179
+ BK: tl.constexpr,
180
+ BV: tl.constexpr,
181
+ NG: tl.constexpr,
182
+ USE_G: tl.constexpr,
183
+ USE_G_GAMMA: tl.constexpr,
184
+ USE_GK: tl.constexpr,
185
+ USE_GV: tl.constexpr,
186
+ STORE_INITIAL_STATE_GRADIENT: tl.constexpr,
187
+ USE_FINAL_STATE_GRADIENT: tl.constexpr,
188
+ IS_VARLEN: tl.constexpr,
189
+ ):
190
+ i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
191
+ i_n, i_hq = i_nh // HQ, i_nh % HQ
192
+ i_h = i_hq // NG
193
+ if IS_VARLEN:
194
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
195
+ T = eos - bos
196
+ NT = tl.cdiv(T, BT)
197
+ NS = tl.cdiv(T, BS)
198
+ boh = tl.load(split_offsets + i_n).to(tl.int32)
199
+ else:
200
+ bos, eos = i_n * T, i_n * T + T
201
+ NT = tl.cdiv(T, BT)
202
+ NS = tl.cdiv(T, BS)
203
+ boh = i_n * NS
204
+
205
+ if USE_G_GAMMA:
206
+ b_gamma = tl.load(g_gamma + i_h)
207
+ b_g = b_gamma * (tl.arange(0, BT) + 1)
208
+
209
+ # [BK, BV]
210
+ b_dh = tl.zeros([BK, BV], dtype=tl.float32)
211
+ if USE_FINAL_STATE_GRADIENT:
212
+ p_dht = tl.make_block_ptr(dht + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
213
+ b_dh += tl.load(p_dht, boundary_check=(0, 1)).to(tl.float32)
214
+
215
+ for i_t in range(NT - 1, -1, -1):
216
+ i_s = i_t // (BS // BT)
217
+ o_dh = ((boh + i_s) * H + i_h).to(tl.int64) * K*V
218
+ p_dh = tl.make_block_ptr(dh + o_dh, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
219
+
220
+ if i_t % (BS // BT) == 0:
221
+ tl.store(p_dh, b_dh.to(p_dh.dtype.element_ty), boundary_check=(0, 1))
222
+ last_idx = min(i_t * BT + BT, T) - 1
223
+ # [BK, BT]
224
+ p_q = tl.make_block_ptr(q + (bos*HQ + i_hq) * K, (K, T), (1, HQ*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
225
+ 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))
226
+ b_q = tl.load(p_q, boundary_check=(0, 1))
227
+ b_q = (b_q * scale).to(b_q.dtype)
228
+ # [BT, BV]
229
+ b_do = tl.load(p_do, boundary_check=(0, 1))
230
+
231
+ if USE_G:
232
+ p_g = g + (bos + i_t * BT + tl.arange(0, BT)) * H + i_h
233
+ b_g_last = tl.load(g + (bos + last_idx) * H + i_h)
234
+ b_g = tl.load(p_g, mask=(i_t * BT + tl.arange(0, BT) < T), other=0.)
235
+ b_q = (b_q * exp(b_g)[None, :]).to(b_q.dtype)
236
+ b_dh *= exp(b_g_last)
237
+
238
+ if USE_G_GAMMA:
239
+ b_g_last = b_gamma * min(BT, T - i_t * BT)
240
+ b_q = (b_q * exp(b_g)[None, :]).to(b_q.dtype)
241
+ b_dh *= exp(b_g_last)
242
+
243
+ if USE_GK:
244
+ p_gk = tl.make_block_ptr(gk + (bos*H + i_h) * K, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
245
+ p_gk_last = gk + (bos + last_idx) * H*K + i_h * K + i_k * BK + tl.arange(0, BK)
246
+
247
+ b_gk = tl.load(p_gk, boundary_check=(0, 1))
248
+ b_q = (b_q * exp(b_gk)).to(b_q.dtype)
249
+ b_gk_last = tl.load(p_gk_last, mask=(i_k * BK + tl.arange(0, BK) < K), other=0.)
250
+ b_dh *= exp(b_gk_last)[:, None]
251
+
252
+ if USE_GV:
253
+ p_gv = tl.make_block_ptr(gv + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
254
+ p_gv_last = gv + (bos + last_idx) * H*V + i_h * V + i_v * BV + tl.arange(0, BV)
255
+
256
+ b_gv = tl.load(p_gv, boundary_check=(0, 1))
257
+ b_do = (b_do * exp(b_gv))
258
+
259
+ b_gv_last = tl.load(p_gv_last, mask=(i_v * BV + tl.arange(0, BV) < V), other=0.)
260
+ b_dh *= exp(b_gv_last)[None, :]
261
+
262
+ b_dh += tl.dot(b_q, b_do.to(b_q.dtype))
263
+
264
+ if STORE_INITIAL_STATE_GRADIENT:
265
+ p_dh0 = tl.make_block_ptr(dh0 + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
266
+ tl.store(p_dh0, b_dh.to(p_dh0.dtype.element_ty), boundary_check=(0, 1))
267
+
268
+
269
+ def chunk_fwd_h(
270
+ k: torch.Tensor,
271
+ v: torch.Tensor,
272
+ g: Optional[torch.Tensor] = None,
273
+ g_gamma: Optional[torch.Tensor] = None,
274
+ gk: Optional[torch.Tensor] = None,
275
+ gv: Optional[torch.Tensor] = None,
276
+ h0: Optional[torch.Tensor] = None,
277
+ output_final_state: bool = False,
278
+ cu_seqlens: Optional[torch.Tensor] = None,
279
+ chunk_size: int = 64,
280
+ split_size: Optional[int] = None,
281
+ states_in_fp32: bool = False
282
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
283
+ B, T, H, K, V = *k.shape, v.shape[-1]
284
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
285
+ BS = BT if split_size is None else min(split_size, max(16, triton.next_power_of_2(T)))
286
+ assert BS % BT == 0, f"The `split_size` (got {BS}) must be a multiple of `chunk_size` {BT}"
287
+ # N: the actual number of sequences in the batch with either equal or variable lengths
288
+ if cu_seqlens is None:
289
+ N, NS, split_offsets = B, triton.cdiv(T, BS), None
290
+ else:
291
+ split_offsets = prepare_chunk_offsets(cu_seqlens, BS)
292
+ N, NS = len(cu_seqlens) - 1, split_offsets[-1].item()
293
+
294
+ h = k.new_empty(B, NS, H, K, V, dtype=k.dtype if not states_in_fp32 else torch.float)
295
+ ht = k.new_empty(N, H, K, V, dtype=torch.float) if output_final_state else None
296
+ def grid(meta): return (triton.cdiv(K, meta['BK']), triton.cdiv(V, meta['BV']), N * H)
297
+ chunk_fwd_kernel_h[grid](
298
+ k=k,
299
+ v=v,
300
+ h=h,
301
+ g=g,
302
+ g_gamma=g_gamma,
303
+ gk=gk,
304
+ gv=gv,
305
+ h0=h0,
306
+ ht=ht,
307
+ cu_seqlens=cu_seqlens,
308
+ split_offsets=split_offsets,
309
+ T=T,
310
+ H=H,
311
+ K=K,
312
+ V=V,
313
+ BT=BT,
314
+ BS=BS,
315
+ USE_G=g is not None,
316
+ USE_G_GAMMA=g_gamma is not None,
317
+ USE_GK=gk is not None,
318
+ USE_GV=gv is not None,
319
+ )
320
+ return h, ht
321
+
322
+
323
+ def chunk_bwd_dh(
324
+ q: torch.Tensor,
325
+ k: torch.Tensor,
326
+ v: torch.Tensor,
327
+ do: torch.Tensor,
328
+ h0: torch.Tensor,
329
+ dht: torch.Tensor,
330
+ scale: float,
331
+ g: Optional[torch.Tensor] = None,
332
+ g_gamma: Optional[torch.Tensor] = None,
333
+ gk: Optional[torch.Tensor] = None,
334
+ gv: Optional[torch.Tensor] = None,
335
+ cu_seqlens: Optional[torch.Tensor] = None,
336
+ chunk_size: int = 64,
337
+ split_size: Optional[int] = None,
338
+ states_in_fp32: bool = False
339
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
340
+ B, T, H, K, V = *k.shape, v.shape[-1]
341
+ HQ = q.shape[2]
342
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
343
+ BS = BT if split_size is None else min(split_size, max(16, triton.next_power_of_2(T)))
344
+ assert BS % BT == 0, f"The `split_size` (got {BS}) must be a multiple of `chunk_size` {BT}"
345
+ # N: the actual number of sequences in the batch with either equal or variable lengths
346
+ # NG: number of groups in GQA
347
+ if cu_seqlens is None:
348
+ N, NS, split_offsets = B, triton.cdiv(T, BS), None
349
+ else:
350
+ split_offsets = prepare_chunk_offsets(cu_seqlens, BS)
351
+ N, NS = len(cu_seqlens) - 1, split_offsets[-1].item()
352
+ NG = HQ // H
353
+
354
+ dh = k.new_empty(B, NS, HQ, K, V, dtype=k.dtype if not states_in_fp32 else torch.float)
355
+ dh0 = torch.empty_like(h0, dtype=torch.float) if h0 is not None else None
356
+
357
+ def grid(meta): return (triton.cdiv(K, meta['BK']), triton.cdiv(V, meta['BV']), N * H)
358
+ chunk_bwd_kernel_dh[grid](
359
+ q=q,
360
+ g=g,
361
+ g_gamma=g_gamma,
362
+ gk=gk,
363
+ gv=gv,
364
+ do=do,
365
+ dh=dh,
366
+ dht=dht,
367
+ dh0=dh0,
368
+ cu_seqlens=cu_seqlens,
369
+ split_offsets=split_offsets,
370
+ scale=scale,
371
+ T=T,
372
+ HQ=HQ,
373
+ H=H,
374
+ K=K,
375
+ V=V,
376
+ BT=BT,
377
+ BS=BS,
378
+ NG=NG,
379
+ USE_G=g is not None,
380
+ USE_G_GAMMA=g_gamma is not None,
381
+ USE_GK=gk is not None,
382
+ USE_GV=gv is not None,
383
+ )
384
+ return dh, dh0