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,551 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ """
5
+ Fully parallelized state passing.
6
+ """
7
+
8
+ from typing import Optional, Tuple
9
+
10
+ import torch
11
+ import triton
12
+ import triton.language as tl
13
+
14
+ from fla.ops.utils import prepare_chunk_indices, prepare_chunk_offsets
15
+ from fla.ops.utils.op import exp
16
+
17
+
18
+ @triton.heuristics({
19
+ 'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
20
+ 'STORE_FINAL_STATE': lambda args: args['ht'] is not None,
21
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
22
+ })
23
+ @triton.autotune(
24
+ configs=[
25
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps, num_stages=num_stages)
26
+ for BK in [32, 64, 128]
27
+ for BV in [32, 64, 128]
28
+ for num_warps in [2, 4, 8]
29
+ for num_stages in [2, 3, 4]
30
+ ],
31
+ key=['BT', 'USE_G', 'USE_GK', 'USE_GV']
32
+ )
33
+ @triton.jit(do_not_specialize=['T'])
34
+ def chunk_fwd_kernel_h_parallel(
35
+ k,
36
+ v,
37
+ h,
38
+ g,
39
+ gk,
40
+ gv,
41
+ h0,
42
+ ht,
43
+ cu_seqlens,
44
+ chunk_indices,
45
+ T,
46
+ H: tl.constexpr,
47
+ K: tl.constexpr,
48
+ V: tl.constexpr,
49
+ BT: tl.constexpr,
50
+ BK: tl.constexpr,
51
+ BV: tl.constexpr,
52
+ USE_G: tl.constexpr,
53
+ USE_GK: tl.constexpr,
54
+ USE_GV: tl.constexpr,
55
+ USE_INITIAL_STATE: tl.constexpr,
56
+ STORE_FINAL_STATE: tl.constexpr,
57
+ IS_VARLEN: tl.constexpr
58
+ ):
59
+ i_kv, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
60
+
61
+ NV = tl.cdiv(V, BV)
62
+ # i_b: batch index
63
+ # i_h: head index
64
+ # i_n: sequence index
65
+ # i_t: chunk index within current sequence
66
+ # i_tg: (global) chunk index across all sequences
67
+ i_k, i_v = i_kv // NV, i_kv % NV
68
+ i_b, i_h = i_bh // H, i_bh % H
69
+ if IS_VARLEN:
70
+ i_tg = i_t
71
+ 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)
72
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
73
+ T = eos - bos
74
+ NT = tl.cdiv(T, BT)
75
+ else:
76
+ bos, eos = i_b * T, i_b * T + T
77
+ NT = tl.cdiv(T, BT)
78
+ i_n, i_tg = i_b, i_b * NT + i_t
79
+ i_nh = i_n * H + i_h
80
+
81
+ 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))
82
+ 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))
83
+ 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))
84
+
85
+ if i_t == 0:
86
+ if USE_INITIAL_STATE:
87
+ 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))
88
+ b_h = tl.load(p_h0, boundary_check=(0, 1)).to(tl.float32)
89
+ else:
90
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
91
+ tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
92
+
93
+ # [BK, BT]
94
+ b_k = tl.load(p_k, boundary_check=(0, 1))
95
+ # [BT, BV]
96
+ b_v = tl.load(p_v, boundary_check=(0, 1))
97
+
98
+ last_idx = min(i_t * BT + BT, T) - 1
99
+ # scalar decay
100
+ if USE_G:
101
+ b_g_last = tl.load(g + bos * H + last_idx * H + i_h)
102
+ p_g = g + bos*H + (i_t * BT + tl.arange(0, BT)) * H + i_h
103
+ b_g = tl.load(p_g, mask=(i_t * BT + tl.arange(0, BT) < T), other=0.)
104
+ b_v = (b_v * exp(b_g_last - b_g)[:, None]).to(b_v.dtype)
105
+
106
+ # vector decay, h = Diag(gk) @ h
107
+ if USE_GK:
108
+ 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))
109
+ p_gk_last = gk + (bos + last_idx) * H*K + i_h * K + i_k * BK + tl.arange(0, BK)
110
+ b_gk_last = tl.load(p_gk_last, mask=(i_k * BK + tl.arange(0, BK) < K), other=0.)
111
+
112
+ b_gk = tl.load(p_gk, boundary_check=(0, 1))
113
+ b_k = (b_k * exp(b_gk_last[:, None] - b_gk)).to(b_k.dtype)
114
+
115
+ # vector decay, h = h @ Diag(gv)
116
+ if USE_GV:
117
+ 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))
118
+ p_gv_last = gv + (bos + last_idx) * H*V + i_h * V + i_v * BV + tl.arange(0, BV)
119
+
120
+ b_gv_last = tl.load(p_gv_last, mask=(i_v * BV + tl.arange(0, BV) < V), other=0.)
121
+ b_gv = tl.load(p_gv, boundary_check=(0, 1))
122
+ b_v = (b_v * exp(b_gv_last[None, :] - b_gv)).to(b_v.dtype)
123
+
124
+ b_h = tl.dot(b_k, b_v)
125
+ if i_t < NT - 1:
126
+ p_h = tl.make_block_ptr(h + ((i_tg + 1) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
127
+ tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
128
+ elif STORE_FINAL_STATE:
129
+ 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))
130
+ tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
131
+
132
+
133
+ @triton.heuristics({
134
+ 'STORE_FINAL_STATE': lambda args: args['ht'] is not None,
135
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
136
+ })
137
+ @triton.autotune(
138
+ configs=[
139
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps, num_stages=num_stages)
140
+ for BK in [32, 64, 128]
141
+ for BV in [32, 64, 128]
142
+ for num_warps in [2, 4, 8, 16]
143
+ for num_stages in [2, 3]
144
+ ],
145
+ key=['BT', 'USE_G', 'USE_GK', 'USE_GV']
146
+ )
147
+ @triton.jit(do_not_specialize=['T'])
148
+ def chunk_fwd_kernel_h_reduction(
149
+ h,
150
+ g,
151
+ gk,
152
+ gv,
153
+ kvt,
154
+ ht,
155
+ cu_seqlens,
156
+ chunk_offsets,
157
+ T,
158
+ H: tl.constexpr,
159
+ K: tl.constexpr,
160
+ V: tl.constexpr,
161
+ BT: tl.constexpr,
162
+ BK: tl.constexpr,
163
+ BV: tl.constexpr,
164
+ USE_G: tl.constexpr,
165
+ USE_GK: tl.constexpr,
166
+ USE_GV: tl.constexpr,
167
+ STORE_FINAL_STATE: tl.constexpr,
168
+ IS_VARLEN: tl.constexpr
169
+ ):
170
+ i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
171
+ i_n, i_h = i_nh // H, i_nh % H
172
+ if IS_VARLEN:
173
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
174
+ T = eos - bos
175
+ NT = tl.cdiv(T, BT)
176
+ boh = tl.load(chunk_offsets + i_n).to(tl.int32)
177
+ else:
178
+ bos, eos = i_n * T, i_n * T + T
179
+ NT = tl.cdiv(T, BT)
180
+ boh = i_n * NT
181
+
182
+ # [BK, BV]
183
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
184
+ for i_t in range(NT):
185
+ p_h = tl.make_block_ptr(h + ((boh + i_t) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
186
+ b_h += tl.load(p_h, boundary_check=(0, 1)).to(tl.float32)
187
+ if i_t > 0:
188
+ tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
189
+
190
+ last_idx = min(i_t * BT + BT, T) - 1
191
+ # scalar decay
192
+ if USE_G:
193
+ b_g_last = tl.load(g + bos * H + last_idx * H + i_h)
194
+ b_h *= exp(b_g_last)
195
+
196
+ # vector decay, h = Diag(gk) @ h
197
+ if USE_GK:
198
+ p_gk_last = gk + (bos + last_idx) * H*K + i_h * K + i_k * BK + tl.arange(0, BK)
199
+
200
+ b_gk_last = tl.load(p_gk_last, mask=(i_k * BK + tl.arange(0, BK) < K), other=0.)
201
+ b_h *= exp(b_gk_last)[:, None]
202
+
203
+ # vector decay, h = h @ Diag(gv)
204
+ if USE_GV:
205
+ p_gv_last = gv + (bos + last_idx) * H*V + i_h * V + i_v * BV + tl.arange(0, BV)
206
+
207
+ b_gv_last = tl.load(p_gv_last, mask=(i_v * BV + tl.arange(0, BV) < V), other=0.)
208
+ b_h *= exp(b_gv_last)[None, :]
209
+
210
+ if STORE_FINAL_STATE:
211
+ p_kvt = tl.make_block_ptr(kvt + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
212
+ 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))
213
+ b_h += tl.load(p_kvt, boundary_check=(0, 1)).to(tl.float32)
214
+ tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
215
+
216
+
217
+ @triton.heuristics({
218
+ 'STORE_INITIAL_STATE_GRADIENT': lambda args: args['dh0'] is not None,
219
+ 'USE_FINAL_STATE_GRADIENT': lambda args: args['dht'] is not None,
220
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
221
+ })
222
+ @triton.autotune(
223
+ configs=[
224
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps, num_stages=num_stages)
225
+ for BK in [32, 64, 128]
226
+ for BV in [32, 64, 128]
227
+ for num_warps in [2, 4, 8]
228
+ for num_stages in [2, 3, 4]
229
+ ],
230
+ key=['BT', 'USE_G', 'USE_GK', 'USE_GV']
231
+ )
232
+ @triton.jit(do_not_specialize=['T'])
233
+ def chunk_bwd_kernel_dh_parallel(
234
+ q,
235
+ g,
236
+ gk,
237
+ gv,
238
+ do,
239
+ dh,
240
+ dht,
241
+ dh0,
242
+ cu_seqlens,
243
+ chunk_indices,
244
+ scale,
245
+ T,
246
+ HQ: tl.constexpr,
247
+ H: tl.constexpr,
248
+ K: tl.constexpr,
249
+ V: tl.constexpr,
250
+ BT: tl.constexpr,
251
+ BK: tl.constexpr,
252
+ BV: tl.constexpr,
253
+ NG: tl.constexpr,
254
+ USE_G: tl.constexpr,
255
+ USE_GK: tl.constexpr,
256
+ USE_GV: tl.constexpr,
257
+ STORE_INITIAL_STATE_GRADIENT: tl.constexpr,
258
+ USE_FINAL_STATE_GRADIENT: tl.constexpr,
259
+ IS_VARLEN: tl.constexpr
260
+ ):
261
+ i_kv, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
262
+
263
+ NV = tl.cdiv(V, BV)
264
+ i_k, i_v = i_kv // NV, i_kv % NV
265
+ i_b, i_hq = i_bh // HQ, i_bh % HQ
266
+ i_h = i_hq // NG
267
+ if IS_VARLEN:
268
+ i_tg = i_t
269
+ 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)
270
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
271
+ T = eos - bos
272
+ NT = tl.cdiv(T, BT)
273
+ else:
274
+ bos, eos = i_b * T, i_b * T + T
275
+ NT = tl.cdiv(T, BT)
276
+ i_n, i_tg = i_b, i_b * NT + i_t
277
+ i_nh = i_n * HQ + i_hq
278
+
279
+ 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))
280
+ 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))
281
+ p_dh = tl.make_block_ptr(dh + (i_tg * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
282
+
283
+ if i_t == NT - 1:
284
+ if USE_FINAL_STATE_GRADIENT:
285
+ 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))
286
+ b_dh = tl.load(p_dht, boundary_check=(0, 1)).to(tl.float32)
287
+ else:
288
+ b_dh = tl.zeros([BK, BV], dtype=tl.float32)
289
+ tl.store(p_dh, b_dh.to(p_dh.dtype.element_ty), boundary_check=(0, 1))
290
+
291
+ # [BK, BT]
292
+ b_q = tl.load(p_q, boundary_check=(0, 1))
293
+ b_q = (b_q * scale).to(b_q.dtype)
294
+ # [BT, BV]
295
+ b_do = tl.load(p_do, boundary_check=(0, 1))
296
+
297
+ if USE_G:
298
+ p_g = g + (bos + i_t * BT + tl.arange(0, BT)) * H + i_h
299
+ b_g = tl.load(p_g, mask=(i_t * BT + tl.arange(0, BT) < T), other=0.)
300
+ b_q = (b_q * exp(b_g)[None, :]).to(b_q.dtype)
301
+
302
+ if USE_GK:
303
+ 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))
304
+ b_gk = tl.load(p_gk, boundary_check=(0, 1))
305
+ b_q = (b_q * exp(b_gk)).to(b_q.dtype)
306
+
307
+ if USE_GV:
308
+ 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))
309
+ b_gv = tl.load(p_gv, boundary_check=(0, 1))
310
+ b_do = (b_do * exp(b_gv)).to(b_do.dtype)
311
+
312
+ b_dh = tl.dot(b_q, b_do)
313
+ if i_t > 0:
314
+ p_dh = tl.make_block_ptr(dh + ((i_tg - 1) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
315
+ tl.store(p_dh, b_dh.to(p_dh.dtype.element_ty), boundary_check=(0, 1))
316
+ elif STORE_INITIAL_STATE_GRADIENT:
317
+ 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))
318
+ tl.store(p_dh0, b_dh.to(p_dh0.dtype.element_ty), boundary_check=(0, 1))
319
+
320
+
321
+ @triton.heuristics({
322
+ 'STORE_INITIAL_STATE_GRADIENT': lambda args: args['dh0'] is not None,
323
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
324
+ })
325
+ @triton.autotune(
326
+ configs=[
327
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps, num_stages=num_stages)
328
+ for BK in [32, 64, 128]
329
+ for BV in [32, 64, 128]
330
+ for num_warps in [2, 4, 8, 16]
331
+ for num_stages in [2, 3]
332
+ ],
333
+ key=['BT', 'USE_G', 'USE_GK', 'USE_GV']
334
+ )
335
+ @triton.jit(do_not_specialize=['T'])
336
+ def chunk_bwd_kernel_dh_reduction(
337
+ g,
338
+ gk,
339
+ gv,
340
+ dh,
341
+ doq0,
342
+ dh0,
343
+ cu_seqlens,
344
+ chunk_offsets,
345
+ T,
346
+ HQ: tl.constexpr,
347
+ H: tl.constexpr,
348
+ K: tl.constexpr,
349
+ V: tl.constexpr,
350
+ BT: tl.constexpr,
351
+ BK: tl.constexpr,
352
+ BV: tl.constexpr,
353
+ NG: tl.constexpr,
354
+ USE_G: tl.constexpr,
355
+ USE_GK: tl.constexpr,
356
+ USE_GV: tl.constexpr,
357
+ STORE_INITIAL_STATE_GRADIENT: tl.constexpr,
358
+ IS_VARLEN: tl.constexpr
359
+ ):
360
+ i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
361
+ i_n, i_hq = i_nh // HQ, i_nh % HQ
362
+ i_h = i_hq // NG
363
+ if IS_VARLEN:
364
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
365
+ T = eos - bos
366
+ NT = tl.cdiv(T, BT)
367
+ boh = tl.load(chunk_offsets + i_n).to(tl.int32)
368
+ else:
369
+ bos, eos = i_n * T, i_n * T + T
370
+ NT = tl.cdiv(T, BT)
371
+ boh = i_n * NT
372
+
373
+ # [BK, BV]
374
+ b_dh = tl.zeros([BK, BV], dtype=tl.float32)
375
+ for i_t in range(NT - 1, -1, -1):
376
+ p_dh = tl.make_block_ptr(dh + ((boh+i_t) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
377
+ b_dh += tl.load(p_dh, boundary_check=(0, 1)).to(tl.float32)
378
+ if i_t < NT - 1:
379
+ tl.store(p_dh, b_dh.to(p_dh.dtype.element_ty), boundary_check=(0, 1))
380
+
381
+ last_idx = min(i_t * BT + BT, T) - 1
382
+ if USE_G:
383
+ b_g_last = tl.load(g + (bos + last_idx) * H + i_h)
384
+ b_dh *= exp(b_g_last)
385
+
386
+ if USE_GK:
387
+ p_gk_last = gk + (bos + last_idx) * H*K + i_h * K + i_k * BK + tl.arange(0, BK)
388
+ b_gk_last = tl.load(p_gk_last, mask=(i_k * BK + tl.arange(0, BK) < K), other=0.)
389
+ b_dh *= exp(b_gk_last)[:, None]
390
+
391
+ if USE_GV:
392
+ p_gv_last = gv + (bos + last_idx) * H*V + i_h * V + i_v * BV + tl.arange(0, BV)
393
+ b_gv_last = tl.load(p_gv_last, mask=(i_v * BV + tl.arange(0, BV) < V), other=0.)
394
+ b_dh *= exp(b_gv_last)[None, :]
395
+
396
+ if STORE_INITIAL_STATE_GRADIENT:
397
+ p_doq0 = tl.make_block_ptr(doq0 + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
398
+ 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))
399
+ b_dh += tl.load(p_doq0, boundary_check=(0, 1)).to(tl.float32)
400
+ tl.store(p_dh0, b_dh.to(p_dh0.dtype.element_ty), boundary_check=(0, 1))
401
+
402
+
403
+ def chunk_fwd_h(
404
+ k: torch.Tensor,
405
+ v: torch.Tensor,
406
+ g: torch.Tensor,
407
+ gk: torch.Tensor,
408
+ gv: torch.Tensor,
409
+ h0: torch.Tensor,
410
+ output_final_state: bool,
411
+ states_in_fp32: bool = False,
412
+ cu_seqlens: Optional[torch.Tensor] = None,
413
+ chunk_size: int = 64
414
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
415
+ B, T, H, K, V = *k.shape, v.shape[-1]
416
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
417
+
418
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
419
+ # N: the actual number of sequences in the batch with either equal or variable lengths
420
+ if cu_seqlens is None:
421
+ N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
422
+ else:
423
+ N, NT, chunk_offsets = len(cu_seqlens) - 1, len(chunk_indices), prepare_chunk_offsets(cu_seqlens, BT)
424
+
425
+ h = k.new_empty(B, NT, H, K, V, dtype=torch.float)
426
+ ht = k.new_empty(N, H, K, V, dtype=torch.float) if output_final_state else None
427
+ def grid(meta): return (triton.cdiv(K, meta['BK']) * triton.cdiv(V, meta['BV']), NT, B * H)
428
+ chunk_fwd_kernel_h_parallel[grid](
429
+ k=k,
430
+ v=v,
431
+ h=h,
432
+ g=g,
433
+ gk=gk,
434
+ gv=gv,
435
+ h0=h0,
436
+ ht=ht,
437
+ cu_seqlens=cu_seqlens,
438
+ chunk_indices=chunk_indices,
439
+ T=T,
440
+ H=H,
441
+ K=K,
442
+ V=V,
443
+ BT=BT,
444
+ USE_G=g is not None,
445
+ USE_GK=gk is not None,
446
+ USE_GV=gv is not None
447
+ )
448
+ kvt, ht = ht, (torch.empty_like(ht) if output_final_state else None)
449
+ def grid(meta): return (triton.cdiv(K, meta['BK']), triton.cdiv(V, meta['BV']), N * H)
450
+ chunk_fwd_kernel_h_reduction[grid](
451
+ h=h,
452
+ g=g,
453
+ gk=gk,
454
+ gv=gv,
455
+ kvt=kvt,
456
+ ht=ht,
457
+ cu_seqlens=cu_seqlens,
458
+ chunk_offsets=chunk_offsets,
459
+ T=T,
460
+ H=H,
461
+ K=K,
462
+ V=V,
463
+ BT=BT,
464
+ USE_G=g is not None,
465
+ USE_GK=gk is not None,
466
+ USE_GV=gv is not None
467
+ )
468
+ h = h.to(k.dtype) if not states_in_fp32 else h
469
+ return h, ht
470
+
471
+
472
+ def chunk_bwd_dh(
473
+ q: torch.Tensor,
474
+ k: torch.Tensor,
475
+ v: torch.Tensor,
476
+ g: torch.Tensor,
477
+ gk: torch.Tensor,
478
+ gv: torch.Tensor,
479
+ do: torch.Tensor,
480
+ h0: torch.Tensor,
481
+ dht: torch.Tensor,
482
+ scale: float,
483
+ states_in_fp32: bool = False,
484
+ cu_seqlens: Optional[torch.Tensor] = None,
485
+ chunk_size: int = 64
486
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
487
+ B, T, H, K, V = *k.shape, v.shape[-1]
488
+ HQ = q.shape[2]
489
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
490
+
491
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
492
+ # N: the actual number of sequences in the batch with either equal or variable lengths
493
+ # NG: number of groups in GQA
494
+ if cu_seqlens is None:
495
+ N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
496
+ else:
497
+ N, NT, chunk_offsets = len(cu_seqlens) - 1, len(chunk_indices), prepare_chunk_offsets(cu_seqlens, BT)
498
+ NG = HQ // H
499
+
500
+ dh = k.new_empty(B, NT, HQ, K, V, dtype=k.dtype if not states_in_fp32 else torch.float)
501
+ dh0 = torch.empty_like(h0, dtype=torch.float) if h0 is not None else None
502
+
503
+ def grid(meta): return (triton.cdiv(K, meta['BK']) * triton.cdiv(V, meta['BV']), NT, B * HQ)
504
+ chunk_bwd_kernel_dh_parallel[grid](
505
+ q=q,
506
+ g=g,
507
+ gk=gk,
508
+ gv=gv,
509
+ do=do,
510
+ dh=dh,
511
+ dht=dht,
512
+ dh0=dh0,
513
+ cu_seqlens=cu_seqlens,
514
+ chunk_indices=chunk_indices,
515
+ scale=scale,
516
+ T=T,
517
+ HQ=HQ,
518
+ H=H,
519
+ K=K,
520
+ V=V,
521
+ BT=BT,
522
+ NG=NG,
523
+ USE_G=g is not None,
524
+ USE_GK=gk is not None,
525
+ USE_GV=gv is not None
526
+ )
527
+
528
+ doq0, dh0 = dh0, (torch.empty_like(dh0) if dh0 is not None else None)
529
+ def grid(meta): return (triton.cdiv(K, meta['BK']), triton.cdiv(V, meta['BV']), N * HQ)
530
+ chunk_bwd_kernel_dh_reduction[grid](
531
+ g=g,
532
+ gk=gk,
533
+ gv=gv,
534
+ dh=dh,
535
+ doq0=doq0,
536
+ dh0=dh0,
537
+ cu_seqlens=cu_seqlens,
538
+ chunk_offsets=chunk_offsets,
539
+ T=T,
540
+ HQ=HQ,
541
+ H=H,
542
+ K=K,
543
+ V=V,
544
+ BT=BT,
545
+ NG=NG,
546
+ USE_G=g is not None,
547
+ USE_GK=gk is not None,
548
+ USE_GV=gv is not None
549
+ )
550
+ dh = dh.to(q.dtype) if not states_in_fp32 else dh
551
+ return dh, dh0