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/gla/chunk.py ADDED
@@ -0,0 +1,1298 @@
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.common.chunk_h import chunk_bwd_dh, chunk_fwd_h
11
+ from fla.ops.utils import prepare_chunk_indices
12
+ from fla.ops.utils.cumsum import chunk_local_cumsum
13
+ from fla.ops.utils.op import exp
14
+ from fla.utils import check_shared_mem, input_guard
15
+
16
+ BK_LIST = [32, 64] if check_shared_mem() else [16, 32]
17
+ BV_LIST = [64, 128] if check_shared_mem('ampere') else [16, 32]
18
+
19
+
20
+ @triton.heuristics({
21
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
22
+ })
23
+ @triton.autotune(
24
+ configs=[
25
+ triton.Config({'BK': BK}, num_warps=num_warps, num_stages=num_stages)
26
+ for BK in [32, 64]
27
+ for num_warps in [1, 2, 4, 8]
28
+ for num_stages in [2, 3, 4]
29
+ ],
30
+ key=["BC"]
31
+ )
32
+ @triton.jit(do_not_specialize=['T'])
33
+ def chunk_gla_fwd_A_kernel_intra_sub_inter(
34
+ q,
35
+ k,
36
+ g,
37
+ A,
38
+ cu_seqlens,
39
+ chunk_indices,
40
+ scale,
41
+ T,
42
+ H: tl.constexpr,
43
+ K: tl.constexpr,
44
+ BT: tl.constexpr,
45
+ BC: tl.constexpr,
46
+ BK: tl.constexpr,
47
+ NC: tl.constexpr,
48
+ IS_VARLEN: tl.constexpr,
49
+ ):
50
+ i_t, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
51
+ i_b, i_h = i_bh // H, i_bh % H
52
+ i_i, i_j = i_c // NC, i_c % NC
53
+ if IS_VARLEN:
54
+ 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)
55
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
56
+ T = eos - bos
57
+ else:
58
+ bos, eos = i_b * T, i_b * T + T
59
+
60
+ if i_t * BT + i_i * BC >= T:
61
+ return
62
+ if i_i <= i_j:
63
+ return
64
+
65
+ b_A = tl.zeros([BC, BC], dtype=tl.float32)
66
+ for i_k in range(tl.cdiv(K, BK)):
67
+ o_k = i_k * BK + tl.arange(0, BK)
68
+ m_k = o_k < K
69
+
70
+ p_q = tl.make_block_ptr(q + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
71
+ p_g = tl.make_block_ptr(g + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
72
+ p_k = tl.make_block_ptr(k + (bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT + i_j * BC), (BK, BC), (0, 1))
73
+ p_gk = tl.make_block_ptr(g + (bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT + i_j * BC), (BK, BC), (0, 1))
74
+ p_gn = g + (bos + i_t * BT + i_i * BC) * H*K + i_h * K + o_k
75
+
76
+ # [BK,]
77
+ b_gn = tl.load(p_gn, mask=m_k, other=0)
78
+ # [BC, BK]
79
+ b_q = tl.load(p_q, boundary_check=(0, 1))
80
+ b_g = tl.load(p_g, boundary_check=(0, 1))
81
+ b_qg = b_q * exp(b_g - b_gn[None, :]) * scale
82
+ # [BK, BC]
83
+ b_k = tl.load(p_k, boundary_check=(0, 1))
84
+ b_gk = tl.load(p_gk, boundary_check=(0, 1))
85
+ b_kg = b_k * exp(b_gn[:, None] - b_gk)
86
+ # [BC, BC] using tf32 to improve precision here.
87
+ b_A += tl.dot(b_qg, b_kg)
88
+
89
+ p_A = tl.make_block_ptr(A + (bos*H + i_h)*BT, (T, BT), (H*BT, 1), (i_t * BT + i_i * BC, i_j * BC), (BC, BC), (1, 0))
90
+ tl.store(p_A, b_A.to(A.dtype.element_ty), boundary_check=(0, 1))
91
+
92
+
93
+ @triton.heuristics({
94
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
95
+ })
96
+ @triton.autotune(
97
+ configs=[
98
+ triton.Config({}, num_warps=1),
99
+ triton.Config({}, num_warps=2),
100
+ triton.Config({}, num_warps=4),
101
+ triton.Config({}, num_warps=8),
102
+ ],
103
+ key=["BK", "BT"]
104
+ )
105
+ @triton.jit(do_not_specialize=['T'])
106
+ def chunk_gla_fwd_A_kernel_intra_sub_intra(
107
+ q,
108
+ k,
109
+ g,
110
+ A,
111
+ cu_seqlens,
112
+ chunk_indices,
113
+ scale,
114
+ T,
115
+ H: tl.constexpr,
116
+ K: tl.constexpr,
117
+ BT: tl.constexpr,
118
+ BC: tl.constexpr,
119
+ BK: tl.constexpr,
120
+ IS_VARLEN: tl.constexpr,
121
+ ):
122
+ i_t, i_i, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
123
+ i_b, i_h = i_bh // H, i_bh % H
124
+ i_j = i_i
125
+ if IS_VARLEN:
126
+ 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)
127
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
128
+ T = eos - bos
129
+ else:
130
+ bos, eos = i_b * T, i_b * T + T
131
+
132
+ if i_t * BT + i_i * BC >= T:
133
+ return
134
+
135
+ o_i = tl.arange(0, BC)
136
+ o_k = tl.arange(0, BK)
137
+ m_k = o_k < K
138
+ m_A = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
139
+ o_A = (bos + i_t * BT + i_i * BC + tl.arange(0, BC)) * H*BT + i_h * BT + i_j * BC
140
+ p_q = tl.make_block_ptr(q + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, 0), (BC, BK), (1, 0))
141
+ p_g = tl.make_block_ptr(g + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, 0), (BC, BK), (1, 0))
142
+ p_k = k + (bos + i_t * BT + i_j * BC) * H*K + i_h * K + o_k
143
+ p_gk = g + (bos + i_t * BT + i_j * BC) * H*K + i_h * K + o_k
144
+
145
+ b_q = tl.load(p_q, boundary_check=(0, 1))
146
+ b_g = tl.load(p_g, boundary_check=(0, 1))
147
+ for j in range(0, min(BC, T - i_t * BT - i_i * BC)):
148
+ b_k = tl.load(p_k, mask=m_k, other=0).to(tl.float32)
149
+ b_gk = tl.load(p_gk, mask=m_k, other=0).to(tl.float32)
150
+ b_A = tl.sum(b_q * b_k[None, :] * exp(b_g - b_gk[None, :]), 1)
151
+ b_A = tl.where(o_i >= j, b_A * scale, 0.)
152
+
153
+ tl.store(A + o_A + j, b_A, mask=m_A)
154
+ p_k += H*K
155
+ p_gk += H*K
156
+
157
+
158
+ @triton.heuristics({
159
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
160
+ })
161
+ @triton.autotune(
162
+ configs=[
163
+ triton.Config({}, num_warps=1),
164
+ triton.Config({}, num_warps=2),
165
+ triton.Config({}, num_warps=4),
166
+ triton.Config({}, num_warps=8),
167
+ ],
168
+ key=['BC', 'BK']
169
+ )
170
+ @triton.jit(do_not_specialize=['T'])
171
+ def chunk_gla_fwd_A_kernel_intra_sub_intra_split(
172
+ q,
173
+ k,
174
+ g,
175
+ A,
176
+ cu_seqlens,
177
+ chunk_indices,
178
+ scale,
179
+ T,
180
+ B: tl.constexpr,
181
+ H: tl.constexpr,
182
+ K: tl.constexpr,
183
+ BT: tl.constexpr,
184
+ BC: tl.constexpr,
185
+ BK: tl.constexpr,
186
+ NC: tl.constexpr,
187
+ IS_VARLEN: tl.constexpr,
188
+ ):
189
+ i_k, i_tc, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
190
+ i_b, i_h = i_bh // H, i_bh % H
191
+ i_t, i_i = i_tc // NC, i_tc % NC
192
+ i_j = i_i
193
+ if IS_VARLEN:
194
+ 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)
195
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
196
+ all = T
197
+ T = eos - bos
198
+ else:
199
+ bos, eos = i_b * T, i_b * T + T
200
+ all = B * T
201
+
202
+ if i_t * BT + i_i * BC >= T:
203
+ return
204
+
205
+ o_i = tl.arange(0, BC)
206
+ o_k = i_k * BK + tl.arange(0, BK)
207
+ m_k = o_k < K
208
+ m_A = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
209
+
210
+ o_A = (i_k * all + bos + i_t * BT + i_i * BC + tl.arange(0, BC)) * H*BC + i_h * BC
211
+ p_q = tl.make_block_ptr(q + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
212
+ p_g = tl.make_block_ptr(g + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
213
+ p_k = k + (bos + i_t * BT + i_j * BC) * H*K + i_h * K + o_k
214
+ p_gk = g + (bos + i_t * BT + i_j * BC) * H*K + i_h * K + o_k
215
+
216
+ b_q = tl.load(p_q, boundary_check=(0, 1))
217
+ b_g = tl.load(p_g, boundary_check=(0, 1))
218
+ for j in range(0, min(BC, T - i_t * BT - i_i * BC)):
219
+ b_A = tl.zeros([BC], dtype=tl.float32)
220
+ b_k = tl.load(p_k, mask=m_k, other=0).to(tl.float32)
221
+ b_gk = tl.load(p_gk, mask=m_k, other=0).to(tl.float32)
222
+ b_A += tl.sum(b_q * b_k[None, :] * exp(b_g - b_gk[None, :]), 1)
223
+ b_A = tl.where(o_i >= j, b_A * scale, 0.)
224
+ tl.store(A + o_A + j, b_A, mask=m_A)
225
+ p_k += H*K
226
+ p_gk += H*K
227
+
228
+
229
+ @triton.heuristics({
230
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
231
+ })
232
+ @triton.autotune(
233
+ configs=[
234
+ triton.Config({}, num_warps=1),
235
+ triton.Config({}, num_warps=2),
236
+ triton.Config({}, num_warps=4),
237
+ triton.Config({}, num_warps=8),
238
+ ],
239
+ key=['BC']
240
+ )
241
+ @triton.jit(do_not_specialize=['T'])
242
+ def chunk_gla_fwd_A_kernel_intra_sub_intra_merge(
243
+ A,
244
+ A2,
245
+ cu_seqlens,
246
+ chunk_indices,
247
+ T,
248
+ B: tl.constexpr,
249
+ H: tl.constexpr,
250
+ BT: tl.constexpr,
251
+ BC: tl.constexpr,
252
+ NK: tl.constexpr,
253
+ IS_VARLEN: tl.constexpr,
254
+ ):
255
+ i_t, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
256
+ i_b, i_h = i_bh // H, i_bh % H
257
+ if IS_VARLEN:
258
+ 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)
259
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
260
+ all = T
261
+ T = eos - bos
262
+ else:
263
+ bos, eos = i_b * T, i_b * T + T
264
+ all = B * T
265
+
266
+ if i_t * BT + i_c * BC >= T:
267
+ return
268
+
269
+ b_A = tl.zeros([BC, BC], dtype=tl.float32)
270
+ for i_k in range(0, NK):
271
+ p_A = tl.make_block_ptr(A + (i_k*all+bos)*H*BC+i_h*BC, (T, BC), (H*BC, 1), (i_t*BT + i_c*BC, 0), (BC, BC), (1, 0))
272
+ b_A += tl.load(p_A, boundary_check=(0, 1))
273
+ p_A2 = tl.make_block_ptr(A2 + (bos*H+i_h)*BT, (T, BT), (H*BT, 1), (i_t * BT + i_c * BC, i_c * BC), (BC, BC), (1, 0))
274
+ tl.store(p_A2, b_A.to(A2.dtype.element_ty), boundary_check=(0, 1))
275
+
276
+
277
+ @triton.heuristics({
278
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
279
+ })
280
+ @triton.autotune(
281
+ configs=[
282
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps)
283
+ for BK in [32, 64]
284
+ for BV in [64, 128]
285
+ for num_warps in [2, 4, 8]
286
+ ],
287
+ key=['BT'],
288
+ )
289
+ @triton.jit(do_not_specialize=['T'])
290
+ def chunk_gla_fwd_kernel_o(
291
+ q,
292
+ v,
293
+ g,
294
+ h,
295
+ o,
296
+ A,
297
+ cu_seqlens,
298
+ chunk_indices,
299
+ scale,
300
+ T,
301
+ H: tl.constexpr,
302
+ K: tl.constexpr,
303
+ V: tl.constexpr,
304
+ BT: tl.constexpr,
305
+ BK: tl.constexpr,
306
+ BV: tl.constexpr,
307
+ IS_VARLEN: tl.constexpr,
308
+ ):
309
+ i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
310
+ i_b, i_h = i_bh // H, i_bh % H
311
+ if IS_VARLEN:
312
+ i_tg = i_t
313
+ 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)
314
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
315
+ T = eos - bos
316
+ NT = tl.cdiv(T, BT)
317
+ else:
318
+ NT = tl.cdiv(T, BT)
319
+ i_tg = i_b * NT + i_t
320
+ bos, eos = i_b * T, i_b * T + T
321
+
322
+ m_s = tl.arange(0, BT)[:, None] >= tl.arange(0, BT)[None, :]
323
+
324
+ b_o = tl.zeros([BT, BV], dtype=tl.float32)
325
+ for i_k in range(tl.cdiv(K, BK)):
326
+ p_q = tl.make_block_ptr(q + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
327
+ p_g = tl.make_block_ptr(g + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
328
+ 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))
329
+
330
+ # [BT, BK]
331
+ b_q = tl.load(p_q, boundary_check=(0, 1))
332
+ b_q = (b_q * scale).to(b_q.dtype)
333
+ # [BT, BK]
334
+ b_g = tl.load(p_g, boundary_check=(0, 1))
335
+ # [BT, BK]
336
+ b_qg = (b_q * exp(b_g)).to(b_q.dtype)
337
+ # [BK, BV]
338
+ b_h = tl.load(p_h, boundary_check=(0, 1))
339
+ # works but dkw, owing to divine benevolence
340
+ # [BT, BV]
341
+ if i_k >= 0:
342
+ b_o += tl.dot(b_qg, b_h.to(b_qg.dtype))
343
+ 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))
344
+ p_o = tl.make_block_ptr(o + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
345
+ p_A = tl.make_block_ptr(A + (bos * H + i_h) * BT, (T, BT), (H*BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
346
+ # [BT, BV]
347
+ b_v = tl.load(p_v, boundary_check=(0, 1))
348
+ # [BT, BT]
349
+ b_A = tl.load(p_A, boundary_check=(0, 1))
350
+ b_A = tl.where(m_s, b_A, 0.).to(b_v.dtype)
351
+ b_o += tl.dot(b_A, b_v, allow_tf32=False)
352
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
353
+
354
+
355
+ @triton.heuristics({
356
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
357
+ })
358
+ @triton.autotune(
359
+ configs=[
360
+ triton.Config({}, num_warps=num_warps)
361
+ for num_warps in [1, 2, 4, 8]
362
+ ],
363
+ key=['BK', 'NC', 'BT'],
364
+ )
365
+ @triton.jit(do_not_specialize=['T'])
366
+ def chunk_gla_bwd_kernel_intra(
367
+ q,
368
+ k,
369
+ g,
370
+ dA,
371
+ dq,
372
+ dk,
373
+ cu_seqlens,
374
+ chunk_indices,
375
+ T,
376
+ H: tl.constexpr,
377
+ K: tl.constexpr,
378
+ BT: tl.constexpr,
379
+ BC: tl.constexpr,
380
+ BK: tl.constexpr,
381
+ NC: tl.constexpr,
382
+ IS_VARLEN: tl.constexpr,
383
+ ):
384
+ i_k, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
385
+ i_b, i_h = i_bh // H, i_bh % H
386
+ i_t, i_i = i_c // NC, i_c % NC
387
+ if IS_VARLEN:
388
+ 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)
389
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
390
+ else:
391
+ bos, eos = i_b * T, i_b * T + T
392
+ T = eos - bos
393
+ if i_t * BT + i_i * BC >= T:
394
+ return
395
+
396
+ o_k = i_k * BK + tl.arange(0, BK)
397
+ m_k = o_k < K
398
+
399
+ p_g = tl.make_block_ptr(g + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
400
+ # [BC, BK]
401
+ b_g = tl.load(p_g, boundary_check=(0, 1))
402
+ b_dq = tl.zeros([BC, BK], dtype=tl.float32)
403
+ if i_i > 0:
404
+ p_gn = g + (bos + i_t * BT + i_i * BC) * H*K + i_h*K + o_k
405
+
406
+ # [BK,]
407
+ b_gn = tl.load(p_gn, mask=m_k, other=0)
408
+ for i_j in range(0, i_i):
409
+ p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT+i_j*BC, i_k * BK), (BC, BK), (1, 0))
410
+ p_gk = tl.make_block_ptr(g+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT+i_j*BC, i_k * BK), (BC, BK), (1, 0))
411
+ p_dA = tl.make_block_ptr(dA+(bos*H+i_h)*BT, (T, BT), (H*BT, 1), (i_t*BT+i_i*BC, i_j * BC), (BC, BC), (1, 0))
412
+ # [BC, BK]
413
+ b_k = tl.load(p_k, boundary_check=(0, 1))
414
+ b_gk = tl.load(p_gk, boundary_check=(0, 1))
415
+ b_kg = (b_k * exp(b_gn[None, :] - b_gk))
416
+ # [BC, BC]
417
+ b_dA = tl.load(p_dA, boundary_check=(0, 1))
418
+ # [BC, BK]
419
+ b_dq += tl.dot(b_dA, b_kg)
420
+ b_dq *= exp(b_g - b_gn[None, :])
421
+
422
+ o_i = tl.arange(0, BC)
423
+ m_dA = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
424
+ o_dA = bos*H*BT + (i_t * BT + i_i * BC + tl.arange(0, BC)) * H*BT + i_h * BT + i_i * BC
425
+ p_kj = k + (bos + i_t * BT + i_i * BC) * H*K + i_h * K + o_k
426
+ p_gkj = g + (bos + i_t * BT + i_i * BC) * H*K + i_h * K + o_k
427
+ p_dq = tl.make_block_ptr(dq + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
428
+
429
+ for j in range(0, min(BC, T - i_t * BT - i_i * BC)):
430
+ # [BC,]
431
+ b_dA = tl.load(dA + o_dA + j, mask=m_dA, other=0)
432
+ # [BK,]
433
+ b_kj = tl.load(p_kj, mask=m_k, other=0).to(tl.float32)
434
+ b_gkj = tl.load(p_gkj, mask=m_k, other=0).to(tl.float32)
435
+ # [BC, BK]
436
+ m_i = o_i[:, None] >= j
437
+ # [BC, BK]
438
+ # (SY 09/17) important to not use bf16 here to have a good precision.
439
+ b_dq += tl.where(m_i, b_dA[:, None] * b_kj[None, :] * exp(b_g - b_gkj[None, :]), 0.)
440
+ p_kj += H*K
441
+ p_gkj += H*K
442
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
443
+
444
+ tl.debug_barrier()
445
+ # [BC, BK]
446
+ b_dk = tl.zeros([BC, BK], dtype=tl.float32)
447
+
448
+ NC = min(NC, tl.cdiv(T - i_t * BT, BC))
449
+ if i_i < NC - 1:
450
+ p_gn = g + (bos + min(i_t * BT + i_i * BC + BC, T) - 1) * H*K + i_h * K + o_k
451
+
452
+ # [BK,]
453
+ b_gn = tl.load(p_gn, mask=m_k, other=0)
454
+ for i_j in range(i_i + 1, NC):
455
+ p_q = tl.make_block_ptr(q + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT+i_j*BC, i_k*BK), (BC, BK), (1, 0))
456
+ p_gq = tl.make_block_ptr(g + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT+i_j*BC, i_k*BK), (BC, BK), (1, 0))
457
+ p_dA = tl.make_block_ptr(dA + (bos*H+i_h)*BT, (BT, T), (1, H*BT), (i_i*BC, i_t*BT + i_j*BC), (BC, BC), (0, 1))
458
+
459
+ o_j = i_t * BT + i_j * BC + o_i
460
+ m_j = o_j < T
461
+ # [BC, BK]
462
+ b_q = tl.load(p_q, boundary_check=(0, 1))
463
+ b_gq = tl.load(p_gq, boundary_check=(0, 1))
464
+ b_qg = b_q * tl.where(m_j[:, None], exp(b_gq - b_gn[None, :]), 0)
465
+ # [BC, BC]
466
+ b_dA = tl.load(p_dA, boundary_check=(0, 1))
467
+ # [BC, BK]
468
+ # (SY 09/17) important to not use bf16 here to have a good precision.
469
+ b_dk += tl.dot(b_dA, b_qg)
470
+ b_dk *= exp(b_gn[None, :] - b_g)
471
+ o_dA = bos*H*BT + (i_t * BT + i_i * BC) * H*BT + i_h * BT + i_i * BC + tl.arange(0, BC)
472
+ p_qj = q + (bos + i_t * BT + i_i * BC) * H*K + i_h * K + o_k
473
+ p_gqj = g + (bos + i_t * BT + i_i * BC) * H*K + i_h * K + o_k
474
+ p_dk = tl.make_block_ptr(dk + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
475
+ for j in range(0, min(BC, T - i_t * BT - i_i * BC)):
476
+ # [BC,]
477
+ b_dA = tl.load(dA + o_dA + j * H*BT)
478
+ # [BK,]
479
+ b_qj = tl.load(p_qj, mask=m_k, other=0).to(tl.float32)
480
+ b_gqj = tl.load(p_gqj, mask=m_k, other=0).to(tl.float32)
481
+ # [BC, BK]
482
+ m_i = o_i[:, None] <= j
483
+ b_dk += tl.where(m_i, b_dA[:, None] * b_qj[None, :] * exp(b_gqj[None, :] - b_g), 0.)
484
+ p_qj += H*K
485
+ p_gqj += H*K
486
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
487
+
488
+
489
+ @triton.heuristics({
490
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
491
+ })
492
+ @triton.autotune(
493
+ configs=[
494
+ triton.Config({}, num_warps=1),
495
+ triton.Config({}, num_warps=2),
496
+ triton.Config({}, num_warps=4),
497
+ triton.Config({}, num_warps=8),
498
+ ],
499
+ key=['BV', 'BT'],
500
+ )
501
+ @triton.jit(do_not_specialize=['T'])
502
+ def chunk_gla_bwd_kernel_dA(
503
+ v,
504
+ do,
505
+ dA,
506
+ cu_seqlens,
507
+ chunk_indices,
508
+ scale,
509
+ T,
510
+ H: tl.constexpr,
511
+ V: tl.constexpr,
512
+ BT: tl.constexpr,
513
+ BV: tl.constexpr,
514
+ IS_VARLEN: tl.constexpr,
515
+ ):
516
+ i_t, i_bh = tl.program_id(0), tl.program_id(1)
517
+ i_b, i_h = i_bh // H, i_bh % H
518
+ if IS_VARLEN:
519
+ 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)
520
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
521
+ else:
522
+ bos, eos = i_b * T, i_b * T + T
523
+ T = eos - bos
524
+
525
+ b_dA = tl.zeros([BT, BT], dtype=tl.float32)
526
+ for i_v in range(tl.cdiv(V, BV)):
527
+ p_do = tl.make_block_ptr(do + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
528
+ p_v = tl.make_block_ptr(v + (bos*H + i_h) * V, (V, T), (1, H*V), (i_v * BV, i_t * BT), (BV, BT), (0, 1))
529
+ b_v = tl.load(p_v, boundary_check=(0, 1))
530
+ b_do = tl.load(p_do, boundary_check=(0, 1))
531
+ b_dA += tl.dot(b_do, b_v)
532
+ p_dA = tl.make_block_ptr(dA + (bos * H + i_h) * BT, (T, BT), (H*BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
533
+ m_s = tl.arange(0, BT)[:, None] >= tl.arange(0, BT)[None, :]
534
+ b_dA = tl.where(m_s, b_dA * scale, 0.)
535
+ tl.store(p_dA, b_dA.to(p_dA.dtype.element_ty), boundary_check=(0, 1))
536
+
537
+
538
+ @triton.heuristics({
539
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
540
+ })
541
+ @triton.autotune(
542
+ configs=[
543
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps)
544
+ for BK in BK_LIST
545
+ for BV in BV_LIST
546
+ for num_warps in [2, 4, 8]
547
+ ],
548
+ key=['BT'],
549
+ )
550
+ @triton.jit(do_not_specialize=['T'])
551
+ def chunk_gla_bwd_kernel_dv(
552
+ k,
553
+ g,
554
+ A,
555
+ do,
556
+ dh,
557
+ dv,
558
+ cu_seqlens,
559
+ chunk_indices,
560
+ T,
561
+ H: tl.constexpr,
562
+ K: tl.constexpr,
563
+ V: tl.constexpr,
564
+ BT: tl.constexpr,
565
+ BK: tl.constexpr,
566
+ BV: tl.constexpr,
567
+ IS_VARLEN: tl.constexpr,
568
+ ):
569
+ i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
570
+ i_b, i_h = i_bh // H, i_bh % H
571
+ if IS_VARLEN:
572
+ i_tg = i_t
573
+ 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)
574
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
575
+ T = eos - bos
576
+ NT = tl.cdiv(T, BT)
577
+ else:
578
+ NT = tl.cdiv(T, BT)
579
+ i_tg = i_b * NT + i_t
580
+ bos, eos = i_b * T, i_b * T + T
581
+
582
+ p_A = tl.make_block_ptr(A + (bos * H + i_h) * BT, (BT, T), (1, H*BT), (0, i_t * BT), (BT, BT), (0, 1))
583
+ p_do = tl.make_block_ptr(do + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
584
+ p_dv = tl.make_block_ptr(dv + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
585
+
586
+ b_A = tl.load(p_A, boundary_check=(0, 1))
587
+ b_A = tl.where(tl.arange(0, BT)[:, None] <= tl.arange(0, BT)[None, :], b_A, 0.)
588
+ b_do = tl.load(p_do, boundary_check=(0, 1))
589
+ # (SY 09/17) important to disallow tf32 here to maintain a good precision.
590
+ b_dv = tl.dot(b_A, b_do.to(b_A.dtype), allow_tf32=False)
591
+
592
+ for i_k in range(tl.cdiv(K, BK)):
593
+ o_k = i_k * BK + tl.arange(0, BK)
594
+ m_k = o_k < K
595
+
596
+ 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))
597
+ p_gk = tl.make_block_ptr(g + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
598
+ p_gn = g + (bos + min(i_t * BT + BT, T) - 1)*H*K + i_h * K + o_k
599
+ 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))
600
+
601
+ b_k = tl.load(p_k, boundary_check=(0, 1))
602
+ b_gk = tl.load(p_gk, boundary_check=(0, 1))
603
+ b_gn = exp(tl.load(p_gn, mask=m_k, other=0)[None, :] - b_gk)
604
+ b_k = (b_k * b_gn).to(b_k.dtype)
605
+ b_dh = tl.load(p_dh, boundary_check=(0, 1))
606
+ # [BT, BV]
607
+ # (SY 09/17) it is ok to have bf16 interchunk gradient contribution here
608
+ b_dv += tl.dot(b_k, b_dh.to(b_k.dtype))
609
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
610
+
611
+
612
+ @triton.heuristics({
613
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
614
+ })
615
+ @triton.autotune(
616
+ configs=[
617
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps)
618
+ for BK in BK_LIST
619
+ for BV in BV_LIST
620
+ for num_warps in [2, 4, 8]
621
+ ],
622
+ key=['BT'],
623
+ )
624
+ @triton.jit(do_not_specialize=['T'])
625
+ def chunk_gla_bwd_kernel_inter(
626
+ q,
627
+ k,
628
+ v,
629
+ h,
630
+ g,
631
+ do,
632
+ dh,
633
+ dq,
634
+ dk,
635
+ dq2,
636
+ dk2,
637
+ dg,
638
+ cu_seqlens,
639
+ chunk_indices,
640
+ scale,
641
+ T,
642
+ H: tl.constexpr,
643
+ K: tl.constexpr,
644
+ V: tl.constexpr,
645
+ BT: tl.constexpr,
646
+ BK: tl.constexpr,
647
+ BV: tl.constexpr,
648
+ IS_VARLEN: tl.constexpr,
649
+ ):
650
+ i_k, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
651
+ i_b, i_h = i_bh // H, i_bh % H
652
+ if IS_VARLEN:
653
+ i_tg = i_t
654
+ 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)
655
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
656
+ T = eos - bos
657
+ NT = tl.cdiv(T, BT)
658
+ else:
659
+ NT = tl.cdiv(T, BT)
660
+ i_tg = i_b * NT + i_t
661
+ bos, eos = i_b * T, i_b * T + T
662
+ o_k = i_k * BK + tl.arange(0, BK)
663
+ m_k = o_k < K
664
+
665
+ p_gk = tl.make_block_ptr(g + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
666
+ p_gn = g + (bos + min(T, i_t * BT + BT)-1) * H*K + i_h * K + o_k
667
+ b_gn = tl.load(p_gn, mask=m_k, other=0)
668
+ b_dq = tl.zeros([BT, BK], dtype=tl.float32)
669
+ b_dk = tl.zeros([BT, BK], dtype=tl.float32)
670
+ b_dgk = tl.zeros([BK,], dtype=tl.float32)
671
+
672
+ for i_v in range(tl.cdiv(V, BV)):
673
+ 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))
674
+ p_do = tl.make_block_ptr(do + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
675
+ 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))
676
+ p_dh = tl.make_block_ptr(dh + (i_tg * H + i_h) * K*V, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
677
+ # [BT, BV]
678
+ b_v = tl.load(p_v, boundary_check=(0, 1))
679
+ b_do = tl.load(p_do, boundary_check=(0, 1))
680
+ # [BV, BK]
681
+ b_h = tl.load(p_h, boundary_check=(0, 1))
682
+ b_dh = tl.load(p_dh, boundary_check=(0, 1))
683
+ # [BK]
684
+ b_dgk += tl.sum(b_h * b_dh, axis=0)
685
+ # [BT, BK]
686
+ b_dq += tl.dot(b_do, b_h.to(b_do.dtype))
687
+ b_dk += tl.dot(b_v, b_dh.to(b_v.dtype))
688
+ b_dgk *= exp(b_gn)
689
+ b_dq *= scale
690
+ b_gk = tl.load(p_gk, boundary_check=(0, 1))
691
+ b_dq = b_dq * exp(b_gk)
692
+ b_dk = b_dk * exp(b_gn[None, :] - b_gk)
693
+
694
+ p_q = tl.make_block_ptr(q + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
695
+ 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))
696
+ p_dq = tl.make_block_ptr(dq + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
697
+ p_dk = tl.make_block_ptr(dk + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
698
+ b_q = tl.load(p_q, boundary_check=(0, 1))
699
+ b_k = tl.load(p_k, boundary_check=(0, 1))
700
+ b_dgk += tl.sum(b_dk * b_k, axis=0)
701
+ b_dq += tl.load(p_dq, boundary_check=(0, 1))
702
+ b_dk += tl.load(p_dk, boundary_check=(0, 1))
703
+ b_dg = b_q * b_dq - b_k * b_dk
704
+ # tl.debug_barrier()
705
+ b_dg = b_dg - tl.cumsum(b_dg, axis=0) + tl.sum(b_dg, axis=0)[None, :] + b_dgk[None, :]
706
+ # Buggy due to strange triton compiler issue.
707
+ # m_s = tl.where(tl.arange(0, BT)[:, None] <= tl.arange(0, BT)[None, :], 1., 0.)
708
+ # b_dg = tl.dot(m_s, b_dg, allow_tf32=False) + b_dgk[None, :]
709
+ p_dq = tl.make_block_ptr(dq2 + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
710
+ p_dk = tl.make_block_ptr(dk2 + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
711
+ p_dg = tl.make_block_ptr(dg + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
712
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
713
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
714
+ tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0, 1))
715
+
716
+
717
+ def chunk_gla_fwd_intra_gk(
718
+ q: torch.Tensor,
719
+ k: torch.Tensor,
720
+ g: torch.Tensor,
721
+ scale: float,
722
+ cu_seqlens: Optional[torch.LongTensor] = None,
723
+ chunk_size: int = 64
724
+ ):
725
+ B, T, H, K = k.shape
726
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
727
+
728
+ chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
729
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
730
+ BC = min(16, BT)
731
+ NC = triton.cdiv(BT, BC)
732
+
733
+ A = q.new_empty(B, T, H, BT, dtype=torch.float)
734
+ grid = (NT, NC * NC, B * H)
735
+ chunk_gla_fwd_A_kernel_intra_sub_inter[grid](
736
+ q,
737
+ k,
738
+ g,
739
+ A,
740
+ cu_seqlens,
741
+ chunk_indices,
742
+ scale,
743
+ T=T,
744
+ H=H,
745
+ K=K,
746
+ BT=BT,
747
+ BC=BC,
748
+ NC=NC,
749
+ )
750
+
751
+ grid = (NT, NC, B * H)
752
+ # load the entire [BC, K] blocks into SRAM at once
753
+ if K <= 256:
754
+ BK = max(triton.next_power_of_2(K), 16)
755
+ chunk_gla_fwd_A_kernel_intra_sub_intra[grid](
756
+ q,
757
+ k,
758
+ g,
759
+ A,
760
+ cu_seqlens,
761
+ chunk_indices,
762
+ scale,
763
+ T=T,
764
+ H=H,
765
+ K=K,
766
+ BT=BT,
767
+ BC=BC,
768
+ BK=BK,
769
+ )
770
+ # split then merge
771
+ else:
772
+ BK = min(128, triton.next_power_of_2(K))
773
+ NK = triton.cdiv(K, BK)
774
+ A_intra = q.new_empty(NK, B, T, H, BC, dtype=torch.float)
775
+
776
+ grid = (NK, NT * NC, B * H)
777
+ chunk_gla_fwd_A_kernel_intra_sub_intra_split[grid](
778
+ q,
779
+ k,
780
+ g,
781
+ A_intra,
782
+ cu_seqlens,
783
+ chunk_indices,
784
+ scale,
785
+ T=T,
786
+ B=B,
787
+ H=H,
788
+ K=K,
789
+ BT=BT,
790
+ BC=BC,
791
+ BK=BK,
792
+ NC=NC,
793
+ )
794
+
795
+ grid = (NT, NC, B * H)
796
+ chunk_gla_fwd_A_kernel_intra_sub_intra_merge[grid](
797
+ A_intra,
798
+ A,
799
+ cu_seqlens,
800
+ chunk_indices,
801
+ T=T,
802
+ B=B,
803
+ H=H,
804
+ BT=BT,
805
+ BC=BC,
806
+ NK=NK,
807
+ )
808
+ return A
809
+
810
+
811
+ def chunk_gla_fwd_o_gk(
812
+ q: torch.Tensor,
813
+ v: torch.Tensor,
814
+ g: torch.Tensor,
815
+ A: torch.Tensor,
816
+ h: torch.Tensor,
817
+ scale: float,
818
+ cu_seqlens: Optional[torch.LongTensor] = None,
819
+ chunk_size: int = 64
820
+ ):
821
+ B, T, H, K, V = *q.shape, v.shape[-1]
822
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
823
+
824
+ chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
825
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
826
+
827
+ o = torch.empty_like(v)
828
+ def grid(meta): return (triton.cdiv(V, meta['BV']), NT, B * H)
829
+ chunk_gla_fwd_kernel_o[grid](
830
+ q,
831
+ v,
832
+ g,
833
+ h,
834
+ o,
835
+ A,
836
+ cu_seqlens,
837
+ chunk_indices,
838
+ scale,
839
+ T=T,
840
+ H=H,
841
+ K=K,
842
+ V=V,
843
+ BT=BT,
844
+ )
845
+ return o
846
+
847
+
848
+ def chunk_gla_bwd_dA(
849
+ v: torch.Tensor,
850
+ do: torch.Tensor,
851
+ scale: float,
852
+ cu_seqlens: Optional[torch.LongTensor] = None,
853
+ chunk_size: int = 64
854
+ ):
855
+ B, T, H, V = v.shape
856
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
857
+
858
+ chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
859
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
860
+ BV = min(64, triton.next_power_of_2(V))
861
+
862
+ dA = v.new_empty(B, T, H, BT, dtype=torch.float)
863
+ grid = (NT, B * H)
864
+ chunk_gla_bwd_kernel_dA[grid](
865
+ v,
866
+ do,
867
+ dA,
868
+ cu_seqlens,
869
+ chunk_indices,
870
+ scale,
871
+ T=T,
872
+ H=H,
873
+ V=V,
874
+ BT=BT,
875
+ BV=BV,
876
+ )
877
+ return dA
878
+
879
+
880
+ def chunk_gla_bwd_dv(
881
+ k: torch.Tensor,
882
+ g: torch.Tensor,
883
+ A: torch.Tensor,
884
+ do: torch.Tensor,
885
+ dh: torch.Tensor,
886
+ cu_seqlens: Optional[torch.LongTensor] = None,
887
+ chunk_size: int = 64
888
+ ):
889
+ B, T, H, K, V = *k.shape, do.shape[-1]
890
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
891
+
892
+ chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
893
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
894
+
895
+ dv = torch.empty_like(do)
896
+ def grid(meta): return (triton.cdiv(V, meta['BV']), NT, B * H)
897
+ chunk_gla_bwd_kernel_dv[grid](
898
+ k,
899
+ g,
900
+ A,
901
+ do,
902
+ dh,
903
+ dv,
904
+ cu_seqlens,
905
+ chunk_indices,
906
+ T=T,
907
+ H=H,
908
+ K=K,
909
+ V=V,
910
+ BT=BT,
911
+ )
912
+ return dv
913
+
914
+
915
+ def chunk_gla_bwd_dqk_intra(
916
+ q: torch.Tensor,
917
+ k: torch.Tensor,
918
+ g: torch.Tensor,
919
+ dA: torch.Tensor,
920
+ cu_seqlens: Optional[torch.LongTensor] = None,
921
+ chunk_size: int = 64
922
+ ):
923
+ B, T, H, K = q.shape
924
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
925
+ BC = min(16, BT)
926
+ BK = min(64, triton.next_power_of_2(K))
927
+
928
+ chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
929
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
930
+ NC = triton.cdiv(BT, BC)
931
+ NK = triton.cdiv(K, BK)
932
+
933
+ dq = torch.empty_like(q, dtype=torch.float)
934
+ dk = torch.empty_like(k, dtype=torch.float)
935
+ grid = (NK, NT * NC, B * H)
936
+ chunk_gla_bwd_kernel_intra[grid](
937
+ q,
938
+ k,
939
+ g,
940
+ dA,
941
+ dq,
942
+ dk,
943
+ cu_seqlens,
944
+ chunk_indices,
945
+ T=T,
946
+ H=H,
947
+ K=K,
948
+ BT=BT,
949
+ BC=BC,
950
+ BK=BK,
951
+ NC=NC,
952
+ )
953
+ return dq, dk
954
+
955
+
956
+ def chunk_gla_bwd_dqkg(
957
+ q: torch.Tensor,
958
+ k: torch.Tensor,
959
+ v: torch.Tensor,
960
+ h: torch.Tensor,
961
+ g: torch.Tensor,
962
+ do: torch.Tensor,
963
+ dh: torch.Tensor,
964
+ dq: torch.Tensor,
965
+ dk: torch.Tensor,
966
+ scale: float,
967
+ cu_seqlens: Optional[torch.LongTensor] = None,
968
+ chunk_size: int = 64
969
+ ):
970
+ B, T, H, K, V = *k.shape, v.shape[-1]
971
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
972
+
973
+ chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
974
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
975
+
976
+ dg = torch.empty_like(g)
977
+ dq2 = torch.empty_like(dq)
978
+ dk2 = torch.empty_like(dk)
979
+ def grid(meta): return (triton.cdiv(K, meta['BK']), NT, B * H)
980
+ chunk_gla_bwd_kernel_inter[grid](
981
+ q,
982
+ k,
983
+ v,
984
+ h,
985
+ g,
986
+ do,
987
+ dh,
988
+ dq,
989
+ dk,
990
+ dq2,
991
+ dk2,
992
+ dg,
993
+ cu_seqlens,
994
+ chunk_indices,
995
+ scale,
996
+ T=T,
997
+ H=H,
998
+ K=K,
999
+ V=V,
1000
+ BT=BT,
1001
+ )
1002
+ return dq2, dk2, dg
1003
+
1004
+
1005
+ def chunk_gla_fwd(
1006
+ q: torch.Tensor,
1007
+ k: torch.Tensor,
1008
+ v: torch.Tensor,
1009
+ g: torch.Tensor,
1010
+ g_cumsum: Optional[torch.Tensor],
1011
+ scale: float,
1012
+ initial_state: torch.Tensor,
1013
+ output_final_state: bool,
1014
+ cu_seqlens: Optional[torch.LongTensor] = None,
1015
+ chunk_size: int = 64
1016
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
1017
+ T = q.shape[1]
1018
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
1019
+ if g_cumsum is None:
1020
+ g_cumsum = chunk_local_cumsum(g, BT, cu_seqlens=cu_seqlens)
1021
+
1022
+ h, ht = chunk_fwd_h(
1023
+ k=k,
1024
+ v=v,
1025
+ g=None,
1026
+ gk=g_cumsum,
1027
+ gv=None,
1028
+ h0=initial_state,
1029
+ output_final_state=output_final_state,
1030
+ states_in_fp32=False,
1031
+ cu_seqlens=cu_seqlens,
1032
+ chunk_size=BT
1033
+ )
1034
+
1035
+ # the intra A is kept in fp32
1036
+ # the computation has very marginal effect on the entire throughput
1037
+ A = chunk_gla_fwd_intra_gk(
1038
+ q=q,
1039
+ k=k,
1040
+ g=g_cumsum,
1041
+ scale=scale,
1042
+ cu_seqlens=cu_seqlens,
1043
+ chunk_size=BT
1044
+ )
1045
+ o = chunk_gla_fwd_o_gk(
1046
+ q=q,
1047
+ v=v,
1048
+ g=g_cumsum,
1049
+ A=A,
1050
+ h=h,
1051
+ scale=scale,
1052
+ cu_seqlens=cu_seqlens,
1053
+ chunk_size=BT
1054
+ )
1055
+ return g_cumsum, A, h, ht, o
1056
+
1057
+
1058
+ def chunk_gla_bwd(
1059
+ q: torch.Tensor,
1060
+ k: torch.Tensor,
1061
+ v: torch.Tensor,
1062
+ g: torch.Tensor,
1063
+ g_cumsum: Optional[torch.Tensor],
1064
+ scale: float,
1065
+ initial_state: torch.Tensor,
1066
+ h: torch.Tensor,
1067
+ A: torch.Tensor,
1068
+ do: torch.Tensor,
1069
+ dht: torch.Tensor,
1070
+ cu_seqlens: Optional[torch.LongTensor] = None,
1071
+ chunk_size: int = 64
1072
+ ):
1073
+ T = q.shape[1]
1074
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
1075
+ if g_cumsum is None:
1076
+ g_cumsum = chunk_local_cumsum(g, BT, cu_seqlens=cu_seqlens)
1077
+
1078
+ if h is None:
1079
+ h, _ = chunk_fwd_h(
1080
+ k=k,
1081
+ v=v,
1082
+ g=None,
1083
+ gk=g_cumsum,
1084
+ gv=None,
1085
+ h0=initial_state,
1086
+ output_final_state=False,
1087
+ cu_seqlens=cu_seqlens,
1088
+ chunk_size=BT,
1089
+ states_in_fp32=True
1090
+ )
1091
+ dh, dh0 = chunk_bwd_dh(
1092
+ q=q,
1093
+ k=k,
1094
+ v=v,
1095
+ g=None,
1096
+ gk=g_cumsum,
1097
+ gv=None,
1098
+ do=do,
1099
+ h0=initial_state,
1100
+ dht=dht,
1101
+ scale=scale,
1102
+ cu_seqlens=cu_seqlens,
1103
+ chunk_size=BT,
1104
+ states_in_fp32=True
1105
+ )
1106
+
1107
+ dv = chunk_gla_bwd_dv(
1108
+ k=k,
1109
+ g=g_cumsum,
1110
+ A=A,
1111
+ do=do,
1112
+ dh=dh,
1113
+ cu_seqlens=cu_seqlens,
1114
+ chunk_size=BT
1115
+ )
1116
+
1117
+ # dq dk in fp32
1118
+ dA = chunk_gla_bwd_dA(
1119
+ v=v,
1120
+ do=do,
1121
+ scale=scale,
1122
+ cu_seqlens=cu_seqlens,
1123
+ chunk_size=BT
1124
+ )
1125
+ dq, dk = chunk_gla_bwd_dqk_intra(
1126
+ q=q,
1127
+ k=k,
1128
+ g=g_cumsum,
1129
+ dA=dA,
1130
+ cu_seqlens=cu_seqlens,
1131
+ chunk_size=BT
1132
+ )
1133
+ dq, dk, dg = chunk_gla_bwd_dqkg(
1134
+ q=q,
1135
+ k=k,
1136
+ v=v,
1137
+ h=h,
1138
+ g=g_cumsum,
1139
+ do=do,
1140
+ dh=dh,
1141
+ dq=dq,
1142
+ dk=dk,
1143
+ scale=scale,
1144
+ cu_seqlens=cu_seqlens,
1145
+ chunk_size=BT
1146
+ )
1147
+ return dq, dk, dv, dg, dh0
1148
+
1149
+
1150
+ class ChunkGLAFunction(torch.autograd.Function):
1151
+
1152
+ @staticmethod
1153
+ @input_guard
1154
+ def forward(
1155
+ ctx,
1156
+ q,
1157
+ k,
1158
+ v,
1159
+ g,
1160
+ scale,
1161
+ initial_state,
1162
+ output_final_state,
1163
+ cu_seqlens,
1164
+ ):
1165
+ T = q.shape[1]
1166
+ chunk_size = min(64, max(16, triton.next_power_of_2(T)))
1167
+
1168
+ g_cumsum, A, h, ht, o = chunk_gla_fwd(
1169
+ q=q,
1170
+ k=k,
1171
+ v=v,
1172
+ g=g,
1173
+ g_cumsum=None,
1174
+ scale=scale,
1175
+ initial_state=initial_state,
1176
+ output_final_state=output_final_state,
1177
+ cu_seqlens=cu_seqlens,
1178
+ chunk_size=chunk_size
1179
+ )
1180
+ # recompute g_cumsum in bwd pass
1181
+ if g.dtype != torch.float:
1182
+ g_cumsum = None
1183
+ else:
1184
+ g = None
1185
+ ctx.save_for_backward(q, k, v, g, g_cumsum, initial_state, A)
1186
+ ctx.chunk_size = chunk_size
1187
+ ctx.scale = scale
1188
+ ctx.cu_seqlens = cu_seqlens
1189
+ return o, ht
1190
+
1191
+ @staticmethod
1192
+ @input_guard
1193
+ def backward(ctx, do, dht):
1194
+ q, k, v, g, g_cumsum, initial_state, A = ctx.saved_tensors
1195
+ chunk_size, scale, cu_seqlens = ctx.chunk_size, ctx.scale, ctx.cu_seqlens
1196
+ dq, dk, dv, dg, dh0 = chunk_gla_bwd(
1197
+ q=q,
1198
+ k=k,
1199
+ v=v,
1200
+ g=g,
1201
+ g_cumsum=g_cumsum,
1202
+ scale=scale,
1203
+ h=None,
1204
+ A=A,
1205
+ initial_state=initial_state,
1206
+ do=do,
1207
+ dht=dht,
1208
+ cu_seqlens=cu_seqlens,
1209
+ chunk_size=chunk_size
1210
+ )
1211
+ return dq.to(q), dk.to(k), dv.to(v), dg, None, dh0, None, None
1212
+
1213
+
1214
+ @torch.compiler.disable
1215
+ def chunk_gla(
1216
+ q: torch.Tensor,
1217
+ k: torch.Tensor,
1218
+ v: torch.Tensor,
1219
+ g: torch.Tensor,
1220
+ scale: Optional[int] = None,
1221
+ initial_state: torch.Tensor = None,
1222
+ output_final_state: bool = False,
1223
+ cu_seqlens: Optional[torch.LongTensor] = None,
1224
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
1225
+ r"""
1226
+ Args:
1227
+ q (torch.Tensor):
1228
+ queries of shape `[B, T, H, K]`.
1229
+ k (torch.Tensor):
1230
+ keys of shape `[B, T, H, K]`.
1231
+ v (torch.Tensor):
1232
+ values of shape `[B, T, H, V]`.
1233
+ g (torch.Tensor):
1234
+ Forget gates of shape `[B, T, H, K]`.
1235
+ scale (Optional[float]):
1236
+ Scale factor for the attention scores.
1237
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
1238
+ initial_state (Optional[torch.Tensor]):
1239
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
1240
+ For equal-length input sequences, `N` equals the batch size `B`.
1241
+ Default: `None`.
1242
+ output_final_state (Optional[bool]):
1243
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
1244
+ cu_seqlens (torch.LongTensor):
1245
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
1246
+ consistent with the FlashAttention API.
1247
+
1248
+ Returns:
1249
+ o (torch.Tensor):
1250
+ Outputs of shape `[B, T, H, V]`.
1251
+ final_state (torch.Tensor):
1252
+ Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
1253
+
1254
+ Examples::
1255
+ >>> import torch
1256
+ >>> import torch.nn.functional as F
1257
+ >>> from einops import rearrange
1258
+ >>> from fla.ops.gla import chunk_gla
1259
+ # inputs with equal lengths
1260
+ >>> B, T, H, K, V = 4, 2048, 4, 512, 512
1261
+ >>> q = torch.randn(B, T, H, K, device='cuda')
1262
+ >>> k = torch.randn(B, T, H, K, device='cuda')
1263
+ >>> v = torch.randn(B, T, H, V, device='cuda')
1264
+ >>> g = F.logsigmoid(torch.randn(B, T, H, K, device='cuda'))
1265
+ >>> h0 = torch.randn(B, H, K, V, device='cuda')
1266
+ >>> o, ht = chunk_gla(
1267
+ q, k, v, g,
1268
+ initial_state=h0,
1269
+ output_final_state=True
1270
+ )
1271
+ # for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
1272
+ >>> q, k, v, g = map(lambda x: rearrange(x, 'b t h d -> 1 (b t) h d'), (q, k, v, g))
1273
+ # for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
1274
+ >>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
1275
+ >>> o_var, ht_var = chunk_gla(
1276
+ q, k, v, g,
1277
+ initial_state=h0,
1278
+ output_final_state=True,
1279
+ cu_seqlens=cu_seqlens
1280
+ )
1281
+ >>> assert o.allclose(o_var.view(o.shape))
1282
+ >>> assert ht.allclose(ht_var)
1283
+ """
1284
+ if cu_seqlens is not None:
1285
+ if q.shape[0] != 1:
1286
+ raise ValueError(
1287
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
1288
+ f"Please flatten variable-length inputs before processing."
1289
+ )
1290
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
1291
+ raise ValueError(
1292
+ f"The number of initial states is expected to be equal to the number of input sequences, "
1293
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
1294
+ )
1295
+ if scale is None:
1296
+ scale = q.shape[-1] ** -0.5
1297
+ o, final_state = ChunkGLAFunction.apply(q, k, v, g, scale, initial_state, output_final_state, cu_seqlens)
1298
+ return o, final_state