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,492 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ import warnings
5
+ from typing import Optional, Tuple
6
+
7
+ import torch
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ from fla.ops.generalized_delta_rule.iplr.wy_fast import prepare_wy_repr_fwd
12
+ from fla.ops.utils import prepare_chunk_indices, prepare_chunk_offsets
13
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, check_shared_mem, input_guard, use_cuda_graph
14
+
15
+ BKV_LIST = [64, 128] if check_shared_mem() else [32, 64]
16
+
17
+
18
+ @triton.heuristics({
19
+ 'USE_INITIAL_STATE': lambda args: args['h0'] 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 [2, 4] + ([] if check_shared_mem('hopper') else [8])
27
+ ],
28
+ key=['BT', 'BK', 'BV'],
29
+ use_cuda_graph=use_cuda_graph,
30
+ )
31
+ @triton.jit(do_not_specialize=['T'])
32
+ def chunk_generalized_iplr_delta_rule_fwd_kernel_h(
33
+ k,
34
+ v,
35
+ d,
36
+ b,
37
+ u,
38
+ v_new,
39
+ h,
40
+ h0,
41
+ ht,
42
+ cu_seqlens,
43
+ chunk_offsets,
44
+ T,
45
+ H: tl.constexpr,
46
+ K: tl.constexpr,
47
+ V: tl.constexpr,
48
+ BT: tl.constexpr,
49
+ BC: tl.constexpr,
50
+ BK: tl.constexpr,
51
+ BV: tl.constexpr,
52
+ USE_INITIAL_STATE: tl.constexpr,
53
+ STORE_FINAL_STATE: tl.constexpr,
54
+ IS_VARLEN: tl.constexpr,
55
+ ):
56
+ i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
57
+ i_n, i_h = i_nh // H, i_nh % H
58
+ if IS_VARLEN:
59
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
60
+ T = eos - bos
61
+ NT = tl.cdiv(T, BT)
62
+ boh = tl.load(chunk_offsets + i_n).to(tl.int32)
63
+ else:
64
+ bos, eos = i_n * T, i_n * T + T
65
+ NT = tl.cdiv(T, BT)
66
+ boh = i_n * NT
67
+
68
+ # [BK, BV]
69
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
70
+ if USE_INITIAL_STATE:
71
+ 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))
72
+ b_h = tl.load(p_h0, boundary_check=(0, 1)).to(tl.float32)
73
+
74
+ for i_t in range(NT):
75
+ 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))
76
+ tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
77
+ b_hc = tl.zeros([BK, BV], dtype=tl.float32)
78
+ # since we need to make all DK in the SRAM. we face serve SRAM memory burden. By subchunking we allievate such burden
79
+ for i_c in range(tl.cdiv(min(BT, T - i_t * BT), BC)):
80
+ p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT + i_c * BC), (BK, BC), (0, 1))
81
+ p_b = tl.make_block_ptr(b+(bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT + i_c * BC), (BK, BC), (0, 1))
82
+ p_d = tl.make_block_ptr(d+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT + i_c * BC, i_k * BK), (BC, BK), (1, 0))
83
+ p_v = tl.make_block_ptr(v+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT + i_c * BC, i_v * BV), (BC, BV), (1, 0))
84
+ p_u = tl.make_block_ptr(u+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t * BT + i_c * BC, i_v * BV), (BC, BV), (1, 0))
85
+ p_v_new = tl.make_block_ptr(v_new+(bos*H+i_h)*V, (T, V), (H*V, 1), (i_t*BT+i_c*BC, i_v * BV), (BC, BV), (1, 0))
86
+ # [BK, BC]
87
+ b_k = tl.load(p_k, boundary_check=(0, 1))
88
+ b_v = tl.load(p_v, boundary_check=(0, 1))
89
+ b_d = tl.load(p_d, boundary_check=(0, 1))
90
+ b_b = tl.load(p_b, boundary_check=(0, 1))
91
+ b_v2 = tl.dot(b_d, b_h.to(b_d.dtype)) + tl.load(p_u, boundary_check=(0, 1))
92
+ b_hc += tl.dot(b_k, b_v)
93
+ b_hc += tl.dot(b_b, b_v2.to(b_k.dtype))
94
+ tl.store(p_v_new, b_v2.to(p_v_new.dtype.element_ty), boundary_check=(0, 1))
95
+ b_h += b_hc
96
+
97
+ if STORE_FINAL_STATE:
98
+ 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))
99
+ tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
100
+
101
+
102
+ @triton.heuristics({
103
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
104
+ })
105
+ @triton.autotune(
106
+ configs=[
107
+ triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps)
108
+ for BK in BKV_LIST
109
+ for BV in BKV_LIST
110
+ for num_warps in [2, 4, 8]
111
+ ],
112
+ key=['BT'],
113
+ use_cuda_graph=use_cuda_graph,
114
+ )
115
+ @triton.jit(do_not_specialize=['T'])
116
+ def chunk_generalized_iplr_delta_rule_fwd_kernel_o(
117
+ q,
118
+ k,
119
+ v,
120
+ u,
121
+ b,
122
+ h,
123
+ o,
124
+ cu_seqlens,
125
+ chunk_indices,
126
+ scale,
127
+ T,
128
+ H: tl.constexpr,
129
+ K: tl.constexpr,
130
+ V: tl.constexpr,
131
+ BT: tl.constexpr,
132
+ BK: tl.constexpr,
133
+ BV: tl.constexpr,
134
+ IS_VARLEN: tl.constexpr,
135
+ ):
136
+ i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
137
+ i_b, i_h = i_bh // H, i_bh % H
138
+
139
+ if IS_VARLEN:
140
+ i_tg = i_t
141
+ 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)
142
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
143
+ T = eos - bos
144
+ NT = tl.cdiv(T, BT)
145
+ else:
146
+ NT = tl.cdiv(T, BT)
147
+ i_tg = i_b * NT + i_t
148
+ bos, eos = i_b * T, i_b * T + T
149
+
150
+ # offset calculation
151
+ q += (bos * H + i_h) * K
152
+ k += (bos * H + i_h) * K
153
+ b += (bos * H + i_h) * K
154
+ v += (bos * H + i_h) * V
155
+ u += (bos * H + i_h) * V
156
+ o += (bos * H + i_h) * V
157
+ h += (i_tg * H + i_h) * K * V
158
+ stride_qk = H*K
159
+ stride_vo = H*V
160
+
161
+ b_o = tl.zeros([BT, BV], dtype=tl.float32)
162
+ b_Aqk = tl.zeros([BT, BT], dtype=tl.float32)
163
+ b_Aqb = tl.zeros([BT, BT], dtype=tl.float32)
164
+
165
+ for i_k in range(tl.cdiv(K, BK)):
166
+ p_q = tl.make_block_ptr(q, (T, K), (stride_qk, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
167
+ p_k = tl.make_block_ptr(k, (K, T), (1, stride_qk), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
168
+ p_h = tl.make_block_ptr(h, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
169
+ p_b = tl.make_block_ptr(b, (K, T), (1, stride_qk), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
170
+ # [BT, BK]
171
+ b_q = tl.load(p_q, boundary_check=(0, 1))
172
+ # [BK, BT]
173
+ b_k = tl.load(p_k, boundary_check=(0, 1))
174
+ b_b = tl.load(p_b, boundary_check=(0, 1))
175
+ # [BK, BV]
176
+ b_h = tl.load(p_h, boundary_check=(0, 1))
177
+ # [BT, BK] @ [BK, BV] -> [BT, BV]
178
+ b_o += tl.dot(b_q, b_h)
179
+ # [BT, BK] @ [BK, BT] -> [BT, BT]
180
+ b_Aqk += tl.dot(b_q, b_k)
181
+ # [BT, BK] @ [BK, BT] -> [BT, BT]
182
+ b_Aqb += tl.dot(b_q, b_b)
183
+
184
+ o_i = tl.arange(0, BT)
185
+ m_A = o_i[:, None] >= o_i[None, :]
186
+ b_Aqk = tl.where(m_A, b_Aqk, 0)
187
+ b_Aqb = tl.where(m_A, b_Aqb, 0)
188
+
189
+ p_v = tl.make_block_ptr(v, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
190
+ p_u = tl.make_block_ptr(u, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
191
+ p_o = tl.make_block_ptr(o, (T, V), (stride_vo, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
192
+ b_v = tl.load(p_v, boundary_check=(0, 1))
193
+ b_u = tl.load(p_u, boundary_check=(0, 1))
194
+ b_o = (b_o + tl.dot(b_Aqk.to(b_v.dtype), b_v) + tl.dot(b_Aqb.to(b_u.dtype), b_u)) * scale
195
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
196
+
197
+
198
+ def chunk_generalized_iplr_delta_rule_fwd_o(
199
+ q: torch.Tensor,
200
+ k: torch.Tensor,
201
+ v: torch.Tensor,
202
+ v_new: torch.Tensor,
203
+ b: torch.Tensor,
204
+ h: torch.Tensor,
205
+ scale: Optional[float] = None,
206
+ cu_seqlens: Optional[torch.LongTensor] = None,
207
+ chunk_size: int = 64
208
+ ) -> torch.Tensor:
209
+ B, T, H, K, V = *q.shape, v.shape[-1]
210
+ if scale is None:
211
+ scale = k.shape[-1] ** -0.5
212
+ BT = min(chunk_size, max(16, triton.next_power_of_2(T)))
213
+
214
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
215
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
216
+
217
+ o = torch.empty_like(v)
218
+
219
+ def grid(meta): return (
220
+ triton.cdiv(V, meta['BV']),
221
+ NT,
222
+ B * H
223
+ )
224
+ chunk_generalized_iplr_delta_rule_fwd_kernel_o[grid](
225
+ q=q,
226
+ k=k,
227
+ v=v,
228
+ u=v_new,
229
+ b=b,
230
+ h=h,
231
+ o=o,
232
+ cu_seqlens=cu_seqlens,
233
+ chunk_indices=chunk_indices,
234
+ scale=scale,
235
+ T=T,
236
+ H=H,
237
+ K=K,
238
+ V=V,
239
+ BT=BT,
240
+ )
241
+ return o
242
+
243
+
244
+ def chunk_generalized_iplr_delta_rule_fwd_h(
245
+ k: torch.Tensor,
246
+ v: torch.Tensor,
247
+ w: torch.Tensor,
248
+ u: torch.Tensor,
249
+ b: torch.Tensor,
250
+ initial_state: Optional[torch.Tensor] = None,
251
+ output_final_state: bool = False,
252
+ cu_seqlens: Optional[torch.LongTensor] = None,
253
+ chunk_size: int = 64
254
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
255
+ B, T, H, K, V = *k.shape, u.shape[-1]
256
+ BT = min(chunk_size, max(triton.next_power_of_2(T), 16))
257
+
258
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
259
+ # N: the actual number of sequences in the batch with either equal or variable lengths
260
+ if cu_seqlens is None:
261
+ N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
262
+ else:
263
+ N, NT, chunk_offsets = len(cu_seqlens) - 1, len(chunk_indices), prepare_chunk_offsets(cu_seqlens, BT)
264
+
265
+ BK = max(triton.next_power_of_2(K), 16)
266
+ assert BK <= 256, "current kernel does not support head dimension larger than 256."
267
+ # H100 can have larger block size
268
+
269
+ if check_shared_mem('hopper', k.device.index):
270
+ BV = 64
271
+ BC = 64 if K <= 128 else 32
272
+ elif check_shared_mem('ampere', k.device.index): # A100
273
+ BV = 32
274
+ BC = 32
275
+ else:
276
+ BV = 16
277
+ BC = 16
278
+
279
+ BC = min(BT, BC)
280
+ NK = triton.cdiv(K, BK)
281
+ NV = triton.cdiv(V, BV)
282
+
283
+ assert NK == 1, 'NK > 1 is not supported because it involves time-consuming synchronization'
284
+
285
+ h = k.new_empty(B, NT, H, K, V)
286
+ final_state = k.new_empty(N, H, K, V, dtype=torch.float32) if output_final_state else None
287
+
288
+ v_new = torch.empty_like(u)
289
+ grid = (NK, NV, N * H)
290
+
291
+ chunk_generalized_iplr_delta_rule_fwd_kernel_h[grid](
292
+ k=k,
293
+ v=v,
294
+ d=w,
295
+ b=b,
296
+ u=u,
297
+ v_new=v_new,
298
+ h=h,
299
+ h0=initial_state,
300
+ ht=final_state,
301
+ cu_seqlens=cu_seqlens,
302
+ chunk_offsets=chunk_offsets,
303
+ T=T,
304
+ H=H,
305
+ K=K,
306
+ V=V,
307
+ BT=BT,
308
+ BC=BC,
309
+ BK=BK,
310
+ BV=BV,
311
+ )
312
+ return h, v_new, final_state
313
+
314
+
315
+ def chunk_generalized_iplr_delta_rule_fwd(
316
+ q: torch.Tensor,
317
+ k: torch.Tensor,
318
+ v: torch.Tensor,
319
+ a: torch.Tensor,
320
+ b: torch.Tensor,
321
+ scale: float,
322
+ initial_state: torch.Tensor,
323
+ output_final_state: bool,
324
+ cu_seqlens: Optional[torch.LongTensor] = None,
325
+ chunk_size: int = 64
326
+ ):
327
+ T = q.shape[1]
328
+ BT = min(chunk_size, max(triton.next_power_of_2(T), 16))
329
+ w, u, _ = prepare_wy_repr_fwd(
330
+ a=a,
331
+ b=b,
332
+ k=k,
333
+ v=v,
334
+ cu_seqlens=cu_seqlens,
335
+ chunk_size=BT
336
+ )
337
+
338
+ h, v_new, final_state = chunk_generalized_iplr_delta_rule_fwd_h(
339
+ k=k,
340
+ v=v,
341
+ b=b,
342
+ w=w,
343
+ u=u,
344
+ initial_state=initial_state,
345
+ output_final_state=output_final_state,
346
+ cu_seqlens=cu_seqlens,
347
+ chunk_size=BT
348
+ )
349
+ o = chunk_generalized_iplr_delta_rule_fwd_o(
350
+ q=q,
351
+ k=k,
352
+ v=v,
353
+ v_new=v_new,
354
+ b=b,
355
+ h=h,
356
+ scale=scale,
357
+ cu_seqlens=cu_seqlens,
358
+ chunk_size=BT
359
+ )
360
+ return o, final_state
361
+
362
+
363
+ class ChunkGeneralizedIPLRDeltaRuleFunction(torch.autograd.Function):
364
+
365
+ @staticmethod
366
+ @input_guard
367
+ @autocast_custom_fwd
368
+ def forward(
369
+ ctx,
370
+ q: torch.Tensor,
371
+ k: torch.Tensor,
372
+ v: torch.Tensor,
373
+ a: torch.Tensor,
374
+ b: torch.Tensor,
375
+ scale: float,
376
+ initial_state: torch.Tensor,
377
+ output_final_state: bool,
378
+ cu_seqlens: Optional[torch.LongTensor] = None,
379
+ ):
380
+ chunk_size = 64
381
+
382
+ o, final_state = chunk_generalized_iplr_delta_rule_fwd(
383
+ q=q,
384
+ k=k,
385
+ v=v,
386
+ a=a,
387
+ b=b,
388
+ scale=scale,
389
+ initial_state=initial_state,
390
+ output_final_state=output_final_state,
391
+ cu_seqlens=cu_seqlens,
392
+ chunk_size=chunk_size
393
+ )
394
+ return o.to(q.dtype), final_state
395
+
396
+ @staticmethod
397
+ @input_guard
398
+ @autocast_custom_bwd
399
+ def backward(
400
+ ctx,
401
+ do: torch.Tensor,
402
+ dht: torch.Tensor
403
+ ):
404
+ raise NotImplementedError(
405
+ "Backward pass for ChunkGeneralizedIPLRDeltaRuleFunction is not implemented yet. "
406
+ "Stay tuned!"
407
+ )
408
+
409
+
410
+ @torch.compiler.disable
411
+ def chunk_iplr_delta_rule(
412
+ q: torch.Tensor,
413
+ k: torch.Tensor,
414
+ v: torch.Tensor,
415
+ a: torch.Tensor,
416
+ b: torch.Tensor,
417
+ scale: float = None,
418
+ initial_state: torch.Tensor = None,
419
+ output_final_state: bool = False,
420
+ cu_seqlens: Optional[torch.LongTensor] = None,
421
+ head_first: bool = False
422
+ ):
423
+ r"""
424
+ Args:
425
+ q (torch.Tensor):
426
+ queries of shape `[B, T, H, K]`.
427
+ k (torch.Tensor):
428
+ keys of shape `[B, T, H, K]`.
429
+ v (torch.Tensor):
430
+ values of shape `[B, T, H, V]`.
431
+ a (torch.Tensor):
432
+ activations of shape `[B, T, H, K]`.
433
+ b (torch.Tensor):
434
+ betas of shape `[B, T, H, K]`.
435
+ scale (Optional[float]):
436
+ Scale factor for the RetNet attention scores.
437
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
438
+ initial_state (Optional[torch.Tensor]):
439
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
440
+ For equal-length input sequences, `N` equals the batch size `B`.
441
+ Default: `None`.
442
+ output_final_state (Optional[bool]):
443
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
444
+ cu_seqlens (torch.LongTensor):
445
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
446
+ consistent with the FlashAttention API.
447
+ head_first (Optional[bool]):
448
+ Whether the inputs are in the head-first format. Default: `False`.
449
+ This argument has been deprecated.
450
+
451
+ Returns:
452
+ o (torch.Tensor):
453
+ Outputs of shape `[B, T, H, V]`.
454
+ final_state (torch.Tensor):
455
+ Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
456
+ """
457
+ if head_first:
458
+ raise DeprecationWarning(
459
+ "head_first is deprecated and will be removed in a future version. "
460
+ "Please use head_first=False for now instead."
461
+ )
462
+ if not head_first and q.shape[1] < q.shape[2]:
463
+ warnings.warn(
464
+ f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
465
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
466
+ "when head_first=False was specified. "
467
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
468
+ )
469
+ if cu_seqlens is not None:
470
+ if q.shape[0] != 1:
471
+ raise ValueError(
472
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
473
+ f"Please flatten variable-length inputs before processing."
474
+ )
475
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
476
+ raise ValueError(
477
+ f"The number of initial states is expected to be equal to the number of input sequences, "
478
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
479
+ )
480
+ scale = k.shape[-1] ** -0.5 if scale is None else scale
481
+ o, final_state = ChunkGeneralizedIPLRDeltaRuleFunction.apply(
482
+ q,
483
+ k,
484
+ v,
485
+ a,
486
+ b,
487
+ scale,
488
+ initial_state,
489
+ output_final_state,
490
+ cu_seqlens,
491
+ )
492
+ return o, final_state