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,722 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ import warnings
5
+ from typing import Optional, Tuple
6
+
7
+ import torch
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ from fla.ops.utils import prepare_chunk_indices
12
+ from fla.ops.utils.cumsum import chunk_global_cumsum, chunk_local_cumsum
13
+ from fla.ops.utils.op import exp
14
+ from fla.utils import (
15
+ autocast_custom_bwd,
16
+ autocast_custom_fwd,
17
+ check_shared_mem,
18
+ input_guard,
19
+ is_intel_alchemist,
20
+ is_nvidia_hopper
21
+ )
22
+
23
+ # https://github.com/intel/intel-xpu-backend-for-triton/issues/3449
24
+ triton_config = {'grf_mode': 'large'} if is_intel_alchemist else {}
25
+ NUM_WARPS = [2, 4, 8] if is_nvidia_hopper else [2, 4, 8, 16]
26
+
27
+
28
+ @triton.heuristics({
29
+ 'NV': lambda args: triton.cdiv(args['V'], args['BV']),
30
+ 'OUTPUT_ATTENTIONS': lambda args: args['attn'] is not None,
31
+ 'USE_G': lambda args: args['g'] is not None,
32
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
33
+ })
34
+ @triton.autotune(
35
+ configs=[
36
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
37
+ for num_warps in [2, 4, 8, 16]
38
+ for num_stages in [2, 3, 4]
39
+ ],
40
+ key=["BT", "BS", "BK", "BV", "USE_G"],
41
+ )
42
+ @triton.jit
43
+ def parallel_simple_gla_fwd_kernel(
44
+ q,
45
+ k,
46
+ v,
47
+ g,
48
+ o,
49
+ attn,
50
+ scale,
51
+ cu_seqlens,
52
+ chunk_indices,
53
+ T,
54
+ B: tl.constexpr,
55
+ H: tl.constexpr,
56
+ K: tl.constexpr,
57
+ V: tl.constexpr,
58
+ BT: tl.constexpr,
59
+ BS: tl.constexpr,
60
+ BK: tl.constexpr,
61
+ BV: tl.constexpr,
62
+ NV: tl.constexpr,
63
+ OUTPUT_ATTENTIONS: tl.constexpr,
64
+ IS_VARLEN: tl.constexpr,
65
+ USE_G: tl.constexpr
66
+ ):
67
+ i_kv, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
68
+ i_k, i_v = i_kv // NV, i_kv % NV
69
+ i_b, i_h = i_bh // H, i_bh % H
70
+
71
+ all = B * T
72
+ if IS_VARLEN:
73
+ 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)
74
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
75
+ T = eos - bos
76
+ else:
77
+ bos, eos = i_b * T, i_b * T + T
78
+
79
+ q += (bos * H + i_h) * K
80
+ k += (bos * H + i_h) * K
81
+ v += (bos * H + i_h) * V
82
+ o += ((i_k * all + bos) * H + i_h) * V
83
+ if USE_G:
84
+ g += bos * H + i_h
85
+ if OUTPUT_ATTENTIONS:
86
+ attn += i_k * B * H * T * T + (bos * H + i_h * T) * T
87
+
88
+ p_q = tl.make_block_ptr(q, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
89
+
90
+ # the Q block is kept in the shared memory throughout the whole kernel
91
+ # [BT, BK]
92
+ b_q = tl.load(p_q, boundary_check=(0, 1))
93
+ b_q = (b_q * scale).to(b_q.dtype)
94
+ b_o = tl.zeros([BT, BV], dtype=tl.float32)
95
+
96
+ # [BT]
97
+ o_q = i_t * BT + tl.arange(0, BT)
98
+ m_q = o_q < T
99
+ # Q block and K block have overlap.
100
+ # masks required
101
+ if USE_G:
102
+ # [BT,]
103
+ b_gq = tl.load(g + o_q * H, mask=m_q, other=float('-inf')).to(tl.float32)
104
+ # rescale interchunk output
105
+ else:
106
+ b_gq = None
107
+
108
+ for i_s in range(i_t * BT, min((i_t + 1) * BT, T), BS):
109
+ p_k = tl.make_block_ptr(k, (K, T), (1, H*K), (i_k * BK, i_s), (BK, BS), (0, 1))
110
+ p_v = tl.make_block_ptr(v, (T, V), (H*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
111
+
112
+ o_k = i_s + tl.arange(0, BS)
113
+ m_k = o_k < T
114
+ # [BK, BS]
115
+ b_k = tl.load(p_k, boundary_check=(0, 1))
116
+ # [BS, BV]
117
+ b_v = tl.load(p_v, boundary_check=(0, 1))
118
+ # [BT, BS]
119
+ m_s = (o_q[:, None] >= o_k[None, :]) & (m_q[:, None] & m_k[None, :])
120
+ b_s = tl.dot(b_q, b_k)
121
+ if USE_G:
122
+ b_gk = tl.load(g + o_k * H, mask=m_k, other=0)
123
+ b_s *= exp(b_gq[:, None] - b_gk[None, :])
124
+ b_s = tl.where(m_s, b_s, 0)
125
+ # [BT, BV]
126
+ if i_s >= 0:
127
+ b_o += tl.dot(b_s.to(b_q.dtype), b_v)
128
+ if OUTPUT_ATTENTIONS:
129
+ p_a = tl.make_block_ptr(attn, (T, T), (T, 1), (i_t * BT, i_s), (BT, BS), (1, 0))
130
+ tl.store(p_a, b_s.to(p_a.dtype.element_ty), boundary_check=(0, 1))
131
+ for i_s in range(i_t * BT - BS, -BS, -BS):
132
+ p_k = tl.make_block_ptr(k, (K, T), (1, H*K), (i_k * BK, i_s), (BK, BS), (0, 1))
133
+ p_v = tl.make_block_ptr(v, (T, V), (H*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
134
+
135
+ o_k = i_s + tl.arange(0, BS)
136
+ m_k = o_k < T
137
+ # [BK, BS]
138
+ b_k = tl.load(p_k, boundary_check=(0, 1))
139
+ # [BS, BV]
140
+ b_v = tl.load(p_v, boundary_check=(0, 1))
141
+ # [BT, BS]
142
+ m_s = m_q[:, None] & m_k[None, :]
143
+ b_s = tl.dot(b_q, b_k)
144
+ if USE_G:
145
+ b_g = tl.load(g + o_k * H, mask=m_k, other=0)
146
+ b_gn = tl.load(g + (min(i_s + BS, T) - 1) * H)
147
+ b_gp = tl.load(g + (i_s-1) * H) if i_s % BT > 0 else 0.
148
+ # No concrete meaning. Just to avoid some layout bugs.
149
+ b_s *= exp(b_gq[:, None] + (b_gn - b_g)[None, :])
150
+ b_gq += b_gn - b_gp
151
+ b_s = tl.where(m_s, b_s, 0)
152
+ if OUTPUT_ATTENTIONS:
153
+ p_a = tl.make_block_ptr(attn, (T, T), (T, 1), (i_t * BT, i_s), (BT, BS), (1, 0))
154
+ tl.store(p_a, b_s.to(p_a.dtype.element_ty), boundary_check=(0, 1))
155
+ if i_s >= 0:
156
+ b_o += tl.dot(b_s.to(b_v.dtype), b_v)
157
+ p_o = tl.make_block_ptr(o, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
158
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
159
+
160
+
161
+ @triton.jit(do_not_specialize=['T'])
162
+ def parallel_simple_gla_bwd_kernel_dq(
163
+ i_t,
164
+ i_k,
165
+ i_v,
166
+ q,
167
+ k,
168
+ v,
169
+ g,
170
+ do,
171
+ dq,
172
+ dg,
173
+ scale,
174
+ T,
175
+ H: tl.constexpr,
176
+ K: tl.constexpr,
177
+ V: tl.constexpr,
178
+ BT: tl.constexpr,
179
+ BS: tl.constexpr,
180
+ BK: tl.constexpr,
181
+ BV: tl.constexpr,
182
+ USE_G: tl.constexpr
183
+ ):
184
+ p_do = tl.make_block_ptr(do, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
185
+ # [BT, BV]
186
+ b_do = tl.load(p_do, boundary_check=(0, 1))
187
+ # [BT, BK]
188
+ b_dq = tl.zeros([BT, BK], dtype=tl.float32)
189
+
190
+ # [BT]
191
+ o_q = i_t * BT + tl.arange(0, BT)
192
+ m_q = o_q < T
193
+ for i_s in range(0, i_t * BT, BS):
194
+ p_k = tl.make_block_ptr(k, (T, K), (H*K, 1), (i_s, i_k * BK), (BS, BK), (1, 0))
195
+ p_v = tl.make_block_ptr(v, (V, T), (1, H*V), (i_v * BV, i_s), (BV, BS), (0, 1))
196
+
197
+ o_k = i_s + tl.arange(0, BS)
198
+ m_k = o_k < T
199
+ # [BS, BK]
200
+ b_k = tl.load(p_k, boundary_check=(0, 1))
201
+ # [BV, BS]
202
+ b_v = tl.load(p_v, boundary_check=(0, 1))
203
+ # [BT, BV] @ [BV, BS] = [BT, BS]
204
+ b_ds = tl.dot(b_do, b_v)
205
+ if USE_G:
206
+ b_g = tl.load(g + o_k * H, mask=m_k, other=0)
207
+ b_gn = tl.load(g + (min(i_s + BS, T) - 1) * H)
208
+ b_gp = tl.load(g + (i_s - 1) * H) if i_s % BT > 0 else 0.
209
+ b_ds *= tl.where(m_k, exp(b_gn - b_g), 0)[None, :]
210
+ if i_s > 0:
211
+ b_dq *= exp(b_gn - b_gp)
212
+ # [BT, BS] @ [BS, BK] = [BT, BK]
213
+ b_dq += tl.dot(b_ds.to(b_v.dtype), b_k)
214
+
215
+ if USE_G:
216
+ # [BT,]
217
+ b_gq = tl.load(g + o_q * H, mask=m_q, other=float('-inf'))
218
+ # [BT, BK]
219
+ b_dq *= exp(b_gq)[:, None]
220
+
221
+ # Q block and K block have overlap. masks required
222
+ for i_s in range(i_t * BT, min((i_t + 1) * BT, T), BS):
223
+ p_k = tl.make_block_ptr(k, (T, K), (H*K, 1), (i_s, i_k * BK), (BS, BK), (1, 0))
224
+ p_v = tl.make_block_ptr(v, (V, T), (1, H*V), (i_v * BV, i_s), (BV, BS), (0, 1))
225
+
226
+ o_k = i_s + tl.arange(0, BS)
227
+ m_k = o_k < T
228
+ # [BS, BK]
229
+ b_k = tl.load(p_k, boundary_check=(0, 1))
230
+ # [BV, BS]
231
+ b_v = tl.load(p_v, boundary_check=(0, 1))
232
+ # [BT, BV] @ [BV, BS] = [BT, BS]
233
+ b_ds = tl.dot(b_do, b_v)
234
+ if USE_G:
235
+ b_gk = tl.load(g + o_k * H, mask=m_k, other=0)
236
+ b_ds *= exp(b_gq[:, None] - b_gk[None, :])
237
+ m_s = (o_q[:, None] >= o_k[None, :]) & (m_q[:, None] & m_k[None, :])
238
+ b_ds = tl.where(m_s, b_ds, 0)
239
+ # [BT, BK]
240
+ b_dq += tl.dot(b_ds.to(b_k.dtype), b_k)
241
+
242
+ b_dq *= scale
243
+ p_dq = tl.make_block_ptr(dq, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
244
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
245
+ if USE_G:
246
+ p_q = tl.make_block_ptr(q, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
247
+ b_q = tl.load(p_q, boundary_check=(0, 1))
248
+ b_dg = tl.sum(b_dq * b_q, 1)
249
+ p_dg = tl.make_block_ptr(dg, (T,), (H,), (i_t * BT,), (BT,), (0,))
250
+ tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0,))
251
+
252
+
253
+ @triton.jit(do_not_specialize=['T'])
254
+ def parallel_simple_gla_bwd_kernel_dkv(
255
+ i_t,
256
+ i_k,
257
+ i_v,
258
+ q,
259
+ k,
260
+ v,
261
+ g,
262
+ do,
263
+ dk,
264
+ dv,
265
+ dg,
266
+ scale,
267
+ T,
268
+ H: tl.constexpr,
269
+ K: tl.constexpr,
270
+ V: tl.constexpr,
271
+ BT: tl.constexpr,
272
+ BS: tl.constexpr,
273
+ BK: tl.constexpr,
274
+ BV: tl.constexpr,
275
+ USE_G: tl.constexpr
276
+ ):
277
+ o_k = i_t * BT + tl.arange(0, BT)
278
+ m_k = o_k < T
279
+ # [BT, BK]
280
+ p_k = tl.make_block_ptr(k, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
281
+ b_k = tl.load(p_k, boundary_check=(0, 1))
282
+ b_dk = tl.zeros([BT, BK], dtype=tl.float32)
283
+ # [BT, BV]
284
+ p_v = tl.make_block_ptr(v, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
285
+ b_v = tl.load(p_v, boundary_check=(0, 1))
286
+ b_dv = tl.zeros([BT, BV], dtype=tl.float32)
287
+ if USE_G:
288
+ b_gk = tl.load(g + o_k * H, mask=m_k, other=0)
289
+ NTS = tl.cdiv(T, BS)
290
+ # [BT, BK]
291
+ for i_s in range(NTS * BS - BS, (i_t + 1) * BT - BS, -BS):
292
+ p_q = tl.make_block_ptr(q, (T, K), (H*K, 1), (i_s, i_k * BK), (BS, BK), (1, 0))
293
+ p_do = tl.make_block_ptr(do, (T, V), (H*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
294
+
295
+ o_q = i_s + tl.arange(0, BS)
296
+ m_q = o_q < T
297
+ # [BS, BK]
298
+ b_q = tl.load(p_q, boundary_check=(0, 1))
299
+ # [BS, BV]
300
+ b_do = tl.load(p_do, boundary_check=(0, 1))
301
+ # [BT, BS]
302
+ b_ds = tl.dot(b_v, tl.trans(b_do))
303
+ b_s = tl.dot(b_k, tl.trans(b_q))
304
+ if USE_G:
305
+ b_gq = tl.load(g + o_q * H, mask=m_q, other=float('-inf'))
306
+ b_gp = tl.load(g + (min(i_s + BS, T) - 1) * H)
307
+ b_gn = tl.load(g + (i_s - 1) * H) if i_s % BT > 0 else 0.
308
+ if i_s >= 0:
309
+ b_gpn = exp(b_gp - b_gn)
310
+ b_dk *= b_gpn
311
+ b_dv *= b_gpn
312
+ b_gqn = exp(b_gq - b_gn)
313
+ b_ds *= b_gqn[None, :]
314
+ b_s *= b_gqn[None, :]
315
+ # [BT, BK]
316
+ b_dk += tl.dot(b_ds.to(b_q.dtype), b_q)
317
+ # [BT, BV]
318
+ b_dv += tl.dot(b_s.to(b_do.dtype), b_do)
319
+
320
+ if USE_G:
321
+ b_gn = tl.load(g + (min(i_t * BT + BT, T) - 1) * H)
322
+ if i_t >= 0:
323
+ b_gpn = exp(b_gn - b_gk)[:, None]
324
+ b_dk *= b_gpn
325
+ b_dv *= b_gpn
326
+
327
+ for i_s in range(i_t * BT, min((i_t + 1) * BT, T), BS):
328
+ p_q = tl.make_block_ptr(q, (T, K), (H*K, 1), (i_s, i_k * BK), (BS, BK), (1, 0))
329
+ p_do = tl.make_block_ptr(do, (T, V), (H*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
330
+
331
+ o_q = i_s + tl.arange(0, BS)
332
+ m_q = o_q < T
333
+ # [BS, BK]
334
+ b_q = tl.load(p_q, boundary_check=(0, 1))
335
+ # [BS, BV]
336
+ b_do = tl.load(p_do, boundary_check=(0, 1))
337
+ # [BS]
338
+ b_s = tl.dot(b_k, tl.trans(b_q))
339
+ b_ds = tl.dot(b_v, tl.trans(b_do))
340
+ if USE_G:
341
+ b_gq = tl.load(g + o_q * H, mask=m_q, other=float('-inf'))
342
+ if i_s >= 0:
343
+ b_gkq = exp(-b_gk[:, None] + b_gq[None, :])
344
+ b_ds *= b_gkq
345
+ b_s *= b_gkq
346
+ m_s = o_k[:, None] <= o_q[None, :]
347
+ b_s = tl.where(m_s, b_s, 0)
348
+ b_ds = tl.where(m_s, b_ds, 0)
349
+ # [BT, BK]
350
+ b_dk += tl.dot(b_ds.to(b_q.dtype), b_q)
351
+ b_dv += tl.dot(b_s.to(b_do.dtype), b_do)
352
+ b_dk *= scale
353
+ b_dv *= scale
354
+ p_dk = tl.make_block_ptr(dk, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
355
+ p_dv = tl.make_block_ptr(dv, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
356
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
357
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
358
+ if USE_G:
359
+ b_dg = tl.load(dg + o_k * H, mask=m_k, other=0)
360
+ b_dg -= tl.sum(b_dk * b_k, 1)
361
+ tl.store(dg + o_k * H, b_dg.to(dg.dtype.element_ty), mask=m_k)
362
+
363
+
364
+ @triton.heuristics({
365
+ 'NV': lambda args: triton.cdiv(args['V'], args['BV']),
366
+ 'USE_G': lambda args: args['g'] is not None,
367
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
368
+ })
369
+ @triton.autotune(
370
+ configs=[
371
+ triton.Config(triton_config, num_warps=num_warps)
372
+ for num_warps in NUM_WARPS
373
+ ],
374
+ key=['BT', 'BS', 'BK', 'BV', 'USE_G'],
375
+ )
376
+ @triton.jit(do_not_specialize=['T'])
377
+ def parallel_simple_gla_bwd_kernel(
378
+ q,
379
+ k,
380
+ v,
381
+ g,
382
+ do,
383
+ dq,
384
+ dk,
385
+ dv,
386
+ dg,
387
+ scale,
388
+ cu_seqlens,
389
+ chunk_indices,
390
+ T,
391
+ B: tl.constexpr,
392
+ H: tl.constexpr,
393
+ K: tl.constexpr,
394
+ V: tl.constexpr,
395
+ BT: tl.constexpr,
396
+ BS: tl.constexpr,
397
+ BK: tl.constexpr,
398
+ BV: tl.constexpr,
399
+ NV: tl.constexpr,
400
+ IS_VARLEN: tl.constexpr,
401
+ USE_G: tl.constexpr
402
+ ):
403
+ i_kv, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
404
+ i_k, i_v = i_kv // NV, i_kv % NV
405
+ i_b, i_h = i_bh // H, i_bh % H
406
+ dq += i_v * B * H * T * K
407
+ dk += i_v * B * H * T * K
408
+ dv += i_k * B * H * T * V
409
+ if USE_G:
410
+ dg += i_kv * B * H * T
411
+
412
+ if IS_VARLEN:
413
+ 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)
414
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
415
+ T = eos - bos
416
+ else:
417
+ bos, eos = i_b * T, i_b * T + T
418
+
419
+ q += (bos * H + i_h) * K
420
+ k += (bos * H + i_h) * K
421
+ v += (bos * H + i_h) * V
422
+ do += (bos * H + i_h) * V
423
+ dq += (bos * H + i_h) * K
424
+ dk += (bos * H + i_h) * K
425
+ dv += (bos * H + i_h) * V
426
+ if USE_G:
427
+ g += bos * H + i_h
428
+ dg += bos * H + i_h
429
+
430
+ parallel_simple_gla_bwd_kernel_dq(
431
+ i_t=i_t,
432
+ i_k=i_k,
433
+ i_v=i_v,
434
+ q=q,
435
+ k=k,
436
+ v=v,
437
+ g=g,
438
+ do=do,
439
+ dq=dq,
440
+ dg=dg,
441
+ scale=scale,
442
+ T=T,
443
+ H=H,
444
+ K=K,
445
+ V=V,
446
+ BT=BT,
447
+ BS=BS,
448
+ BK=BK,
449
+ BV=BV,
450
+ USE_G=USE_G
451
+ )
452
+ tl.debug_barrier()
453
+ parallel_simple_gla_bwd_kernel_dkv(
454
+ i_t=i_t,
455
+ i_k=i_k,
456
+ i_v=i_v,
457
+ q=q,
458
+ k=k,
459
+ v=v,
460
+ g=g,
461
+ do=do,
462
+ dk=dk,
463
+ dv=dv,
464
+ dg=dg,
465
+ scale=scale,
466
+ T=T,
467
+ H=H,
468
+ K=K,
469
+ V=V,
470
+ BT=BT,
471
+ BS=BS,
472
+ BK=BK,
473
+ BV=BV,
474
+ USE_G=USE_G
475
+ )
476
+
477
+
478
+ def parallel_simple_gla_fwd(
479
+ q: torch.Tensor,
480
+ k: torch.Tensor,
481
+ v: torch.Tensor,
482
+ g: torch.Tensor,
483
+ scale: float,
484
+ output_attentions: bool = False,
485
+ chunk_size: int = 128,
486
+ cu_seqlens: Optional[torch.LongTensor] = None,
487
+ ):
488
+ B, T, H, K, V = *k.shape, v.shape[-1]
489
+ BT, BS = chunk_size, 32
490
+ if check_shared_mem('hopper', k.device.index):
491
+ BK = min(256, triton.next_power_of_2(K))
492
+ BV = min(256, triton.next_power_of_2(V))
493
+ elif check_shared_mem('ampere', k.device.index):
494
+ BK = min(128, triton.next_power_of_2(K))
495
+ BV = min(128, triton.next_power_of_2(V))
496
+ else:
497
+ BK = min(64, triton.next_power_of_2(K))
498
+ BV = min(64, triton.next_power_of_2(V))
499
+
500
+ NK = triton.cdiv(K, BK)
501
+ NV = triton.cdiv(V, BV)
502
+ assert BT % BS == 0
503
+
504
+ chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
505
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
506
+
507
+ # local cumulative decay in log space
508
+ if g is not None:
509
+ g = chunk_local_cumsum(g, chunk_size, cu_seqlens=cu_seqlens)
510
+ grid = (NK * NV, NT, B * H)
511
+ o = torch.empty(NK, *v.shape, dtype=v.dtype if NK == 1 else torch.float, device=q.device)
512
+ attn = q.new_zeros(NK, B, H, T, T) if output_attentions else None
513
+
514
+ parallel_simple_gla_fwd_kernel[grid](
515
+ q=q,
516
+ k=k,
517
+ v=v,
518
+ g=g,
519
+ o=o,
520
+ attn=attn,
521
+ scale=scale,
522
+ cu_seqlens=cu_seqlens,
523
+ chunk_indices=chunk_indices,
524
+ B=B,
525
+ H=H,
526
+ T=T,
527
+ K=K,
528
+ V=V,
529
+ BT=BT,
530
+ BS=BS,
531
+ BK=BK,
532
+ BV=BV,
533
+ )
534
+ o = o.sum(0)
535
+
536
+ if output_attentions:
537
+ attn = attn.sum(0)
538
+ return o, g, attn
539
+
540
+
541
+ def parallel_simple_gla_bwd(
542
+ q: torch.Tensor,
543
+ k: torch.Tensor,
544
+ v: torch.Tensor,
545
+ g: torch.Tensor,
546
+ do: torch.Tensor,
547
+ scale: float,
548
+ chunk_size: int = 128,
549
+ cu_seqlens: Optional[torch.LongTensor] = None,
550
+ ):
551
+ B, T, H, K, V = *k.shape, v.shape[-1]
552
+ BT, BS = chunk_size, 32
553
+ if check_shared_mem('hopper', k.device.index):
554
+ BK = min(256, triton.next_power_of_2(K))
555
+ BV = min(256, triton.next_power_of_2(V))
556
+ elif check_shared_mem('ampere', k.device.index):
557
+ BK = min(128, triton.next_power_of_2(K))
558
+ BV = min(128, triton.next_power_of_2(V))
559
+ elif check_shared_mem('ada', k.device.index):
560
+ BK = min(64, triton.next_power_of_2(K))
561
+ BV = min(64, triton.next_power_of_2(V))
562
+ else:
563
+ BK = min(32, triton.next_power_of_2(K))
564
+ BV = min(32, triton.next_power_of_2(V))
565
+
566
+ NK = triton.cdiv(K, BK)
567
+ NV = triton.cdiv(V, BV)
568
+ assert BT % BS == 0
569
+
570
+ dq = torch.empty(NV, * q.shape, dtype=q.dtype if NV == 1 else torch.float, device=q.device)
571
+ dk = torch.empty(NV, * k.shape, dtype=k.dtype if NV == 1 else torch.float, device=q.device)
572
+ dv = torch.empty(NK, * v.shape, dtype=v.dtype if NK == 1 else torch.float, device=q.device)
573
+ dg = torch.empty(NK*NV, *g.shape, dtype=torch.float, device=q.device) if g is not None else None
574
+
575
+ chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
576
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
577
+
578
+ grid = (NK * NV, NT, B * H)
579
+ parallel_simple_gla_bwd_kernel[grid](
580
+ q=q,
581
+ k=k,
582
+ v=v,
583
+ g=g,
584
+ do=do,
585
+ dq=dq,
586
+ dk=dk,
587
+ dv=dv,
588
+ dg=dg,
589
+ cu_seqlens=cu_seqlens,
590
+ chunk_indices=chunk_indices,
591
+ scale=scale,
592
+ T=T,
593
+ B=B,
594
+ H=H,
595
+ K=K,
596
+ V=V,
597
+ BT=BT,
598
+ BS=BS,
599
+ BK=BK,
600
+ BV=BV,
601
+ )
602
+ dq = dq.sum(0)
603
+ dk = dk.sum(0)
604
+ dv = dv.sum(0)
605
+ dg = chunk_global_cumsum(dg.sum(0), reverse=True, cu_seqlens=cu_seqlens) if g is not None else None
606
+ return dq, dk, dv, dg
607
+
608
+
609
+ class ParallelSimpleGLAFunction(torch.autograd.Function):
610
+
611
+ @staticmethod
612
+ @input_guard
613
+ @autocast_custom_fwd
614
+ def forward(ctx, q, k, v, g, scale, output_attentions, cu_seqlens):
615
+ chunk_size = 128
616
+ ctx.dtype = q.dtype
617
+
618
+ o, g, attn = parallel_simple_gla_fwd(
619
+ q=q,
620
+ k=k,
621
+ v=v,
622
+ g=g,
623
+ scale=scale,
624
+ output_attentions=output_attentions,
625
+ chunk_size=chunk_size,
626
+ cu_seqlens=cu_seqlens,
627
+ )
628
+ ctx.save_for_backward(q, k, v, g, cu_seqlens)
629
+ ctx.scale = scale
630
+ ctx.chunk_size = chunk_size
631
+ return o.to(q.dtype), attn
632
+
633
+ @staticmethod
634
+ @input_guard
635
+ @autocast_custom_bwd
636
+ def backward(ctx, do, da=None):
637
+ q, k, v, g, cu_seqlens = ctx.saved_tensors
638
+ dq, dk, dv, dg = parallel_simple_gla_bwd(
639
+ q=q,
640
+ k=k,
641
+ v=v,
642
+ g=g,
643
+ do=do,
644
+ scale=ctx.scale,
645
+ chunk_size=ctx.chunk_size,
646
+ cu_seqlens=cu_seqlens,
647
+ )
648
+ return dq.to(q), dk.to(k), dv.to(v), dg.to(ctx.dtype) if dg is not None else None, None, None, None
649
+
650
+
651
+ def parallel_simple_gla(
652
+ q: torch.Tensor,
653
+ k: torch.Tensor,
654
+ v: torch.Tensor,
655
+ g: Optional[torch.Tensor] = None,
656
+ scale: Optional[float] = None,
657
+ output_attentions: bool = False,
658
+ cu_seqlens: Optional[torch.LongTensor] = None,
659
+ head_first: bool = False
660
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
661
+ r"""
662
+ Args:
663
+ q (torch.Tensor):
664
+ queries of shape `[B, T, H, K]`.
665
+ k (torch.Tensor):
666
+ keys of shape `[B, T, H, K]`.
667
+ v (torch.Tensor):
668
+ values of shape `[B, T, H, V]`.
669
+ g (torch.Tensor):
670
+ Forget gates of shape `[B, T, H]`.
671
+ Compared to GLA, the gating is head-wise instead of elementwise.
672
+ scale (Optional[float]):
673
+ Scale factor for attention scores.
674
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
675
+ output_attentions (bool):
676
+ Whether to output the materialized attention scores of shape [B, H, T, T]. Default: `False`.
677
+ cu_seqlens (torch.LongTensor):
678
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
679
+ consistent with the FlashAttention API.
680
+ head_first (Optional[bool]):
681
+ Whether the inputs are in the head-first format. Default: `False`.
682
+ This argument has been deprecated.
683
+
684
+ Returns:
685
+ o (torch.Tensor):
686
+ Outputs of shape `[B, T, H, V]`.
687
+ attn (torch.Tensor):
688
+ Attention scores of shape `[B, H, T, T]` if `output_attentions=True` else `None`
689
+ """
690
+ if head_first:
691
+ raise DeprecationWarning(
692
+ "head_first is deprecated and will be removed in a future version. "
693
+ "Please use head_first=False for now instead."
694
+ )
695
+ if not head_first and q.shape[1] < q.shape[2]:
696
+ warnings.warn(
697
+ f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
698
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
699
+ "when head_first=False was specified. "
700
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
701
+ )
702
+ if cu_seqlens is not None:
703
+ if q.shape[0] != 1:
704
+ raise ValueError(
705
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
706
+ f"Please flatten variable-length inputs before processing."
707
+ )
708
+ if output_attentions:
709
+ assert cu_seqlens is None, "output_attentions=True is not supported with variable-length sequences"
710
+
711
+ if scale is None:
712
+ scale = k.shape[-1] ** -0.5
713
+ o, attn = ParallelSimpleGLAFunction.apply(
714
+ q,
715
+ k,
716
+ v,
717
+ g,
718
+ scale,
719
+ output_attentions,
720
+ cu_seqlens
721
+ )
722
+ return o, attn