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,642 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ import warnings
5
+ from typing import Tuple
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ import triton
10
+ import triton.language as tl
11
+ from einops import rearrange
12
+ from packaging import version
13
+
14
+ from fla.ops.utils import chunk_local_cumsum
15
+ from fla.ops.utils.op import exp, safe_exp
16
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
17
+
18
+
19
+ @triton.jit(do_not_specialize=['T'])
20
+ def prepare_qg_kg(
21
+ q,
22
+ k,
23
+ g,
24
+ qg,
25
+ kg,
26
+ scale,
27
+ T,
28
+ K: tl.constexpr,
29
+ BT: tl.constexpr,
30
+ BK: tl.constexpr
31
+ ):
32
+ i_k, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
33
+ p_q = q + i_bh * T*K + i_c * BT * K + i_k * BK + tl.arange(0, BK)
34
+ p_g = g + i_bh * T*K + i_c * BT * K + i_k * BK + tl.arange(0, BK)
35
+ p_k = k + i_bh * T*K + i_c * BT * K + i_k * BK + tl.arange(0, BK)
36
+ p_qg = qg + i_bh * T*K + i_c * BT * K + i_k * BK + tl.arange(0, BK)
37
+ p_kg = kg + i_bh * T*K + i_c * BT * K + i_k * BK + tl.arange(0, BK)
38
+
39
+ mask = (i_k * BK + tl.arange(0, BK)) < K
40
+
41
+ last_decay = tl.load(g + i_bh * T*K + (i_c * BT + BT - 1) * K + i_k * BK + tl.arange(0, BK))
42
+
43
+ for _ in range(BT):
44
+ b_q = tl.load(p_q, mask=mask, other=0)
45
+ b_k = tl.load(p_k, mask=mask, other=0)
46
+ b_g = tl.load(p_g, mask=mask, other=0).to(tl.float32)
47
+ b_q *= exp(b_g) * scale
48
+ b_k *= exp(last_decay - b_g)
49
+ tl.store(p_kg, b_k.to(p_kg.dtype.element_ty), mask=mask)
50
+ tl.store(p_qg, b_q.to(p_qg.dtype.element_ty), mask=mask)
51
+ p_q += K
52
+ p_g += K
53
+ p_k += K
54
+ p_kg += K
55
+ p_qg += K
56
+
57
+
58
+ @triton.jit(do_not_specialize=['T'])
59
+ def bwd_decay_global_cumsum(
60
+ dq_inner,
61
+ dq_inter,
62
+ dk_inner,
63
+ dk_inter,
64
+ q,
65
+ k,
66
+ g,
67
+ dg,
68
+ T,
69
+ K: tl.constexpr,
70
+ BT: tl.constexpr,
71
+ BK: tl.constexpr
72
+ ):
73
+ i_k, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
74
+ p_q = q + i_bh * T*K + i_k * BK + tl.arange(0, BK) + (i_c * BT + BT - 1) * K
75
+ p_k = k + i_bh * T*K + i_k * BK + tl.arange(0, BK) + (i_c * BT + BT - 1) * K
76
+ p_g = g + i_bh * T*K + i_k * BK + tl.arange(0, BK) + (i_c * BT + BT - 1) * K
77
+ p_dg = dg + i_bh * T*K + i_k * BK + tl.arange(0, BK) + (i_c * BT + BT - 1) * K
78
+ p_dq_inner = dq_inner + i_bh * T*K + i_k * BK + tl.arange(0, BK) + (i_c * BT + BT - 1) * K
79
+ p_dk_inner = dk_inner + i_bh * T*K + i_k * BK + tl.arange(0, BK) + (i_c * BT + BT - 1) * K
80
+ p_dq_inter = dq_inter + i_bh * T*K + i_k * BK + tl.arange(0, BK) + (i_c * BT + BT - 1) * K
81
+ p_dk_inter = dk_inter + i_bh * T*K + i_k * BK + tl.arange(0, BK) + (i_c * BT + BT - 1) * K
82
+ cum_grad_dg = tl.zeros([BK], dtype=tl.float32)
83
+ mask = (i_k * BK + tl.arange(0, BK)) < K
84
+ last_g = tl.zeros([BK], dtype=tl.float32)
85
+ for j in range(BT-1, -1, -1):
86
+ b_g = tl.load(p_g, mask=mask, other=0).to(tl.float32)
87
+ if j == (BT-1):
88
+ last_g = b_g
89
+ b_dq1 = tl.load(p_dq_inner, mask=mask, other=0)
90
+ b_dq2 = tl.load(p_dq_inter, mask=mask, other=0)
91
+ b_dq2 *= exp(b_g)
92
+ b_dq = b_dq1 + b_dq2
93
+ tl.store(p_dq_inter, b_dq, mask=mask)
94
+ b_dk1 = tl.load(p_dk_inner, mask=mask, other=0)
95
+ b_dk2 = tl.load(p_dk_inter, mask=mask, other=0)
96
+ b_dk2 *= safe_exp(last_g - b_g)
97
+ b_dk = b_dk1 + b_dk2
98
+ tl.store(p_dk_inter, b_dk, mask=mask)
99
+ b_q = tl.load(p_q, mask=mask, other=0)
100
+ b_k = tl.load(p_k, mask=mask, other=0)
101
+ b_dg = b_dq * b_q - b_dk * b_k
102
+ cum_grad_dg += b_dg
103
+ tl.store(p_dg, cum_grad_dg.to(p_dg.dtype.element_ty), mask=mask)
104
+ p_g -= K
105
+ p_k -= K
106
+ p_q -= K
107
+ p_dq_inner -= K
108
+ p_dk_inner -= K
109
+ p_dq_inter -= K
110
+ p_dk_inter -= K
111
+ p_dg -= K
112
+
113
+
114
+ @triton.jit(do_not_specialize=['T'])
115
+ def fused_chunk_gla_fwd_kernel(
116
+ q,
117
+ k,
118
+ v,
119
+ g,
120
+ o,
121
+ h0,
122
+ ht,
123
+ T,
124
+ B: tl.constexpr,
125
+ H: tl.constexpr,
126
+ K: tl.constexpr,
127
+ V: tl.constexpr,
128
+ BT: tl.constexpr,
129
+ BK: tl.constexpr,
130
+ BV: tl.constexpr,
131
+ USE_INITIAL_STATE: tl.constexpr,
132
+ STORE_FINAL_STATE: tl.constexpr,
133
+ CHECK: tl.constexpr
134
+ ):
135
+ i_v, i_k, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
136
+
137
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
138
+
139
+ # make block pointers
140
+ p_q = tl.make_block_ptr(q + i_bh * T*K, (T, K), (K, 1), (0, i_k * BK), (BT, BK), (1, 0))
141
+ p_gn = g + i_bh * T*K + (BT - 1) * K + i_k * BK + tl.arange(0, BK)
142
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (K, T), (1, K), (i_k * BK, 0), (BK, BT), (0, 1))
143
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (0, i_v * BV), (BT, BV), (1, 0))
144
+ p_o = tl.make_block_ptr(o + (i_bh + i_k * B * H) * T*V, (T, V), (V, 1), (0, i_v * BV), (BT, BV), (1, 0))
145
+
146
+ if USE_INITIAL_STATE:
147
+ p_h = tl.make_block_ptr(h0 + i_bh * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
148
+ b_h += tl.load(p_h, boundary_check=(0, 1)).to(tl.float32)
149
+
150
+ mask = (i_k * BK + tl.arange(0, BK)) < K
151
+
152
+ for i in range(0, tl.cdiv(T, BT)):
153
+ # [BK, BT]
154
+ b_k = tl.load(p_k, boundary_check=(0, 1))
155
+ # [BT, BV]
156
+ b_v = tl.load(p_v, boundary_check=(0, 1))
157
+ # [BT, BK]
158
+ b_q = tl.load(p_q, boundary_check=(0, 1))
159
+ b_gn = tl.load(p_gn, mask=mask, other=0).to(tl.float32)
160
+ if CHECK and i == 0:
161
+ b_o = tl.dot(b_q.to(b_v.dtype), b_h.to(b_v.dtype), allow_tf32=False)
162
+ b_h = b_h * exp(b_gn)[:, None] + tl.dot(b_k.to(b_v.dtype), b_v, allow_tf32=False)
163
+ else:
164
+ b_o = tl.dot(b_q.to(b_v.dtype), b_h.to(b_v.dtype), allow_tf32=False)
165
+ b_h = b_h * exp(b_gn)[:, None] + tl.dot(b_k.to(b_v.dtype), b_v, allow_tf32=False)
166
+
167
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
168
+ p_q = tl.advance(p_q, (BT, 0))
169
+ p_k = tl.advance(p_k, (0, BT))
170
+ p_v = tl.advance(p_v, (BT, 0))
171
+ p_o = tl.advance(p_o, (BT, 0))
172
+ p_gn += BT * K
173
+
174
+ if STORE_FINAL_STATE:
175
+ p_final = tl.make_block_ptr(ht + i_bh * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
176
+ tl.store(p_final, b_h.to(p_final.dtype.element_ty), boundary_check=(0, 1))
177
+
178
+
179
+ # Similar to Algorithm1 of https://arxiv.org/abs/2006.16236
180
+ @triton.jit(do_not_specialize=['T'])
181
+ def fused_chunk_gla_bwd_kernel(
182
+ q, k, v, g,
183
+ do,
184
+ dq,
185
+ dk,
186
+ dv,
187
+ h0,
188
+ scale,
189
+ T,
190
+ B: tl.constexpr,
191
+ H: tl.constexpr,
192
+ K: tl.constexpr,
193
+ V: tl.constexpr,
194
+ # clamp_min, # minimum log value of the gate for numerical stability. default: -5
195
+ BT: tl.constexpr,
196
+ BK: tl.constexpr,
197
+ BV: tl.constexpr,
198
+ USE_INITIAL_STATE: tl.constexpr,
199
+ CHECK: tl.constexpr
200
+ ):
201
+ i_v, i_k, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
202
+ # [BV, BK]
203
+ b_h = tl.zeros([BV, BK], dtype=tl.float32)
204
+
205
+ if USE_INITIAL_STATE:
206
+ p_h = tl.make_block_ptr(h0 + i_bh * K * V, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
207
+ b_h += tl.load(p_h, boundary_check=(0, 1)).to(tl.float32)
208
+
209
+ mask = (i_k * BK + tl.arange(0, BK)) < K
210
+ for i in range(0, tl.cdiv(T, BT)):
211
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (i * BT, i_k * BK), (BT, BK), (1, 0))
212
+ p_gn = g + i_bh * T*K + ((i+1) * BT - 1) * K + i_k * BK + tl.arange(0, BK)
213
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (V, T), (1, V), (i_v * BV, i * BT), (BV, BT), (0, 1))
214
+ p_do = tl.make_block_ptr(do + i_bh * T*V, (T, V), (V, 1), (i * BT, i_v * BV), (BT, BV), (1, 0))
215
+ p_dq = tl.make_block_ptr(dq + (i_bh+i_v*B*H)*T*K, (T, K), (K, 1), (i * BT, i_k * BK), (BT, BK), (1, 0))
216
+ b_dq = tl.zeros([BT, BK], dtype=tl.float32)
217
+ # [BT, K]
218
+ b_k = tl.load(p_k, boundary_check=(0, 1))
219
+ b_gn = tl.load(p_gn, mask=mask, other=0).to(tl.float32)
220
+
221
+ # [V, BT]
222
+ b_v = tl.load(p_v, boundary_check=(0, 1))
223
+ # [BT, V]
224
+ b_do = tl.load(p_do, boundary_check=(0, 1))
225
+ # [V, K]
226
+ if CHECK and i == 0:
227
+ b_dq += tl.dot(b_do, b_h.to(b_do.dtype), allow_tf32=False)
228
+ b_h = b_h * exp(b_gn)[None, :] + tl.dot(b_v, b_k.to(b_v.dtype), allow_tf32=False)
229
+ else:
230
+ b_dq += tl.dot(b_do, b_h.to(b_do.dtype), allow_tf32=False)
231
+ b_h = b_h * exp(b_gn)[None, :] + tl.dot(b_v, b_k.to(b_v.dtype), allow_tf32=False)
232
+ b_dq *= scale
233
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
234
+
235
+ # sync threads
236
+ b_h = None
237
+ tl.debug_barrier()
238
+ # [BK, BV]
239
+ b_dh = tl.zeros([BK, BV], dtype=tl.float32)
240
+
241
+ # cum = tl.zeros([BK], dtype=tl.float32)
242
+ for i in range(1, tl.cdiv(T, BT) + 1):
243
+ p_q = tl.make_block_ptr(q + i_bh * T*K, (K, T), (1, K), (i_k * BK, T - i * BT), (BK, BT), (0, 1))
244
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (T - i * BT, i_k * BK), (BT, BK), (1, 0))
245
+ p_gn = g + i_bh * T*K + (T - (i-1) * BT - 1) * K + i_k * BK + tl.arange(0, BK)
246
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (T - i * BT, i_v * BV), (BT, BV), (1, 0))
247
+ p_do = tl.make_block_ptr(do + i_bh * T*V, (T, V), (V, 1), (T - i * BT, i_v * BV), (BT, BV), (1, 0))
248
+ p_dk = tl.make_block_ptr(dk + (i_bh + i_v * B * H) * T*K, (T, K),
249
+ (K, 1), (T - i * BT, i_k * BK), (BT, BK), (1, 0))
250
+ p_dv = tl.make_block_ptr(dv + (i_bh + i_k * B * H) * T*V, (T, V),
251
+ (V, 1), (T - i * BT, i_v * BV), (BT, BV), (1, 0))
252
+ # [K, BT]
253
+ b_q = tl.load(p_q, boundary_check=(0, 1))
254
+ # [BT, K]
255
+ b_k = tl.load(p_k, boundary_check=(0, 1))
256
+ # [BT, V]
257
+ b_v = tl.load(p_v, boundary_check=(0, 1))
258
+ b_do = tl.load(p_do, boundary_check=(0, 1))
259
+ b_db = tl.load(p_gn, mask=mask, other=0).to(tl.float32)
260
+
261
+ # inter-chunk
262
+ # [K, V]
263
+ if CHECK and i == 1:
264
+ b_dk = tl.trans(tl.dot(b_dh.to(b_v.dtype), tl.trans(b_v), allow_tf32=False))
265
+ b_dv = tl.dot((b_k).to(b_v.dtype), b_dh.to(b_v.dtype), allow_tf32=False)
266
+ b_dh = b_dh * exp(b_db)[:, None] + tl.dot(b_q.to(b_do.dtype), b_do, allow_tf32=False)
267
+ else:
268
+ b_dk = tl.trans(tl.dot(b_dh.to(b_v.dtype), tl.trans(b_v), allow_tf32=False))
269
+ b_dv = tl.dot((b_k).to(b_v.dtype), b_dh.to(b_v.dtype), allow_tf32=False)
270
+ b_dh = b_dh * exp(b_db)[:, None] + tl.dot(b_q.to(b_do.dtype), b_do, allow_tf32=False)
271
+
272
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
273
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
274
+
275
+
276
+ @triton.jit
277
+ def fwd_inner_chunk(
278
+ q, k, g, A,
279
+ scale, # K ** -0.5
280
+ B: tl.constexpr, # B
281
+ H: tl.constexpr, # H
282
+ T, # T
283
+ K: tl.constexpr, # K
284
+ BT: tl.constexpr, # BLOCK SIZE along the sequence dimension, a.k.a. chunk size
285
+ BK: tl.constexpr # BLOCK SIZE along the K dimension
286
+ ):
287
+
288
+ i_k, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
289
+
290
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
291
+ p_g = tl.make_block_ptr(g + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
292
+
293
+ b_k = tl.load(p_k, boundary_check=(0, 1))
294
+ b_g = tl.load(p_g, boundary_check=(0, 1)).to(tl.float32)
295
+
296
+ mask = (i_k * BK + tl.arange(0, BK)) < K
297
+ o_i = tl.arange(0, BT)
298
+
299
+ p_q = q + i_bh * T*K + i_k * BK + i_t * BT * K + tl.arange(0, BK)
300
+ p_gq = g + i_bh * T*K + i_k * BK + i_t * BT * K + tl.arange(0, BK)
301
+ p_A = A + (i_bh + (i_k * B * H)) * (tl.cdiv(T, BT) * BT * BT) + i_t * BT * BT + tl.arange(0, BT)
302
+
303
+ for i in range(BT):
304
+ b_q = tl.load(p_q, mask=mask, other=0) * scale
305
+ b_gq = tl.load(p_gq, mask=mask, other=0).to(tl.float32)
306
+ s = b_q[None, :] * b_k * safe_exp(b_gq[None, :] - b_g)
307
+ score = tl.sum(s, axis=1)
308
+ score = tl.where(o_i <= i, score, 0)
309
+ tl.store(p_A, score.to(p_A.dtype.element_ty))
310
+ p_q += K
311
+ p_gq += K
312
+ p_A += BT
313
+
314
+
315
+ @triton.jit
316
+ def bwd_inner_chunk(
317
+ q,
318
+ k,
319
+ g,
320
+ dA,
321
+ dq,
322
+ dk,
323
+ T, # T
324
+ K: tl.constexpr, # K
325
+ # clamp_min, # minimum log value of the gate for numerical stability. default: -5
326
+ BT: tl.constexpr, # BLOCK SIZE along the sequence dimension, a.k.a. chunk size
327
+ BK: tl.constexpr, # BLOCK SIZE along the K dimension
328
+ ):
329
+ i_k, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
330
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
331
+ b_k = tl.load(p_k, boundary_check=(0, 1))
332
+ p_g = tl.make_block_ptr(g + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
333
+ b_g = tl.load(p_g, boundary_check=(0, 1)).to(tl.float32)
334
+
335
+ mask = (i_k * BK + tl.arange(0, BK)) < K
336
+ o_i = tl.arange(0, BT)
337
+
338
+ p_q = q + i_bh * T*K + i_k * BK + i_t * BT * K + tl.arange(0, BK)
339
+ p_dq = dq + (i_bh) * T*K + i_k * BK + i_t * BT * K + tl.arange(0, BK)
340
+ p_gq = g + i_bh * T*K + i_k * BK + i_t * BT * K + tl.arange(0, BK)
341
+ p_dA = dA + i_bh * (tl.cdiv(T, BT) * BT * BT) + i_t * BT * BT + tl.arange(0, BT)
342
+
343
+ b_dk = tl.zeros([BT, BK], dtype=tl.float32)
344
+
345
+ for i in range(BT):
346
+ b_q = tl.load(p_q, mask=mask, other=0)
347
+ b_gq = tl.load(p_gq, mask=mask, other=0).to(tl.float32)
348
+ score = safe_exp(b_gq[None, :] - b_g)
349
+ score = tl.where(o_i[:, None] <= i, score, 0)
350
+ b_dA = tl.load(p_dA)
351
+ b_dA = tl.where(o_i <= i, b_dA, 0)
352
+ b_dk += (b_dA[:, None] * score * b_q[None, :])
353
+ b_dq = tl.sum(b_dA[:, None] * score * b_k, axis=0)
354
+ tl.store(p_dq, b_dq, mask=mask)
355
+ p_q += K
356
+ p_dq += K
357
+ p_gq += K
358
+ p_dA += BT
359
+
360
+ p_dk = tl.make_block_ptr(dk + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
361
+ tl.store(p_dk, b_dk.to(dk.dtype.element_ty), boundary_check=(0, 1))
362
+
363
+
364
+ class FusedChunkGLAFunction(torch.autograd.Function):
365
+
366
+ @staticmethod
367
+ @input_guard
368
+ @autocast_custom_fwd
369
+ def forward(ctx, q, k, v, g, scale, initial_state, output_final_state):
370
+ ctx.g_dtype = g.dtype
371
+ ctx.scale = scale
372
+ B, H, T, K, V = *k.shape, v.shape[-1]
373
+ BT = 16 # chunk_size
374
+ BK, BV = min(K, 64), min(V, 64)
375
+ NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
376
+ num_stages = 1
377
+ num_warps = 2
378
+
379
+ g_org = g
380
+ # cumulative decay should be in float32, otherwise the err will be accumulated and amplified.
381
+ g = chunk_local_cumsum(g_org, chunk_size=BT)
382
+ o = q.new_empty(NK, B, H, T, V)
383
+ q_g = torch.empty_like(q)
384
+ k_g = torch.empty_like(k)
385
+
386
+ grid = (NK, triton.cdiv(T, BT), B * H)
387
+ prepare_qg_kg[grid](
388
+ q,
389
+ k,
390
+ g,
391
+ q_g,
392
+ k_g,
393
+ scale,
394
+ T=T,
395
+ K=K,
396
+ BT=BT,
397
+ BK=BK,
398
+ num_warps=1
399
+ )
400
+
401
+ if output_final_state:
402
+ final_state = q.new_empty(B, H, K, V, dtype=torch.float, requires_grad=False)
403
+ else:
404
+ final_state = None
405
+ # the bug still exists even for Triton 2.2 on H100 GPUs
406
+ # so we always enable initial checks
407
+ CHECK = True
408
+ if version.parse(triton.__version__) < version.parse('2.2.0'):
409
+ import warnings
410
+ warnings.warn(
411
+ "Triton<2.2.0 detected for running this kernel, "
412
+ "which is known to have some weird compiler issues (refer to https://github.com/openai/triton/issues/2852) "
413
+ "that lead to significant precision loss. "
414
+ "We've add some initial condition checks to resolve this, sadly at the sacrifice of the speed. "
415
+ "For optimal performance, it is recommended to install Triton>=2.2.0 (if possible)."
416
+ )
417
+ CHECK = True
418
+
419
+ grid = (NV, NK, B * H)
420
+ fused_chunk_gla_fwd_kernel[grid](
421
+ q_g, k_g, v, g, o, initial_state, final_state,
422
+ T=T,
423
+ B=B,
424
+ H=H,
425
+ K=K,
426
+ V=V,
427
+ BT=BT,
428
+ BK=BK,
429
+ BV=BV,
430
+ USE_INITIAL_STATE=initial_state is not None,
431
+ STORE_FINAL_STATE=output_final_state,
432
+ CHECK=CHECK,
433
+ num_warps=num_warps,
434
+ num_stages=num_stages
435
+ )
436
+
437
+ o = o.sum(0)
438
+
439
+ # intra-chunk
440
+ chunk_size = 16
441
+ num_chunk = T // chunk_size
442
+ v2 = rearrange(v, 'b h (n c) d -> b h n c d', n=num_chunk)
443
+ BK = min(K, 64)
444
+ NK = triton.cdiv(K, BK)
445
+ A = q.new_empty(NK, B, H, triton.cdiv(T, BT), BT, BT)
446
+ grid = (NK, triton.cdiv(T, BT), B * H)
447
+ fwd_inner_chunk[grid](
448
+ q, k, g, A,
449
+ scale,
450
+ B=B,
451
+ H=H,
452
+ T=T,
453
+ K=K,
454
+ BT=BT,
455
+ BK=BK,
456
+ num_stages=3,
457
+ num_warps=4
458
+ )
459
+ A = A.sum(0)
460
+ o2 = A @ v2
461
+ o2 = rearrange(o2, 'b h n c d -> b h (n c) d')
462
+ # combine inner and inter
463
+ o.add_(o2)
464
+ ctx.save_for_backward(q, k, v, g_org, A, initial_state)
465
+ ctx.CHECK = CHECK
466
+ return o.to(v), final_state
467
+
468
+ @staticmethod
469
+ @input_guard
470
+ @autocast_custom_bwd
471
+ def backward(ctx, do, dht=None):
472
+ q, k, v, g_org, A, initial_state = ctx.saved_tensors
473
+ B, H, T, K, V = *k.shape, v.shape[-1]
474
+ scale = ctx.scale
475
+
476
+ # recomputation
477
+ # inter-chunk
478
+ BT = 16 # chunk_size
479
+ g = chunk_local_cumsum(g_org, chunk_size=BT)
480
+ BK, BV = min(K, 64), min(V, 64)
481
+ NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
482
+ q_g = torch.empty_like(q)
483
+ k_g = torch.empty_like(k)
484
+ grid = (NK, triton.cdiv(T, BT), B * H)
485
+ prepare_qg_kg[grid](
486
+ q,
487
+ k,
488
+ g,
489
+ q_g,
490
+ k_g,
491
+ scale,
492
+ T=T,
493
+ K=K,
494
+ BT=BT,
495
+ BK=BK,
496
+ num_warps=1
497
+ )
498
+
499
+ BK, BV = min(max(triton.next_power_of_2(K), 16), 64), min(max(triton.next_power_of_2(V), 16), 64)
500
+ NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
501
+ num_stages = 1
502
+ num_warps = 2
503
+ dq = q.new_empty(NV, B, H, T, K)
504
+ dk = q.new_empty(NV, B, H, T, K)
505
+ dv = q.new_empty(NK, B, H, T, V)
506
+
507
+ grid = (NV, NK, B * H)
508
+
509
+ fused_chunk_gla_bwd_kernel[grid](
510
+ q_g,
511
+ k_g,
512
+ v,
513
+ g,
514
+ do,
515
+ dq,
516
+ dk,
517
+ dv,
518
+ initial_state,
519
+ scale,
520
+ T=T,
521
+ B=B,
522
+ H=H,
523
+ K=K,
524
+ V=V,
525
+ BT=BT,
526
+ BK=BK,
527
+ BV=BV,
528
+ USE_INITIAL_STATE=initial_state is not None,
529
+ CHECK=ctx.CHECK,
530
+ num_warps=num_warps,
531
+ num_stages=num_stages,
532
+ )
533
+ dq = dq.sum(0)
534
+ dk = dk.sum(0)
535
+ dv = dv.sum(0)
536
+
537
+ # intra chunk
538
+ NT = T // BT
539
+ v2 = rearrange(v, 'b h (n c) d -> b h n c d', n=NT)
540
+ do2 = rearrange(do, 'b h (n c) d -> b h n c d', n=NT)
541
+ dA2 = (do2 @ v2.transpose(-2, -1)) * scale
542
+ dv2 = A.transpose(-1, -2) @ do2
543
+ dv2 = rearrange(dv2, 'b h n c d -> b h (n c) d', n=NT)
544
+
545
+ BK = 16
546
+ NK = triton.cdiv(K, BK)
547
+ dk2 = torch.empty_like(k)
548
+ dq2 = torch.empty_like(q)
549
+
550
+ grid = (NK, NT, B * H)
551
+ bwd_inner_chunk[grid](
552
+ q, k, g,
553
+ dA2,
554
+ dq2,
555
+ dk2,
556
+ T=T,
557
+ K=K,
558
+ BT=BT,
559
+ BK=BK,
560
+ num_warps=1,
561
+ num_stages=3
562
+ )
563
+
564
+ BK = min(max(triton.next_power_of_2(K), 16), 32)
565
+ NK = triton.cdiv(K, BK)
566
+ dg = torch.empty_like(g, dtype=torch.float32)
567
+ grid = (NK, triton.cdiv(T, BT), B * H)
568
+ bwd_decay_global_cumsum[grid](
569
+ dq2,
570
+ dq,
571
+ dk2,
572
+ dk,
573
+ q,
574
+ k,
575
+ g,
576
+ dg,
577
+ T=T,
578
+ K=K,
579
+ BT=BT,
580
+ BK=BK,
581
+ num_warps=1,
582
+ num_stages=1
583
+ )
584
+ dg = rearrange(dg, 'b h (n c) d -> b h n c d', c=BT)
585
+
586
+ def rev_cumsum_exclusive(x):
587
+ cumsum_x = x.cumsum(-2)
588
+ rev_cumsum_x = cumsum_x[..., -1, None, :] - cumsum_x
589
+ return rev_cumsum_x
590
+
591
+ rev_cumsum_dg = rev_cumsum_exclusive(dg[..., 0, :])
592
+ dg.add_(rev_cumsum_dg.unsqueeze(-2))
593
+ dv.add_(dv2)
594
+ dg = rearrange(dg, 'b h n c d -> b h (n c) d')
595
+
596
+ return dq.to(q), dk.to(k), dv.to(v), dg.to(ctx.g_dtype), None, None, None
597
+
598
+
599
+ def ceildiv(a, b):
600
+ return -(a // -b)
601
+
602
+
603
+ def pad(x, chunk_size=16):
604
+ T = x.shape[-2]
605
+ padded_seq_len = ceildiv(T, chunk_size) * chunk_size
606
+ if x.shape[-2] % chunk_size != 0:
607
+ x = F.pad(x, (0, 0, 0, padded_seq_len - T))
608
+ return x
609
+
610
+
611
+ def fused_chunk_gla(
612
+ q: torch.Tensor,
613
+ k: torch.Tensor,
614
+ v: torch.Tensor,
615
+ g: torch.Tensor,
616
+ scale: int = -1,
617
+ initial_state: torch.Tensor = None,
618
+ output_final_state: bool = False,
619
+ head_first: bool = False,
620
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
621
+ if head_first:
622
+ warnings.warn(
623
+ "head_first is deprecated and will be removed in a future version. "
624
+ "Please use head_first=False for now instead."
625
+ )
626
+ q, k, v, g = map(lambda x: rearrange(x, 'b h t ... -> b t h ...'), (q, k, v, g))
627
+ if not head_first and q.shape[1] < q.shape[2]:
628
+ warnings.warn(
629
+ f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
630
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
631
+ "when head_first=False was specified. "
632
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
633
+ )
634
+ if scale == -1:
635
+ scale = q.shape[-1] ** -0.5
636
+ seq_len = q.shape[-2]
637
+ q, k, v, g = map(lambda x: pad(x), [q, k, v, g])
638
+ o, final_state = FusedChunkGLAFunction.apply(q, k, v, g, scale, initial_state, output_final_state)
639
+ o = o[..., :seq_len, :].contiguous()
640
+ if head_first:
641
+ o = rearrange(o, 'b t h ... -> b h t ...')
642
+ return o, final_state