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/modules/rotary.py ADDED
@@ -0,0 +1,500 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Optional, Tuple, Union
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import triton
9
+ import triton.language as tl
10
+ from einops import rearrange, repeat
11
+
12
+ from fla.ops.utils import prepare_chunk_indices
13
+ from fla.utils import get_multiprocessor_count, input_guard, is_amd
14
+
15
+ NUM_WARPS_AUTOTUNE = [2, 4, 8, 16] if is_amd else [2, 4, 8, 16, 32]
16
+
17
+
18
+ def rotate_half(x, interleaved=False):
19
+ if not interleaved:
20
+ x1, x2 = x.chunk(2, dim=-1)
21
+ return torch.cat((-x2, x1), dim=-1)
22
+ else:
23
+ x1, x2 = x[..., ::2], x[..., 1::2]
24
+ return rearrange(torch.stack((-x2, x1), dim=-1), '... d two -> ... (d two)', two=2)
25
+
26
+
27
+ def rotary_embedding_ref(x, cos, sin, interleaved=False):
28
+ ro_dim = cos.shape[-1] * 2
29
+ assert ro_dim <= x.shape[-1]
30
+ cos = repeat(cos, '... d -> ... 1 (2 d)' if not interleaved else '... d -> ... 1 (d 2)')
31
+ sin = repeat(sin, '... d -> ... 1 (2 d)' if not interleaved else '... d -> ... 1 (d 2)')
32
+ return torch.cat([x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]], -1)
33
+
34
+
35
+ @triton.autotune(
36
+ configs=[
37
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
38
+ for num_warps in NUM_WARPS_AUTOTUNE
39
+ for num_stages in [2, 3, 4]
40
+ ],
41
+ key=['B', 'H', 'D', 'INTERLEAVED'],
42
+ )
43
+ @triton.jit(do_not_specialize=['T'])
44
+ def rotary_embedding_kernel(
45
+ x,
46
+ cos,
47
+ sin,
48
+ y,
49
+ cu_seqlens,
50
+ chunk_indices,
51
+ seq_offsets,
52
+ T,
53
+ B: tl.constexpr,
54
+ H: tl.constexpr,
55
+ D: tl.constexpr,
56
+ R: tl.constexpr,
57
+ TR: tl.constexpr,
58
+ BT: tl.constexpr,
59
+ BD: tl.constexpr,
60
+ IS_SEQLEN_OFFSETS_TENSOR: tl.constexpr,
61
+ IS_VARLEN: tl.constexpr,
62
+ INTERLEAVED: tl.constexpr,
63
+ CONJUGATE: tl.constexpr
64
+ ):
65
+ i_t, i_b, i_h = tl.program_id(0), tl.program_id(1), tl.program_id(2)
66
+
67
+ if IS_VARLEN:
68
+ 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)
69
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
70
+ T = eos - bos
71
+ x = x + bos * H*D + i_h * D
72
+ y = y + bos * H*D + i_h * D
73
+ else:
74
+ i_n = i_b
75
+ x = x + i_n * T*H*D + i_h * D
76
+ y = y + i_n * T*H*D + i_h * D
77
+
78
+ if i_t * BT >= T:
79
+ return
80
+
81
+ o_t = i_t * BT + tl.arange(0, BT)
82
+ if not IS_SEQLEN_OFFSETS_TENSOR:
83
+ o_cs = o_t + seq_offsets
84
+ else:
85
+ o_cs = o_t + tl.load(seq_offsets + i_n)
86
+ m_t = (o_t >= 0) & (o_t < T) & (o_cs >= 0) & (o_cs < TR)
87
+
88
+ if not INTERLEAVED:
89
+ # Load the 1st and 2nd halves of x, do calculation, then store to 1st and 2nd halves of out
90
+ o_r = tl.arange(0, BD // 2)
91
+ p_x = x + o_t[:, None] * H*D + o_r[None, :]
92
+ p_cos = cos + (o_cs[:, None] * R + o_r[None, :])
93
+ p_sin = sin + (o_cs[:, None] * R + o_r[None, :])
94
+ mask = m_t[:, None] & (o_r < R)[None, :]
95
+
96
+ b_cos = tl.load(p_cos, mask=mask, other=1.0).to(tl.float32)
97
+ b_sin = tl.load(p_sin, mask=mask, other=0.0).to(tl.float32)
98
+ b_x0 = tl.load(p_x, mask=mask, other=0.0).to(tl.float32)
99
+ b_x1 = tl.load(p_x + R, mask=mask, other=0.0).to(tl.float32)
100
+ if CONJUGATE:
101
+ b_sin = -b_sin
102
+ b_o0 = b_x0 * b_cos - b_x1 * b_sin
103
+ b_o1 = b_x0 * b_sin + b_x1 * b_cos
104
+ # write back result
105
+ p_y = y + (o_t[:, None] * H*D + o_r[None, :])
106
+ tl.store(p_y, b_o0, mask=mask)
107
+ tl.store(p_y + R, b_o1, mask=mask)
108
+ else:
109
+ # We don't want to load x[0, 2, 4, ...] and x[1, 3, 5, ...] separately since both are slow.
110
+ # Instead, we load x0 = x[0, 1, 2, 3, ...] and x1 = x[1, 0, 3, 2, ...].
111
+ # Loading x0 will be fast but x1 will be slow.
112
+ # Then we load cos = cos[0, 0, 1, 1, ...] and sin = sin[0, 0, 1, 1, ...].
113
+ # Then we do the calculation and use tl.where to pick put the right outputs for the even
114
+ # and for the odd indices.
115
+ o_d = tl.arange(0, BD)
116
+ o_d_swap = o_d + ((o_d + 1) % 2) * 2 - 1 # 1, 0, 3, 2, 5, 4, ...
117
+ o_d_repeat = tl.arange(0, BD) // 2
118
+ p_x0 = x + o_t[:, None] * H*D + o_d[None, :]
119
+ p_x1 = x + o_t[:, None] * H*D + o_d_swap[None, :]
120
+ p_cos = cos + (o_cs[:, None] * R + o_d_repeat[None, :])
121
+ p_sin = sin + (o_cs[:, None] * R + o_d_repeat[None, :])
122
+ mask = m_t[:, None] & (o_d_repeat < R)[None, :]
123
+
124
+ b_cos = tl.load(p_cos, mask=mask, other=1.0).to(tl.float32)
125
+ b_sin = tl.load(p_sin, mask=mask, other=0.0).to(tl.float32)
126
+ b_x0 = tl.load(p_x0, mask=mask, other=0.0).to(tl.float32)
127
+ b_x1 = tl.load(p_x1, mask=mask, other=0.0).to(tl.float32)
128
+ if CONJUGATE:
129
+ b_sin = -b_sin
130
+ b_o0 = b_x0 * b_cos
131
+ b_o1 = b_x1 * b_sin
132
+ b_y = tl.where(o_d[None, :] % 2 == 0, b_o0 - b_o1, b_o0 + b_o1)
133
+ p_y = y + (o_t[:, None] * H*D + o_d[None, :])
134
+ tl.store(p_y, b_y, mask=mask)
135
+
136
+
137
+ def rotary_embedding_fwdbwd(
138
+ x: torch.Tensor,
139
+ cos: torch.Tensor,
140
+ sin: torch.Tensor,
141
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
142
+ cu_seqlens: Optional[torch.Tensor] = None,
143
+ interleaved: bool = False,
144
+ inplace: bool = False,
145
+ conjugate: bool = False
146
+ ) -> torch.Tensor:
147
+ """
148
+ Args:
149
+ x: [B, T, H, D].
150
+ cos: [TR, R / 2]
151
+ sin: [TR, R / 2]
152
+ seqlen_offsets: integer or integer tensor of size [N]
153
+ cu_seqlens: [N + 1,] or None
154
+
155
+ Returns:
156
+ y: [B, T, H, D]
157
+ """
158
+ is_varlen = cu_seqlens is not None
159
+
160
+ B, T, H, D = x.shape
161
+ N = B if not is_varlen else cu_seqlens.shape[0] - 1
162
+ TR, R = cos.shape
163
+ R2 = R * 2
164
+
165
+ assert D <= 256, "Only support D <= 256"
166
+ assert TR >= T, f"TR must be >= T, got {TR} and {T}"
167
+
168
+ assert cos.dtype == sin.dtype, f"cos and sin must have the same dtype, got {cos.dtype} and {sin.dtype}"
169
+ assert x.dtype == cos.dtype, f"Input and cos/sin must have the same dtype, got {x.dtype} and {cos.dtype}"
170
+
171
+ if isinstance(seqlen_offsets, torch.Tensor):
172
+ assert seqlen_offsets.shape == (N,)
173
+ assert seqlen_offsets.dtype in [torch.int32, torch.int64]
174
+ else:
175
+ assert seqlen_offsets + T <= TR
176
+
177
+ y = torch.empty_like(x) if not inplace else x
178
+ if R2 < D and not inplace:
179
+ y[..., R2:].copy_(x[..., R2:])
180
+
181
+ BD = triton.next_power_of_2(R2)
182
+ BT = min(128, triton.next_power_of_2(triton.cdiv(T, get_multiprocessor_count(x.device.index))))
183
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if is_varlen else None
184
+ NT = len(chunk_indices) if is_varlen else triton.cdiv(T, BT)
185
+
186
+ grid = (NT, B, H)
187
+ rotary_embedding_kernel[grid](
188
+ x,
189
+ cos,
190
+ sin,
191
+ y,
192
+ cu_seqlens,
193
+ chunk_indices,
194
+ seqlen_offsets,
195
+ B=B,
196
+ T=T,
197
+ H=H,
198
+ D=D,
199
+ R=R,
200
+ TR=TR,
201
+ BT=BT,
202
+ BD=BD,
203
+ IS_SEQLEN_OFFSETS_TENSOR=isinstance(seqlen_offsets, torch.Tensor),
204
+ IS_VARLEN=is_varlen,
205
+ INTERLEAVED=interleaved,
206
+ CONJUGATE=conjugate
207
+ )
208
+ return y
209
+
210
+
211
+ class RotaryEmbeddingFunction(torch.autograd.Function):
212
+
213
+ @staticmethod
214
+ @input_guard
215
+ def forward(
216
+ ctx,
217
+ x,
218
+ cos,
219
+ sin,
220
+ interleaved=False,
221
+ inplace=False,
222
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
223
+ cu_seqlens: Optional[torch.Tensor] = None,
224
+ ):
225
+ y = rotary_embedding_fwdbwd(
226
+ x,
227
+ cos,
228
+ sin,
229
+ seqlen_offsets=seqlen_offsets,
230
+ cu_seqlens=cu_seqlens,
231
+ interleaved=interleaved,
232
+ inplace=inplace,
233
+ )
234
+ if isinstance(seqlen_offsets, int):
235
+ # Can't save int with save_for_backward
236
+ ctx.save_for_backward(cos, sin, cu_seqlens)
237
+ ctx.seqlen_offsets = seqlen_offsets
238
+ else:
239
+ ctx.save_for_backward(cos, sin, cu_seqlens, seqlen_offsets)
240
+ ctx.seqlen_offsets = None
241
+ ctx.interleaved = interleaved
242
+ ctx.inplace = inplace
243
+ return y if not inplace else x
244
+
245
+ @staticmethod
246
+ @input_guard
247
+ def backward(ctx, do):
248
+ seqlen_offsets = ctx.seqlen_offsets
249
+ if seqlen_offsets is None:
250
+ cos, sin, cu_seqlens, seqlen_offsets = ctx.saved_tensors
251
+ else:
252
+ cos, sin, cu_seqlens = ctx.saved_tensors
253
+ # TD [2023-09-02]: For some reason Triton (2.0.0.post1) errors with
254
+ # "[CUDA]: invalid device context", and cloning makes it work. Idk why. Triton 2.1.0 works.
255
+ if not ctx.interleaved and not ctx.inplace:
256
+ do = do.clone()
257
+ dx = rotary_embedding_fwdbwd(
258
+ do,
259
+ cos,
260
+ sin,
261
+ seqlen_offsets=seqlen_offsets,
262
+ cu_seqlens=cu_seqlens,
263
+ interleaved=ctx.interleaved,
264
+ inplace=ctx.inplace,
265
+ conjugate=True,
266
+ )
267
+ return dx, None, None, None, None, None, None, None
268
+
269
+
270
+ def rotary_embedding(
271
+ x,
272
+ cos,
273
+ sin,
274
+ interleaved=False,
275
+ inplace=False,
276
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
277
+ cu_seqlens: Optional[torch.Tensor] = None
278
+ ):
279
+ """
280
+ Args:
281
+ x: [B, T, H, D]
282
+ cos, sin: [TR, R//2]
283
+ interleaved:
284
+ If True, rotate pairs of even and odd dimensions (GPT-J style) instead of 1st half and 2nd half (GPT-NeoX style).
285
+ inplace:
286
+ If True, apply rotary embedding in-place.
287
+ seqlen_offsets: [N,] or int.
288
+ Each sequence in x is shifted by this amount.
289
+ Most commonly used in inference when we have KV cache.
290
+ cu_seqlens: [N + 1,] or None
291
+
292
+ Returns:
293
+ out: [B, T, H, D]
294
+ """
295
+ return RotaryEmbeddingFunction.apply(
296
+ x,
297
+ cos,
298
+ sin,
299
+ interleaved,
300
+ inplace,
301
+ seqlen_offsets,
302
+ cu_seqlens
303
+ )
304
+
305
+
306
+ class RotaryEmbedding(nn.Module):
307
+ """
308
+ The rotary position embeddings from RoFormer_ (Su et. al).
309
+ A crucial insight from the method is that the query and keys are
310
+ transformed by rotation matrices which depend on the relative positions.
311
+
312
+ Other implementations are available in the Rotary Transformer repo_ and in
313
+ GPT-NeoX_, GPT-NeoX was an inspiration
314
+
315
+ .. _RoFormer: https://arxiv.org/abs/2104.09864
316
+ .. _repo: https://github.com/ZhuiyiTechnology/roformer
317
+ .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox
318
+
319
+ If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554).
320
+ A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96
321
+ Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py
322
+ """
323
+
324
+ def __init__(
325
+ self,
326
+ dim: int,
327
+ base: float = 10000.0,
328
+ scale_base: Optional[float] = None,
329
+ interleaved: bool = False,
330
+ pos_idx_in_fp32: bool = True,
331
+ device: Optional[torch.device] = None,
332
+ ):
333
+ """
334
+ interleaved:
335
+ If True, rotate pairs of even and odd dimensions (GPT-J style) instead of 1st half and 2nd half (GPT-NeoX style).
336
+ pos_idx_in_fp32:
337
+ If True, the position indices [0.0, ..., seqlen - 1] are in fp32, otherwise they might be in lower precision.
338
+ This option was added because previously (before 2023-07-02), when we construct
339
+ the position indices, we use the dtype of self.inv_freq.
340
+ In most cases this would be fp32, but if the model is trained in pure bf16 (not mixed precision), then
341
+ self.inv_freq would be bf16, and the position indices are also in bf16.
342
+ Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the
343
+ embeddings for some positions will coincide.
344
+ To maintain compatibility with models previously trained in pure bf16, we add this option.
345
+ """
346
+ super().__init__()
347
+
348
+ self.dim = dim
349
+ self.base = float(base)
350
+ self.scale_base = scale_base
351
+ self.interleaved = interleaved
352
+ self.pos_idx_in_fp32 = pos_idx_in_fp32
353
+ self.device = device
354
+
355
+ # Generate and save the inverse frequency buffer (non trainable)
356
+ self.register_buffer("inv_freq", torch.empty(-(dim // -2), dtype=torch.float32, device=device), persistent=False)
357
+
358
+ scale = None
359
+ if scale_base is not None:
360
+ scale = torch.empty(-(dim // -2), dtype=torch.float32, device=device)
361
+ self.register_buffer("scale", scale, persistent=False)
362
+
363
+ self._seq_len_cached = 0
364
+ self._cos_cached = None
365
+ self._sin_cached = None
366
+ self._cos_k_cached = None
367
+ self._sin_k_cached = None
368
+
369
+ self.reset_parameters()
370
+
371
+ def reset_parameters(self):
372
+ with torch.no_grad():
373
+ self.inv_freq.copy_(self._compute_inv_freq(device=self.inv_freq.device))
374
+ if self.scale_base is not None:
375
+ self.scale.copy_(self._compute_scale(device=self.scale.device))
376
+
377
+ def __repr__(self):
378
+ s = f"{self.__class__.__name__}("
379
+ s += f"dim={self.dim}, "
380
+ s += f"base={self.base}, "
381
+ s += f"interleaved={self.interleaved}, "
382
+ if self.scale_base is not None:
383
+ s += f"scale_base={self.scale_base}, "
384
+ s += f"pos_idx_in_fp32={self.pos_idx_in_fp32})"
385
+ return s
386
+
387
+ def _compute_inv_freq(self, device=None):
388
+ return 1.0 / (
389
+ self.base
390
+ ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim)
391
+ )
392
+
393
+ def _compute_scale(self, device=None):
394
+ return (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) + 0.4 * self.dim) / (1.4 * self.dim)
395
+
396
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
397
+ # Reset the tables if the sequence length has changed,
398
+ # if we're on a new device (possibly due to tracing for instance),
399
+ # or if we're switching from inference mode to training
400
+ if (
401
+ seqlen > self._seq_len_cached
402
+ or self._cos_cached is None
403
+ or self._cos_cached.device != device
404
+ or self._cos_cached.dtype != dtype
405
+ or (self.training and self._cos_cached.is_inference())
406
+ ):
407
+ self._seq_len_cached = seqlen
408
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
409
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
410
+ # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
411
+ if self.pos_idx_in_fp32:
412
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
413
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
414
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
415
+ # cos & sin output to change significantly.
416
+ # We want to recompute self.inv_freq if it was not loaded in fp32
417
+ if self.inv_freq.dtype != torch.float32:
418
+ inv_freq = self._compute_inv_freq(device=device)
419
+ else:
420
+ inv_freq = self.inv_freq
421
+ else:
422
+ t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
423
+ inv_freq = self.inv_freq
424
+ # Don't do einsum, it converts fp32 to fp16 under AMP
425
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
426
+ freqs = torch.outer(t, inv_freq)
427
+ if self.scale is None:
428
+ self._cos_cached = torch.cos(freqs).to(dtype)
429
+ self._sin_cached = torch.sin(freqs).to(dtype)
430
+ else:
431
+ power = (
432
+ torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device)
433
+ - seqlen // 2
434
+ ) / self.scale_base
435
+ scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
436
+ # We want the multiplication by scale to happen in fp32
437
+ self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
438
+ self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
439
+ self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
440
+ self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
441
+
442
+ def forward(
443
+ self,
444
+ q: torch.Tensor,
445
+ k: torch.Tensor,
446
+ seqlen_offset: Union[int, torch.Tensor] = 0,
447
+ cu_seqlens: Optional[torch.Tensor] = None,
448
+ max_seqlen: Optional[int] = None,
449
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
450
+ """
451
+ q: [B, T, H, D]
452
+ k: [B, T, H, D]
453
+ seqlen_offset:
454
+ [N] or int.
455
+ Each sequence in x is shifted by this amount.
456
+ Most commonly used in inference when we have KV cache.
457
+ cu_seqlens: [N + 1] or None
458
+ max_seqlen: int
459
+ """
460
+ if max_seqlen is not None:
461
+ self._update_cos_sin_cache(max_seqlen, device=q.device, dtype=q.dtype)
462
+ elif isinstance(seqlen_offset, int):
463
+ self._update_cos_sin_cache(q.shape[1] + seqlen_offset, device=q.device, dtype=q.dtype)
464
+ if self.scale is None:
465
+ q = rotary_embedding(
466
+ q,
467
+ self._cos_cached,
468
+ self._sin_cached,
469
+ interleaved=self.interleaved,
470
+ seqlen_offsets=seqlen_offset,
471
+ cu_seqlens=cu_seqlens,
472
+ )
473
+ k = rotary_embedding(
474
+ k,
475
+ self._cos_cached,
476
+ self._sin_cached,
477
+ interleaved=self.interleaved,
478
+ seqlen_offsets=seqlen_offset,
479
+ cu_seqlens=cu_seqlens,
480
+ )
481
+
482
+ else:
483
+ q = rotary_embedding(
484
+ q,
485
+ self._cos_cached,
486
+ self._sin_cached,
487
+ interleaved=self.interleaved,
488
+ seqlen_offsets=seqlen_offset,
489
+ cu_seqlens=cu_seqlens,
490
+ )
491
+ k = rotary_embedding(
492
+ k,
493
+ self._cos_k_cached,
494
+ self._sin_k_cached,
495
+ interleaved=self.interleaved,
496
+ seqlen_offsets=seqlen_offset,
497
+ cu_seqlens=cu_seqlens,
498
+ )
499
+
500
+ return q, k