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,831 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang, Yuqi Pan
3
+
4
+ import warnings
5
+ from typing import Optional
6
+
7
+ import torch
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ from fla.modules.layernorm import group_norm
12
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard, is_nvidia_hopper
13
+
14
+ NUM_WARPS = [1, 2] if is_nvidia_hopper else [1, 2, 4, 8]
15
+
16
+
17
+ @triton.heuristics({
18
+ 'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
19
+ 'USE_INITIAL_STATE_B': lambda args: args['hb0'] is not None,
20
+ 'STORE_FINAL_STATE': lambda args: args['ht'] is not None,
21
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
22
+ })
23
+ @triton.autotune(
24
+ configs=[
25
+ triton.Config({}, num_warps=1),
26
+ triton.Config({}, num_warps=2),
27
+ triton.Config({}, num_warps=4)
28
+ ],
29
+ key=['BT', 'BK', 'BV'],
30
+ )
31
+ @triton.jit(do_not_specialize=['T'])
32
+ def fused_chunk_ttt_linear_fwd_kernel(
33
+ q,
34
+ k,
35
+ v,
36
+ eta,
37
+ w,
38
+ b,
39
+ o,
40
+ scale,
41
+ eps,
42
+ h0,
43
+ hb0,
44
+ ht,
45
+ hbt,
46
+ cu_seqlens,
47
+ T,
48
+ H: tl.constexpr,
49
+ K: tl.constexpr,
50
+ V: tl.constexpr,
51
+ BT: tl.constexpr,
52
+ BK: tl.constexpr,
53
+ BV: tl.constexpr,
54
+ USE_INITIAL_STATE: tl.constexpr,
55
+ USE_INITIAL_STATE_B: tl.constexpr,
56
+ STORE_FINAL_STATE: tl.constexpr,
57
+ IS_VARLEN: tl.constexpr,
58
+ ):
59
+ i_nh = tl.program_id(0)
60
+ i_n, i_h = i_nh // H, i_nh % H
61
+ if IS_VARLEN:
62
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
63
+ T = eos - bos
64
+ NT = tl.cdiv(T, BT)
65
+ else:
66
+ bos, eos = i_n * T, i_n * T + T
67
+ NT = tl.cdiv(T, BT)
68
+
69
+ o_i = tl.arange(0, BT)
70
+ v_i = tl.arange(0, BV)
71
+ m_A = o_i[:, None] >= o_i[None, :]
72
+ b_w = tl.load(w + i_h * V + v_i, mask=v_i < V, other=0.)
73
+ b_b = tl.load(b + i_h * V + v_i, mask=v_i < V, other=0.)
74
+
75
+ # [BK, BV]
76
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
77
+ # [BV]
78
+ b_hb = tl.zeros([BV], dtype=tl.float32)
79
+ if USE_INITIAL_STATE:
80
+ p_h0 = tl.make_block_ptr(h0 + i_nh * K * V, (K, V), (V, 1), (0, 0), (BK, BV), (1, 0))
81
+ b_h = tl.load(p_h0, boundary_check=(0, 1), padding_option="zero").to(tl.float32)
82
+ if USE_INITIAL_STATE_B:
83
+ p_hb0 = tl.make_block_ptr(hb0 + i_nh * V, (V,), (1,), (0,), (BV,), (0,))
84
+ b_hb = tl.load(p_hb0, boundary_check=(0,), padding_option="zero").to(tl.float32)
85
+
86
+ for i_t in range(NT):
87
+ p_q = tl.make_block_ptr(q+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT, 0), (BT, BK), (1, 0))
88
+ p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (K, T), (1, H*K), (0, i_t*BT), (BK, BT), (0, 1))
89
+ p_v = tl.make_block_ptr(v+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
90
+ p_o = tl.make_block_ptr(o+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
91
+ p_e = tl.make_block_ptr(eta+(bos*H+i_h), (T,), (H,), (i_t*BT,), (BT,), (0,))
92
+ p_e_last = eta+bos*H+i_h + (T-1)*H if i_t == NT-1 else eta+bos*H+i_h + (i_t*BT+BT-1)*H
93
+ # [BK, BT]
94
+ b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
95
+ # [BT, BV]
96
+ b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
97
+
98
+ # [BT, BV]
99
+ b_kh = tl.dot(tl.trans(b_k), b_h.to(b_k.dtype), allow_tf32=False).to(tl.float32) + b_hb[None, :]
100
+ b_kh = tl.where((v_i < V)[None, :], b_kh, 0.)
101
+ mean = tl.sum(b_kh, axis=1, keep_dims=True) / V
102
+ xbar = tl.where((v_i < V)[None, :], b_kh - mean, 0.)
103
+ var = tl.sum(xbar * xbar, axis=1, keep_dims=True) / V
104
+ rstd = 1 / tl.sqrt(var.to(tl.float32) + eps)
105
+ b_kh_hat = (b_kh - mean) * rstd
106
+
107
+ b_v = b_kh_hat.to(b_k.dtype) * b_w[None, :].to(b_k.dtype) + \
108
+ b_b[None, :].to(b_k.dtype) - b_v.to(b_k.dtype) + tl.trans(b_k)
109
+ b_v = tl.where((v_i < V)[None, :], b_v * b_w[None, :].to(b_k.dtype), 0.)
110
+ b_v2 = rstd * (V * b_v - tl.sum(b_v, axis=1, keep_dims=True) - b_kh_hat.to(b_k.dtype)
111
+ * tl.sum(b_v * b_kh_hat.to(b_k.dtype), axis=1, keep_dims=True)) / V
112
+
113
+ # [BT, BK]
114
+ b_q = tl.load(p_q, boundary_check=(0, 1), padding_option="zero")
115
+ # [BT]
116
+ b_e = tl.load(p_e, boundary_check=(0,), padding_option="zero")
117
+ b_q = (b_q * scale).to(b_k.dtype)
118
+
119
+ # [BT, BT]
120
+ b_A = tl.dot(b_q, b_k, allow_tf32=False)
121
+ b_A = tl.where(m_A, b_A, 0)
122
+ b_Ae = tl.where(m_A, b_e[:, None], 0.0)
123
+
124
+ b_o = - tl.dot(b_e[:, None] * b_A.to(b_v2.dtype), b_v2, allow_tf32=False)
125
+ b_o += b_hb[None, :] - tl.dot(b_Ae.to(b_v2.dtype), b_v2, allow_tf32=False)
126
+ b_o += tl.dot(b_q, b_h.to(b_q.dtype), allow_tf32=False)
127
+ b_e_last = tl.load(p_e_last)
128
+ b_h = b_h - tl.dot(b_e_last * b_k, b_v2.to(b_k.dtype), allow_tf32=False)
129
+ b_hb = b_hb - tl.sum(b_e_last * b_v2.to(b_k.dtype), axis=0)
130
+ b_h = tl.where((v_i < V)[None, :], b_h, 0.)
131
+ b_hb = tl.where((v_i < V), b_hb, 0.)
132
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
133
+
134
+ if STORE_FINAL_STATE:
135
+ p_ht = tl.make_block_ptr(ht + i_nh * K*V, (K, V), (V, 1), (0, 0), (BK, BV), (1, 0))
136
+ p_hbt = tl.make_block_ptr(hbt + i_nh * V, (V,), (1,), (0,), (BV,), (0,))
137
+ tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
138
+ tl.store(p_hbt, b_hb.to(p_hbt.dtype.element_ty), boundary_check=(0,))
139
+
140
+
141
+ @triton.heuristics({
142
+ 'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
143
+ 'USE_INITIAL_STATE_B': lambda args: args['hb0'] is not None,
144
+ })
145
+ @triton.autotune(
146
+ configs=[
147
+ triton.Config({}, num_warps=1),
148
+ triton.Config({}, num_warps=2),
149
+ triton.Config({}, num_warps=4)
150
+ ],
151
+ key=['BT', 'BK', 'BV'],
152
+ )
153
+ @triton.jit(do_not_specialize=['T'])
154
+ def fused_chunk_ttt_linear_bwd_kernel_h(
155
+ k,
156
+ v,
157
+ v2,
158
+ x,
159
+ y,
160
+ r,
161
+ w,
162
+ b,
163
+ eta,
164
+ h0,
165
+ hb0,
166
+ h,
167
+ do,
168
+ dq,
169
+ scale,
170
+ eps,
171
+ T,
172
+ H: tl.constexpr,
173
+ K: tl.constexpr,
174
+ V: tl.constexpr,
175
+ BT: tl.constexpr,
176
+ BK: tl.constexpr,
177
+ BV: tl.constexpr,
178
+ USE_INITIAL_STATE: tl.constexpr,
179
+ USE_INITIAL_STATE_B: tl.constexpr,
180
+ ):
181
+ i_nh = tl.program_id(0)
182
+ i_n, i_h = i_nh // H, i_nh % H
183
+ bos, _ = i_n * T, i_n * T + T
184
+ NT = tl.cdiv(T, BT)
185
+ boh = i_n * NT
186
+
187
+ o_i = tl.arange(0, BT)
188
+ v_i = tl.arange(0, BV)
189
+ m_A = o_i[:, None] >= o_i[None, :]
190
+ b_w = tl.load(w + i_h * V + v_i, mask=v_i < V, other=0.)
191
+ b_b = tl.load(b + i_h * V + v_i, mask=v_i < V, other=0.)
192
+
193
+ # [BK, BV]
194
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
195
+ # [BV]
196
+ b_hb = tl.zeros([BV], dtype=tl.float32)
197
+ if USE_INITIAL_STATE:
198
+ p_h0 = tl.make_block_ptr(h0 + i_nh * K * V, (K, V), (V, 1), (0, 0), (BK, BV), (1, 0))
199
+ b_h = tl.load(p_h0, boundary_check=(0, 1), padding_option="zero").to(tl.float32)
200
+ if USE_INITIAL_STATE_B:
201
+ p_hb0 = tl.make_block_ptr(hb0 + i_nh * V, (V,), (1,), (0,), (BV,), (0,))
202
+ b_hb = tl.load(p_hb0, boundary_check=(0,), padding_option="zero").to(tl.float32)
203
+
204
+ for i_t in range(NT):
205
+ p_h = tl.make_block_ptr(h+((boh+i_t)*H+i_h)*K*V, (K, V), (V, 1), (0, 0), (BK, BV), (1, 0))
206
+ p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (K, T), (1, H*K), (0, i_t*BT), (BK, BT), (0, 1))
207
+ p_v = tl.make_block_ptr(v+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
208
+ p_v2 = tl.make_block_ptr(v2+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
209
+ p_x = tl.make_block_ptr(x+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
210
+ p_y = tl.make_block_ptr(y+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
211
+ p_r = tl.make_block_ptr(r+bos*H+i_h, (T, 1), (H, 1), (i_t*BT, 0), (BT, 1), (1, 0))
212
+ p_e = tl.make_block_ptr(eta+(bos*H+i_h), (T,), (H,), (i_t*BT,), (BT,), (0,))
213
+ p_dq = tl.make_block_ptr(dq+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT, 0), (BT, BK), (1, 0))
214
+ p_do = tl.make_block_ptr(do+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
215
+ p_e_last = eta+bos*H+i_h + (T-1)*H if i_t == NT-1 else eta+bos*H+i_h + (i_t*BT+BT-1)*H
216
+ tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
217
+ # [BK, BT]
218
+ b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
219
+ # [BT, BV]
220
+ b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
221
+
222
+ b_kh = tl.dot(tl.trans(b_k), b_h.to(b_k.dtype), allow_tf32=False).to(tl.float32) + b_hb[None, :]
223
+ b_kh = tl.where((v_i < V)[None, :], b_kh, 0.)
224
+ mean = tl.sum(b_kh, axis=1, keep_dims=True) / V
225
+ xbar = tl.where((v_i < V)[None, :], b_kh - mean, 0.)
226
+ var = tl.sum(xbar * xbar, axis=1, keep_dims=True) / V
227
+ rstd = 1 / tl.sqrt(var.to(tl.float32) + eps)
228
+ b_kh_hat = (b_kh - mean) * rstd
229
+
230
+ b_v = b_kh_hat.to(b_k.dtype) * b_w[None, :].to(b_k.dtype) + \
231
+ b_b[None, :].to(b_k.dtype) - b_v.to(b_k.dtype) + tl.trans(b_k)
232
+ b_v = tl.where((v_i < V)[None, :], b_v * b_w[None, :].to(b_k.dtype), 0.)
233
+ b_v2 = rstd * (V * b_v - tl.sum(b_v, axis=1, keep_dims=True) - b_kh_hat.to(b_k.dtype)
234
+ * tl.sum(b_v * b_kh_hat.to(b_k.dtype), axis=1, keep_dims=True)) / V
235
+ tl.store(p_x, b_kh_hat.to(p_x.dtype.element_ty), boundary_check=(0, 1))
236
+ tl.store(p_y, b_v.to(p_y.dtype.element_ty), boundary_check=(0, 1))
237
+ tl.store(p_r, rstd.to(p_r.dtype.element_ty), boundary_check=(0, 1))
238
+ tl.store(p_v2, b_v2.to(p_v2.dtype.element_ty), boundary_check=(0, 1))
239
+
240
+ b_e = tl.load(p_e, boundary_check=(0,), padding_option="zero")
241
+ b_do = tl.load(p_do, boundary_check=(0, 1), padding_option="zero")
242
+
243
+ b_v2 = tl.where((v_i < V)[None, :], b_v2, 0.)
244
+ b_ds = tl.dot(b_do, tl.trans(b_v2).to(b_do.dtype))
245
+ b_ds = tl.where(m_A, b_ds, 0)
246
+ b_ds = b_ds.to(b_k.dtype)
247
+ b_dq = tl.dot(b_do, tl.trans(b_h).to(b_do.dtype))
248
+ b_dq -= tl.dot(b_ds, tl.trans(b_k)) * b_e[:, None]
249
+ b_dq *= scale
250
+
251
+ b_e_last = tl.load(p_e_last)
252
+ b_h = b_h - tl.dot(b_e_last * b_k, b_v2.to(b_k.dtype), allow_tf32=False)
253
+ b_hb = b_hb - tl.sum(b_e_last * b_v2.to(b_k.dtype), axis=0)
254
+ b_h = tl.where((v_i < V)[None, :], b_h, 0.)
255
+ b_hb = tl.where((v_i < V), b_hb, 0.)
256
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
257
+
258
+
259
+ @triton.heuristics({
260
+ 'USE_INITIAL_STATE': lambda args: args['dh0'] is not None,
261
+ 'USE_INITIAL_STATE_B': lambda args: args['dhb0'] is not None,
262
+ 'USE_FINAL_STATE_GRADIENT': lambda args: args['dht'] is not None,
263
+ 'USE_FINAL_STATE_GRADIENT_B': lambda args: args['dhbt'] is not None,
264
+ })
265
+ @triton.autotune(
266
+ configs=[
267
+ triton.Config({}, num_warps=num_warps)
268
+ for num_warps in NUM_WARPS
269
+ ],
270
+ key=['BT', 'BK', 'BV'],
271
+ )
272
+ @triton.jit(do_not_specialize=['T'])
273
+ def fused_chunk_ttt_linear_bwd_kernel_dh(
274
+ q,
275
+ k,
276
+ v,
277
+ v2,
278
+ x,
279
+ y,
280
+ r,
281
+ w,
282
+ b,
283
+ eta,
284
+ h,
285
+ dht,
286
+ dhbt,
287
+ dh0,
288
+ dhb0,
289
+ do,
290
+ dk,
291
+ dv,
292
+ de,
293
+ dw,
294
+ db,
295
+ scale,
296
+ T,
297
+ H: tl.constexpr,
298
+ K: tl.constexpr,
299
+ V: tl.constexpr,
300
+ BT: tl.constexpr,
301
+ BK: tl.constexpr,
302
+ BV: tl.constexpr,
303
+ USE_INITIAL_STATE: tl.constexpr,
304
+ USE_INITIAL_STATE_B: tl.constexpr,
305
+ USE_FINAL_STATE_GRADIENT: tl.constexpr,
306
+ USE_FINAL_STATE_GRADIENT_B: tl.constexpr,
307
+ ):
308
+ i_nh = tl.program_id(0)
309
+ i_n, i_h = i_nh // H, i_nh % H
310
+ bos, _ = i_n * T, i_n * T + T
311
+ NT = tl.cdiv(T, BT)
312
+ boh = i_n * NT
313
+
314
+ # [BK, BV]
315
+ b_dh = tl.zeros([BK, BV], dtype=tl.float32)
316
+ # [BV]
317
+ b_dhb = tl.zeros([BV], dtype=tl.float32)
318
+ if USE_FINAL_STATE_GRADIENT:
319
+ p_dht = tl.make_block_ptr(dht + i_nh * K*V, (K, V), (V, 1), (0, 0), (BK, BV), (1, 0))
320
+ b_dh += tl.load(p_dht, boundary_check=(0, 1), padding_option="zero")
321
+ if USE_FINAL_STATE_GRADIENT_B:
322
+ p_dhbt = tl.make_block_ptr(dhbt + i_nh * V, (V,), (1,), (0,), (BV,), (0,))
323
+ b_dhb += tl.load(p_dhbt, boundary_check=(0,), padding_option="zero")
324
+
325
+ # [BV]
326
+ o_i = tl.arange(0, BT)
327
+ v_i = tl.arange(0, BV)
328
+ m_A = o_i[:, None] >= o_i[None, :]
329
+ m_A_t = o_i[:, None] <= o_i[None, :]
330
+ b_w = tl.load(w + i_h * V + v_i, mask=v_i < V, other=0.)
331
+ b_b = tl.load(b + i_h * V + v_i, mask=v_i < V, other=0.)
332
+ b_dw = tl.zeros([BV,], dtype=b_w.dtype)
333
+ b_db = tl.zeros([BV,], dtype=b_b.dtype)
334
+ p_dw = tl.make_block_ptr(dw + i_nh * V, (V,), (1,), (0,), (BV,), (0,))
335
+ p_db = tl.make_block_ptr(db + i_nh * V, (V,), (1,), (0,), (BV,), (0,))
336
+
337
+ for i_t in range(NT - 1, -1, -1):
338
+ p_h = tl.make_block_ptr(h+((boh+i_t)*H+i_h)*K*V, (V, K), (1, V), (0, 0), (BV, BK), (0, 1))
339
+ p_q = tl.make_block_ptr(q+(bos*H+i_h)*K, (K, T), (1, H*K), (0, i_t*BT), (BK, BT), (0, 1))
340
+ p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT, 0), (BT, BK), (1, 0))
341
+ p_v = tl.make_block_ptr(v+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
342
+ p_v2 = tl.make_block_ptr(v2+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
343
+ p_x = tl.make_block_ptr(x+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
344
+ p_y = tl.make_block_ptr(y+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
345
+ p_r = tl.make_block_ptr(r+bos*H+i_h, (T, 1), (H, 1), (i_t*BT, 0), (BT, 1), (1, 0))
346
+ p_e = tl.make_block_ptr(eta+(bos*H+i_h), (T,), (H,), (i_t*BT,), (BT,), (0,))
347
+ p_dv = tl.make_block_ptr(dv+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
348
+ p_dk = tl.make_block_ptr(dk+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT, 0), (BT, BK), (1, 0))
349
+ p_do = tl.make_block_ptr(do+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, 0), (BT, BV), (1, 0))
350
+ p_de = tl.make_block_ptr(de+(bos*H+i_h), (T,), (H,), (i_t*BT,), (BT,), (0,))
351
+ p_e_last = eta+bos*H+i_h + (T-1)*H if i_t == NT-1 else eta+bos*H+i_h + (i_t*BT+BT-1)*H
352
+ b_q = tl.load(p_q, boundary_check=(0, 1), padding_option="zero")
353
+ b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
354
+ b_e = tl.load(p_e, boundary_check=(0,), padding_option="zero")
355
+ b_do = tl.load(p_do, boundary_check=(0, 1), padding_option="zero")
356
+ b_e_last = tl.load(p_e_last)
357
+ b_A = tl.dot(b_k, b_q)
358
+ b_A = - tl.where(m_A_t, b_A * scale * b_e[None, :], 0).to(do.dtype.element_ty)
359
+ b_Ae = - tl.where(m_A_t, b_e[None, :], 0).to(do.dtype.element_ty)
360
+ b_dv_new = tl.dot(b_A.to(b_do.dtype), b_do) + tl.dot(b_Ae.to(b_do.dtype), b_do)
361
+ b_dv_new -= tl.dot(b_e_last * b_k, b_dh.to(b_k.dtype))
362
+ b_dv_new -= b_e_last * b_dhb.to(b_k.dtype)[None, :]
363
+
364
+ b_v2 = tl.load(p_v2, boundary_check=(0, 1), padding_option="zero").to(b_k.dtype)
365
+ b_x = tl.load(p_x, boundary_check=(0, 1), padding_option="zero").to(b_k.dtype)
366
+ b_y = tl.load(p_y, boundary_check=(0, 1), padding_option="zero").to(b_k.dtype)
367
+ b_rstd = tl.load(p_r, boundary_check=(0, 1), padding_option="zero").to(tl.float32)
368
+ b_dy = b_rstd * (b_dv_new * V - tl.sum(b_dv_new, axis=1, keep_dims=True) -
369
+ b_x * tl.sum(b_dv_new * b_x, axis=1, keep_dims=True)) / V
370
+ b_dx = -b_rstd * (b_dv_new * tl.sum(b_x * b_y, axis=1, keep_dims=True) +
371
+ b_y * tl.sum(b_dv_new * b_x, axis=1, keep_dims=True)) / V
372
+ b_drstd = tl.sum(b_dv_new.to(b_rstd.dtype) * b_v2.to(b_rstd.dtype) / b_rstd, axis=1, keep_dims=True)
373
+
374
+ b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
375
+ b_w = b_w.to(b_k.dtype)
376
+ b_b = b_b.to(b_k.dtype)
377
+ b_dv = -b_w * b_dy.to(b_k.dtype)
378
+ b_dk = b_w * b_dy.to(b_k.dtype)
379
+ b_dw += tl.sum(2 * b_w * b_x * b_dy.to(b_k.dtype) +
380
+ (b_b - b_v.to(b_k.dtype) + b_k) * b_dy.to(b_k.dtype), axis=0).to(b_dw.dtype)
381
+ b_db += tl.sum(b_w * b_dy.to(b_k.dtype), axis=0).to(b_db.dtype)
382
+ b_dx = b_dx.to(b_k.dtype) + b_w * b_w * b_dy.to(b_k.dtype)
383
+
384
+ b_h = tl.load(p_h, boundary_check=(0, 1), padding_option="zero")
385
+ b_q = (b_q * scale).to(b_q.dtype)
386
+ b_dkh = b_rstd * (V * b_dx - tl.sum(b_dx, axis=1, keep_dims=True) -
387
+ b_x * tl.sum(b_x * b_dx, axis=1, keep_dims=True)) / V
388
+ b_dkh -= b_rstd * b_rstd * b_drstd * b_x / V
389
+ b_dkh = tl.where((v_i < V)[None, :] * (o_i < T-i_t*BT)[:, None], b_dkh, 0.)
390
+ b_dk += tl.dot(b_dkh, b_h.to(b_dkh.dtype)).to(b_k.dtype)
391
+
392
+ b_ds = tl.dot(b_do, tl.trans(b_v2))
393
+ b_ds = tl.where(m_A, b_ds, 0)
394
+ b_ds = b_ds.to(b_k.dtype)
395
+ i_last = (BT-1) if (i_t*BT+BT) <= T else (T % BT-1)
396
+ mask = (o_i == i_last)
397
+ b_dk -= b_e_last * tl.dot(b_v2, tl.trans(b_dh).to(b_v2.dtype))
398
+ b_dk -= tl.dot(tl.trans(b_ds), tl.trans(b_q) * b_e[:, None])
399
+ b_de = mask * tl.sum(- b_dh * tl.trans(tl.dot(tl.trans(b_v2), b_k))).to(b_k.dtype)
400
+ b_de -= mask * tl.sum(b_dhb * tl.sum(b_v2, axis=0)).to(b_k.dtype)
401
+ b_de -= tl.sum(tl.dot(b_ds, b_k) * tl.trans(b_q).to(b_k.dtype), axis=1)
402
+ b_de -= tl.sum(b_ds, axis=1)
403
+ b_dh += tl.dot(b_q, b_do.to(b_q.dtype)) + tl.dot(tl.trans(b_k).to(b_dkh.dtype), b_dkh)
404
+ b_dhb += tl.sum(b_do + b_dkh, axis=0)
405
+ b_dh = tl.where((v_i < V)[None, :], b_dh, 0.)
406
+ b_dhb = tl.where((v_i < V), b_dhb, 0.)
407
+
408
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
409
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
410
+ tl.store(p_de, b_de.to(p_de.dtype.element_ty), boundary_check=(0,))
411
+ tl.store(p_dw, b_dw.to(p_dw.dtype.element_ty), boundary_check=(0,))
412
+ tl.store(p_db, b_db.to(p_db.dtype.element_ty), boundary_check=(0,))
413
+
414
+ if USE_INITIAL_STATE:
415
+ p_dh0 = tl.make_block_ptr(dh0+i_nh*K*V, (K, V), (V, 1), (0, 0), (BK, BV), (1, 0))
416
+ tl.store(p_dh0, b_dh.to(p_dh0.dtype.element_ty), boundary_check=(0, 1))
417
+ if USE_INITIAL_STATE_B:
418
+ p_dhb0 = tl.make_block_ptr(dhb0+i_nh*V, (V,), (1,), (0,), (BV,), (0,))
419
+ tl.store(p_dhb0, b_dhb.to(p_dhb0.dtype.element_ty), boundary_check=(0,))
420
+
421
+
422
+ def fused_chunk_ttt_linear_bwd_h(
423
+ q: torch.Tensor,
424
+ k: torch.Tensor,
425
+ v: torch.Tensor,
426
+ w: torch.Tensor,
427
+ b: torch.Tensor,
428
+ eta: torch.Tensor,
429
+ scale: float,
430
+ eps: float,
431
+ do: torch.Tensor,
432
+ BT: int = 16,
433
+ initial_state: torch.Tensor = None,
434
+ initial_state_bias: torch.Tensor = None,
435
+ cu_seqlens: Optional[torch.LongTensor] = None,
436
+ ):
437
+ assert cu_seqlens is None, "bwd of varlen is not implemented yet."
438
+ B, T, H, K, V = *k.shape, v.shape[-1]
439
+ # N: the actual number of sequences in the batch with either equal or variable lengths
440
+ N, NT = B, triton.cdiv(T, BT)
441
+ BK, BV = max(triton.next_power_of_2(K), 16), max(triton.next_power_of_2(V), 16)
442
+ assert max(BK, BV) <= 128, "current kernel does not support head dimension larger than 128."
443
+
444
+ h = k.new_empty(B, NT, H, K, V)
445
+ r = v.new_empty(B, T, H, 1, dtype=torch.float32)
446
+ v2 = torch.empty_like(v)
447
+ x = torch.empty_like(v)
448
+ y = torch.empty_like(v)
449
+ dq = torch.empty_like(q)
450
+
451
+ grid = (N * H,)
452
+ fused_chunk_ttt_linear_bwd_kernel_h[grid](
453
+ k=k,
454
+ v=v,
455
+ v2=v2,
456
+ x=x,
457
+ y=y,
458
+ r=r,
459
+ w=w,
460
+ b=b,
461
+ eta=eta,
462
+ h0=initial_state,
463
+ hb0=initial_state_bias,
464
+ h=h,
465
+ do=do,
466
+ dq=dq,
467
+ scale=scale,
468
+ eps=eps,
469
+ T=T,
470
+ H=H,
471
+ K=K,
472
+ V=V,
473
+ BT=BT,
474
+ BK=BK,
475
+ BV=BV,
476
+ )
477
+ return dq, h, v2, x, y, r
478
+
479
+
480
+ def fused_chunk_ttt_linear_bwd_dh(
481
+ q: torch.Tensor,
482
+ k: torch.Tensor,
483
+ v: torch.Tensor,
484
+ v2: torch.Tensor,
485
+ x: torch.Tensor,
486
+ y: torch.Tensor,
487
+ r: torch.Tensor,
488
+ w: torch.Tensor,
489
+ b: torch.Tensor,
490
+ eta: torch.Tensor,
491
+ scale: float,
492
+ h: torch.Tensor,
493
+ do: torch.Tensor,
494
+ dht: torch.Tensor,
495
+ dhbt: torch.Tensor,
496
+ BT: int = 16,
497
+ initial_state: torch.Tensor = None,
498
+ initial_state_bias: torch.Tensor = None,
499
+ cu_seqlens: Optional[torch.LongTensor] = None,
500
+ ):
501
+ assert cu_seqlens is None, "bwd of varlen is not implemented yet."
502
+ B, T, H, K, V = *k.shape, v.shape[-1]
503
+ # N: the actual number of sequences in the batch with either equal or variable lengths
504
+ N = B
505
+ BK, BV = max(triton.next_power_of_2(K), 16), max(triton.next_power_of_2(V), 16)
506
+ assert max(BK, BV) <= 128, "current kernel does not support head dimension larger than 128."
507
+
508
+ dh0 = torch.empty_like(initial_state, dtype=torch.float32) if initial_state is not None else None
509
+ dhb0 = torch.empty_like(initial_state_bias, dtype=torch.float32) if initial_state_bias is not None else None
510
+ dk = torch.empty_like(k)
511
+ dv = torch.empty_like(v)
512
+ de = torch.empty_like(eta)
513
+ dw = w.new_empty(B, H, V)
514
+ db = b.new_empty(B, H, V)
515
+
516
+ grid = (N * H,)
517
+ fused_chunk_ttt_linear_bwd_kernel_dh[grid](
518
+ q=q,
519
+ k=k,
520
+ v=v,
521
+ v2=v2,
522
+ x=x,
523
+ y=y,
524
+ r=r,
525
+ w=w,
526
+ b=b,
527
+ eta=eta,
528
+ h=h,
529
+ dht=dht,
530
+ dhbt=dhbt,
531
+ dh0=dh0,
532
+ dhb0=dhb0,
533
+ do=do,
534
+ dk=dk,
535
+ dv=dv,
536
+ de=de,
537
+ dw=dw,
538
+ db=db,
539
+ scale=scale,
540
+ T=T,
541
+ H=H,
542
+ K=K,
543
+ V=V,
544
+ BT=BT,
545
+ BK=BK,
546
+ BV=BV,
547
+ )
548
+ dw = dw.sum(dim=0)
549
+ db = db.sum(dim=0)
550
+ return dk, dv, de, dw, db, dh0, dhb0
551
+
552
+
553
+ def fused_chunk_ttt_linear_fwd(
554
+ q: torch.Tensor,
555
+ k: torch.Tensor,
556
+ v: torch.Tensor,
557
+ w: torch.Tensor,
558
+ b: torch.Tensor,
559
+ eta: torch.Tensor,
560
+ scale: float,
561
+ eps: float,
562
+ initial_state: torch.Tensor,
563
+ initial_state_bias: torch.Tensor,
564
+ output_final_state: bool,
565
+ cu_seqlens: Optional[torch.LongTensor] = None,
566
+ BT: int = 16
567
+ ):
568
+ B, T, H, K, V = *k.shape, v.shape[-1]
569
+ # N: the actual number of sequences in the batch with either equal or variable lengths
570
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
571
+ BK, BV = max(triton.next_power_of_2(K), 16), max(triton.next_power_of_2(V), 16)
572
+ assert max(BK, BV) <= 128, "current kernel does not support head dimension larger than 128."
573
+ o = torch.empty_like(v)
574
+ final_state = k.new_empty(N, H, K, V, dtype=torch.float32) if output_final_state else None
575
+ final_state_bias = k.new_empty(N, H, 1, V, dtype=torch.float32) if output_final_state else None
576
+
577
+ grid = (N * H,)
578
+ fused_chunk_ttt_linear_fwd_kernel[grid](
579
+ q=q,
580
+ k=k,
581
+ v=v,
582
+ eta=eta,
583
+ w=w,
584
+ b=b,
585
+ o=o,
586
+ scale=scale,
587
+ eps=eps,
588
+ h0=initial_state,
589
+ hb0=initial_state_bias,
590
+ ht=final_state,
591
+ hbt=final_state_bias,
592
+ cu_seqlens=cu_seqlens,
593
+ T=T,
594
+ H=H,
595
+ K=K,
596
+ V=V,
597
+ BT=BT,
598
+ BK=BK,
599
+ BV=BV,
600
+ )
601
+ return o, final_state, final_state_bias
602
+
603
+
604
+ def fused_chunk_ttt_linear_bwd(
605
+ q: torch.Tensor,
606
+ k: torch.Tensor,
607
+ v: torch.Tensor,
608
+ w: torch.Tensor,
609
+ b: torch.Tensor,
610
+ eta: torch.Tensor,
611
+ scale: float,
612
+ eps: float,
613
+ do: torch.Tensor,
614
+ dht: torch.Tensor,
615
+ dhbt: torch.Tensor,
616
+ BT: int = 16,
617
+ initial_state: torch.Tensor = None,
618
+ initial_state_bias: torch.Tensor = None,
619
+ cu_seqlens: Optional[torch.LongTensor] = None,
620
+ ):
621
+ assert cu_seqlens is None, "bwd of varlen is not implemented yet."
622
+ dq, h, v2, x, y, rstd = fused_chunk_ttt_linear_bwd_h(
623
+ q=q,
624
+ k=k,
625
+ v=v,
626
+ w=w,
627
+ b=b,
628
+ eta=eta,
629
+ scale=scale,
630
+ eps=eps,
631
+ do=do,
632
+ BT=BT,
633
+ initial_state=initial_state,
634
+ initial_state_bias=initial_state_bias,
635
+ cu_seqlens=cu_seqlens,
636
+ )
637
+ dk, dv, de, dw, db, dh0, dhb0 = fused_chunk_ttt_linear_bwd_dh(
638
+ q=q,
639
+ k=k,
640
+ v=v,
641
+ v2=v2,
642
+ x=x,
643
+ y=y,
644
+ r=rstd,
645
+ w=w,
646
+ b=b,
647
+ eta=eta,
648
+ scale=scale,
649
+ h=h,
650
+ do=do,
651
+ dht=dht,
652
+ dhbt=dhbt,
653
+ BT=BT,
654
+ initial_state=initial_state,
655
+ initial_state_bias=initial_state_bias,
656
+ cu_seqlens=cu_seqlens,
657
+ )
658
+ return dq, dk, dv, de, dw, db, dh0, dhb0
659
+
660
+
661
+ class FusedChunkTTTLinearFunction(torch.autograd.Function):
662
+
663
+ @staticmethod
664
+ @input_guard
665
+ @autocast_custom_fwd
666
+ def forward(ctx, q, k, v, w, b, BT, eta, scale, eps, initial_state,
667
+ initial_state_bias, output_final_state, cu_seqlens):
668
+ o, final_state, final_state_bias = fused_chunk_ttt_linear_fwd(
669
+ q=q,
670
+ k=k,
671
+ v=v,
672
+ w=w,
673
+ b=b,
674
+ eta=eta,
675
+ scale=scale,
676
+ eps=eps,
677
+ BT=BT,
678
+ initial_state=initial_state,
679
+ initial_state_bias=initial_state_bias,
680
+ output_final_state=output_final_state,
681
+ cu_seqlens=cu_seqlens,
682
+ )
683
+ ctx.save_for_backward(q, k, v, eta, w, b, initial_state, initial_state_bias)
684
+ ctx.BT = BT
685
+ ctx.scale = scale
686
+ ctx.eps = eps
687
+ ctx.cu_seqlens = cu_seqlens
688
+ return o.to(q.dtype), final_state, final_state_bias
689
+
690
+ @staticmethod
691
+ @input_guard
692
+ @autocast_custom_bwd
693
+ def backward(ctx, do, dht, dhbt):
694
+ q, k, v, eta, w, b, initial_state, initial_state_bias = ctx.saved_tensors
695
+ dq, dk, dv, de, dw, db, dh0, dhb0 = fused_chunk_ttt_linear_bwd(
696
+ q=q,
697
+ k=k,
698
+ v=v,
699
+ w=w,
700
+ b=b,
701
+ eta=eta,
702
+ scale=ctx.scale,
703
+ eps=ctx.eps,
704
+ do=do,
705
+ dht=dht,
706
+ dhbt=dhbt,
707
+ BT=ctx.BT,
708
+ initial_state=initial_state,
709
+ initial_state_bias=initial_state_bias,
710
+ cu_seqlens=ctx.cu_seqlens,
711
+ )
712
+ return dq.to(q), dk.to(k), dv.to(v), dw.to(w), db.to(b), None, de.to(eta), None, None, dh0, dhb0, None, None
713
+
714
+
715
+ def norm_residual(x, weight, bias, eps):
716
+ # GroupNorm and Residual
717
+ B, T, H, D = x.shape
718
+ x += group_norm(
719
+ x.reshape(B, T, -1).clone(),
720
+ weight=weight.reshape(-1).clone(),
721
+ bias=bias.reshape(-1).clone(),
722
+ eps=eps,
723
+ num_groups=H,
724
+ ).reshape(x.shape)
725
+ return x
726
+
727
+
728
+ def fused_chunk_ttt_linear(
729
+ q: torch.Tensor,
730
+ k: torch.Tensor,
731
+ v: torch.Tensor,
732
+ w: torch.Tensor,
733
+ b: torch.Tensor,
734
+ eta: torch.Tensor,
735
+ scale: float = None,
736
+ eps: float = 1e-6,
737
+ chunk_size: int = 16,
738
+ initial_state: torch.Tensor = None,
739
+ initial_state_bias: torch.Tensor = None,
740
+ output_final_state: bool = False,
741
+ cu_seqlens: Optional[torch.LongTensor] = None,
742
+ head_first: bool = False,
743
+ ):
744
+ r"""
745
+ Args:
746
+ q (torch.Tensor):
747
+ queries of shape `(B, H, T, K)`
748
+ k (torch.Tensor):
749
+ keys of shape `(B, H, T, K)`
750
+ v (torch.Tensor):
751
+ values of shape `(B, H, T, V)`
752
+ w (torch.Tensor):
753
+ layer norm weight of shape `(H, V)`
754
+ b (torch.Tensor):
755
+ layer norm bias of shape `(H, V)`
756
+ eta (torch.Tensor):
757
+ Learning rate for hidden state, of shape `(B, H, T, 1)`.
758
+ scale (Optional[float]):
759
+ Scale factor for the RetNet attention scores.
760
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
761
+ chunk_size (int):
762
+ chunk size. Default: `16`.
763
+ initial_state (Optional[torch.Tensor]):
764
+ Initial state of shape `(B, H, K, V)`. Default: `None`.
765
+ initial_state_bias (Optional[torch.Tensor]):
766
+ Initial state bias of shape `(B, H, 1, V)`. Default: `None`.
767
+ output_final_state (Optional[bool]):
768
+ Whether to output the final state of shape `(B, H, K, V)`. Default: `False`.
769
+ cu_seqlens (torch.LongTensor):
770
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
771
+ consistent with the FlashAttention API.
772
+ head_first (Optional[bool]):
773
+ Whether the inputs are in the head-first format. Default: `False`.
774
+ This argument has been deprecated.
775
+
776
+ Returns:
777
+ o (torch.Tensor):
778
+ Outputs of shape `[B, H, T, V]`
779
+ final_state (torch.Tensor):
780
+ Final state of shape `[B, H, K, V]` if `output_final_state=True` else `None`.
781
+ final_state_bias (torch.Tensor):
782
+ Final state bias of shape `[B, H, 1, V]` if `output_final_state=True` else `None`.
783
+ """
784
+ assert q.dtype == k.dtype == v.dtype
785
+ assert k.shape[-1] == v.shape[-1], "DK must equal to DV."
786
+ if isinstance(eta, float):
787
+ eta = torch.full_like(q[:, :, :, :1], eta)
788
+ if head_first:
789
+ raise DeprecationWarning(
790
+ "head_first is deprecated and will be removed in a future version. "
791
+ "Please use head_first=False for now instead."
792
+ )
793
+ if not head_first and q.shape[1] < q.shape[2]:
794
+ warnings.warn(
795
+ f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
796
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
797
+ "when head_first=False was specified. "
798
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
799
+ )
800
+ if cu_seqlens is not None:
801
+ if q.shape[0] != 1:
802
+ raise ValueError(
803
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
804
+ f"Please flatten variable-length inputs before processing."
805
+ )
806
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
807
+ raise ValueError(
808
+ f"The number of initial states is expected to be equal to the number of input sequences, "
809
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
810
+ )
811
+ if scale is None:
812
+ scale = k.shape[-1] ** -0.5
813
+ else:
814
+ assert scale > 0, "Scale must be positive."
815
+ o, final_state, final_state_bias = FusedChunkTTTLinearFunction.apply(
816
+ q,
817
+ k,
818
+ v,
819
+ w,
820
+ b,
821
+ chunk_size,
822
+ eta,
823
+ scale,
824
+ eps,
825
+ initial_state,
826
+ initial_state_bias,
827
+ output_final_state,
828
+ cu_seqlens,
829
+ )
830
+ o = norm_residual(o, w, b, eps)
831
+ return o, final_state, final_state_bias