fla-core 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. fla/__init__.py +4 -0
  2. fla/modules/__init__.py +33 -0
  3. fla/modules/activations.py +548 -0
  4. fla/modules/convolution.py +1143 -0
  5. fla/modules/feature_map.py +300 -0
  6. fla/modules/fused_bitlinear.py +632 -0
  7. fla/modules/fused_cross_entropy.py +419 -0
  8. fla/modules/fused_kl_div.py +324 -0
  9. fla/modules/fused_linear_cross_entropy.py +620 -0
  10. fla/modules/fused_norm_gate.py +1253 -0
  11. fla/modules/grpo.py +411 -0
  12. fla/modules/l2norm.py +285 -0
  13. fla/modules/l2warp.py +38 -0
  14. fla/modules/layernorm.py +1433 -0
  15. fla/modules/layernorm_gated.py +528 -0
  16. fla/modules/mlp.py +132 -0
  17. fla/modules/parallel.py +42 -0
  18. fla/modules/rotary.py +500 -0
  19. fla/modules/token_shift.py +543 -0
  20. fla/ops/__init__.py +53 -0
  21. fla/ops/abc/__init__.py +7 -0
  22. fla/ops/abc/chunk.py +1117 -0
  23. fla/ops/abc/naive.py +96 -0
  24. fla/ops/attn/__init__.py +7 -0
  25. fla/ops/attn/decoding.py +182 -0
  26. fla/ops/attn/parallel.py +730 -0
  27. fla/ops/based/__init__.py +9 -0
  28. fla/ops/based/fused_chunk.py +373 -0
  29. fla/ops/based/naive.py +72 -0
  30. fla/ops/based/parallel.py +408 -0
  31. fla/ops/comba/__init__.py +7 -0
  32. fla/ops/comba/chunk.py +342 -0
  33. fla/ops/comba/fused_recurrent.py +332 -0
  34. fla/ops/comba/utils.py +172 -0
  35. fla/ops/comba/wy_fast.py +423 -0
  36. fla/ops/common/__init__.py +1 -0
  37. fla/ops/common/chunk_delta_h.py +527 -0
  38. fla/ops/common/chunk_h.py +384 -0
  39. fla/ops/common/chunk_h_parallel.py +551 -0
  40. fla/ops/common/chunk_h_split.py +596 -0
  41. fla/ops/common/chunk_o.py +681 -0
  42. fla/ops/common/chunk_scaled_dot_kkt.py +305 -0
  43. fla/ops/common/fused_chunk.py +629 -0
  44. fla/ops/common/fused_recurrent.py +567 -0
  45. fla/ops/delta_rule/__init__.py +11 -0
  46. fla/ops/delta_rule/chunk.py +311 -0
  47. fla/ops/delta_rule/fused_chunk.py +6 -0
  48. fla/ops/delta_rule/fused_recurrent.py +535 -0
  49. fla/ops/delta_rule/naive.py +120 -0
  50. fla/ops/delta_rule/parallel.py +403 -0
  51. fla/ops/delta_rule/wy_fast.py +294 -0
  52. fla/ops/forgetting_attn/__init__.py +7 -0
  53. fla/ops/forgetting_attn/parallel.py +64 -0
  54. fla/ops/gated_delta_product/__init__.py +5 -0
  55. fla/ops/gated_delta_product/chunk.py +305 -0
  56. fla/ops/gated_delta_product/chunk_deltaproduct_h.py +502 -0
  57. fla/ops/gated_delta_product/chunk_deltaproduct_o.py +154 -0
  58. fla/ops/gated_delta_product/chunk_ref.py +68 -0
  59. fla/ops/gated_delta_product/naive.py +36 -0
  60. fla/ops/gated_delta_rule/__init__.py +7 -0
  61. fla/ops/gated_delta_rule/chunk.py +340 -0
  62. fla/ops/gated_delta_rule/fused_recurrent.py +351 -0
  63. fla/ops/gated_delta_rule/wy_fast.py +296 -0
  64. fla/ops/generalized_delta_rule/__init__.py +9 -0
  65. fla/ops/generalized_delta_rule/dplr/__init__.py +7 -0
  66. fla/ops/generalized_delta_rule/dplr/chunk.py +362 -0
  67. fla/ops/generalized_delta_rule/dplr/chunk_A_bwd.py +367 -0
  68. fla/ops/generalized_delta_rule/dplr/chunk_A_fwd.py +198 -0
  69. fla/ops/generalized_delta_rule/dplr/chunk_h_bwd.py +175 -0
  70. fla/ops/generalized_delta_rule/dplr/chunk_h_fwd.py +175 -0
  71. fla/ops/generalized_delta_rule/dplr/chunk_o_bwd.py +430 -0
  72. fla/ops/generalized_delta_rule/dplr/chunk_o_fwd.py +125 -0
  73. fla/ops/generalized_delta_rule/dplr/fused_recurrent.py +268 -0
  74. fla/ops/generalized_delta_rule/dplr/naive.py +96 -0
  75. fla/ops/generalized_delta_rule/dplr/wy_fast_bwd.py +164 -0
  76. fla/ops/generalized_delta_rule/dplr/wy_fast_fwd.py +284 -0
  77. fla/ops/generalized_delta_rule/iplr/__init__.py +7 -0
  78. fla/ops/generalized_delta_rule/iplr/chunk.py +492 -0
  79. fla/ops/generalized_delta_rule/iplr/fused_recurrent.py +452 -0
  80. fla/ops/generalized_delta_rule/iplr/naive.py +69 -0
  81. fla/ops/generalized_delta_rule/iplr/wy_fast.py +300 -0
  82. fla/ops/gla/__init__.py +11 -0
  83. fla/ops/gla/chunk.py +1298 -0
  84. fla/ops/gla/fused_chunk.py +642 -0
  85. fla/ops/gla/fused_recurrent.py +111 -0
  86. fla/ops/gla/naive.py +41 -0
  87. fla/ops/gsa/__init__.py +9 -0
  88. fla/ops/gsa/chunk.py +1133 -0
  89. fla/ops/gsa/fused_recurrent.py +536 -0
  90. fla/ops/gsa/naive.py +69 -0
  91. fla/ops/hgrn/__init__.py +9 -0
  92. fla/ops/hgrn/chunk.py +282 -0
  93. fla/ops/hgrn/fused_recurrent.py +308 -0
  94. fla/ops/hgrn/naive.py +63 -0
  95. fla/ops/lightning_attn/__init__.py +9 -0
  96. fla/ops/lightning_attn/chunk.py +84 -0
  97. fla/ops/lightning_attn/fused_recurrent.py +84 -0
  98. fla/ops/linear_attn/__init__.py +11 -0
  99. fla/ops/linear_attn/chunk.py +76 -0
  100. fla/ops/linear_attn/fused_chunk.py +61 -0
  101. fla/ops/linear_attn/fused_recurrent.py +35 -0
  102. fla/ops/linear_attn/naive.py +64 -0
  103. fla/ops/linear_attn/utils.py +10 -0
  104. fla/ops/log_linear_attn/__init__.py +7 -0
  105. fla/ops/log_linear_attn/chunk.py +1904 -0
  106. fla/ops/log_linear_attn/naive.py +50 -0
  107. fla/ops/mesa_net/__init__.py +5 -0
  108. fla/ops/mesa_net/chunk.py +371 -0
  109. fla/ops/mesa_net/chunk_cg_solver_bwd.py +162 -0
  110. fla/ops/mesa_net/chunk_cg_solver_fwd.py +186 -0
  111. fla/ops/mesa_net/chunk_h_fwd.py +170 -0
  112. fla/ops/mesa_net/chunk_h_kk_intra_bwd.py +191 -0
  113. fla/ops/mesa_net/chunk_h_kv_intra_bwd.py +209 -0
  114. fla/ops/mesa_net/chunk_h_kv_intra_bwd_separate.py +300 -0
  115. fla/ops/mesa_net/decoding_one_step.py +175 -0
  116. fla/ops/mesa_net/naive.py +131 -0
  117. fla/ops/nsa/__init__.py +9 -0
  118. fla/ops/nsa/compression.py +536 -0
  119. fla/ops/nsa/naive.py +103 -0
  120. fla/ops/nsa/parallel.py +879 -0
  121. fla/ops/nsa/utils.py +92 -0
  122. fla/ops/path_attn/__init__.py +7 -0
  123. fla/ops/path_attn/cumprod_householder_bwd.py +140 -0
  124. fla/ops/path_attn/cumprod_householder_fwd.py +119 -0
  125. fla/ops/path_attn/intra_chunk_preprocess_bwd.py +140 -0
  126. fla/ops/path_attn/intra_chunk_preprocess_bwd_prepare.py +208 -0
  127. fla/ops/path_attn/intra_chunk_preprocess_fwd.py +168 -0
  128. fla/ops/path_attn/parallel.py +270 -0
  129. fla/ops/path_attn/parallel_path_bwd_inter_dkv.py +189 -0
  130. fla/ops/path_attn/parallel_path_bwd_inter_dqh.py +200 -0
  131. fla/ops/path_attn/parallel_path_bwd_intra.py +172 -0
  132. fla/ops/path_attn/parallel_path_fwd.py +195 -0
  133. fla/ops/path_attn/prepare_k_cache.py +74 -0
  134. fla/ops/path_attn/transform_q.py +108 -0
  135. fla/ops/rebased/__init__.py +7 -0
  136. fla/ops/rebased/naive.py +27 -0
  137. fla/ops/rebased/parallel.py +464 -0
  138. fla/ops/retention/__init__.py +13 -0
  139. fla/ops/retention/chunk.py +77 -0
  140. fla/ops/retention/fused_chunk.py +78 -0
  141. fla/ops/retention/fused_recurrent.py +33 -0
  142. fla/ops/retention/naive.py +15 -0
  143. fla/ops/retention/parallel.py +71 -0
  144. fla/ops/rwkv4/__init__.py +7 -0
  145. fla/ops/rwkv4/fused_recurrent.py +472 -0
  146. fla/ops/rwkv6/__init__.py +9 -0
  147. fla/ops/rwkv6/chunk.py +1300 -0
  148. fla/ops/rwkv6/chunk_naive.py +43 -0
  149. fla/ops/rwkv6/fused_recurrent.py +673 -0
  150. fla/ops/rwkv6/recurrent_naive.py +103 -0
  151. fla/ops/rwkv7/__init__.py +10 -0
  152. fla/ops/rwkv7/channel_mixing.py +323 -0
  153. fla/ops/rwkv7/chunk.py +78 -0
  154. fla/ops/rwkv7/fused_addcmul.py +293 -0
  155. fla/ops/rwkv7/fused_k_update.py +346 -0
  156. fla/ops/rwkv7/fused_recurrent.py +334 -0
  157. fla/ops/rwkv7/gate_output_correction.py +244 -0
  158. fla/ops/simple_gla/__init__.py +13 -0
  159. fla/ops/simple_gla/chunk.py +303 -0
  160. fla/ops/simple_gla/fused_chunk.py +108 -0
  161. fla/ops/simple_gla/fused_recurrent.py +112 -0
  162. fla/ops/simple_gla/naive.py +114 -0
  163. fla/ops/simple_gla/parallel.py +722 -0
  164. fla/ops/titans/__init__.py +7 -0
  165. fla/ops/titans/log_impl.py +153 -0
  166. fla/ops/titans/naive.py +375 -0
  167. fla/ops/ttt/__init__.py +9 -0
  168. fla/ops/ttt/chunk.py +1441 -0
  169. fla/ops/ttt/fused_chunk.py +831 -0
  170. fla/ops/ttt/naive.py +126 -0
  171. fla/ops/utils/__init__.py +58 -0
  172. fla/ops/utils/constant.py +6 -0
  173. fla/ops/utils/cumsum.py +465 -0
  174. fla/ops/utils/index.py +133 -0
  175. fla/ops/utils/logcumsumexp.py +52 -0
  176. fla/ops/utils/logsumexp.py +80 -0
  177. fla/ops/utils/matmul.py +245 -0
  178. fla/ops/utils/op.py +62 -0
  179. fla/ops/utils/pack.py +208 -0
  180. fla/ops/utils/pooling.py +207 -0
  181. fla/ops/utils/softmax.py +106 -0
  182. fla/ops/utils/solve_tril.py +381 -0
  183. fla/utils.py +462 -0
  184. fla_core-0.3.2.dist-info/METADATA +575 -0
  185. fla_core-0.3.2.dist-info/RECORD +188 -0
  186. fla_core-0.3.2.dist-info/WHEEL +5 -0
  187. fla_core-0.3.2.dist-info/licenses/LICENSE +21 -0
  188. fla_core-0.3.2.dist-info/top_level.txt +1 -0
fla/ops/ttt/chunk.py ADDED
@@ -0,0 +1,1441 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang, Yuqi Pan
3
+
4
+ import warnings
5
+ from typing import Optional, Tuple
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ import triton
10
+ import triton.language as tl
11
+
12
+ from fla.modules.layernorm import group_norm
13
+ from fla.ops.utils import prepare_chunk_indices, prepare_chunk_offsets
14
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
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=num_warps)
26
+ for num_warps in [1, 2, 4, 8]
27
+ ],
28
+ key=['BT', 'BK', 'BV']
29
+ )
30
+ @triton.jit(do_not_specialize=['T'])
31
+ def chunk_ttt_linear_fwd_kernel_h(
32
+ k,
33
+ v,
34
+ v_new,
35
+ eta,
36
+ w,
37
+ b,
38
+ eps,
39
+ h,
40
+ hb,
41
+ h0,
42
+ hb0,
43
+ ht,
44
+ hbt,
45
+ cu_seqlens,
46
+ chunk_offsets,
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_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
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
+ boh = tl.load(chunk_offsets + i_n).to(tl.int32)
66
+ else:
67
+ bos, eos = i_n * T, i_n * T + T
68
+ NT = tl.cdiv(T, BT)
69
+ boh = i_n * NT
70
+
71
+ # [BK, BV]
72
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
73
+ # [BV]
74
+ b_hb = tl.zeros([BV], dtype=tl.float32)
75
+ if USE_INITIAL_STATE:
76
+ p_h0 = tl.make_block_ptr(h0 + i_nh * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
77
+ b_h = tl.load(p_h0, boundary_check=(0, 1), padding_option="zero").to(tl.float32)
78
+ if USE_INITIAL_STATE_B:
79
+ p_hb0 = tl.make_block_ptr(hb0 + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
80
+ b_hb = tl.load(p_hb0, boundary_check=(0,), padding_option="zero").to(tl.float32)
81
+
82
+ offs = tl.arange(0, BV)
83
+ b_w = tl.load(w + i_h * V + offs, mask=offs < V, other=0.)
84
+ b_b = tl.load(b + i_h * V + offs, mask=offs < V, other=0.)
85
+
86
+ for i_t in range(NT):
87
+ p_h = tl.make_block_ptr(h + ((boh + i_t) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
88
+ p_hb = tl.make_block_ptr(hb + ((boh + i_t) * H + i_h) * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
89
+ tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
90
+ tl.store(p_hb, b_hb.to(p_hb.dtype.element_ty), boundary_check=(0,))
91
+ p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
92
+ p_v = tl.make_block_ptr(v+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
93
+ p_v_new = tl.make_block_ptr(v_new+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
94
+ p_eta_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
95
+ b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
96
+ b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
97
+
98
+ b_kh = tl.dot(tl.trans(b_k), b_h.to(b_k.dtype), allow_tf32=False).to(tl.float32) + b_hb[None, :]
99
+ b_kh = tl.where((offs < V)[None, :], b_kh, 0.)
100
+ mean = tl.sum(b_kh, axis=1, keep_dims=True) / V
101
+ xbar = tl.where((offs < V)[None, :], b_kh - mean, 0.)
102
+ var = tl.sum(xbar * xbar, axis=1, keep_dims=True) / V
103
+ rstd = 1 / tl.sqrt(var.to(tl.float32) + eps)
104
+ b_kh_hat = (b_kh - mean) * rstd
105
+
106
+ b_v = b_kh_hat.to(b_k.dtype) * b_w[None, :].to(b_k.dtype) + \
107
+ b_b[None, :].to(b_k.dtype) - b_v.to(b_k.dtype) + tl.trans(b_k)
108
+ b_v = tl.where((offs < V)[None, :], b_v * b_w[None, :].to(b_k.dtype), 0.)
109
+ b_v2 = rstd * (V * b_v - tl.sum(b_v, axis=1, keep_dims=True) - b_kh_hat.to(b_k.dtype)
110
+ * tl.sum(b_v * b_kh_hat.to(b_k.dtype), axis=1, keep_dims=True)) / V
111
+ tl.store(p_v_new, b_v2.to(p_v_new.dtype.element_ty), boundary_check=(0, 1))
112
+ b_eta_last = tl.load(p_eta_last)
113
+ b_h = b_h - tl.dot(b_eta_last * b_k, b_v2.to(b_k.dtype), allow_tf32=False)
114
+ b_hb = b_hb - tl.sum(b_eta_last * b_v2.to(b_k.dtype), axis=0)
115
+
116
+ if STORE_FINAL_STATE:
117
+ p_ht = tl.make_block_ptr(ht + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
118
+ p_hbt = tl.make_block_ptr(hbt + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
119
+ tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
120
+ tl.store(p_hbt, b_hb.to(p_hbt.dtype.element_ty), boundary_check=(0,))
121
+
122
+
123
+ @triton.heuristics({
124
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
125
+ })
126
+ @triton.autotune(
127
+ configs=[
128
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
129
+ for num_warps in [2, 4, 8]
130
+ for num_stages in [2, 3]
131
+ ],
132
+ key=['BT'],
133
+ )
134
+ @triton.jit(do_not_specialize=['T'])
135
+ def chunk_ttt_linear_fwd_kernel_o(
136
+ q,
137
+ k,
138
+ v,
139
+ eta,
140
+ h,
141
+ hb,
142
+ o,
143
+ cu_seqlens,
144
+ chunk_indices,
145
+ scale,
146
+ T,
147
+ H: tl.constexpr,
148
+ K: tl.constexpr,
149
+ V: tl.constexpr,
150
+ BT: tl.constexpr,
151
+ BK: tl.constexpr,
152
+ BV: tl.constexpr,
153
+ IS_VARLEN: tl.constexpr,
154
+ ):
155
+ i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
156
+ i_b, i_h = i_bh // H, i_bh % H
157
+
158
+ if IS_VARLEN:
159
+ i_tg = i_t
160
+ 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)
161
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
162
+ T = eos - bos
163
+ NT = tl.cdiv(T, BT)
164
+ else:
165
+ NT = tl.cdiv(T, BT)
166
+ i_tg = i_b * NT + i_t
167
+ bos, eos = i_b * T, i_b * T + T
168
+
169
+ # offset calculation
170
+ q += (bos * H + i_h) * K
171
+ k += (bos * H + i_h) * K
172
+ v += (bos * H + i_h) * V
173
+ eta += bos * H + i_h
174
+ o += (bos * H + i_h) * V
175
+ h += (i_tg * H + i_h) * K * V
176
+ hb += (i_tg * H + i_h) * V
177
+ stride_qk = H*K
178
+ stride_vo = H*V
179
+ stride_eta = H
180
+
181
+ p_q = tl.make_block_ptr(q, (T, K), (stride_qk, 1), (i_t * BT, 0), (BT, BK), (1, 0))
182
+ p_k = tl.make_block_ptr(k, (K, T), (1, stride_qk), (0, i_t * BT), (BK, BT), (0, 1))
183
+ p_eta = tl.make_block_ptr(eta, (T,), (stride_eta,), (i_t * BT,), (BT,), (0,))
184
+ p_h = tl.make_block_ptr(h, (K, V), (V, 1), (0, i_v * BV), (BK, BV), (1, 0))
185
+ p_hb = tl.make_block_ptr(hb, (V,), (1,), (i_v * BV,), (BV,), (0,))
186
+ # [BT, BK]
187
+ b_q = tl.load(p_q, boundary_check=(0, 1), padding_option="zero")
188
+ # [BK, BT]
189
+ b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
190
+ # [BT, 1]
191
+ b_eta = tl.load(p_eta, boundary_check=(0,), padding_option="zero")
192
+ # [BK, BV]
193
+ b_h = tl.load(p_h, boundary_check=(0, 1), padding_option="zero")
194
+ # [BV]
195
+ b_hb = tl.load(p_hb, boundary_check=(0,), padding_option="zero")
196
+ # [BT, BK] @ [BK, BV] -> [BT, BV]
197
+ b_o = tl.dot(b_q, b_h, allow_tf32=False)
198
+ # [BT, BK] @ [BK, BT] -> [BT, BT]
199
+ b_A = tl.dot(b_q, b_k, allow_tf32=False)
200
+
201
+ o_i = tl.arange(0, BT)
202
+ m_A = o_i[:, None] >= o_i[None, :]
203
+ b_A = tl.where(m_A, b_A, 0)
204
+ b_Ae = tl.where(m_A, b_eta[:, None], 0.0)
205
+
206
+ p_v = tl.make_block_ptr(v, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
207
+ p_o = tl.make_block_ptr(o, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
208
+ b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
209
+ b_o = (b_o - tl.dot(b_eta[:, None] * b_A.to(b_v.dtype), b_v, allow_tf32=False)) * scale
210
+ b_o += b_hb[None, :] - tl.dot(b_Ae.to(b_v.dtype), b_v, allow_tf32=False)
211
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
212
+
213
+
214
+ @triton.heuristics({
215
+ 'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
216
+ 'USE_INITIAL_STATE_B': lambda args: args['hb0'] is not None,
217
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
218
+ })
219
+ @triton.autotune(
220
+ configs=[
221
+ triton.Config({}, num_warps=num_warps)
222
+ for num_warps in [1, 2, 4, 8]
223
+ ],
224
+ key=['BT', 'BK', 'BV'],
225
+ )
226
+ @triton.jit(do_not_specialize=['T'])
227
+ def chunk_ttt_linear_bwd_kernel_h(
228
+ k,
229
+ v,
230
+ v_new,
231
+ eta,
232
+ w,
233
+ b,
234
+ eps,
235
+ h,
236
+ h0,
237
+ hb0,
238
+ x,
239
+ y,
240
+ r,
241
+ cu_seqlens,
242
+ chunk_offsets,
243
+ T,
244
+ H: tl.constexpr,
245
+ K: tl.constexpr,
246
+ V: tl.constexpr,
247
+ BT: tl.constexpr,
248
+ BK: tl.constexpr,
249
+ BV: tl.constexpr,
250
+ NT: tl.constexpr,
251
+ USE_INITIAL_STATE: tl.constexpr,
252
+ USE_INITIAL_STATE_B: tl.constexpr,
253
+ IS_VARLEN: tl.constexpr,
254
+ ):
255
+ i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
256
+ i_n, i_h = i_nh // H, i_nh % H
257
+ if IS_VARLEN:
258
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
259
+ T = eos - bos
260
+ NT = tl.cdiv(T, BT)
261
+ boh = tl.load(chunk_offsets + i_n).to(tl.int32)
262
+ else:
263
+ bos, eos = i_n * T, i_n * T + T
264
+ NT = tl.cdiv(T, BT)
265
+ boh = i_n * NT
266
+
267
+ # [BK, BV]
268
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
269
+ # [BV]
270
+ b_hb = tl.zeros([BV], dtype=tl.float32)
271
+ if USE_INITIAL_STATE:
272
+ p_h0 = tl.make_block_ptr(h0 + i_nh * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
273
+ b_h = tl.load(p_h0, boundary_check=(0, 1), padding_option="zero").to(tl.float32)
274
+ if USE_INITIAL_STATE_B:
275
+ p_hb0 = tl.make_block_ptr(hb0 + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
276
+ b_hb = tl.load(p_hb0, boundary_check=(0,), padding_option="zero").to(tl.float32)
277
+
278
+ offs = tl.arange(0, BV)
279
+ b_w = tl.load(w + i_h * V + offs, mask=offs < V, other=0.)
280
+ b_b = tl.load(b + i_h * V + offs, mask=offs < V, other=0.)
281
+
282
+ for i_t in range(NT):
283
+ p_h = tl.make_block_ptr(h + ((boh + i_t) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
284
+ tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
285
+ p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
286
+ p_v = tl.make_block_ptr(v+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
287
+ p_v_new = tl.make_block_ptr(v_new+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
288
+ p_x = tl.make_block_ptr(x+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
289
+ p_y = tl.make_block_ptr(y+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
290
+ p_r = tl.make_block_ptr(r+bos*H+i_h, (T, 1), (H, 1), (i_t*BT, 0), (BT, 1), (1, 0))
291
+ p_eta_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
292
+ b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
293
+ b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
294
+
295
+ b_kh = tl.dot(tl.trans(b_k), b_h.to(b_k.dtype), allow_tf32=False).to(tl.float32) + b_hb[None, :]
296
+ b_kh = tl.where((offs < V)[None, :], b_kh, 0.)
297
+ mean = tl.sum(b_kh, axis=1, keep_dims=True) / V
298
+ xbar = tl.where((offs < V)[None, :], b_kh - mean, 0.)
299
+ var = tl.sum(xbar * xbar, axis=1, keep_dims=True) / V
300
+ rstd = 1 / tl.sqrt(var.to(tl.float32) + eps)
301
+ b_kh_hat = (b_kh - mean) * rstd
302
+
303
+ b_v = b_kh_hat.to(b_k.dtype) * b_w[None, :].to(b_k.dtype) + \
304
+ b_b[None, :].to(b_k.dtype) - b_v.to(b_k.dtype) + tl.trans(b_k)
305
+ b_v = tl.where((offs < V)[None, :], b_v * b_w[None, :].to(b_k.dtype), 0.)
306
+ b_v2 = rstd * (V * b_v - tl.sum(b_v, axis=1, keep_dims=True) - b_kh_hat.to(b_k.dtype)
307
+ * tl.sum(b_v * b_kh_hat.to(b_k.dtype), axis=1, keep_dims=True)) / V
308
+ tl.store(p_x, b_kh_hat.to(p_x.dtype.element_ty), boundary_check=(0, 1))
309
+ tl.store(p_y, b_v.to(p_y.dtype.element_ty), boundary_check=(0, 1))
310
+ tl.store(p_r, rstd.to(p_r.dtype.element_ty), boundary_check=(0, 1))
311
+ tl.store(p_v_new, b_v2.to(p_v_new.dtype.element_ty), boundary_check=(0, 1))
312
+ b_eta_last = tl.load(p_eta_last)
313
+ b_h = b_h - tl.dot(b_eta_last * b_k, b_v2.to(b_k.dtype), allow_tf32=False)
314
+ b_hb = b_hb - tl.sum(b_eta_last * b_v2.to(b_k.dtype), axis=0)
315
+
316
+
317
+ @triton.heuristics({
318
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
319
+ })
320
+ @triton.autotune(
321
+ configs=[
322
+ triton.Config({}, num_warps=num_warps)
323
+ for num_warps in [4]
324
+ ],
325
+ key=['BT', 'BK', 'BV'],
326
+ )
327
+ @triton.jit(do_not_specialize=['T'])
328
+ def chunk_ttt_linear_bwd_kernel_dv_local(
329
+ q,
330
+ k,
331
+ eta,
332
+ do,
333
+ dv,
334
+ cu_seqlens,
335
+ chunk_indices,
336
+ scale,
337
+ T,
338
+ H: tl.constexpr,
339
+ K: tl.constexpr,
340
+ V: tl.constexpr,
341
+ BT: tl.constexpr,
342
+ BK: tl.constexpr,
343
+ BV: tl.constexpr,
344
+ IS_VARLEN: tl.constexpr,
345
+ ):
346
+ i_t, i_bh = tl.program_id(0), tl.program_id(1)
347
+ i_b, i_h = i_bh // H, i_bh % H
348
+ if IS_VARLEN:
349
+ 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)
350
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
351
+ T = eos - bos
352
+ else:
353
+ bos, eos = i_b * T, i_b * T + T
354
+
355
+ # offset calculation
356
+ q += (bos * H + i_h) * K
357
+ k += (bos * H + i_h) * K
358
+ eta += bos * H + i_h
359
+ do += (bos * H + i_h) * V
360
+ dv += (bos * H + i_h) * V
361
+ stride_qk = H*K
362
+ stride_vo = H*V
363
+ stride_eta = H
364
+
365
+ b_A = tl.zeros([BT, BT], dtype=tl.float32)
366
+ for i_k in range(tl.cdiv(K, BK)):
367
+ p_k = tl.make_block_ptr(k, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
368
+ p_q = tl.make_block_ptr(q, (K, T), (1, stride_qk), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
369
+ b_q = tl.load(p_q, boundary_check=(0, 1))
370
+ b_k = tl.load(p_k, boundary_check=(0, 1))
371
+ b_A += tl.dot(b_k, b_q)
372
+
373
+ p_eta = tl.make_block_ptr(eta, (T,), (stride_eta,), (i_t * BT,), (BT,), (0,))
374
+ b_eta = tl.load(p_eta, boundary_check=(0,))
375
+ mask = (tl.arange(0, BT)[:, None] <= tl.arange(0, BT)[None, :])
376
+ b_A = - tl.where(mask, b_A * scale * b_eta[None, :], 0).to(do.dtype.element_ty)
377
+ b_Ae = - tl.where(mask, b_eta[None, :], 0).to(do.dtype.element_ty)
378
+
379
+ for i_v in range(tl.cdiv(V, BV)):
380
+ p_do = tl.make_block_ptr(do, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
381
+ p_dv = tl.make_block_ptr(dv, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
382
+ b_do = tl.load(p_do, boundary_check=(0, 1))
383
+ b_dv = tl.dot(b_A.to(b_do.dtype), b_do) + tl.dot(b_Ae.to(b_do.dtype), b_do)
384
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
385
+
386
+
387
+ @triton.heuristics({
388
+ 'USE_FINAL_STATE_GRADIENT': lambda args: args['dht'] is not None,
389
+ 'USE_FINAL_STATE_GRADIENT_B': lambda args: args['dhbt'] is not None,
390
+ 'USE_INITIAL_STATE': lambda args: args['dh0'] is not None,
391
+ 'USE_INITIAL_STATE_B': lambda args: args['dhb0'] is not None,
392
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
393
+ })
394
+ @triton.autotune(
395
+ configs=[
396
+ triton.Config({}, num_warps=num_warps)
397
+ for num_warps in [2, 4, 8, 16]
398
+ ],
399
+ key=['BT', 'BK', 'BV'],
400
+ )
401
+ @triton.jit(do_not_specialize=['T'])
402
+ def chunk_ttt_linear_bwd_kernel_norm(
403
+ q,
404
+ k,
405
+ v,
406
+ v_new,
407
+ x,
408
+ y,
409
+ r,
410
+ w,
411
+ b,
412
+ eta,
413
+ h,
414
+ dht,
415
+ dhbt,
416
+ dh0,
417
+ dhb0,
418
+ do,
419
+ dh,
420
+ dhb,
421
+ dv,
422
+ dv_new,
423
+ dk,
424
+ dw,
425
+ db,
426
+ cu_seqlens,
427
+ chunk_offsets,
428
+ scale,
429
+ T,
430
+ H: tl.constexpr,
431
+ K: tl.constexpr,
432
+ V: tl.constexpr,
433
+ BT: tl.constexpr,
434
+ BK: tl.constexpr,
435
+ BV: tl.constexpr,
436
+ USE_FINAL_STATE_GRADIENT: tl.constexpr,
437
+ USE_FINAL_STATE_GRADIENT_B: tl.constexpr,
438
+ USE_INITIAL_STATE: tl.constexpr,
439
+ USE_INITIAL_STATE_B: tl.constexpr,
440
+ IS_VARLEN: tl.constexpr,
441
+ ):
442
+ i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
443
+ i_n, i_h = i_nh // H, i_nh % H
444
+ if IS_VARLEN:
445
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
446
+ T = eos - bos
447
+ NT = tl.cdiv(T, BT)
448
+ boh = tl.load(chunk_offsets + i_n).to(tl.int32)
449
+ else:
450
+ bos, eos = i_n * T, i_n * T + T
451
+ NT = tl.cdiv(T, BT)
452
+ boh = i_n * NT
453
+
454
+ # [BK, BV]
455
+ b_dh = tl.zeros([BK, BV], dtype=tl.float32)
456
+ # [BV]
457
+ b_dhb = tl.zeros([BV], dtype=tl.float32)
458
+ if USE_FINAL_STATE_GRADIENT:
459
+ p_dht = tl.make_block_ptr(dht + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
460
+ b_dh += tl.load(p_dht, boundary_check=(0, 1), padding_option="zero")
461
+ if USE_FINAL_STATE_GRADIENT_B:
462
+ p_dhbt = tl.make_block_ptr(dhbt + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
463
+ b_dhb += tl.load(p_dhbt, boundary_check=(0,), padding_option="zero")
464
+
465
+ # [BV]
466
+ offs_v = tl.arange(0, BV)
467
+ offs_t = tl.arange(0, BT)
468
+ b_w = tl.load(w + i_h * V + offs_v, mask=offs_v < V, other=0.)
469
+ b_b = tl.load(b + i_h * V + offs_v, mask=offs_v < V, other=0.)
470
+ b_dw = tl.zeros([BV,], dtype=b_w.dtype)
471
+ b_db = tl.zeros([BV,], dtype=b_b.dtype)
472
+ p_dw = tl.make_block_ptr(dw + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
473
+ p_db = tl.make_block_ptr(db + i_nh * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
474
+
475
+ for i_t in range(NT - 1, -1, -1):
476
+ p_h = tl.make_block_ptr(h + ((boh+i_t) * H + i_h) * K*V, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
477
+ p_dh = tl.make_block_ptr(dh + ((boh+i_t) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
478
+ p_dhb = tl.make_block_ptr(dhb + ((boh+i_t) * H + i_h) * V, (V,), (1,), (i_v * BV,), (BV,), (0,))
479
+ tl.store(p_dh, b_dh.to(p_dh.dtype.element_ty), boundary_check=(0, 1))
480
+ tl.store(p_dhb, b_dhb.to(p_dhb.dtype.element_ty), boundary_check=(0,))
481
+ p_q = tl.make_block_ptr(q+(bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
482
+ p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
483
+ p_v = tl.make_block_ptr(v+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
484
+ p_v_new = tl.make_block_ptr(v_new+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
485
+ p_x = tl.make_block_ptr(x+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
486
+ p_y = tl.make_block_ptr(y+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
487
+ p_dv_new = tl.make_block_ptr(dv_new+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
488
+ p_dv = tl.make_block_ptr(dv+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
489
+ p_dk = tl.make_block_ptr(dk+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT, i_k * BK), (BT, BK), (1, 0))
490
+ p_do = tl.make_block_ptr(do+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT, i_v * BV), (BT, BV), (1, 0))
491
+ p_r = tl.make_block_ptr(r+bos*H+i_h, (T, 1), (H, 1), (i_t*BT, 0), (BT, 1), (1, 0))
492
+ p_eta_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
493
+ b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
494
+ b_dv_new = tl.load(p_dv_new, boundary_check=(0, 1), padding_option="zero").to(b_k.dtype)
495
+ b_eta_last = tl.load(p_eta_last)
496
+ b_dv_new -= tl.dot(b_eta_last * b_k, b_dh.to(b_k.dtype))
497
+ b_dv_new -= b_eta_last * b_dhb.to(b_k.dtype)[None, :]
498
+
499
+ b_v_new = tl.load(p_v_new, boundary_check=(0, 1), padding_option="zero")
500
+ b_x = tl.load(p_x, boundary_check=(0, 1), padding_option="zero").to(b_k.dtype)
501
+ b_y = tl.load(p_y, boundary_check=(0, 1), padding_option="zero").to(b_k.dtype)
502
+ b_rstd = tl.load(p_r, boundary_check=(0, 1), padding_option="zero").to(tl.float32)
503
+ b_dy = b_rstd * (b_dv_new * V - tl.sum(b_dv_new, axis=1, keep_dims=True) -
504
+ b_x * tl.sum(b_dv_new * b_x, axis=1, keep_dims=True)) / V
505
+ b_dx = -b_rstd * (b_dv_new * tl.sum(b_x * b_y, axis=1, keep_dims=True) +
506
+ b_y * tl.sum(b_dv_new * b_x, axis=1, keep_dims=True)) / V
507
+ b_drstd = tl.sum(b_dv_new.to(b_rstd.dtype) * b_v_new.to(b_rstd.dtype) / b_rstd, axis=1, keep_dims=True)
508
+
509
+ b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
510
+ b_w = b_w.to(b_k.dtype)
511
+ b_b = b_b.to(b_k.dtype)
512
+ b_dv = -b_w * b_dy.to(b_k.dtype)
513
+ b_dk = b_w * b_dy.to(b_k.dtype)
514
+ b_dw += tl.sum(2 * b_w * b_x * b_dy.to(b_k.dtype) +
515
+ (b_b - b_v.to(b_k.dtype) + b_k) * b_dy.to(b_k.dtype), axis=0).to(b_dw.dtype)
516
+ b_db += tl.sum(b_w * b_dy.to(b_k.dtype), axis=0).to(b_db.dtype)
517
+ b_dx = b_dx.to(b_k.dtype) + b_w * b_w * b_dy.to(b_k.dtype)
518
+
519
+ # d_rstd, dx --> dkh --> dk, dh
520
+ b_q = tl.load(p_q, boundary_check=(0, 1), padding_option="zero")
521
+ b_h = tl.load(p_h, boundary_check=(0, 1), padding_option="zero")
522
+ b_do = tl.load(p_do, boundary_check=(0, 1), padding_option="zero")
523
+ b_q = (b_q * scale).to(b_q.dtype)
524
+ b_dkh = b_rstd * (V * b_dx - tl.sum(b_dx, axis=1, keep_dims=True) -
525
+ b_x * tl.sum(b_x * b_dx, axis=1, keep_dims=True)) / V
526
+ b_dkh -= b_rstd * b_rstd * b_drstd * b_x / V
527
+ b_dkh = tl.where((offs_v < V)[None, :] * (offs_t < T-i_t*BT)[:, None], b_dkh, 0.)
528
+ b_dk += tl.dot(b_dkh, b_h.to(b_dkh.dtype)).to(b_k.dtype)
529
+ b_dh += tl.dot(b_q, b_do.to(b_q.dtype)) + tl.dot(tl.trans(b_k).to(b_dkh.dtype), b_dkh)
530
+ b_dhb += tl.sum(b_do + b_dkh, axis=0)
531
+ b_dh = tl.where((offs_v < V)[None, :], b_dh, 0.)
532
+ b_dhb = tl.where((offs_v < V), b_dhb, 0.)
533
+
534
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
535
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
536
+ tl.store(p_dw, b_dw.to(p_dw.dtype.element_ty), boundary_check=(0,))
537
+ tl.store(p_db, b_db.to(p_db.dtype.element_ty), boundary_check=(0,))
538
+
539
+ if USE_INITIAL_STATE:
540
+ p_dh0 = tl.make_block_ptr(dh0 + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
541
+ tl.store(p_dh0, b_dh.to(p_dh0.dtype.element_ty), boundary_check=(0, 1))
542
+ if USE_INITIAL_STATE_B:
543
+ p_dhb0 = tl.make_block_ptr(dhb0+i_nh*V, (V,), (1,), (i_v * BV,), (BV,), (0,))
544
+ tl.store(p_dhb0, b_dhb.to(p_dhb0.dtype.element_ty), boundary_check=(0,))
545
+
546
+
547
+ @triton.heuristics({
548
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
549
+ })
550
+ @triton.autotune(
551
+ configs=[
552
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
553
+ for num_warps in [2, 4, 8]
554
+ for num_stages in [2, 3]
555
+ ],
556
+ key=['BT', 'BK', 'BV'],
557
+ )
558
+ @triton.jit(do_not_specialize=['T'])
559
+ def chunk_bwd_kernel_dqke(
560
+ q,
561
+ k,
562
+ v,
563
+ e,
564
+ h,
565
+ do,
566
+ dh,
567
+ dhb,
568
+ dq,
569
+ dk,
570
+ de,
571
+ cu_seqlens,
572
+ chunk_indices,
573
+ scale,
574
+ T,
575
+ B: tl.constexpr,
576
+ H: tl.constexpr,
577
+ K: tl.constexpr,
578
+ V: tl.constexpr,
579
+ BT: tl.constexpr,
580
+ BK: tl.constexpr,
581
+ BV: tl.constexpr,
582
+ IS_VARLEN: tl.constexpr,
583
+ ):
584
+ i_k, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
585
+ i_b, i_h = i_bh // H, i_bh % H
586
+ if IS_VARLEN:
587
+ i_tg = i_t
588
+ 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)
589
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
590
+ T = eos - bos
591
+ NT = tl.cdiv(T, BT)
592
+ else:
593
+ NT = tl.cdiv(T, BT)
594
+ i_tg = i_b * NT + i_t
595
+ bos, eos = i_b * T, i_b * T + T
596
+
597
+ # offset calculation
598
+ v += (bos * H + i_h) * V
599
+ do += (bos * H + i_h) * V
600
+ h += (i_tg * H + i_h) * K * V
601
+ dh += (i_tg * H + i_h) * K * V
602
+ dhb += (i_tg * H + i_h) * V
603
+ q += (bos * H + i_h) * K
604
+ k += (bos * H + i_h) * K
605
+ dq += (bos * H + i_h) * K
606
+ dk += (bos * H + i_h) * K
607
+ e += bos * H + i_h
608
+ de += bos * H + i_h
609
+ stride_qk = H*K
610
+ stride_vo = H*V
611
+ stride_e = H
612
+
613
+ b_dq = tl.zeros([BT, BK], dtype=tl.float32)
614
+ b_dk = tl.zeros([BT, BK], dtype=tl.float32)
615
+ b_ds = tl.zeros([BT, BT], dtype=tl.float32)
616
+ b_de = tl.zeros([BT,], dtype=tl.float32)
617
+
618
+ p_k = tl.make_block_ptr(k, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
619
+ b_k = tl.load(p_k, boundary_check=(0, 1))
620
+ p_e_last = (e + (i_t*BT+BT-1)*stride_e) if (i_t*BT+BT) <= T else (e + (T-1)*stride_e)
621
+ i_last = (BT-1) if (i_t*BT+BT) <= T else (T % BT-1)
622
+ mask = (tl.arange(0, BT) == i_last)
623
+ b_e_last = tl.load(p_e_last)
624
+
625
+ for i_v in range(tl.cdiv(V, BV)):
626
+ p_v = tl.make_block_ptr(v, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
627
+ p_do = tl.make_block_ptr(do, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
628
+ p_h = tl.make_block_ptr(h, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
629
+ p_dh = tl.make_block_ptr(dh, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
630
+ p_dhb = tl.make_block_ptr(dhb, (V,), (1,), (i_v * BV,), (BV,), (0,))
631
+ # [BT, BV]
632
+ b_v = tl.load(p_v, boundary_check=(0, 1))
633
+ b_do = tl.load(p_do, boundary_check=(0, 1))
634
+ # [BV, BK]
635
+ b_h = tl.load(p_h, boundary_check=(0, 1))
636
+ b_dh = tl.load(p_dh, boundary_check=(0, 1))
637
+ # [BV]
638
+ b_dhb = tl.load(p_dhb, boundary_check=(0,))
639
+ # [BT, BV] @ [BV, BT] -> [BT, BT]
640
+ b_ds += tl.dot(b_do, tl.trans(b_v))
641
+ # [BT, BV] @ [BV, BK] -> [BT, BK]
642
+ b_dq += tl.dot(b_do, b_h.to(b_do.dtype))
643
+ # [BT, BV] @ [BV, BK] -> [BT, BK]
644
+ b_dk -= b_e_last * tl.dot(b_v, b_dh.to(b_v.dtype))
645
+ b_de -= mask * tl.sum(tl.trans(b_dh) * tl.dot(tl.trans(b_k), b_v.to(b_k.dtype)))
646
+ b_de -= mask * tl.sum(b_dhb * tl.sum(b_v, axis=0).to(b_k.dtype))
647
+
648
+ o_i = tl.arange(0, BT)
649
+ p_q = tl.make_block_ptr(q, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
650
+ p_e = tl.make_block_ptr(e, (T,), (stride_e,), (i_t * BT,), (BT,), (0,))
651
+ b_q = tl.load(p_q, boundary_check=(0, 1))
652
+ b_e = tl.load(p_e, boundary_check=(0,))
653
+
654
+ p_dq = tl.make_block_ptr(dq, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
655
+ p_dk = tl.make_block_ptr(dk, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
656
+ p_de = tl.make_block_ptr(de, (T,), (stride_e,), (i_t * BT,), (BT,), (0,))
657
+
658
+ b_ds = tl.where(o_i[:, None] >= o_i[None, :], b_ds, 0)
659
+ b_ds = b_ds.to(b_k.dtype)
660
+ b_dq -= tl.dot(b_ds, b_k) * b_e[:, None]
661
+ b_dk -= tl.dot(tl.trans(b_ds), b_q * b_e[:, None]) * scale
662
+ b_de -= tl.sum(scale * tl.dot(b_ds, b_k) * b_q, axis=1)
663
+ b_de -= tl.sum(b_ds, axis=1)
664
+ b_dq *= scale
665
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
666
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
667
+ tl.store(p_de, b_de.to(p_de.dtype.element_ty), boundary_check=(0,))
668
+
669
+
670
+ def chunk_ttt_linear_fwd_h(
671
+ k: torch.Tensor,
672
+ v: torch.Tensor,
673
+ w: torch.Tensor,
674
+ b: torch.Tensor,
675
+ eta: torch.Tensor,
676
+ eps: float,
677
+ initial_state: Optional[torch.Tensor] = None,
678
+ initial_state_bias: Optional[torch.Tensor] = None,
679
+ output_final_state: bool = False,
680
+ cu_seqlens: Optional[torch.LongTensor] = None,
681
+ chunk_size: int = 16,
682
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
683
+ B, T, H, K, V = *k.shape, v.shape[-1]
684
+ BT = chunk_size
685
+
686
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
687
+ # N: the actual number of sequences in the batch with either equal or variable lengths
688
+ if cu_seqlens is None:
689
+ N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
690
+ else:
691
+ N, NT, chunk_offsets = len(cu_seqlens) - 1, len(chunk_indices), prepare_chunk_offsets(cu_seqlens, BT)
692
+ BK = max(triton.next_power_of_2(K), 16)
693
+ BV = max(triton.next_power_of_2(V), 16)
694
+ assert max(BK, BV) <= 128, "current kernel does not support head dimension larger than 128."
695
+ NK = triton.cdiv(K, BK)
696
+ NV = triton.cdiv(V, BV)
697
+ assert NK == 1, 'NK > 1 is not supported because it involves time-consuming synchronization'
698
+ assert NV == 1, 'NV > 1 is not supported by TTT update rule.'
699
+
700
+ h = k.new_empty(B, NT, H, K, V)
701
+ hb = k.new_empty(B, NT, H, 1, V)
702
+ final_state = k.new_empty(N, H, K, V, dtype=torch.float32) if output_final_state else None
703
+ final_state_bias = k.new_empty(N, H, 1, V, dtype=torch.float32) if output_final_state else None
704
+
705
+ v_new = torch.empty_like(v)
706
+ grid = (NK, NV, N * H)
707
+
708
+ chunk_ttt_linear_fwd_kernel_h[grid](
709
+ k=k,
710
+ v=v,
711
+ v_new=v_new,
712
+ eta=eta,
713
+ w=w,
714
+ b=b,
715
+ eps=eps,
716
+ h=h,
717
+ hb=hb,
718
+ h0=initial_state,
719
+ hb0=initial_state_bias,
720
+ ht=final_state,
721
+ hbt=final_state_bias,
722
+ cu_seqlens=cu_seqlens,
723
+ chunk_offsets=chunk_offsets,
724
+ T=T,
725
+ H=H,
726
+ K=K,
727
+ V=V,
728
+ BT=BT,
729
+ BK=BK,
730
+ BV=BV,
731
+ )
732
+ return h, hb, v_new, final_state, final_state_bias
733
+
734
+
735
+ def chunk_ttt_linear_fwd_o(
736
+ q: torch.Tensor,
737
+ k: torch.Tensor,
738
+ v: torch.Tensor,
739
+ eta: torch.Tensor,
740
+ h: torch.Tensor,
741
+ hb: torch.Tensor,
742
+ scale: Optional[float] = None,
743
+ cu_seqlens: Optional[torch.LongTensor] = None,
744
+ chunk_size: int = 64
745
+ ) -> torch.Tensor:
746
+ B, T, H, K, V = *q.shape, v.shape[-1]
747
+ if scale is None:
748
+ scale = k.shape[-1] ** -0.5
749
+ BT = chunk_size
750
+
751
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
752
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
753
+ BK = max(triton.next_power_of_2(K), 16)
754
+ BV = max(triton.next_power_of_2(V), 16)
755
+ NK = triton.cdiv(K, BK)
756
+ NV = triton.cdiv(V, BV)
757
+ assert NK == 1, 'NK > 1 is not supported because it involves time-consuming synchronization'
758
+ assert NV == 1, 'NV > 1 is not supported by TTT update rule.'
759
+
760
+ o = torch.empty_like(v)
761
+
762
+ grid = (NV, NT, B * H)
763
+ chunk_ttt_linear_fwd_kernel_o[grid](
764
+ q,
765
+ k,
766
+ v,
767
+ eta,
768
+ h,
769
+ hb,
770
+ o,
771
+ cu_seqlens,
772
+ chunk_indices,
773
+ scale,
774
+ T=T,
775
+ H=H,
776
+ K=K,
777
+ V=V,
778
+ BT=BT,
779
+ BK=BK,
780
+ BV=BV,
781
+ )
782
+ return o
783
+
784
+
785
+ def chunk_ttt_linear_bwd_h(
786
+ k: torch.Tensor,
787
+ v: torch.Tensor,
788
+ w: torch.Tensor,
789
+ b: torch.Tensor,
790
+ eta: torch.Tensor,
791
+ eps: float,
792
+ initial_state: Optional[torch.Tensor] = None,
793
+ initial_state_bias: Optional[torch.Tensor] = None,
794
+ cu_seqlens: Optional[torch.LongTensor] = None,
795
+ chunk_size: int = 16,
796
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
797
+ B, T, H, K, V = *k.shape, v.shape[-1]
798
+ BT = chunk_size
799
+
800
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
801
+ # N: the actual number of sequences in the batch with either equal or variable lengths
802
+ if cu_seqlens is None:
803
+ N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
804
+ else:
805
+ N, NT, chunk_offsets = len(cu_seqlens) - 1, len(chunk_indices), prepare_chunk_offsets(cu_seqlens, BT)
806
+ BK = max(triton.next_power_of_2(K), 16)
807
+ BV = max(triton.next_power_of_2(V), 16)
808
+ assert max(BK, BV) <= 128, "current kernel does not support head dimension larger than 128."
809
+ NK = triton.cdiv(K, BK)
810
+ NV = triton.cdiv(V, BV)
811
+ assert NK == 1, 'NK > 1 is not supported because it involves time-consuming synchronization'
812
+ assert NV == 1, 'NV > 1 is not supported by TTT update rule.'
813
+
814
+ h = k.new_empty(B, NT, H, K, V)
815
+ rstd = v.new_empty(B, T, H, 1, dtype=torch.float32)
816
+ x = torch.empty_like(v)
817
+ y = torch.empty_like(v)
818
+
819
+ v_new = torch.empty_like(v)
820
+ grid = (NK, NV, N * H)
821
+
822
+ chunk_ttt_linear_bwd_kernel_h[grid](
823
+ k=k,
824
+ v=v,
825
+ v_new=v_new,
826
+ eta=eta,
827
+ w=w,
828
+ b=b,
829
+ eps=eps,
830
+ h=h,
831
+ h0=initial_state,
832
+ hb0=initial_state_bias,
833
+ x=x,
834
+ y=y,
835
+ r=rstd,
836
+ cu_seqlens=cu_seqlens,
837
+ chunk_offsets=chunk_offsets,
838
+ T=T,
839
+ H=H,
840
+ K=K,
841
+ V=V,
842
+ BT=BT,
843
+ BK=BK,
844
+ BV=BV,
845
+ NT=NT,
846
+ )
847
+ return h, v_new, x, y, rstd
848
+
849
+
850
+ def chunk_ttt_linear_bwd_dv_local(
851
+ q: torch.Tensor,
852
+ k: torch.Tensor,
853
+ eta: torch.Tensor,
854
+ do: torch.Tensor,
855
+ scale: float,
856
+ cu_seqlens: Optional[torch.LongTensor] = None,
857
+ chunk_size: int = 16
858
+ ) -> torch.Tensor:
859
+ B, T, H, K, V = *k.shape, do.shape[-1]
860
+ BT = chunk_size
861
+
862
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
863
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
864
+ BK = min(max(triton.next_power_of_2(K), 16), 128)
865
+ BV = min(max(triton.next_power_of_2(V), 16), 128)
866
+
867
+ dv = torch.empty_like(do)
868
+ grid = (NT, B * H)
869
+ chunk_ttt_linear_bwd_kernel_dv_local[grid](
870
+ q,
871
+ k,
872
+ eta,
873
+ do,
874
+ dv,
875
+ cu_seqlens,
876
+ chunk_indices,
877
+ scale,
878
+ T=T,
879
+ H=H,
880
+ K=K,
881
+ V=V,
882
+ BT=BT,
883
+ BK=BK,
884
+ BV=BV,
885
+ )
886
+ return dv
887
+
888
+
889
+ def chunk_ttt_linear_bwd_norm(
890
+ q: torch.Tensor, # [B, H, L, D]
891
+ k: torch.Tensor, # [B, H, L, D]
892
+ v: torch.Tensor, # [B, H, L, D]
893
+ v_new: torch.Tensor, # [B, H, L, D]
894
+ x: torch.Tensor, # [B, H, L, D]
895
+ y: torch.Tensor, # [B, H, L, D]
896
+ rstd: torch.Tensor, # [B, H, L, 1]
897
+ w: torch.Tensor, # [H, D]
898
+ b: torch.Tensor, # [H, D]
899
+ eta: torch.Tensor, # [B, H, L, 1]
900
+ h0: torch.Tensor, # [B, H, D, D]
901
+ hb0: torch.Tensor, # [B, H, 1, D]
902
+ h: torch.Tensor, # [B, H, NT, D, D]
903
+ dht: Optional[torch.Tensor], # [B, H, D, D]
904
+ dhbt: Optional[torch.Tensor], # [B, H, 1, D]
905
+ dv_new: Optional[torch.Tensor], # [B, H, L, D]
906
+ do: torch.Tensor, # [B, H, L, D]
907
+ scale: float,
908
+ cu_seqlens: Optional[torch.LongTensor] = None,
909
+ chunk_size: int = 16
910
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
911
+ # torch implementation of `dkh, dw, db, dk, dv` for LN^2
912
+ assert cu_seqlens is None, "bwd of varlen is not implemented yet."
913
+ B, T, H, K, V = *q.shape, do.shape[-1]
914
+ BT = chunk_size
915
+
916
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
917
+ if cu_seqlens is None:
918
+ N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
919
+ else:
920
+ N, NT, chunk_offsets = len(cu_seqlens) - 1, len(chunk_indices), prepare_chunk_offsets(cu_seqlens, BT)
921
+
922
+ BK = max(triton.next_power_of_2(K), 16)
923
+ BV = max(triton.next_power_of_2(V), 16)
924
+ NK = triton.cdiv(K, BK)
925
+ NV = triton.cdiv(V, BV)
926
+ assert NK == 1, 'NK > 1 is not supported by TTT.'
927
+ assert NV == 1, 'NV > 1 is not supported by TTT.'
928
+
929
+ dh = q.new_empty(B, NT, H, K, V)
930
+ dhb = q.new_empty(B, NT, H, 1, V)
931
+ dh0 = torch.empty_like(h0, dtype=torch.float32) if h0 is not None else None
932
+ dhb0 = torch.empty_like(hb0, dtype=torch.float32) if hb0 is not None else None
933
+ dv = torch.empty_like(v)
934
+ dk = torch.empty_like(k)
935
+ dw = w.new_empty(B, H, V)
936
+ db = b.new_empty(B, H, V)
937
+
938
+ grid = (NK, NV, N * H)
939
+ chunk_ttt_linear_bwd_kernel_norm[grid](
940
+ q=q,
941
+ k=k,
942
+ v=v,
943
+ v_new=v_new,
944
+ x=x,
945
+ y=y,
946
+ r=rstd,
947
+ w=w,
948
+ b=b,
949
+ eta=eta,
950
+ h=h,
951
+ dht=dht,
952
+ dhbt=dhbt,
953
+ dh0=dh0,
954
+ dhb0=dhb0,
955
+ do=do,
956
+ dh=dh,
957
+ dhb=dhb,
958
+ dv=dv,
959
+ dv_new=dv_new,
960
+ dk=dk,
961
+ dw=dw,
962
+ db=db,
963
+ cu_seqlens=cu_seqlens,
964
+ chunk_offsets=chunk_offsets,
965
+ scale=scale,
966
+ T=T,
967
+ H=H,
968
+ K=K,
969
+ V=V,
970
+ BT=BT,
971
+ BK=BK,
972
+ BV=BV,
973
+ )
974
+ dw = dw.sum(dim=0)
975
+ db = db.sum(dim=0)
976
+ return dh, dhb, dh0, dhb0, dv, dk, dw, db
977
+
978
+
979
+ def chunk_ttt_linear_bwd_norm_ref(
980
+ q: torch.Tensor, # [B, H, L, D]
981
+ k: torch.Tensor, # [B, H, L, D]
982
+ v: torch.Tensor, # [B, H, L, D]
983
+ v_new: torch.Tensor, # [B, H, L, D]
984
+ kh: torch.Tensor, # [B, H, L, D]
985
+ y: torch.Tensor, # [B, H, L, D]
986
+ w: torch.Tensor, # [H, D]
987
+ b: torch.Tensor, # [H, D]
988
+ eta: torch.Tensor, # [B, H, L, 1]
989
+ h0: torch.Tensor, # [B, H, D, D]
990
+ h: torch.Tensor, # [B, H, NT, D, D]
991
+ dht: Optional[torch.Tensor], # [B, H, D, D]
992
+ dv_new: Optional[torch.Tensor], # [B, H, L, D]
993
+ do: torch.Tensor, # [B, H, L, D]
994
+ scale: float,
995
+ eps: float,
996
+ cu_seqlens: Optional[torch.LongTensor] = None,
997
+ chunk_size: int = 16
998
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
999
+ # torch implementation of `dkh, dw, db, dk, dv` for LN^2
1000
+ assert cu_seqlens is None, "bwd of varlen is not implemented yet."
1001
+ B, T, H, K, V = *q.shape, do.shape[-1]
1002
+ # [B, L, H, D] -> [B, H, L, D]
1003
+ q, k, v, v_new, kh, y, h, eta, dv_new, do = [
1004
+ x.transpose(1, 2) for x in
1005
+ [q, k, v, v_new, kh, y, h, eta, dv_new, do]
1006
+ ]
1007
+ BT = chunk_size
1008
+
1009
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
1010
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
1011
+ pad_len = (BT - (T % BT)) % BT
1012
+ if pad_len > 0:
1013
+ q, k, v, v_new, kh, y, eta, dv_new, do = [
1014
+ F.pad(x, (0, 0, 0, pad_len)) for x in
1015
+ [q, k, v, v_new, kh, y, eta, dv_new, do]
1016
+ ]
1017
+ eta[:, :, -1, :] = eta[:, :, -(pad_len+1), :]
1018
+ # [NT, B, H, BT, D]
1019
+ q, k, v, v_new, kh, y, eta, dv_new, do = [
1020
+ x.reshape(B, H, NT, BT, -1).permute(2, 0, 1, 3, 4) for x in
1021
+ [q, k, v, v_new, kh, y, eta, dv_new, do]
1022
+ ]
1023
+ h = h.permute(2, 0, 1, 3, 4)
1024
+
1025
+ # allocate
1026
+ dh = q.new_zeros(NT, B, H, K, V)
1027
+ dv = torch.zeros_like(v)
1028
+ dk = torch.zeros_like(k)
1029
+ dw = torch.zeros_like(w)
1030
+ db = torch.zeros_like(b)
1031
+ # recurrent state
1032
+ b_dh = dht if dht is not None else torch.zeros_like(dh[0])
1033
+ b_dh = b_dh.to(torch.float32)
1034
+
1035
+ # [H, 1, D]
1036
+ _w = w.reshape(H, 1, V).to(torch.float32)
1037
+ _b = b.reshape(H, 1, V).to(torch.float32)
1038
+
1039
+ # d_state passing
1040
+ for i_t in range(NT - 1, -1, -1):
1041
+ dh[i_t] = b_dh.to(dh.dtype)
1042
+ # [B, H, BT, D]
1043
+ _q, _k, _v, _v_new, _kh, _y, _h, _eta, _dv_new, _do = [
1044
+ x[i_t].to(torch.float32) for x in
1045
+ (q, k, v, v_new, kh, y, h, eta, dv_new, do)
1046
+ ]
1047
+ _dv_new -= (_eta[:, :, -1, :, None] * _k) @ b_dh
1048
+
1049
+ mean = _kh.mean(dim=-1, keepdim=True)
1050
+ var = _kh.var(dim=-1, unbiased=False, keepdim=True).to(torch.float32)
1051
+ rstd = 1 / torch.sqrt(var + eps).to(torch.float32)
1052
+ x = (_kh - mean) * rstd
1053
+ # [B, H, BT, D]
1054
+ dy = rstd * (_dv_new*V - _dv_new.sum(dim=-1, keepdim=True) - x*(x*_dv_new).sum(dim=-1, keepdim=True)) / V
1055
+ dx = -rstd * (_dv_new*(x*_y).sum(dim=-1, keepdim=True) + _y*(x*_dv_new).sum(dim=-1, keepdim=True)) / V
1056
+ d_rstd = (_dv_new * _v_new / rstd).sum(dim=-1, keepdim=True)
1057
+
1058
+ dv[i_t] = (-_w*dy).to(dv.dtype)
1059
+ dk[i_t] += (_w*dy).to(dk.dtype)
1060
+ dw += (2*_w*x*dy+(_b-_v+_k)*dy).sum(dim=(0, 2)).to(dw.dtype)
1061
+ db += (_w*dy).sum(dim=(0, 2)).to(db.dtype)
1062
+ dx += _w*_w*dy
1063
+
1064
+ # d_rstd, dx --> dkh --> dk, dh
1065
+ dkh = rstd * (V * dx - dx.sum(dim=-1, keepdim=True) - x * (x * dx).sum(dim=-1, keepdim=True)) / V
1066
+ dkh -= rstd**2 * d_rstd * x / V
1067
+ dk[i_t] += (dkh @ _h.transpose(-2, -1)).to(dk.dtype)
1068
+ b_dh += (_q.transpose(-2, -1) * scale) @ _do + _k.transpose(-2, -1) @ dkh
1069
+ dh0 = b_dh.to(torch.float32) if h0 is not None else None
1070
+
1071
+ # [NT, B, H, BT, D] -> [B, H, T, D]
1072
+ dv = dv.permute(1, 2, 0, 3, 4).reshape(B, H, -1, V)[:, :, :T, :]
1073
+ dk = dk.permute(1, 2, 0, 3, 4).reshape(B, H, -1, K)[:, :, :T, :]
1074
+ # [B, H, NT, D, D]
1075
+ dh = dh.permute(1, 2, 0, 3, 4)
1076
+ dv, dk, dh = [x.transpose(1, 2) for x in (dv, dk, dh)]
1077
+ dh, dv, dk, dw, db = [x.contiguous() for x in (dh, dv, dk, dw, db)]
1078
+ dh0 = dh0.contiguous() if h0 is not None else None
1079
+ return dh, dh0, dv, dk, dw, db
1080
+
1081
+
1082
+ def chunk_ttt_linear_bwd_dqke(
1083
+ q: torch.Tensor,
1084
+ k: torch.Tensor,
1085
+ v: torch.Tensor,
1086
+ eta: torch.Tensor,
1087
+ h: torch.Tensor,
1088
+ do: torch.Tensor,
1089
+ dh: torch.Tensor,
1090
+ dhb: torch.Tensor,
1091
+ scale: float,
1092
+ cu_seqlens: Optional[torch.LongTensor] = None,
1093
+ chunk_size: int = 16,
1094
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
1095
+ B, T, H, K, V = *k.shape, v.shape[-1]
1096
+ BT = chunk_size
1097
+
1098
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
1099
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
1100
+
1101
+ BK = max(triton.next_power_of_2(K), 16)
1102
+ BV = min(max(triton.next_power_of_2(V), 16), 64)
1103
+ NK = triton.cdiv(K, BK)
1104
+ assert NK == 1, "NK > 1 is not supported."
1105
+
1106
+ dq = torch.empty_like(q)
1107
+ dk = torch.empty_like(k)
1108
+ de = torch.empty_like(eta)
1109
+ grid = (NK, NT, B * H)
1110
+
1111
+ chunk_bwd_kernel_dqke[grid](
1112
+ q=q,
1113
+ k=k,
1114
+ v=v,
1115
+ e=eta,
1116
+ h=h,
1117
+ do=do,
1118
+ dh=dh,
1119
+ dhb=dhb,
1120
+ dq=dq,
1121
+ dk=dk,
1122
+ de=de,
1123
+ cu_seqlens=cu_seqlens,
1124
+ chunk_indices=chunk_indices,
1125
+ scale=scale,
1126
+ B=B,
1127
+ T=T,
1128
+ H=H,
1129
+ K=K,
1130
+ V=V,
1131
+ BT=BT,
1132
+ BK=BK,
1133
+ BV=BV,
1134
+ )
1135
+ return dq, dk, de
1136
+
1137
+
1138
+ def chunk_ttt_linear_fwd(
1139
+ q: torch.Tensor,
1140
+ k: torch.Tensor,
1141
+ v: torch.Tensor,
1142
+ w: torch.Tensor,
1143
+ b: torch.Tensor,
1144
+ eta: torch.Tensor,
1145
+ scale: float,
1146
+ eps: float,
1147
+ initial_state: torch.Tensor,
1148
+ initial_state_bias: torch.Tensor,
1149
+ output_final_state: bool,
1150
+ cu_seqlens: Optional[torch.LongTensor] = None,
1151
+ chunk_size: int = 16
1152
+ ):
1153
+ BT = chunk_size
1154
+ h, hb, v_new, final_state, final_state_bias = chunk_ttt_linear_fwd_h(
1155
+ k=k,
1156
+ v=v,
1157
+ w=w,
1158
+ b=b,
1159
+ eta=eta,
1160
+ eps=eps,
1161
+ initial_state=initial_state,
1162
+ initial_state_bias=initial_state_bias,
1163
+ output_final_state=output_final_state,
1164
+ cu_seqlens=cu_seqlens,
1165
+ chunk_size=BT
1166
+ )
1167
+ o = chunk_ttt_linear_fwd_o(
1168
+ q=q,
1169
+ k=k,
1170
+ v=v_new,
1171
+ eta=eta,
1172
+ h=h,
1173
+ hb=hb,
1174
+ scale=scale,
1175
+ cu_seqlens=cu_seqlens,
1176
+ chunk_size=BT
1177
+ )
1178
+ return o, final_state, final_state_bias
1179
+
1180
+
1181
+ def chunk_ttt_linear_bwd(
1182
+ q: torch.Tensor,
1183
+ k: torch.Tensor,
1184
+ v: torch.Tensor,
1185
+ w: torch.Tensor,
1186
+ b: torch.Tensor,
1187
+ eta: torch.Tensor,
1188
+ scale: float,
1189
+ eps: float,
1190
+ do: torch.Tensor,
1191
+ dht: torch.Tensor,
1192
+ dhbt: torch.Tensor,
1193
+ chunk_size: int = 16,
1194
+ initial_state: torch.Tensor = None,
1195
+ initial_state_bias: torch.Tensor = None,
1196
+ cu_seqlens: Optional[torch.LongTensor] = None,
1197
+ ):
1198
+ BT = chunk_size
1199
+ h, v_new, x, y, rstd = chunk_ttt_linear_bwd_h(
1200
+ k=k,
1201
+ v=v,
1202
+ w=w,
1203
+ b=b,
1204
+ eta=eta,
1205
+ eps=eps,
1206
+ initial_state=initial_state,
1207
+ initial_state_bias=initial_state_bias,
1208
+ cu_seqlens=cu_seqlens,
1209
+ chunk_size=BT
1210
+ )
1211
+ dv_new = chunk_ttt_linear_bwd_dv_local(
1212
+ q=q,
1213
+ k=k,
1214
+ eta=eta,
1215
+ do=do,
1216
+ scale=scale,
1217
+ cu_seqlens=cu_seqlens,
1218
+ chunk_size=BT
1219
+ )
1220
+ dh, dhb, dh0, dhb0, dv, dk, dw, db = chunk_ttt_linear_bwd_norm(
1221
+ q=q,
1222
+ k=k,
1223
+ v=v,
1224
+ v_new=v_new,
1225
+ x=x,
1226
+ y=y,
1227
+ rstd=rstd,
1228
+ w=w,
1229
+ b=b,
1230
+ eta=eta,
1231
+ h0=initial_state,
1232
+ hb0=initial_state_bias,
1233
+ h=h,
1234
+ dht=dht,
1235
+ dhbt=dhbt,
1236
+ dv_new=dv_new,
1237
+ do=do,
1238
+ scale=scale,
1239
+ cu_seqlens=cu_seqlens,
1240
+ chunk_size=BT
1241
+ )
1242
+ dq, dk2, de = chunk_ttt_linear_bwd_dqke(
1243
+ q=q,
1244
+ k=k,
1245
+ v=v_new,
1246
+ eta=eta,
1247
+ h=h,
1248
+ do=do,
1249
+ dh=dh,
1250
+ dhb=dhb,
1251
+ scale=scale,
1252
+ cu_seqlens=cu_seqlens,
1253
+ chunk_size=BT
1254
+ )
1255
+ dk.add_(dk2)
1256
+ return dq, dk, dv, de, dw, db, dh0, dhb0
1257
+
1258
+
1259
+ class ChunkTTTLinearFunction(torch.autograd.Function):
1260
+
1261
+ @staticmethod
1262
+ @input_guard
1263
+ @autocast_custom_fwd
1264
+ def forward(
1265
+ ctx,
1266
+ q,
1267
+ k,
1268
+ v,
1269
+ w,
1270
+ b,
1271
+ chunk_size,
1272
+ eta,
1273
+ scale,
1274
+ eps,
1275
+ initial_state,
1276
+ initial_state_bias,
1277
+ output_final_state,
1278
+ cu_seqlens
1279
+ ):
1280
+ o, final_state, final_state_bias = chunk_ttt_linear_fwd(
1281
+ q=q,
1282
+ k=k,
1283
+ v=v,
1284
+ w=w,
1285
+ b=b,
1286
+ eta=eta,
1287
+ scale=scale,
1288
+ eps=eps,
1289
+ chunk_size=chunk_size,
1290
+ initial_state=initial_state,
1291
+ initial_state_bias=initial_state_bias,
1292
+ output_final_state=output_final_state,
1293
+ cu_seqlens=cu_seqlens,
1294
+ )
1295
+ ctx.save_for_backward(q, k, v, eta, w, b, initial_state, initial_state_bias)
1296
+ ctx.chunk_size = chunk_size
1297
+ ctx.scale = scale
1298
+ ctx.eps = eps
1299
+ ctx.cu_seqlens = cu_seqlens
1300
+ return o.to(q.dtype), final_state, final_state_bias
1301
+
1302
+ @staticmethod
1303
+ @input_guard
1304
+ @autocast_custom_bwd
1305
+ def backward(ctx, do, dht, dhbt):
1306
+ q, k, v, eta, w, b, initial_state, initial_state_bias = ctx.saved_tensors
1307
+ dq, dk, dv, de, dw, db, dh0, dhb0 = chunk_ttt_linear_bwd(
1308
+ q=q,
1309
+ k=k,
1310
+ v=v,
1311
+ w=w,
1312
+ b=b,
1313
+ eta=eta,
1314
+ scale=ctx.scale,
1315
+ eps=ctx.eps,
1316
+ do=do,
1317
+ dht=dht,
1318
+ dhbt=dhbt,
1319
+ chunk_size=ctx.chunk_size,
1320
+ initial_state=initial_state,
1321
+ initial_state_bias=initial_state_bias,
1322
+ cu_seqlens=ctx.cu_seqlens,
1323
+ )
1324
+ 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, None
1325
+
1326
+
1327
+ def norm_residual(x, weight, bias, eps):
1328
+ # GroupNorm and Residual
1329
+ B, T, H, D = x.shape
1330
+ x += group_norm(
1331
+ x.reshape(B, T, -1).clone(),
1332
+ weight=weight.reshape(-1).clone(),
1333
+ bias=bias.reshape(-1).clone(),
1334
+ eps=eps,
1335
+ num_groups=H,
1336
+ ).reshape(x.shape)
1337
+ return x
1338
+
1339
+
1340
+ def chunk_ttt_linear(
1341
+ q: torch.Tensor,
1342
+ k: torch.Tensor,
1343
+ v: torch.Tensor,
1344
+ w: torch.Tensor,
1345
+ b: torch.Tensor,
1346
+ eta: torch.Tensor,
1347
+ scale: float = None,
1348
+ eps: float = 1e-6,
1349
+ chunk_size: int = 16,
1350
+ initial_state: torch.Tensor = None,
1351
+ initial_state_bias: torch.Tensor = None,
1352
+ output_final_state: bool = False,
1353
+ cu_seqlens: Optional[torch.LongTensor] = None,
1354
+ head_first: bool = False,
1355
+ ):
1356
+ r"""
1357
+ Args:
1358
+ q (torch.Tensor):
1359
+ queries of shape `(B, H, T, K)`
1360
+ k (torch.Tensor):
1361
+ keys of shape `(B, H, T, K)`
1362
+ v (torch.Tensor):
1363
+ values of shape `(B, H, T, V)`
1364
+ w (torch.Tensor):
1365
+ layer norm weight of shape `(H, V)`
1366
+ b (torch.Tensor):
1367
+ layer norm bias of shape `(H, V)`
1368
+ eta (torch.Tensor):
1369
+ Learning rate for hidden state, of shape `(B, H, T, 1)`.
1370
+ scale (Optional[float]):
1371
+ Scale factor for the RetNet attention scores.
1372
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
1373
+ chunk_size (int):
1374
+ chunk size. Default: `16`.
1375
+ initial_state (Optional[torch.Tensor]):
1376
+ Initial state of shape `(B, H, K, V)`. Default: `None`.
1377
+ initial_state_bias (Optional[torch.Tensor]):
1378
+ Initial state bias of shape `(B, H, 1, V)`. Default: `None`.
1379
+ output_final_state (Optional[bool]):
1380
+ Whether to output the final state of shape `(B, H, K, V)`. Default: `False`.
1381
+ cu_seqlens (torch.LongTensor):
1382
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
1383
+ consistent with the FlashAttention API.
1384
+ head_first (Optional[bool]):
1385
+ Whether the inputs are in the head-first format. Default: `False`.
1386
+ This argument has been deprecated.
1387
+
1388
+ Returns:
1389
+ o (torch.Tensor):
1390
+ Outputs of shape `[B, H, T, V]`
1391
+ final_state (torch.Tensor):
1392
+ Final state of shape `[B, H, K, V]` if `output_final_state=True` else `None`
1393
+ """
1394
+ assert q.dtype == k.dtype == v.dtype
1395
+ assert k.shape[-1] == v.shape[-1], "DK must equal to DV."
1396
+ if isinstance(eta, float):
1397
+ eta = torch.full_like(q[:, :, :, :1], eta)
1398
+ if head_first:
1399
+ raise DeprecationWarning(
1400
+ "head_first is deprecated and will be removed in a future version. "
1401
+ "Please use head_first=False for now instead."
1402
+ )
1403
+ if not head_first and q.shape[1] < q.shape[2]:
1404
+ warnings.warn(
1405
+ f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
1406
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
1407
+ "when head_first=False was specified. "
1408
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
1409
+ )
1410
+ if cu_seqlens is not None:
1411
+ if q.shape[0] != 1:
1412
+ raise ValueError(
1413
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
1414
+ f"Please flatten variable-length inputs before processing."
1415
+ )
1416
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
1417
+ raise ValueError(
1418
+ f"The number of initial states is expected to be equal to the number of input sequences, "
1419
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
1420
+ )
1421
+ if scale is None:
1422
+ scale = k.shape[-1] ** -0.5
1423
+ else:
1424
+ assert scale > 0, "Scale must be positive."
1425
+ o, final_state, final_state_bias = ChunkTTTLinearFunction.apply(
1426
+ q,
1427
+ k,
1428
+ v,
1429
+ w,
1430
+ b,
1431
+ chunk_size,
1432
+ eta,
1433
+ scale,
1434
+ eps,
1435
+ initial_state,
1436
+ initial_state_bias,
1437
+ output_final_state,
1438
+ cu_seqlens,
1439
+ )
1440
+ o = norm_residual(o, w, b, eps)
1441
+ return o, final_state, final_state_bias