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/utils/pack.py ADDED
@@ -0,0 +1,208 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ # Code adapted from https://github.com/mayank31398/cute-kernels
5
+
6
+ from typing import Optional
7
+
8
+ import torch
9
+ import triton
10
+ import triton.language as tl
11
+
12
+ from fla.ops.utils.index import prepare_lens
13
+ from fla.utils import input_guard
14
+
15
+
16
+ @triton.autotune(
17
+ configs=[
18
+ triton.Config({}, num_warps=num_warps)
19
+ for num_warps in [4, 8, 16, 32]
20
+ ],
21
+ key=['D', 'PADDING_SIDE', 'PACK']
22
+ )
23
+ @triton.jit
24
+ def packunpack_sequence_kernel(
25
+ x,
26
+ y,
27
+ cu_seqlens,
28
+ S,
29
+ D,
30
+ BD: tl.constexpr,
31
+ PADDING_SIDE: tl.constexpr,
32
+ PACK: tl.constexpr,
33
+ ):
34
+ i_d, i_s, i_b = tl.program_id(0), tl.program_id(1), tl.program_id(2)
35
+ bos, eos = tl.load(cu_seqlens + i_b), tl.load(cu_seqlens + i_b + 1)
36
+
37
+ T = eos - bos
38
+ if PADDING_SIDE == 'left':
39
+ NP = S - T
40
+ if i_s < NP:
41
+ return
42
+ i_t = bos + (i_s - NP)
43
+ else:
44
+ if i_s >= T:
45
+ return
46
+ i_t = bos + i_s
47
+
48
+ o_d = i_d * BD + tl.arange(0, BD)
49
+ mask = o_d < D
50
+
51
+ if PACK:
52
+ b_x = tl.load(x + (i_b * S + i_s) * D + o_d, mask=mask)
53
+ tl.store(y + i_t * D + o_d, b_x, mask=mask)
54
+ else:
55
+ b_x = tl.load(x + i_t * D + o_d, mask=mask)
56
+ tl.store(y + (i_b * S + i_s) * D + o_d, b_x, mask=mask)
57
+
58
+
59
+ def pack_sequence_fwdbwd(
60
+ x: torch.Tensor,
61
+ cu_seqlens: torch.Tensor,
62
+ padding_side: str,
63
+ ) -> torch.Tensor:
64
+ B, S = x.shape[:2]
65
+ D = x.numel() // (B * S)
66
+ BD = min(triton.next_power_of_2(D), 4096)
67
+ ND = triton.cdiv(D, BD)
68
+
69
+ y = torch.empty(cu_seqlens[-1].item(), *x.shape[2:], device=x.device, dtype=x.dtype)
70
+ packunpack_sequence_kernel[ND, S, B](
71
+ x=x,
72
+ y=y,
73
+ cu_seqlens=cu_seqlens,
74
+ S=S,
75
+ D=D,
76
+ BD=BD,
77
+ PADDING_SIDE=padding_side,
78
+ PACK=True,
79
+ )
80
+ return y
81
+
82
+
83
+ def unpack_sequence_fwdbwd(
84
+ x: torch.Tensor,
85
+ cu_seqlens: torch.Tensor,
86
+ padding_side: str,
87
+ desired_shape: torch.Size,
88
+ ) -> torch.Tensor:
89
+ if desired_shape is None:
90
+ desired_shape = (len(cu_seqlens) - 1, prepare_lens(cu_seqlens).max().item(), *x.shape[1:])
91
+ y = torch.zeros(desired_shape, device=x.device, dtype=x.dtype)
92
+ B, S = y.shape[:2]
93
+ D = y.numel() // (B * S)
94
+ BD = min(triton.next_power_of_2(D), 4096)
95
+ ND = triton.cdiv(D, BD)
96
+
97
+ packunpack_sequence_kernel[ND, S, B](
98
+ x=x,
99
+ y=y,
100
+ cu_seqlens=cu_seqlens,
101
+ S=S,
102
+ D=D,
103
+ BD=BD,
104
+ PADDING_SIDE=padding_side,
105
+ PACK=False,
106
+ )
107
+ return y
108
+
109
+
110
+ class PackSequenceFunction(torch.autograd.Function):
111
+
112
+ @staticmethod
113
+ @input_guard
114
+ def forward(
115
+ ctx,
116
+ x: torch.Tensor,
117
+ cu_seqlens: torch.Tensor,
118
+ padding_side: str,
119
+ ) -> torch.Tensor:
120
+ assert padding_side in ['left', 'right']
121
+ assert x.ndim >= 2
122
+
123
+ ctx.cu_seqlens = cu_seqlens
124
+ ctx.padding_side = padding_side
125
+ ctx.desired_shape = x.shape
126
+
127
+ y = pack_sequence_fwdbwd(
128
+ x=x,
129
+ cu_seqlens=cu_seqlens,
130
+ padding_side=padding_side,
131
+ )
132
+ return y
133
+
134
+ @staticmethod
135
+ @input_guard
136
+ def backward(ctx, dy: torch.Tensor) -> tuple[torch.Tensor | None]:
137
+ dx = unpack_sequence_fwdbwd(
138
+ x=dy,
139
+ cu_seqlens=ctx.cu_seqlens,
140
+ padding_side=ctx.padding_side,
141
+ desired_shape=ctx.desired_shape,
142
+ )
143
+ return dx, *[None] * 10
144
+
145
+
146
+ class UnpackSequenceFunction(torch.autograd.Function):
147
+
148
+ @staticmethod
149
+ @input_guard
150
+ def forward(
151
+ ctx,
152
+ x: torch.Tensor,
153
+ cu_seqlens: torch.Tensor,
154
+ padding_side: str,
155
+ desired_shape: Optional[torch.Size] = None,
156
+ ) -> torch.Tensor:
157
+ assert padding_side in ['left', 'right']
158
+ assert x.ndim >= 2
159
+ if desired_shape is not None:
160
+ assert desired_shape[0] == cu_seqlens.shape[0] - 1
161
+ assert desired_shape[2:] == x.shape[1:]
162
+
163
+ ctx.cu_seqlens = cu_seqlens
164
+ ctx.padding_side = padding_side
165
+
166
+ y = unpack_sequence_fwdbwd(
167
+ x=x,
168
+ cu_seqlens=cu_seqlens,
169
+ padding_side=padding_side,
170
+ desired_shape=desired_shape,
171
+ )
172
+ return y
173
+
174
+ @staticmethod
175
+ @input_guard
176
+ def backward(ctx, dy: torch.Tensor) -> tuple[torch.Tensor | None]:
177
+ dx = pack_sequence_fwdbwd(
178
+ x=dy,
179
+ cu_seqlens=ctx.cu_seqlens,
180
+ padding_side=ctx.padding_side,
181
+ )
182
+ return dx, None, None, None
183
+
184
+
185
+ def pack_sequence(
186
+ x: torch.Tensor,
187
+ cu_seqlens: torch.Tensor,
188
+ padding_side: str = 'left'
189
+ ) -> torch.Tensor:
190
+ return PackSequenceFunction.apply(
191
+ x,
192
+ cu_seqlens,
193
+ padding_side,
194
+ )
195
+
196
+
197
+ def unpack_sequence(
198
+ x: torch.Tensor,
199
+ cu_seqlens: torch.Tensor,
200
+ padding_side: str = 'left',
201
+ desired_shape: Optional[torch.Size] = None,
202
+ ) -> torch.Tensor:
203
+ return UnpackSequenceFunction.apply(
204
+ x,
205
+ cu_seqlens,
206
+ padding_side,
207
+ desired_shape,
208
+ )
@@ -0,0 +1,207 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Optional, Tuple
5
+
6
+ import torch
7
+ import triton
8
+ import triton.language as tl
9
+
10
+ from fla.ops.utils.index import prepare_chunk_indices
11
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
12
+
13
+
14
+ @triton.heuristics({
15
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
16
+ })
17
+ @triton.autotune(
18
+ configs=[
19
+ triton.Config({'BD': BD}, num_warps=num_warps)
20
+ for BD in [16, 32, 64, 128]
21
+ for num_warps in [1, 2, 4, 8]
22
+ ],
23
+ key=['BT']
24
+ )
25
+ @triton.jit(do_not_specialize=['T'])
26
+ def mean_pooling_fwd_kernel(
27
+ x,
28
+ o,
29
+ cu_seqlens,
30
+ chunk_indices,
31
+ T,
32
+ H: tl.constexpr,
33
+ D: tl.constexpr,
34
+ BT: tl.constexpr,
35
+ BD: tl.constexpr,
36
+ IS_VARLEN: tl.constexpr
37
+ ):
38
+ i_d, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
39
+ i_b, i_h = i_bh // H, i_bh % H
40
+ if IS_VARLEN:
41
+ i_tg = i_t
42
+ 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)
43
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
44
+ T = eos - bos
45
+ NT = tl.cdiv(T, BT)
46
+ else:
47
+ NT = tl.cdiv(T, BT)
48
+ i_tg = i_b * NT + i_t
49
+ bos, eos = i_b * T, i_b * T + T
50
+
51
+ p_x = tl.make_block_ptr(x + (bos * H + i_h) * D, (T, D), (H*D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
52
+ p_o = tl.make_block_ptr(o + (i_tg * H + i_h) * D, (D,), (1,), (i_d * BD,), (BD,), (0,))
53
+ # [BT, BD]
54
+ b_x = tl.load(p_x, boundary_check=(0, 1)).to(tl.float32)
55
+ # [BD]
56
+ b_o = tl.sum(b_x, axis=0) / min(BT, T - i_t * BT)
57
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0,))
58
+
59
+
60
+ @triton.heuristics({
61
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
62
+ })
63
+ @triton.autotune(
64
+ configs=[
65
+ triton.Config({'BD': BD}, num_warps=num_warps)
66
+ for BD in [16, 32, 64, 128]
67
+ for num_warps in [1, 2, 4, 8]
68
+ ],
69
+ key=['BT']
70
+ )
71
+ @triton.jit(do_not_specialize=['T'])
72
+ def mean_pooling_bwd_kernel(
73
+ do,
74
+ dx,
75
+ cu_seqlens,
76
+ chunk_indices,
77
+ T,
78
+ H: tl.constexpr,
79
+ D: tl.constexpr,
80
+ BT: tl.constexpr,
81
+ BD: tl.constexpr,
82
+ IS_VARLEN: tl.constexpr
83
+ ):
84
+ i_d, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
85
+ i_b, i_h = i_bh // H, i_bh % H
86
+ if IS_VARLEN:
87
+ i_tg = i_t
88
+ 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)
89
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
90
+ T = eos - bos
91
+ NT = tl.cdiv(T, BT)
92
+ else:
93
+ NT = tl.cdiv(T, BT)
94
+ i_tg = i_b * NT + i_t
95
+ bos, eos = i_b * T, i_b * T + T
96
+
97
+ p_dx = tl.make_block_ptr(dx + (bos * H + i_h) * D, (T, D), (H*D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
98
+ p_do = tl.make_block_ptr(do + (i_tg * H + i_h) * D, (D,), (1,), (i_d * BD,), (BD,), (0,))
99
+ # [BD]
100
+ b_do = tl.load(p_do, boundary_check=(0,)).to(tl.float32)
101
+ # [BT, BD]
102
+ b_dx = b_do / tl.full((BT,), min(BT, T - i_t * BT), dtype=tl.float32)[:, None]
103
+ tl.store(p_dx, b_dx.to(p_dx.dtype.element_ty), boundary_check=(0, 1))
104
+
105
+
106
+ def mean_pooling_fwd(
107
+ x: torch.Tensor,
108
+ chunk_size: int,
109
+ cu_seqlens: Optional[torch.LongTensor] = None
110
+ ) -> torch.Tensor:
111
+ B, T, H, D = x.shape
112
+ BT = chunk_size
113
+ chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
114
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
115
+
116
+ o = x.new_empty(B, NT, H, D)
117
+ def grid(meta): return (triton.cdiv(D, meta['BD']), NT, B * H)
118
+ mean_pooling_fwd_kernel[grid](
119
+ x,
120
+ o,
121
+ cu_seqlens,
122
+ chunk_indices,
123
+ T=T,
124
+ H=H,
125
+ D=D,
126
+ BT=BT,
127
+ )
128
+ return o
129
+
130
+
131
+ def mean_pooling_bwd(
132
+ do: torch.Tensor,
133
+ batch_size: int,
134
+ seq_len: int,
135
+ chunk_size: int,
136
+ cu_seqlens: Optional[torch.LongTensor] = None
137
+ ) -> torch.Tensor:
138
+ B, T, H, D = batch_size, seq_len, *do.shape[-2:]
139
+ BT = chunk_size
140
+ chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
141
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
142
+
143
+ dx = do.new_empty(B, T, H, D)
144
+ def grid(meta): return (triton.cdiv(D, meta['BD']), NT, B * H)
145
+ mean_pooling_bwd_kernel[grid](
146
+ do,
147
+ dx,
148
+ cu_seqlens,
149
+ chunk_indices,
150
+ T=T,
151
+ H=H,
152
+ D=D,
153
+ BT=BT,
154
+ )
155
+ return dx
156
+
157
+
158
+ class MeanPoolingFunction(torch.autograd.Function):
159
+
160
+ @staticmethod
161
+ @input_guard
162
+ @autocast_custom_fwd
163
+ def forward(
164
+ ctx,
165
+ x: torch.Tensor,
166
+ chunk_size: int,
167
+ cu_seqlens: Optional[torch.LongTensor] = None
168
+ ) -> torch.Tensor:
169
+ o = mean_pooling_fwd(x, chunk_size, cu_seqlens)
170
+ ctx.batch_size = x.shape[0]
171
+ ctx.seq_len = x.shape[1]
172
+ ctx.chunk_size = chunk_size
173
+ ctx.cu_seqlens = cu_seqlens
174
+ return o
175
+
176
+ @staticmethod
177
+ @input_guard
178
+ @autocast_custom_bwd
179
+ def backward(
180
+ ctx, do
181
+ ) -> Tuple[torch.Tensor, None, None]:
182
+ batch_size = ctx.batch_size
183
+ seq_len = ctx.seq_len
184
+ chunk_size = ctx.chunk_size
185
+ cu_seqlens = ctx.cu_seqlens
186
+ dx = mean_pooling_bwd(do, batch_size, seq_len, chunk_size, cu_seqlens)
187
+ return dx, None, None
188
+
189
+
190
+ def mean_pooling(
191
+ x: torch.Tensor,
192
+ chunk_size: int,
193
+ cu_seqlens: Optional[torch.LongTensor] = None,
194
+ head_first: bool = False
195
+ ) -> torch.Tensor:
196
+ if head_first:
197
+ x = x.transpose(1, 2)
198
+ if cu_seqlens is not None:
199
+ if x.shape[0] != 1:
200
+ raise ValueError(
201
+ f"The batch size is expected to be 1 rather than {x.shape[0]} when using `cu_seqlens`."
202
+ f"Please flatten variable-length inputs before processing."
203
+ )
204
+ o = MeanPoolingFunction.apply(x, chunk_size, cu_seqlens)
205
+ if head_first:
206
+ o = o.transpose(1, 2)
207
+ return o
@@ -0,0 +1,106 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2024, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Optional
5
+
6
+ import torch
7
+ import triton
8
+ import triton.language as tl
9
+
10
+ from fla.ops.utils.op import exp
11
+ from fla.utils import is_amd
12
+
13
+ NUM_WARPS_AUTOTUNE = [1, 2, 4, 8, 16] if is_amd else [1, 2, 4, 8, 16, 32]
14
+
15
+
16
+ @triton.autotune(
17
+ configs=[
18
+ triton.Config({}, num_warps=num_warps)
19
+ for num_warps in NUM_WARPS_AUTOTUNE
20
+ ],
21
+ key=['D']
22
+ )
23
+ @triton.jit
24
+ def softmax_fwd_kernel(
25
+ x,
26
+ p,
27
+ D: tl.constexpr,
28
+ B: tl.constexpr
29
+ ):
30
+ i_n = tl.program_id(0)
31
+ o_d = tl.arange(0, B)
32
+ m_d = o_d < D
33
+
34
+ b_x = tl.load(x + i_n * D + o_d, mask=m_d, other=-float('inf'))
35
+ b_m = tl.max(b_x, 0)
36
+ b_x = exp(b_x - b_m)
37
+ b_p = b_x / tl.sum(b_x, 0)
38
+
39
+ tl.store(p + i_n * D + o_d, b_p.to(p.dtype.element_ty), mask=m_d)
40
+
41
+
42
+ @triton.autotune(
43
+ configs=[
44
+ triton.Config({}, num_warps=num_warps)
45
+ for num_warps in NUM_WARPS_AUTOTUNE
46
+ ],
47
+ key=['D']
48
+ )
49
+ @triton.jit
50
+ def softmax_bwd_kernel(
51
+ p,
52
+ dp,
53
+ ds,
54
+ D: tl.constexpr,
55
+ B: tl.constexpr
56
+ ):
57
+ i_n = tl.program_id(0)
58
+ o_d = tl.arange(0, B)
59
+ m_d = o_d < D
60
+
61
+ b_p = tl.load(p + i_n * D + o_d, mask=m_d, other=0.)
62
+ b_dp = tl.load(dp + i_n * D + o_d, mask=m_d, other=0.)
63
+ b_pp = tl.sum(b_p * b_dp, 0)
64
+ b_ds = b_p * b_dp - b_p * b_pp
65
+ tl.store(ds + i_n * D + o_d, b_ds.to(ds.dtype.element_ty), mask=m_d)
66
+
67
+
68
+ def softmax_fwd(
69
+ x: torch.Tensor,
70
+ dtype: Optional[torch.dtype] = torch.float
71
+ ) -> torch.Tensor:
72
+ shape = x.shape
73
+ x = x.view(-1, x.shape[-1])
74
+
75
+ N, D = x.shape
76
+ B = triton.next_power_of_2(D)
77
+
78
+ p = torch.empty_like(x, dtype=dtype)
79
+ softmax_fwd_kernel[(N,)](
80
+ x=x,
81
+ p=p,
82
+ D=D,
83
+ B=B
84
+ )
85
+ return p.view(*shape)
86
+
87
+
88
+ def softmax_bwd(
89
+ p: torch.Tensor,
90
+ dp: torch.Tensor,
91
+ dtype: Optional[torch.dtype] = torch.float
92
+ ) -> torch.Tensor:
93
+ shape = p.shape
94
+ p = p.view(-1, p.shape[-1])
95
+ ds = torch.empty_like(p, dtype=dtype)
96
+
97
+ N, D = p.shape
98
+ B = triton.next_power_of_2(D)
99
+ softmax_bwd_kernel[(N,)](
100
+ p=p,
101
+ dp=dp,
102
+ ds=ds,
103
+ D=D,
104
+ B=B
105
+ )
106
+ return ds.view(*shape)