msj19 commited on
Commit
7dcf46d
·
verified ·
1 Parent(s): e0fffc1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. layers/past_gdn.py +1407 -0
  2. layers/rebased.py +130 -0
  3. layers/rodimus.py +390 -0
  4. layers/rwkv6.py +362 -0
  5. layers/sig_tr_gka.py +336 -0
  6. layers/sigma_gka.py +1212 -0
  7. layers/simple_gla.py +274 -0
  8. layers/state_org.py +330 -0
  9. models/forgetting_transformer/configuration_forgetting_transformer.py +84 -0
  10. models/gated_deltanet/__init__.py +12 -0
  11. models/gated_deltaproduct/modeling_gated_deltaproduct.py +374 -0
  12. models/gka_attn/__init__.py +12 -0
  13. models/gka_attn/modeling_gka_attn.py +371 -0
  14. models/gka_net/configuration_gka_net.py +103 -0
  15. models/gka_net/modeling_gka_net.py +370 -0
  16. models/gla/__init__.py +13 -0
  17. models/gla/configuration_gla.py +111 -0
  18. models/gla/modeling_gla.py +374 -0
  19. models/gsa/configuration_gsa.py +113 -0
  20. models/gsa/modeling_gsa.py +377 -0
  21. models/hgrn/__init__.py +13 -0
  22. models/hgrn2/modeling_hgrn2.py +377 -0
  23. models/linear_attn/configuration_linear_attn.py +107 -0
  24. models/log_linear_mamba2/configuration_log_linear_mamba2.py +18 -0
  25. models/rwkv6/modeling_rwkv6.py +449 -0
  26. models/samba/__init__.py +13 -0
  27. models/samba/modeling_samba.py +386 -0
  28. models/sig_tr_gka_net/modeling_sig_tr_gka_net.py +373 -0
  29. models/sigma_gka_net/__init__.py +12 -0
  30. models/sigma_gka_net/modeling_sigma_gka_net.py +372 -0
  31. models/transformer/configuration_transformer.py +87 -0
  32. models/transformer/modeling_transformer.py +358 -0
  33. modules/__init__.py +33 -0
  34. modules/activations.py +556 -0
  35. modules/convolution.py +1168 -0
  36. modules/feature_map.py +300 -0
  37. modules/fused_bitlinear.py +634 -0
  38. modules/fused_cross_entropy.py +419 -0
  39. modules/fused_linear_cross_entropy.py +620 -0
  40. modules/fused_norm_gate.py +1257 -0
  41. modules/grpo.py +413 -0
  42. modules/l2norm.py +289 -0
  43. modules/l2warp.py +38 -0
  44. modules/layernorm_gated.py +528 -0
  45. modules/mlp.py +132 -0
  46. modules/rotary.py +501 -0
  47. modules/token_shift.py +547 -0
  48. ops/__init__.py +55 -0
  49. ops/abc/__init__.py +7 -0
  50. ops/abc/chunk.py +1117 -0
layers/past_gdn.py ADDED
@@ -0,0 +1,1407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Optional
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from einops import rearrange, repeat
10
+ from ..modules import FusedRMSNormSwishGate, RMSNorm
11
+ from fla.modules import ShortConvolution
12
+ import torch.nn.init as init
13
+ import math
14
+ from ..modules.l2norm import l2norm
15
+ from einops import rearrange
16
+ from fla.models.utils import Cache
17
+ from transformers.processing_utils import Unpack
18
+ import math
19
+ from typing import TYPE_CHECKING, Dict, Optional, Tuple
20
+ from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
21
+ # from ..modules import RotaryEmbedding
22
+ # from ..ops.gla import chunk_gla,fused_recurrent_gla
23
+
24
+
25
+ def simple_norm(x):
26
+ return (F.normalize(x, dim=-1) * x.shape[-1] ** 0.5).to(x)
27
+
28
+
29
+ # @torch.jit.script
30
+ def elu_p1(x):
31
+ return (F.elu(x, 1., False) + 1.).to(x)
32
+
33
+
34
+ # @torch.jit.script
35
+ def sum_norm(x):
36
+ return (x / x.sum(-1, keepdim=True)).to(x)
37
+
38
+
39
+ # @torch.jit.script
40
+ def elu_norm(x):
41
+ dtype = x.dtype
42
+ x = F.elu(x, 1., False) + 1.
43
+ return (x / x.sum(-1, keepdim=True)).to(dtype)
44
+
45
+ from typing import Optional, Tuple, Union
46
+
47
+ import torch
48
+ import torch.nn as nn
49
+ import triton
50
+ import triton.language as tl
51
+ from einops import rearrange, repeat
52
+
53
+ from fla.ops.utils import prepare_chunk_indices
54
+ from fla.utils import get_multiprocessor_count, input_guard
55
+
56
+
57
+ def rotate_half(x, interleaved=False):
58
+ if not interleaved:
59
+ x1, x2 = x.chunk(2, dim=-1)
60
+ return torch.cat((-x2, x1), dim=-1)
61
+ else:
62
+ x1, x2 = x[..., ::2], x[..., 1::2]
63
+ return rearrange(torch.stack((-x2, x1), dim=-1), '... d two -> ... (d two)', two=2)
64
+
65
+
66
+ def rotary_embedding_ref(x, cos, sin, interleaved=False):
67
+ ro_dim = cos.shape[-1] * 2
68
+ assert ro_dim <= x.shape[-1]
69
+ cos = repeat(cos, '... d -> ... 1 (2 d)' if not interleaved else '... d -> ... 1 (d 2)')
70
+ sin = repeat(sin, '... d -> ... 1 (2 d)' if not interleaved else '... d -> ... 1 (d 2)')
71
+ return torch.cat([x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]], -1)
72
+
73
+
74
+ @triton.autotune(
75
+ configs=[
76
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
77
+ for num_warps in [2, 4, 8, 16, 32]
78
+ for num_stages in [2, 3, 4]
79
+ ],
80
+ key=['B', 'H', 'D', 'INTERLEAVED'],
81
+ )
82
+ @triton.jit(do_not_specialize=['T'])
83
+ def rotary_embedding_kernel(
84
+ x,
85
+ cos,
86
+ sin,
87
+ y,
88
+ cu_seqlens,
89
+ chunk_indices,
90
+ seq_offsets,
91
+ T,
92
+ B: tl.constexpr,
93
+ H: tl.constexpr,
94
+ D: tl.constexpr,
95
+ R: tl.constexpr,
96
+ TR: tl.constexpr,
97
+ BT: tl.constexpr,
98
+ BD: tl.constexpr,
99
+ IS_SEQLEN_OFFSETS_TENSOR: tl.constexpr,
100
+ IS_VARLEN: tl.constexpr,
101
+ INTERLEAVED: tl.constexpr,
102
+ CONJUGATE: tl.constexpr
103
+ ):
104
+ i_t, i_b, i_h = tl.program_id(0), tl.program_id(1), tl.program_id(2)
105
+
106
+ if IS_VARLEN:
107
+ 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)
108
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
109
+ T = eos - bos
110
+ x = x + bos * H*D + i_h * D
111
+ y = y + bos * H*D + i_h * D
112
+ else:
113
+ i_n = i_b
114
+ x = x + i_n * T*H*D + i_h * D
115
+ y = y + i_n * T*H*D + i_h * D
116
+
117
+ if i_t * BT >= T:
118
+ return
119
+
120
+ o_t = i_t * BT + tl.arange(0, BT)
121
+ if not IS_SEQLEN_OFFSETS_TENSOR:
122
+ o_cs = o_t + seq_offsets
123
+ else:
124
+ o_cs = o_t + tl.load(seq_offsets + i_n)
125
+
126
+ if not INTERLEAVED:
127
+ # Load the 1st and 2nd halves of x, do calculation, then store to 1st and 2nd halves of out
128
+ o_r = tl.arange(0, BD // 2)
129
+ p_x = x + o_t[:, None] * H*D + o_r[None, :]
130
+ p_cos = cos + (o_cs[:, None] * R + o_r[None, :])
131
+ p_sin = sin + (o_cs[:, None] * R + o_r[None, :])
132
+ mask = (o_t[:, None] >= 0) & (o_t[:, None] < T) & (o_r[None, :] < R)
133
+
134
+ b_cos = tl.load(p_cos, mask=mask, other=1.0).to(tl.float32)
135
+ b_sin = tl.load(p_sin, mask=mask, other=0.0).to(tl.float32)
136
+ b_x0 = tl.load(p_x, mask=mask, other=0.0).to(tl.float32)
137
+ b_x1 = tl.load(p_x + R, mask=mask, other=0.0).to(tl.float32)
138
+ if CONJUGATE:
139
+ b_sin = -b_sin
140
+ b_o0 = b_x0 * b_cos - b_x1 * b_sin
141
+ b_o1 = b_x0 * b_sin + b_x1 * b_cos
142
+ # write back result
143
+ p_y = y + (o_t[:, None] * H*D + o_r[None, :])
144
+ tl.store(p_y, b_o0, mask=mask)
145
+ tl.store(p_y + R, b_o1, mask=mask)
146
+ else:
147
+ # We don't want to load x[0, 2, 4, ...] and x[1, 3, 5, ...] separately since both are slow.
148
+ # Instead, we load x0 = x[0, 1, 2, 3, ...] and x1 = x[1, 0, 3, 2, ...].
149
+ # Loading x0 will be fast but x1 will be slow.
150
+ # Then we load cos = cos[0, 0, 1, 1, ...] and sin = sin[0, 0, 1, 1, ...].
151
+ # Then we do the calculation and use tl.where to pick put the right outputs for the even
152
+ # and for the odd indices.
153
+ o_d = tl.arange(0, BD)
154
+ o_d_swap = o_d + ((o_d + 1) % 2) * 2 - 1 # 1, 0, 3, 2, 5, 4, ...
155
+ o_d_repeat = tl.arange(0, BD) // 2
156
+ p_x0 = x + o_t[:, None] * H*D + o_d[None, :]
157
+ p_x1 = x + o_t[:, None] * H*D + o_d_swap[None, :]
158
+ p_cos = cos + (o_cs[:, None] * R + o_d_repeat[None, :])
159
+ p_sin = sin + (o_cs[:, None] * R + o_d_repeat[None, :])
160
+ mask = (o_cs[:, None] >= 0) & (o_cs[:, None] < TR) & (o_d_repeat[None, :] < R)
161
+
162
+ b_cos = tl.load(p_cos, mask=mask, other=1.0).to(tl.float32)
163
+ b_sin = tl.load(p_sin, mask=mask, other=0.0).to(tl.float32)
164
+ b_x0 = tl.load(p_x0, mask=mask, other=0.0).to(tl.float32)
165
+ b_x1 = tl.load(p_x1, mask=mask, other=0.0).to(tl.float32)
166
+ if CONJUGATE:
167
+ b_sin = -b_sin
168
+ b_o0 = b_x0 * b_cos
169
+ b_o1 = b_x1 * b_sin
170
+ b_y = tl.where(o_d[None, :] % 2 == 0, b_o0 - b_o1, b_o0 + b_o1)
171
+ p_y = y + (o_t[:, None] * H*D + o_d[None, :])
172
+ tl.store(p_y, b_y, mask=mask)
173
+
174
+
175
+ def rotary_embedding_fwdbwd(
176
+ x: torch.Tensor,
177
+ cos: torch.Tensor,
178
+ sin: torch.Tensor,
179
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
180
+ cu_seqlens: Optional[torch.Tensor] = None,
181
+ interleaved: bool = False,
182
+ inplace: bool = False,
183
+ conjugate: bool = False
184
+ ) -> torch.Tensor:
185
+ """
186
+ Args:
187
+ x: [B, T, H, D].
188
+ cos: [TR, R / 2]
189
+ sin: [TR, R / 2]
190
+ seqlen_offsets: integer or integer tensor of size [N]
191
+ cu_seqlens: [N + 1,] or None
192
+
193
+ Returns:
194
+ y: [B, T, H, D]
195
+ """
196
+ is_varlen = cu_seqlens is not None
197
+
198
+ B, T, H, D = x.shape
199
+ N = B if not is_varlen else cu_seqlens.shape[0] - 1
200
+ TR, R = cos.shape
201
+ R2 = R * 2
202
+
203
+ assert D <= 256, "Only support D <= 256"
204
+ assert TR >= T, "TR must be >= T"
205
+
206
+ assert cos.dtype == sin.dtype, f"cos and sin must have the same dtype, got {cos.dtype} and {sin.dtype}"
207
+ assert x.dtype == cos.dtype, f"Input and cos/sin must have the same dtype, got {x.dtype} and {cos.dtype}"
208
+
209
+ if isinstance(seqlen_offsets, torch.Tensor):
210
+ assert seqlen_offsets.shape == (N,)
211
+ assert seqlen_offsets.dtype in [torch.int32, torch.int64]
212
+ else:
213
+ assert seqlen_offsets + T <= TR
214
+
215
+ y = torch.empty_like(x) if not inplace else x
216
+ if R2 < D and not inplace:
217
+ y[..., R2:].copy_(x[..., R2:])
218
+
219
+ BD = triton.next_power_of_2(R2)
220
+ BT = min(128, triton.next_power_of_2(triton.cdiv(T, get_multiprocessor_count(x.device.index))))
221
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if is_varlen else None
222
+ NT = len(chunk_indices) if is_varlen else triton.cdiv(T, BT)
223
+
224
+ grid = (NT, B, H)
225
+ rotary_embedding_kernel[grid](
226
+ x,
227
+ cos,
228
+ sin,
229
+ y,
230
+ cu_seqlens,
231
+ chunk_indices,
232
+ seqlen_offsets,
233
+ B=B,
234
+ T=T,
235
+ H=H,
236
+ D=D,
237
+ R=R,
238
+ TR=TR,
239
+ BT=BT,
240
+ BD=BD,
241
+ IS_SEQLEN_OFFSETS_TENSOR=isinstance(seqlen_offsets, torch.Tensor),
242
+ IS_VARLEN=is_varlen,
243
+ INTERLEAVED=interleaved,
244
+ CONJUGATE=conjugate
245
+ )
246
+ return y
247
+
248
+
249
+ class RotaryEmbeddingFunction(torch.autograd.Function):
250
+
251
+ @staticmethod
252
+ @input_guard
253
+ def forward(
254
+ ctx,
255
+ x,
256
+ cos,
257
+ sin,
258
+ interleaved=False,
259
+ inplace=False,
260
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
261
+ cu_seqlens: Optional[torch.Tensor] = None,
262
+ ):
263
+ y = rotary_embedding_fwdbwd(
264
+ x,
265
+ cos,
266
+ sin,
267
+ seqlen_offsets=seqlen_offsets,
268
+ cu_seqlens=cu_seqlens,
269
+ interleaved=interleaved,
270
+ inplace=inplace,
271
+ )
272
+ if isinstance(seqlen_offsets, int):
273
+ # Can't save int with save_for_backward
274
+ ctx.save_for_backward(cos, sin, cu_seqlens)
275
+ ctx.seqlen_offsets = seqlen_offsets
276
+ else:
277
+ ctx.save_for_backward(cos, sin, cu_seqlens, seqlen_offsets)
278
+ ctx.seqlen_offsets = None
279
+ ctx.interleaved = interleaved
280
+ ctx.inplace = inplace
281
+ return y if not inplace else x
282
+
283
+ @staticmethod
284
+ @input_guard
285
+ def backward(ctx, do):
286
+ seqlen_offsets = ctx.seqlen_offsets
287
+ if seqlen_offsets is None:
288
+ cos, sin, cu_seqlens, seqlen_offsets = ctx.saved_tensors
289
+ else:
290
+ cos, sin, cu_seqlens = ctx.saved_tensors
291
+ # TD [2023-09-02]: For some reason Triton (2.0.0.post1) errors with
292
+ # "[CUDA]: invalid device context", and cloning makes it work. Idk why. Triton 2.1.0 works.
293
+ if not ctx.interleaved and not ctx.inplace:
294
+ do = do.clone()
295
+ dx = rotary_embedding_fwdbwd(
296
+ do,
297
+ cos,
298
+ sin,
299
+ seqlen_offsets=seqlen_offsets,
300
+ cu_seqlens=cu_seqlens,
301
+ interleaved=ctx.interleaved,
302
+ inplace=ctx.inplace,
303
+ conjugate=True,
304
+ )
305
+ return dx, None, None, None, None, None, None, None
306
+
307
+
308
+ def rotary_embedding(
309
+ x,
310
+ cos,
311
+ sin,
312
+ interleaved=False,
313
+ inplace=False,
314
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
315
+ cu_seqlens: Optional[torch.Tensor] = None
316
+ ):
317
+ """
318
+ Args:
319
+ x: [B, T, H, D]
320
+ cos, sin: [TR, R//2]
321
+ interleaved:
322
+ If True, rotate pairs of even and odd dimensions (GPT-J style) instead of 1st half and 2nd half (GPT-NeoX style).
323
+ inplace:
324
+ If True, apply rotary embedding in-place.
325
+ seqlen_offsets: [N,] or int.
326
+ Each sequence in x is shifted by this amount.
327
+ Most commonly used in inference when we have KV cache.
328
+ cu_seqlens: [N + 1,] or None
329
+
330
+ Returns:
331
+ out: [B, T, H, D]
332
+ """
333
+ return RotaryEmbeddingFunction.apply(
334
+ x,
335
+ cos,
336
+ sin,
337
+ interleaved,
338
+ inplace,
339
+ seqlen_offsets,
340
+ cu_seqlens
341
+ )
342
+
343
+
344
+ class RotaryEmbedding(nn.Module):
345
+ """
346
+ The rotary position embeddings from RoFormer_ (Su et. al).
347
+ A crucial insight from the method is that the query and keys are
348
+ transformed by rotation matrices which depend on the relative positions.
349
+
350
+ Other implementations are available in the Rotary Transformer repo_ and in
351
+ GPT-NeoX_, GPT-NeoX was an inspiration
352
+
353
+ .. _RoFormer: https://arxiv.org/abs/2104.09864
354
+ .. _repo: https://github.com/ZhuiyiTechnology/roformer
355
+ .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox
356
+
357
+ If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554).
358
+ A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96
359
+ Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py
360
+ """
361
+
362
+ def __init__(
363
+ self,
364
+ dim: int,
365
+ base: float = 10000.0,
366
+ scale_base: Optional[float] = None,
367
+ interleaved: bool = False,
368
+ pos_idx_in_fp32: bool = True,
369
+ device: Optional[torch.device] = None,
370
+ ):
371
+ """
372
+ interleaved:
373
+ If True, rotate pairs of even and odd dimensions (GPT-J style) instead of 1st half and 2nd half (GPT-NeoX style).
374
+ pos_idx_in_fp32:
375
+ If True, the position indices [0.0, ..., seqlen - 1] are in fp32, otherwise they might be in lower precision.
376
+ This option was added because previously (before 2023-07-02), when we construct
377
+ the position indices, we use the dtype of self.inv_freq.
378
+ In most cases this would be fp32, but if the model is trained in pure bf16 (not mixed precision), then
379
+ self.inv_freq would be bf16, and the position indices are also in bf16.
380
+ Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the
381
+ embeddings for some positions will coincide.
382
+ To maintain compatibility with models previously trained in pure bf16, we add this option.
383
+ """
384
+ super().__init__()
385
+
386
+ self.dim = dim
387
+ self.base = float(base)
388
+ self.scale_base = scale_base
389
+ self.interleaved = interleaved
390
+ self.pos_idx_in_fp32 = pos_idx_in_fp32
391
+ self.device = device
392
+
393
+ # Generate and save the inverse frequency buffer (non trainable)
394
+ self.register_buffer("inv_freq", torch.empty(-(dim // -2), dtype=torch.float32, device=device), persistent=False)
395
+
396
+ scale = None
397
+ if scale_base is not None:
398
+ scale = torch.empty(-(dim // -2), dtype=torch.float32, device=device)
399
+ self.register_buffer("scale", scale, persistent=False)
400
+
401
+ self._seq_len_cached = 0
402
+ self._cos_cached = None
403
+ self._sin_cached = None
404
+ self._cos_k_cached = None
405
+ self._sin_k_cached = None
406
+
407
+ self.reset_parameters()
408
+
409
+ def reset_parameters(self):
410
+ with torch.no_grad():
411
+ self.inv_freq.copy_(self._compute_inv_freq(device=self.inv_freq.device))
412
+ if self.scale_base is not None:
413
+ self.scale.copy_(self._compute_scale(device=self.scale.device))
414
+
415
+ def __repr__(self):
416
+ s = f"{self.__class__.__name__}("
417
+ s += f"dim={self.dim}, "
418
+ s += f"base={self.base}, "
419
+ s += f"interleaved={self.interleaved}, "
420
+ if self.scale_base is not None:
421
+ s += f"scale_base={self.scale_base}, "
422
+ s += f"pos_idx_in_fp32={self.pos_idx_in_fp32})"
423
+ return s
424
+
425
+ def _compute_inv_freq(self, device=None):
426
+ return 1.0 / (
427
+ self.base
428
+ ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim)
429
+ )
430
+
431
+ def _compute_scale(self, device=None):
432
+ return (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) + 0.4 * self.dim) / (1.4 * self.dim)
433
+
434
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
435
+ # Reset the tables if the sequence length has changed,
436
+ # if we're on a new device (possibly due to tracing for instance),
437
+ # or if we're switching from inference mode to training
438
+ if (
439
+ seqlen > self._seq_len_cached
440
+ or self._cos_cached is None
441
+ or self._cos_cached.device != device
442
+ or self._cos_cached.dtype != dtype
443
+ or (self.training and self._cos_cached.is_inference())
444
+ ):
445
+ self._seq_len_cached = seqlen
446
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
447
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
448
+ # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
449
+ if self.pos_idx_in_fp32:
450
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
451
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
452
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
453
+ # cos & sin output to change significantly.
454
+ # We want to recompute self.inv_freq if it was not loaded in fp32
455
+ if self.inv_freq.dtype != torch.float32:
456
+ inv_freq = self._compute_inv_freq(device=device)
457
+ else:
458
+ inv_freq = self.inv_freq
459
+ else:
460
+ t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
461
+ inv_freq = self.inv_freq
462
+ # Don't do einsum, it converts fp32 to fp16 under AMP
463
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
464
+ freqs = torch.outer(t, inv_freq)
465
+ if self.scale is None:
466
+ self._cos_cached = torch.cos(freqs).to(dtype)
467
+ self._sin_cached = torch.sin(freqs).to(dtype)
468
+ else:
469
+ power = (
470
+ torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device)
471
+ - seqlen // 2
472
+ ) / self.scale_base
473
+ scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
474
+ # We want the multiplication by scale to happen in fp32
475
+ self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
476
+ self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
477
+ self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
478
+ self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
479
+
480
+ def forward(
481
+ self,
482
+ q: torch.Tensor,
483
+ k: torch.Tensor,
484
+ seqlen_offset: Union[int, torch.Tensor] = 0,
485
+ cu_seqlens: Optional[torch.Tensor] = None,
486
+ max_seqlen: Optional[int] = None,
487
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
488
+ """
489
+ q: [B, T, H, D]
490
+ k: [B, T, H, D]
491
+ seqlen_offset:
492
+ [N] or int.
493
+ Each sequence in x is shifted by this amount.
494
+ Most commonly used in inference when we have KV cache.
495
+ cu_seqlens: [N + 1] or None
496
+ max_seqlen: int
497
+ """
498
+ if max_seqlen is not None:
499
+ self._update_cos_sin_cache(max_seqlen, device=q.device, dtype=q.dtype)
500
+ elif isinstance(seqlen_offset, int):
501
+ self._update_cos_sin_cache(q.shape[1] + seqlen_offset, device=q.device, dtype=q.dtype)
502
+ if self.scale is None:
503
+ q = rotary_embedding(
504
+ q,
505
+ self._cos_cached,
506
+ self._sin_cached,
507
+ interleaved=self.interleaved,
508
+ seqlen_offsets=seqlen_offset,
509
+ cu_seqlens=cu_seqlens,
510
+ )
511
+ k = rotary_embedding(
512
+ k,
513
+ self._cos_cached,
514
+ -self._sin_cached,
515
+ interleaved=self.interleaved,
516
+ seqlen_offsets=seqlen_offset,
517
+ cu_seqlens=cu_seqlens,
518
+ )
519
+
520
+ else:
521
+ q = rotary_embedding(
522
+ q,
523
+ self._cos_cached,
524
+ self._sin_cached,
525
+ interleaved=self.interleaved,
526
+ seqlen_offsets=seqlen_offset,
527
+ cu_seqlens=cu_seqlens,
528
+ )
529
+ k = rotary_embedding(
530
+ k,
531
+ self._cos_k_cached,
532
+ -self._sin_k_cached,
533
+ interleaved=self.interleaved,
534
+ seqlen_offsets=seqlen_offset,
535
+ cu_seqlens=cu_seqlens,
536
+ )
537
+ return q, k
538
+
539
+ def stride_blhdtoblhrd(x,ratio:int,head_chunk_size,left=False):
540
+ assert x.dim() == 4 #blhd
541
+ batch_size, q_len, num_heads, head_qk_dim = x.shape
542
+ x_exp = []
543
+ for i in range(num_heads):
544
+ xi_exp = []
545
+ xi_exp.append(x[:,:,i:i+1,:])
546
+ for ratio_i in range(1,ratio):
547
+ pad = x.new_zeros((batch_size, head_chunk_size[i]*ratio_i, 1, head_qk_dim))###BL1D
548
+ xi_exp.append(torch.cat([x[:,:,i:i+1,:], pad], dim=1)[:,-q_len:,...])###BL1D
549
+ x_exp.append(torch.cat(xi_exp, dim=2).unsqueeze(2))###BL1D->BLRD->BL1RD
550
+ x_exp = torch.cat(x_exp, dim=2)###BL1RD->BLHRD
551
+ return x_exp
552
+
553
+ def stride_blhrdtoblhrd(x,ratio:int,head_chunk_size,left=True,inf=False):
554
+ assert x.dim() == 5 #blhrd
555
+ assert x.shape[-2] == ratio
556
+ batch_size, q_len, num_heads, _ , head_qk_dim = x.shape
557
+ x_exp = []
558
+ if inf:
559
+ for i in range(num_heads):
560
+ xi_exp = []
561
+ xi_exp.append(x[:,:,i:i+1,0,:])###BL1D
562
+ for ratio_i in range(1,ratio):
563
+ pad = x.new_full((batch_size, head_chunk_size[i]*ratio_i, 1, head_qk_dim), float('-inf'))###BL1D
564
+ xi_exp.append(torch.cat([pad, x[:,head_chunk_size[i]*ratio_i:,i:i+1,ratio_i,:]], dim=1)[:,:q_len,...])###BL1D
565
+ x_exp.append(torch.cat(xi_exp, dim=2).unsqueeze(2))###BL1D->BLRD->BL1RD
566
+ x_exp = torch.cat(x_exp, dim=2)###BL1RD->BLHRD
567
+ return x_exp
568
+ else:
569
+ for i in range(num_heads):
570
+ xi_exp = []
571
+ xi_exp.append(x[:,:,i:i+1,0,:])
572
+ for ratio_i in range(1,ratio):
573
+ pad = x.new_zeros((batch_size, head_chunk_size[i]*ratio_i, 1, head_qk_dim))
574
+ xi_exp.append(torch.cat([pad, x[:,head_chunk_size[i]*ratio_i:,i:i+1,ratio_i,:]], dim=1)[:,:q_len,...])
575
+ x_exp.append(torch.cat(xi_exp, dim=2).unsqueeze(2))###BL1D->BLRD->BL1RD
576
+ x_exp = torch.cat(x_exp, dim=2)###BL1RD->BLHRD
577
+ return x_exp
578
+
579
+ # def stride_blhdtoblhrd(x,ratio:int,head_chunk_size,left=False):
580
+ # assert x.dim() == 4 #blhd
581
+ # batch_size, q_len, num_heads, head_qk_dim = x.shape
582
+ # x_exp = []
583
+ # for i in range(num_heads):
584
+ # for ratio_i in range(ratio):
585
+ # pad = x.new_zeros((batch_size, head_chunk_size[i]*1, 1, head_qk_dim))
586
+ # x_exp.append(torch.cat([x[:,:,i:i+1,:], pad], dim=1)[:,head_chunk_size[i]*1:,...])
587
+ # x_exp = torch.cat(x_exp, dim=2)
588
+ # return x_exp
589
+
590
+ # def stride_blhrdtoblhrd(x,ratio:int,head_chunk_size,left=True,inf=False):
591
+ # assert x.dim() == 5 #blhrd
592
+ # assert x.shape[-2] == ratio
593
+ # batch_size, q_len, num_heads, _ , head_qk_dim = x.shape
594
+ # x_exp = []
595
+ # if inf:
596
+ # for i in range(num_heads):
597
+ # for ratio_i in range(ratio):
598
+ # pad = x.new_full((batch_size, head_chunk_size[i]*1, 1, head_qk_dim), float('-inf'))
599
+ # x_exp.append(torch.cat([pad, x[:,head_chunk_size[i]*1:,i:i+1,ratio_i,:]], dim=1)[:,:q_len,...])
600
+ # x_exp = torch.cat(x_exp, dim=2)
601
+ # return x_exp
602
+ # else:
603
+ # for i in range(num_heads):
604
+ # for ratio_i in range(ratio):
605
+ # pad = x.new_zeros((batch_size, head_chunk_size[i]*1, 1, head_qk_dim))
606
+ # x_exp.append(torch.cat([pad, x[:,head_chunk_size[i]*1:,i:i+1,ratio_i,:]], dim=1)[:,:q_len,...])
607
+ # x_exp = torch.cat(x_exp, dim=2)
608
+ # return x_exp
609
+
610
+
611
+
612
+
613
+ # from ..ops.gated_delta_rule import chunk_gated_delta_rule,fused_recurrent_gated_delta_rule
614
+ # class past_gdn(nn.Module):
615
+ # def __init__(
616
+ # self,
617
+ # d_model: int = None,
618
+ # hidden_size: int = 1024,
619
+ # expand_k: float = 1.0,
620
+ # expand_v: float = 1.0,
621
+ # num_heads: int = 4,
622
+ # mode: str = 'chunk',
623
+ # chunk_size: int = 64,
624
+ # use_beta: bool = True,
625
+ # use_gate: bool = False,
626
+ # use_output_norm: bool = True,
627
+ # use_elu: bool = False,
628
+ # use_short_conv: bool = True,
629
+ # conv_size: int = 4,
630
+ # conv_bias: bool = False,
631
+ # layer_idx: int = None,
632
+ # qk_activation: str = 'silu',
633
+ # qk_norm: str = 'l2',
634
+ # norm_first: bool = False,
635
+ # norm_eps: float = 1e-6,
636
+ # ratio :int = 2,
637
+ # topk : int = 1,
638
+ # **kwargs
639
+ # ) :
640
+ # super().__init__()
641
+
642
+ # self.mode = mode
643
+ # self.qk_activation = qk_activation
644
+ # self.qk_norm = qk_norm
645
+
646
+ # assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
647
+ # assert self.qk_norm in ['l2', 'sum']
648
+
649
+ # if d_model is not None:
650
+ # hidden_size = d_model
651
+ # self.hidden_size = hidden_size
652
+ # self.expand_k = expand_k
653
+ # self.expand_v = expand_v
654
+ # self.num_heads = num_heads
655
+ # self.chunk_size = chunk_size
656
+ # self.use_gate = use_gate
657
+ # self.use_output_norm = use_output_norm
658
+ # self.use_short_conv = use_short_conv
659
+ # self.conv_size = conv_size
660
+ # self.conv_bias = conv_bias
661
+
662
+ # self.key_dim = int(hidden_size * expand_k)
663
+ # self.value_dim = int(hidden_size * expand_v)
664
+ # self.head_qk_dim = self.key_dim // num_heads
665
+ # self.head_v_dim = self.value_dim // num_heads
666
+ # self.norm_first = norm_first
667
+ # self.layer_idx = layer_idx
668
+ # self.top_k = topk
669
+ # self.silu = nn.SiLU()
670
+ # assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
671
+ # assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
672
+ # assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
673
+ # if norm_first:
674
+ # self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
675
+ # self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
676
+ # self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
677
+ # self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
678
+ # self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
679
+
680
+ # A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
681
+ # self.A_log = nn.Parameter(torch.log(A))
682
+ # self.A_log._no_weight_decay = True
683
+ # # hard coded for now
684
+ # dt_min = 0.001
685
+ # dt_max = 0.1
686
+ # dt_init_floor = 1e-4
687
+ # dt = torch.exp(
688
+ # torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
689
+ # + math.log(dt_min)
690
+ # )
691
+ # dt = torch.clamp(dt, min=dt_init_floor)
692
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
693
+ # inv_dt = dt + torch.log(-torch.expm1(-dt))
694
+ # self.dt_bias = nn.Parameter(inv_dt)
695
+ # # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
696
+ # # name.endswith("bias") in param_grouping.py
697
+ # self.dt_bias._no_weight_decay = True
698
+
699
+
700
+ # self.use_beta = use_beta
701
+ # self.use_elu = use_elu
702
+ # if self.use_beta:
703
+ # self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
704
+ # if use_short_conv:
705
+ # self.conv_size = conv_size
706
+ # self.q_conv1d = ShortConvolution(self.key_dim,
707
+ # conv_size,
708
+ # activation='silu' if qk_activation == 'silu' else None)
709
+ # self.k_conv1d = ShortConvolution(self.key_dim,
710
+ # conv_size,
711
+ # activation='silu' if qk_activation == 'silu' else None)
712
+ # self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
713
+ # self.add_dim = 16 ###相当于差值get 旋转,然而这里我们有一定的控制,实质得到的结果可能需要再给一个映射到1的系数
714
+ # if self.add_dim !=1:
715
+ # self.rotary = RotaryEmbedding(dim=self.add_dim, base=50000)
716
+ # self.vector_to_one = nn.Linear(self.add_dim, 1, bias=False)
717
+ # print('rotary')
718
+ # if use_gate:
719
+ # self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
720
+ # self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
721
+ # else:
722
+ # self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
723
+ # self.rmsnorm = RMSNorm(self.head_v_dim, eps=norm_eps,elementwise_affine=False)
724
+ # self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
725
+ # self.ratio = ratio
726
+ # self.top_k = topk
727
+ # print(self.ratio)
728
+ # print(self.top_k)
729
+ # ###64 128 256 512 for num_heads=4
730
+ # self.past_chunk_size = [64 for i in range(self.num_heads)]
731
+ # # self.past_chunk_size = [64*(2**i) for i in range(self.num_heads)] ###或许需要根据不同头调整past_chunk_size
732
+ # ###根据ratio看保留最近的几个chunk_state
733
+
734
+ # def _initialize_weights(self, module: nn.Module):
735
+ # if getattr(module, "_is_hf_initialized", False):
736
+ # return
737
+ # if isinstance(module, nn.Linear):
738
+ # nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
739
+ # if module.bias is not None:
740
+ # nn.init.zeros_(module.bias)
741
+ # module._is_hf_initialized = True
742
+
743
+ # def forward(
744
+ # self,
745
+ # hidden_states: torch.Tensor,
746
+ # attention_mask: Optional[torch.Tensor] = None,
747
+ # past_key_values: Optional[Cache] = None,
748
+ # use_cache: Optional[bool] = False,
749
+ # output_attentions: Optional[bool] = False,
750
+ # **kwargs
751
+ # ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
752
+ # # change to inference mode.
753
+ # if attention_mask is not None:
754
+ # assert len(attention_mask.shape) == 2, (
755
+ # "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
756
+ # "for padding purposes (0 indicating padding). "
757
+ # "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
758
+ # )
759
+ # batch_size, q_len, _ = hidden_states.shape
760
+ # # change to inference mode.
761
+ # mode = 'fused_recurrent' if q_len <= 64 else self.mode
762
+ # if self.training:
763
+ # assert mode == 'chunk', "Only chunk mode is supported in training."
764
+
765
+ # last_state = None
766
+ # if past_key_values is not None and len(past_key_values) > self.layer_idx:
767
+ # last_state = past_key_values[self.layer_idx]
768
+
769
+ # cu_seqlens = kwargs.get('cu_seqlens', None)
770
+ # if attention_mask is not None:
771
+ # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
772
+ # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
773
+
774
+ # if self.use_short_conv:
775
+ # conv_state_q , conv_state_k , conv_state_v = None,None,None
776
+ # if last_state is not None:
777
+ # conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
778
+ # q = self.q_proj(hidden_states)
779
+ # k = self.k_proj(hidden_states)
780
+ # v = self.v_proj(hidden_states)
781
+ # q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
782
+ # k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
783
+ # v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
784
+ # else:
785
+ # q = F.silu(self.q_proj(hidden_states))
786
+ # k = F.silu(self.k_proj(hidden_states))
787
+ # v = F.silu(self.v_proj(hidden_states))
788
+
789
+ # q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_qk_dim), (q, k))
790
+ # v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
791
+ # beta = self.b_proj(hidden_states).sigmoid()
792
+ # # if self.allow_neg_eigval:
793
+ # # beta = beta * 2.
794
+
795
+ # q = l2norm(q)
796
+ # k = l2norm(k)
797
+ # recurrent_state = None
798
+ # if last_state is not None:
799
+ # recurrent_state = last_state['recurrent_state']
800
+ # g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
801
+
802
+
803
+ # seqlen_offset, max_seqlen = 0, q_len
804
+ # if past_key_values is not None:
805
+ # seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
806
+ # max_seqlen = q.shape[1] + seqlen_offset
807
+
808
+ # v_add = torch.ones(batch_size, q_len,self.num_heads,self.add_dim,device=v.device,dtype=v.dtype)
809
+ # if self.add_dim !=1:
810
+ # v_add, _ = self.rotary(v_add,v_add, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
811
+ # v_expand = torch.cat([v, v_add], dim=-1)###B L H D+16
812
+ # ####################需要调整一下q,前部分mask掉
813
+ # q_exp = stride_blhdtoblhrd(q,self.ratio,self.past_chunk_size)
814
+ # # print(q_exp[0,:,0,0])####
815
+ # k_exp = rearrange(k.unsqueeze(-2).repeat(1,1,1,self.ratio,1),'b l h r d->b l (h r) d')###B L (HR) D
816
+ # v_exp = rearrange(v_expand.unsqueeze(-2).repeat(1,1,1,self.ratio,1),'b l h r d->b l (h r) d')###B L (HR) D
817
+ # beta_exp = rearrange(beta.unsqueeze(-1).repeat(1,1,1,self.ratio),'b l h r->b l (h r)')###B L (HR)
818
+ # g_exp = rearrange(g.unsqueeze(-1).repeat(1,1,1,self.ratio),'b l h r->b l (h r)')###B L (HR)
819
+
820
+ # # if self.num_v_heads > self.num_heads:
821
+ # # q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k))
822
+ # if mode == 'recurrent':
823
+ # o, recurrent_state = fused_recurrent_gated_delta_rule(
824
+ # q=q_exp,
825
+ # k=k_exp,
826
+ # v=v_exp,
827
+ # g=g_exp,
828
+ # beta=beta_exp,
829
+ # initial_state=recurrent_state,
830
+ # output_final_state=use_cache,
831
+ # cu_seqlens=cu_seqlens,
832
+ # use_qk_l2norm_in_kernel=False
833
+ # )
834
+ # else:
835
+ # o,recurrent_state = chunk_gated_delta_rule(
836
+ # q=q_exp,
837
+ # k=k_exp,
838
+ # v=v_exp,
839
+ # g=g_exp,
840
+ # beta=beta_exp,
841
+ # initial_state=recurrent_state,
842
+ # output_final_state=use_cache,
843
+ # cu_seqlens=cu_seqlens,
844
+ # use_qk_l2norm_in_kernel=False
845
+ # )
846
+ # if past_key_values is not None:
847
+ # past_key_values.update(
848
+ # recurrent_state=(recurrent_state),
849
+ # conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
850
+ # layer_idx=self.layer_idx,
851
+ # offset=q_len
852
+ # )
853
+ # ####先考虑把序列重新拉出来
854
+
855
+ # represent_qk_sep = (o[...,-self.add_dim:])###BLHR16
856
+ # o_sep = o[...,:-self.add_dim]###BL(HR)D
857
+ # represent_qk_sep = rearrange(represent_qk_sep,'b l (h r) d->b l h r d',h=self.num_heads)
858
+ # o_sep = rearrange(o_sep,'b l (h r) d->b l h r d',h=self.num_heads)
859
+ # o_sep = stride_blhrdtoblhrd(o_sep,self.ratio,self.past_chunk_size,inf=False)
860
+ # o_sep = rearrange(o_sep,'b l (h r) d->b l h r d',h=self.num_heads)
861
+ # o_sep = self.rmsnorm(o_sep)##随意缩放一下,基本等价于L2norm,除了多了一个缩放稀疏,让每个state平权
862
+
863
+
864
+ # mask = stride_blhrdtoblhrd(represent_qk_sep,self.ratio,self.past_chunk_size,inf=True)[:,:,0,0]###BL
865
+ # mask = torch.isinf(mask)
866
+
867
+ # represent_qk_sep = stride_blhrdtoblhrd(represent_qk_sep,self.ratio,self.past_chunk_size,inf=False)
868
+ # _, represent_qk_sep = self.rotary(represent_qk_sep,represent_qk_sep, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
869
+ # represent_qk_sep = rearrange(represent_qk_sep,'b l (h r) d->b l h r d',h=self.num_heads)
870
+ # represent_qk_sep = self.vector_to_one(represent_qk_sep).squeeze()###B L H R
871
+ # ####根据mask 哪里是inf把represent qk也inf
872
+ # represent_qk_sep = represent_qk_sep.masked_fill(mask[:,:,None,None], float('-inf'))
873
+
874
+ # o = o_sep.sum(dim=-2)
875
+ # # softmax_qk = torch.softmax(represent_qk_sep,dim=-1)###BLH r
876
+ # # o = torch.einsum('b l h r d, b l h r ->b l h d',o_sep,softmax_qk)###B L H D
877
+ # # print(o)
878
+ # # o = rearrange(o,'b l (h r) d->b l h r d',h=self.num_heads)
879
+ # # o = stride_blhrdtoblhrd(o,self.ratio,self.past_chunk_size,inf=True)
880
+ # # o = rearrange(o,'b l (h r) d->b l h r d',h=self.num_heads)
881
+ # # print(o[0,:,0,0,0])####
882
+ # # assert 1==0
883
+ # # _, represent_qk_sep = self.rotary(represent_qk_sep,represent_qk_sep, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
884
+ # # represent_qk_sep = self.vector_to_one(represent_qk_sep).squeeze()###B L H R
885
+ # # softmax_qk = torch.softmax(represent_qk_sep,dim=-1)###BLH r
886
+ # # # print(o_sep.shape)
887
+ # # o_sep = self.rmsnorm(o_sep)##随意缩放一下,基本等价于L2norm,除了多了一个缩放稀疏,让每个state平权
888
+ # # o = torch.einsum('b l h r d, b l h r ->b l h d',o_sep,softmax_qk)###B L H D
889
+ # # if self.use_gate:
890
+ # # g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads)
891
+ # # o = self.o_norm(o, g)
892
+ # # else:
893
+ # o = self.o_norm(o)
894
+ # o = rearrange(o, 'b l h d -> b l (h d)')
895
+ # # print(o.shape)
896
+ # o = self.o_proj(o)
897
+ # if attention_mask is not None:
898
+ # o = pad_input(o.squeeze(0), indices, batch_size, q_len)
899
+ # return o, None, past_key_values,None
900
+
901
+
902
+ # #######################################这个版本的代码使用固定的scale,用于控制不同state的占比
903
+ # from ..ops.gated_delta_rule import chunk_gated_delta_rule,fused_recurrent_gated_delta_rule
904
+ # class past_gdn(nn.Module):
905
+ # def __init__(
906
+ # self,
907
+ # d_model: int = None,
908
+ # hidden_size: int = 1024,
909
+ # expand_k: float = 1.0,
910
+ # expand_v: float = 1.0,
911
+ # num_heads: int = 4,
912
+ # mode: str = 'chunk',
913
+ # chunk_size: int = 64,
914
+ # use_beta: bool = True,
915
+ # use_gate: bool = False,
916
+ # use_output_norm: bool = True,
917
+ # use_elu: bool = False,
918
+ # use_short_conv: bool = True,
919
+ # conv_size: int = 4,
920
+ # conv_bias: bool = False,
921
+ # layer_idx: int = None,
922
+ # qk_activation: str = 'silu',
923
+ # qk_norm: str = 'l2',
924
+ # norm_first: bool = False,
925
+ # norm_eps: float = 1e-6,
926
+ # ratio: int = 2,
927
+ # **kwargs
928
+ # ) :
929
+ # super().__init__()
930
+
931
+ # self.mode = mode
932
+ # self.qk_activation = qk_activation
933
+ # self.qk_norm = qk_norm
934
+
935
+ # assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
936
+ # assert self.qk_norm in ['l2', 'sum']
937
+
938
+ # if d_model is not None:
939
+ # hidden_size = d_model
940
+ # self.hidden_size = hidden_size
941
+ # self.expand_k = expand_k
942
+ # self.expand_v = expand_v
943
+ # self.num_heads = num_heads
944
+ # self.chunk_size = chunk_size
945
+ # self.use_gate = use_gate
946
+ # self.use_output_norm = use_output_norm
947
+ # self.use_short_conv = use_short_conv
948
+ # self.conv_size = conv_size
949
+ # self.conv_bias = conv_bias
950
+
951
+ # self.key_dim = int(hidden_size * expand_k)
952
+ # self.value_dim = int(hidden_size * expand_v)
953
+ # self.head_qk_dim = self.key_dim // num_heads
954
+ # self.head_v_dim = self.value_dim // num_heads
955
+ # self.norm_first = norm_first
956
+ # self.layer_idx = layer_idx
957
+
958
+ # self.silu = nn.SiLU()
959
+ # assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
960
+ # assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
961
+ # assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
962
+ # if norm_first:
963
+ # self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
964
+ # self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
965
+ # self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
966
+ # self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
967
+ # self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
968
+
969
+ # A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
970
+ # self.A_log = nn.Parameter(torch.log(A))
971
+ # self.A_log._no_weight_decay = True
972
+ # # hard coded for now
973
+ # dt_min = 0.001
974
+ # dt_max = 0.1
975
+ # dt_init_floor = 1e-4
976
+ # dt = torch.exp(
977
+ # torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
978
+ # + math.log(dt_min)
979
+ # )
980
+ # dt = torch.clamp(dt, min=dt_init_floor)
981
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
982
+ # inv_dt = dt + torch.log(-torch.expm1(-dt))
983
+ # self.dt_bias = nn.Parameter(inv_dt)
984
+ # # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
985
+ # # name.endswith("bias") in param_grouping.py
986
+ # self.dt_bias._no_weight_decay = True
987
+
988
+
989
+ # self.use_beta = use_beta
990
+ # self.use_elu = use_elu
991
+ # if self.use_beta:
992
+ # self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
993
+ # if use_short_conv:
994
+ # self.conv_size = conv_size
995
+ # self.q_conv1d = ShortConvolution(self.key_dim,
996
+ # conv_size,
997
+ # activation='silu' if qk_activation == 'silu' else None)
998
+ # self.k_conv1d = ShortConvolution(self.key_dim,
999
+ # conv_size,
1000
+ # activation='silu' if qk_activation == 'silu' else None)
1001
+ # self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
1002
+ # if use_gate:
1003
+ # self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
1004
+ # self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
1005
+ # else:
1006
+ # self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
1007
+ # self.rmsnorm = RMSNorm(self.head_v_dim, eps=norm_eps,elementwise_affine=False)
1008
+ # self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
1009
+ # self.ratio = ratio
1010
+ # self.chunk_scale = nn.Parameter(torch.ones(self.num_heads,self.ratio))
1011
+ # self.past_chunk_size = [64*(2**i) for i in range(self.num_heads)]
1012
+
1013
+ # def _initialize_weights(self, module: nn.Module):
1014
+ # if getattr(module, "_is_hf_initialized", False):
1015
+ # return
1016
+ # if isinstance(module, nn.Linear):
1017
+ # nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
1018
+ # if module.bias is not None:
1019
+ # nn.init.zeros_(module.bias)
1020
+ # module._is_hf_initialized = True
1021
+
1022
+ # def forward(
1023
+ # self,
1024
+ # hidden_states: torch.Tensor,
1025
+ # attention_mask: Optional[torch.Tensor] = None,
1026
+ # past_key_values: Optional[Cache] = None,
1027
+ # use_cache: Optional[bool] = False,
1028
+ # output_attentions: Optional[bool] = False,
1029
+ # **kwargs
1030
+ # ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
1031
+ # # change to inference mode.
1032
+ # if attention_mask is not None:
1033
+ # assert len(attention_mask.shape) == 2, (
1034
+ # "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
1035
+ # "for padding purposes (0 indicating padding). "
1036
+ # "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
1037
+ # )
1038
+ # batch_size, q_len, _ = hidden_states.shape
1039
+ # # change to inference mode.
1040
+ # mode = 'fused_recurrent' if q_len <= 64 else self.mode
1041
+ # if self.training:
1042
+ # assert mode == 'chunk', "Only chunk mode is supported in training."
1043
+
1044
+ # last_state = None
1045
+ # if past_key_values is not None and len(past_key_values) > self.layer_idx:
1046
+ # last_state = past_key_values[self.layer_idx]
1047
+
1048
+ # cu_seqlens = kwargs.get('cu_seqlens', None)
1049
+ # if attention_mask is not None:
1050
+ # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
1051
+ # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
1052
+
1053
+ # if self.use_short_conv:
1054
+ # conv_state_q , conv_state_k , conv_state_v = None,None,None
1055
+ # if last_state is not None:
1056
+ # conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
1057
+ # q = self.q_proj(hidden_states)
1058
+ # k = self.k_proj(hidden_states)
1059
+ # v = self.v_proj(hidden_states)
1060
+ # q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
1061
+ # k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
1062
+ # v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
1063
+ # else:
1064
+ # q = F.silu(self.q_proj(hidden_states))
1065
+ # k = F.silu(self.k_proj(hidden_states))
1066
+ # v = F.silu(self.v_proj(hidden_states))
1067
+
1068
+ # q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_qk_dim), (q, k))
1069
+ # v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
1070
+ # beta = self.b_proj(hidden_states).sigmoid()
1071
+ # # if self.allow_neg_eigval:
1072
+ # # beta = beta * 2.
1073
+
1074
+ # q = l2norm(q)
1075
+ # k = l2norm(k)
1076
+ # recurrent_state1,recurrent_state2 = None,None
1077
+ # if last_state is not None:
1078
+ # recurrent_state1,recurrent_state2 = last_state['recurrent_state']
1079
+ # g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
1080
+
1081
+
1082
+ # seqlen_offset, max_seqlen = 0, q_len
1083
+ # if past_key_values is not None:
1084
+ # seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
1085
+ # max_seqlen = q.shape[1] + seqlen_offset
1086
+
1087
+ # q1=[]
1088
+ # for i in range(self.num_heads):
1089
+ # q1.append(torch.cat([q[:,:,i:i+1,:],q.new_zeros(batch_size,self.past_chunk_size[i],1,self.head_qk_dim)], dim=1)[:,-q_len:,...])
1090
+ # q1 = torch.cat(q1, dim=2).contiguous()
1091
+
1092
+ # o1,recurrent_state1 = chunk_gated_delta_rule(
1093
+ # q=q,
1094
+ # k=k,
1095
+ # v=v,
1096
+ # g=g,
1097
+ # beta=beta,
1098
+ # initial_state=recurrent_state1,
1099
+ # output_final_state=use_cache,
1100
+ # cu_seqlens=cu_seqlens,
1101
+ # use_qk_l2norm_in_kernel=False
1102
+ # )
1103
+ # o2,recurrent_state2 = chunk_gated_delta_rule(
1104
+ # q=q1,
1105
+ # k=k,
1106
+ # v=v,
1107
+ # g=g,
1108
+ # beta=beta,
1109
+ # initial_state=recurrent_state2,
1110
+ # output_final_state=use_cache,
1111
+ # cu_seqlens=cu_seqlens,
1112
+ # use_qk_l2norm_in_kernel=False
1113
+ # )
1114
+ # if past_key_values is not None:
1115
+ # past_key_values.update(
1116
+ # recurrent_state=(recurrent_state1,recurrent_state2),
1117
+ # conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
1118
+ # layer_idx=self.layer_idx,
1119
+ # offset=q_len
1120
+ # )
1121
+
1122
+ # o2_new = []
1123
+ # for i in range(self.num_heads):
1124
+ # o2_new.append(torch.cat([o2.new_zeros(batch_size,self.past_chunk_size[i],1,self.head_v_dim),o2[:,:,i:i+1,:]], dim=1)[:,:q_len,...])
1125
+ # o2_new = torch.cat(o2_new, dim=2).contiguous()
1126
+ # o1 = self.rmsnorm(o1)#BLHD
1127
+ # o2_new = self.rmsnorm(o2_new)###BLHD###need
1128
+ # o = torch.stack([o1,o2_new], dim=-2)###BLHRD
1129
+ # o = torch.einsum('b l h r d, h r -> b l h d',o,self.chunk_scale)
1130
+ # o = self.o_norm(o)
1131
+ # o = rearrange(o, 'b l h d -> b l (h d)')
1132
+ # o = self.o_proj(o)
1133
+ # if attention_mask is not None:
1134
+ # o = pad_input(o.squeeze(0), indices, batch_size, q_len)
1135
+ # return o, None, past_key_values,None
1136
+
1137
+
1138
+ from ..ops.gated_delta_rule import chunk_gated_delta_rule,fused_recurrent_gated_delta_rule
1139
+ class past_gdn(nn.Module):
1140
+ def __init__(
1141
+ self,
1142
+ d_model: int = None,
1143
+ hidden_size: int = 1024,
1144
+ expand_k: float = 1.0,
1145
+ expand_v: float = 1.0,
1146
+ num_heads: int = 4,
1147
+ mode: str = 'chunk',
1148
+ chunk_size: int = 64,
1149
+ use_beta: bool = True,
1150
+ use_gate: bool = False,
1151
+ use_output_norm: bool = True,
1152
+ use_elu: bool = False,
1153
+ use_short_conv: bool = True,
1154
+ conv_size: int = 4,
1155
+ conv_bias: bool = False,
1156
+ layer_idx: int = None,
1157
+ qk_activation: str = 'silu',
1158
+ qk_norm: str = 'l2',
1159
+ norm_first: bool = False,
1160
+ norm_eps: float = 1e-6,
1161
+ ratio: int = 2,
1162
+ **kwargs
1163
+ ) :
1164
+ super().__init__()
1165
+
1166
+ self.mode = mode
1167
+ self.qk_activation = qk_activation
1168
+ self.qk_norm = qk_norm
1169
+
1170
+ assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
1171
+ assert self.qk_norm in ['l2', 'sum']
1172
+
1173
+ if d_model is not None:
1174
+ hidden_size = d_model
1175
+ self.hidden_size = hidden_size
1176
+ self.expand_k = expand_k
1177
+ self.expand_v = expand_v
1178
+ self.num_heads = num_heads
1179
+ self.chunk_size = chunk_size
1180
+ self.use_gate = use_gate
1181
+ self.use_output_norm = use_output_norm
1182
+ self.use_short_conv = use_short_conv
1183
+ self.conv_size = conv_size
1184
+ self.conv_bias = conv_bias
1185
+
1186
+ self.key_dim = int(hidden_size * expand_k)
1187
+ self.value_dim = int(hidden_size * expand_v)
1188
+ self.head_qk_dim = self.key_dim // num_heads
1189
+ self.head_v_dim = self.value_dim // num_heads
1190
+ self.norm_first = norm_first
1191
+ self.layer_idx = layer_idx
1192
+
1193
+ self.silu = nn.SiLU()
1194
+ assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
1195
+ assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
1196
+ assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
1197
+ if norm_first:
1198
+ self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
1199
+ self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
1200
+ self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
1201
+ self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
1202
+ self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
1203
+
1204
+ A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
1205
+ self.A_log = nn.Parameter(torch.log(A))
1206
+ self.A_log._no_weight_decay = True
1207
+ # hard coded for now
1208
+ dt_min = 0.001
1209
+ dt_max = 0.1
1210
+ dt_init_floor = 1e-4
1211
+ dt = torch.exp(
1212
+ torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
1213
+ + math.log(dt_min)
1214
+ )
1215
+ dt = torch.clamp(dt, min=dt_init_floor)
1216
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
1217
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
1218
+ self.dt_bias = nn.Parameter(inv_dt)
1219
+ # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
1220
+ # name.endswith("bias") in param_grouping.py
1221
+ self.dt_bias._no_weight_decay = True
1222
+
1223
+
1224
+ self.use_beta = use_beta
1225
+ self.use_elu = use_elu
1226
+ if self.use_beta:
1227
+ self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
1228
+ if use_short_conv:
1229
+ self.conv_size = conv_size
1230
+ self.q_conv1d = ShortConvolution(self.key_dim,
1231
+ conv_size,
1232
+ activation='silu' if qk_activation == 'silu' else None)
1233
+ self.k_conv1d = ShortConvolution(self.key_dim,
1234
+ conv_size,
1235
+ activation='silu' if qk_activation == 'silu' else None)
1236
+ self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
1237
+ if use_gate:
1238
+ self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
1239
+ self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
1240
+ else:
1241
+ self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
1242
+ self.rmsnorm = RMSNorm(self.head_v_dim, eps=norm_eps,elementwise_affine=False)
1243
+ self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
1244
+ self.ratio = ratio
1245
+ self.chunk_scale = nn.Parameter(torch.ones(self.num_heads,self.ratio))
1246
+ self.past_chunk_size = [64*(2**i) for i in range(self.num_heads)]
1247
+ self.add_dim = 16 ###相当于差值get 旋转,然而这里我们有一定的控制,实质得到的结果可能需要再给一个映射到1的系数
1248
+ if self.add_dim !=1:
1249
+ self.rotary = RotaryEmbedding(dim=self.add_dim, base=50000)
1250
+ self.vector_to_one = nn.Linear(self.add_dim, 1, bias=False)
1251
+ print('rotary')
1252
+
1253
+
1254
+ def _initialize_weights(self, module: nn.Module):
1255
+ if getattr(module, "_is_hf_initialized", False):
1256
+ return
1257
+ if isinstance(module, nn.Linear):
1258
+ nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
1259
+ if module.bias is not None:
1260
+ nn.init.zeros_(module.bias)
1261
+ module._is_hf_initialized = True
1262
+
1263
+ def forward(
1264
+ self,
1265
+ hidden_states: torch.Tensor,
1266
+ attention_mask: Optional[torch.Tensor] = None,
1267
+ past_key_values: Optional[Cache] = None,
1268
+ use_cache: Optional[bool] = False,
1269
+ output_attentions: Optional[bool] = False,
1270
+ **kwargs
1271
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
1272
+ # change to inference mode.
1273
+ if attention_mask is not None:
1274
+ assert len(attention_mask.shape) == 2, (
1275
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
1276
+ "for padding purposes (0 indicating padding). "
1277
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
1278
+ )
1279
+ batch_size, q_len, _ = hidden_states.shape
1280
+ # change to inference mode.
1281
+ mode = 'fused_recurrent' if q_len <= 64 else self.mode
1282
+ if self.training:
1283
+ assert mode == 'chunk', "Only chunk mode is supported in training."
1284
+
1285
+ last_state = None
1286
+ if past_key_values is not None and len(past_key_values) > self.layer_idx:
1287
+ last_state = past_key_values[self.layer_idx]
1288
+
1289
+ cu_seqlens = kwargs.get('cu_seqlens', None)
1290
+ if attention_mask is not None:
1291
+ indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
1292
+ hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
1293
+
1294
+ if self.use_short_conv:
1295
+ conv_state_q , conv_state_k , conv_state_v = None,None,None
1296
+ if last_state is not None:
1297
+ conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
1298
+ q = self.q_proj(hidden_states)
1299
+ k = self.k_proj(hidden_states)
1300
+ v = self.v_proj(hidden_states)
1301
+ q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
1302
+ k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
1303
+ v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
1304
+ else:
1305
+ q = F.silu(self.q_proj(hidden_states))
1306
+ k = F.silu(self.k_proj(hidden_states))
1307
+ v = F.silu(self.v_proj(hidden_states))
1308
+
1309
+ seqlen_offset, max_seqlen = 0, q_len
1310
+ if past_key_values is not None:
1311
+ seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
1312
+ max_seqlen = q.shape[1] + seqlen_offset
1313
+
1314
+ q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_qk_dim), (q, k))
1315
+ v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
1316
+ beta = self.b_proj(hidden_states).sigmoid()
1317
+ # if self.allow_neg_eigval:
1318
+ # beta = beta * 2.
1319
+ v_add = torch.ones(batch_size, q_len,self.num_heads,self.add_dim,device=v.device,dtype=v.dtype)
1320
+ if self.add_dim !=1:
1321
+ v_add, _ = self.rotary(v_add,v_add, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
1322
+ v = torch.cat([v, v_add], dim=-1)###B L H D+16
1323
+
1324
+ q = l2norm(q)
1325
+ k = l2norm(k)
1326
+ recurrent_state1,recurrent_state2 = None,None
1327
+ if last_state is not None:
1328
+ recurrent_state1,recurrent_state2 = last_state['recurrent_state']
1329
+ g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
1330
+
1331
+
1332
+ # q1 = torch.cat([q,q.new_zeros(batch_size, 48, self.num_heads, self.head_qk_dim)], dim=1)[:,-q_len:,...]
1333
+ q1=[]
1334
+ for i in range(self.num_heads):
1335
+ q1.append(torch.cat([q[:,:,i:i+1,:],q.new_zeros(batch_size,self.past_chunk_size[i],1,self.head_qk_dim)], dim=1)[:,-q_len:,...])
1336
+ q1 = torch.cat(q1, dim=2).contiguous()
1337
+
1338
+ o1,recurrent_state1 = chunk_gated_delta_rule(
1339
+ q=q,
1340
+ k=k,
1341
+ v=v,
1342
+ g=g,
1343
+ beta=beta,
1344
+ initial_state=recurrent_state1,
1345
+ output_final_state=use_cache,
1346
+ cu_seqlens=cu_seqlens,
1347
+ use_qk_l2norm_in_kernel=False
1348
+ )
1349
+ o2,recurrent_state2 = chunk_gated_delta_rule(
1350
+ q=q1,
1351
+ k=k,
1352
+ v=v,
1353
+ g=g,
1354
+ beta=beta,
1355
+ initial_state=recurrent_state2,
1356
+ output_final_state=use_cache,
1357
+ cu_seqlens=cu_seqlens,
1358
+ use_qk_l2norm_in_kernel=False
1359
+ )
1360
+ if past_key_values is not None:
1361
+ past_key_values.update(
1362
+ recurrent_state=(recurrent_state1,recurrent_state2),
1363
+ conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
1364
+ layer_idx=self.layer_idx,
1365
+ offset=q_len
1366
+ )
1367
+ a_range = 1/(torch.arange(q_len,device=o1.device,dtype=o1.dtype) + 1.0)###L
1368
+ o2_new = []
1369
+ a_o2_range = []
1370
+ for i in range(self.num_heads):
1371
+ o2_new.append(torch.cat([o2.new_zeros(batch_size,self.past_chunk_size[i],1,self.head_v_dim+self.add_dim),o2[:,:,i:i+1,:]], dim=1)[:,:q_len,...])
1372
+ a_o2_range.append(torch.cat([a_range.new_zeros((self.past_chunk_size[i])),a_range], dim=0)[:q_len])#qlen
1373
+ o2_new = torch.cat(o2_new, dim=2).contiguous()
1374
+ a_o2_range = torch.stack(a_o2_range, dim=-1).contiguous()##HL
1375
+
1376
+ #####占据比例有所差距,需要考虑除以什么去均衡嘛###B L H 16
1377
+ o1_sep = o1[...,-self.add_dim:]
1378
+ o2_new_sep = o2_new[...,-self.add_dim:]
1379
+ if self.add_dim !=1:
1380
+ _,o1_sep = self.rotary(o1_sep,o1_sep, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
1381
+ _,o2_new_sep = self.rotary(o2_new_sep,o2_new_sep, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
1382
+ o1_sep = self.vector_to_one(o1_sep).squeeze(-1)
1383
+ o2_new_sep = self.vector_to_one(o2_new_sep).squeeze(-1)###BLH
1384
+ o1_sep = o1_sep * a_range.unsqueeze(0).unsqueeze(-1)###L->BLH
1385
+ o2_new_sep = o2_new_sep * a_o2_range.unsqueeze(0)###LH->BLH
1386
+ else:
1387
+ o1_sep = o1_sep.squeeze(-1)####BLH
1388
+ o2_new_sep = o2_new_sep.squeeze(-1)####BLH
1389
+ o1_sep = o1_sep * a_range.unsqueeze(0).unsqueeze(-1)###L->BLH
1390
+ o2_new_sep = o2_new_sep * a_o2_range.unsqueeze(0)###LH->BLH
1391
+
1392
+ o1 = o1[...,:-self.add_dim]
1393
+ o2_new = o2_new[...,:-self.add_dim]
1394
+
1395
+ o1 = self.rmsnorm(o1)#BLHD
1396
+ o2_new = self.rmsnorm(o2_new)###BLHD###need
1397
+ o = torch.stack([o1,o2_new], dim=-2)###BLHRD
1398
+ sep = torch.stack([o1_sep,o2_new_sep], dim=-1)###BLHR
1399
+ sep = torch.softmax(sep, dim=-1)###BLHR
1400
+ o = torch.einsum('b l h r d, b l h r -> b l h d',o,sep)
1401
+ o = self.o_norm(o)
1402
+ o = rearrange(o, 'b l h d -> b l (h d)')
1403
+ o = self.o_proj(o)
1404
+ if attention_mask is not None:
1405
+ o = pad_input(o.squeeze(0), indices, batch_size, q_len)
1406
+ return o, None, past_key_values,None
1407
+
layers/rebased.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ """
5
+ https://github.com/corl-team/rebased/blob/main/flash_linear_attention/fla/layers/rebased_fast.py
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Optional
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from einops import rearrange
15
+
16
+ from fla.modules.feature_map import RebasedFeatureMap
17
+ from fla.ops.linear_attn import chunk_linear_attn, fused_chunk_linear_attn
18
+ from fla.ops.rebased import parallel_rebased
19
+
20
+
21
+ class ReBasedLinearAttention(nn.Module):
22
+
23
+ def __init__(
24
+ self,
25
+ hidden_size: int,
26
+ l_max: int = 2048,
27
+ feature_dim: int = 16,
28
+ num_key_value_heads: int = 16,
29
+ num_heads: int = 16,
30
+ use_gamma: Optional[bool] = True,
31
+ use_beta: Optional[bool] = True,
32
+ normalize: Optional[bool] = True,
33
+ causal: bool = True,
34
+ eps: float = 1e-5,
35
+ mode: str = "parallel",
36
+ layer_idx: Optional[int] = None,
37
+ **kwargs
38
+ ) -> ReBasedLinearAttention:
39
+ super().__init__()
40
+ self.hidden_size = hidden_size
41
+ self.l_max = l_max
42
+ self.mode = mode
43
+ assert self.mode in ["fused_chunk", "parallel", 'chunk']
44
+
45
+ self.feature_dim = feature_dim
46
+ self.num_key_value_heads = num_key_value_heads
47
+ self.num_heads = num_heads
48
+ self.head_dim = self.hidden_size // self.num_key_value_heads
49
+ self.use_gamma = use_gamma
50
+ self.use_beta = use_beta
51
+ self.normalize = normalize
52
+ self.causal = causal
53
+ self.eps = eps
54
+ self.mode = mode
55
+ self.layer_idx = layer_idx
56
+
57
+ self.feature_map = RebasedFeatureMap(self.feature_dim, use_gamma, use_beta, normalize)
58
+ self.q_proj = nn.Linear(self.hidden_size, self.feature_dim * self.num_heads, bias=False)
59
+ self.k_proj = nn.Linear(self.hidden_size, self.feature_dim * self.num_heads, bias=False)
60
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
61
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
62
+ self.dropout = nn.Identity()
63
+
64
+ def forward(self, hidden_states: torch.Tensor, **kwargs):
65
+ mode = self.mode
66
+ q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
67
+ q, k, v = map(lambda x: rearrange(x, "... (h d) -> ... h d", d=self.head_dim), [q, k, v])
68
+ q, k = self.feature_map(q, flatten=(mode != 'parallel')), self.feature_map(k, flatten=(mode != 'parallel'))
69
+ if mode == "fused_chunk":
70
+ o = fused_chunk_linear_attn(
71
+ q=q,
72
+ k=k,
73
+ v=v,
74
+ normalize=True,
75
+ scale=1,
76
+ )
77
+ elif mode == 'chunk':
78
+ o = chunk_linear_attn(
79
+ q=q,
80
+ k=k,
81
+ v=v,
82
+ normalize=True,
83
+ scale=1,
84
+ )
85
+ elif mode == 'parallel':
86
+ assert q.shape[-1] <= 128
87
+ o = parallel_rebased(
88
+ q=q,
89
+ k=k,
90
+ v=v,
91
+ eps=self.eps,
92
+ use_scale=True,
93
+ use_normalize=True,
94
+ )
95
+ o = self.o_proj(o)
96
+ o = self.dropout(o)
97
+ return o
98
+
99
+ # https://github.com/HazyResearch/zoology/blob/main/zoology/mixers/based.py#L119
100
+ def forward_reference(
101
+ self,
102
+ hidden_states: torch.Tensor,
103
+ filters: torch.Tensor = None,
104
+ *args,
105
+ **kwargs
106
+ ):
107
+ """
108
+ x (torch.Tensor): tensor of shape (b, d, t)
109
+ y (torch.Tensor): tensor of shape (b, d, t)
110
+ """
111
+ b, t, _ = hidden_states.size()
112
+ q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
113
+
114
+ q = q.view(b, t, -1, self.feature_dim).transpose(1, 2)
115
+ k = k.view(b, t, -1, self.feature_dim).transpose(1, 2)
116
+ v = v.view(b, t, -1, self.head_dim).transpose(1, 2)
117
+
118
+ # Linear attention
119
+ q, k = self.feature_map(q), self.feature_map(k)
120
+ q, k, v = q.unsqueeze(-2), k.unsqueeze(-2), v.unsqueeze(-1)
121
+
122
+ # Compute attention
123
+ if self.causal:
124
+ y = ((q * (k * v).cumsum(2)).sum(-1) / ((q * k.cumsum(2)).sum(-1) + self.eps))
125
+ else:
126
+ y = ((q * (k * v).sum(2, True)).sum(-1) / ((q * k.sum(2, True)).sum(-1) + self.eps))
127
+ y = rearrange(y, 'b h t d -> b t (h d)')
128
+ y = self.o_proj(y.to(hidden_states.dtype))
129
+ y = self.dropout(y)
130
+ return y.to(hidden_states.dtype)
layers/rodimus.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from __future__ import annotations
5
+
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ import torch.utils.checkpoint
13
+ from einops import rearrange, repeat
14
+ from transformers.utils import logging
15
+
16
+ from fla.layers.utils import get_unpad_data, index_first_axis, pad_input, unpad_input
17
+ from fla.modules import RMSNorm, RotaryEmbedding, ShortConvolution
18
+ from fla.modules.layernorm_gated import RMSNormGated
19
+ from fla.ops.gla import chunk_gla, fused_chunk_gla, fused_recurrent_gla
20
+
21
+ if TYPE_CHECKING:
22
+ from transformers.processing_utils import Unpack
23
+
24
+ from fla.models.utils import Cache
25
+
26
+ try:
27
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
28
+ except ImportError:
29
+ warnings.warn(
30
+ "Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
31
+ category=ImportWarning
32
+ )
33
+ flash_attn_func = None
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ def align_multiple(value, multiple_size=8):
39
+ if value % multiple_size != 0:
40
+ value += multiple_size - (value % multiple_size)
41
+ return value
42
+
43
+
44
+ def autocast_to_fp16(x):
45
+ if x.dtype not in {torch.float16, torch.bfloat16}:
46
+ return x.to(dtype=torch.bfloat16)
47
+ else:
48
+ return x
49
+
50
+
51
+ class RodimusAttention(nn.Module):
52
+ def __init__(
53
+ self,
54
+ block_type: str = 'rodimus',
55
+ mode: str = 'chunk',
56
+ hidden_size: int = 1024,
57
+ input_gate_low_rank: Optional[Union[float, str]] = 'auto',
58
+ expand_ratio: int = 64,
59
+ use_short_conv: bool = True,
60
+ conv_size: int = 4,
61
+ conv_bias: bool = True,
62
+ norm_eps: float = 1e-5,
63
+ k_norm_eps: Optional[float] = None,
64
+ residual_in_fp32: bool = True,
65
+ layer_idx: int = None
66
+ ):
67
+ super().__init__()
68
+
69
+ self.block_type = block_type
70
+ self.mode = mode
71
+ self.hidden_size = hidden_size
72
+ self.d_inner = align_multiple(int(self.hidden_size * 2), 8)
73
+
74
+ self.expand_ratio = expand_ratio
75
+ self.input_gate_low_rank = max(self.hidden_size // 64, 16) if input_gate_low_rank == "auto" else input_gate_low_rank
76
+
77
+ self.use_short_conv = use_short_conv
78
+ self.conv_size = conv_size
79
+ self.conv_bias = conv_bias
80
+
81
+ self.norm_eps = norm_eps
82
+ self.k_norm_eps = k_norm_eps if k_norm_eps is not None else 1e-12
83
+ self.mem_size = expand_ratio
84
+
85
+ self.residual_in_fp32 = residual_in_fp32
86
+ self.layer_idx = layer_idx
87
+
88
+ assert mode in ['chunk', 'fused_recurrent', 'fused_chunk'], f"Not supported mode `{mode}`."
89
+
90
+ self.gate_proj = nn.Linear(self.hidden_size, self.d_inner, bias=False)
91
+ self.up_proj = nn.Linear(self.hidden_size, self.d_inner, bias=False)
92
+ self.activation_norm = RMSNormGated(hidden_size=self.d_inner, eps=norm_eps, norm_before_gate=False)
93
+ self.down_proj = nn.Linear(self.d_inner, self.hidden_size, bias=False)
94
+
95
+ if use_short_conv:
96
+ self.short_conv = ShortConvolution(
97
+ hidden_size=self.d_inner,
98
+ kernel_size=conv_size,
99
+ bias=conv_bias,
100
+ activation='silu'
101
+ )
102
+
103
+ self.residual_weight = nn.Parameter(torch.ones(
104
+ (self.d_inner, ), dtype=torch.float32 if self.residual_in_fp32 else None), requires_grad=True)
105
+
106
+ self.k_proj = nn.Linear(self.d_inner, self.mem_size, bias=False)
107
+ self.q_proj = nn.Linear(self.d_inner, self.mem_size, bias=False)
108
+
109
+ self.g_gate_proj = nn.Linear(self.d_inner, self.mem_size, bias=True)
110
+ self.tau_gate_proj = nn.Linear(self.d_inner, self.mem_size, bias=True)
111
+ self.i_gate_proj = nn.Sequential(
112
+ nn.Linear(self.d_inner, self.input_gate_low_rank, bias=False),
113
+ nn.Linear(self.input_gate_low_rank, self.d_inner, bias=True),
114
+ nn.Sigmoid(),
115
+ )
116
+
117
+ def forward(
118
+ self,
119
+ hidden_states: torch.Tensor,
120
+ attention_mask: Optional[torch.Tensor] = None,
121
+ past_key_values: Optional[Cache] = None,
122
+ use_cache: Optional[bool] = False,
123
+ output_attentions: Optional[bool] = False,
124
+ **kwargs: Unpack[Dict]
125
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
126
+ if attention_mask is not None:
127
+ assert len(attention_mask.shape) == 2, (
128
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
129
+ "for padding purposes (0 indicating padding). "
130
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
131
+ )
132
+
133
+ batch_size, q_len, _ = hidden_states.shape
134
+ # mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
135
+ mode = 'fused_recurrent' if hidden_states.shape[1] == 1 else self.mode
136
+
137
+ last_state = None
138
+ if past_key_values is not None and len(past_key_values) > self.layer_idx:
139
+ last_state = past_key_values[self.layer_idx]
140
+
141
+ cu_seqlens = kwargs.get('cu_seqlens', None)
142
+ if attention_mask is not None:
143
+ indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
144
+ hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
145
+
146
+ hidden_states, final_gate = self.up_proj(hidden_states), self.gate_proj(hidden_states)
147
+
148
+ if self.use_short_conv:
149
+ conv_state = None
150
+ if last_state is not None:
151
+ conv_state = last_state['conv_state']
152
+ shift_hidden_states, conv_state = self.short_conv(
153
+ x=hidden_states,
154
+ cache=conv_state,
155
+ output_final_state=use_cache,
156
+ cu_seqlens=cu_seqlens
157
+ )
158
+ else:
159
+ shift_hidden_states = hidden_states
160
+
161
+ q = self.q_proj(shift_hidden_states)
162
+ k = self.k_proj(shift_hidden_states)
163
+ v = self.i_gate_proj(hidden_states) * hidden_states
164
+
165
+ g_gate = F.linear(shift_hidden_states, self.g_gate_proj.weight) + self.g_gate_proj.bias.float()
166
+ tau_gate = F.linear(shift_hidden_states, self.tau_gate_proj.weight) + self.tau_gate_proj.bias.float()
167
+
168
+ g_gate = F.softplus(g_gate)
169
+ it_gate = g_gate
170
+ rt_gate_log = -g_gate
171
+
172
+ tau_gate = F.sigmoid(tau_gate)
173
+ it_gate = it_gate ** tau_gate
174
+ rt_gate_log = rt_gate_log * tau_gate
175
+
176
+ k = F.normalize(k.float(), dim=-1, eps=self.k_norm_eps) * it_gate
177
+ q, k, v, rt_gate_log = map(lambda x: x.unsqueeze(1).transpose(1, 2), (q, k, v, rt_gate_log))
178
+
179
+ recurrent_state = last_state['recurrent_state'] if last_state is not None else None
180
+ if mode == 'fused_recurrent':
181
+ o, recurrent_state = fused_recurrent_gla(
182
+ q=q,
183
+ k=k,
184
+ v=v,
185
+ gk=rt_gate_log,
186
+ initial_state=recurrent_state,
187
+ output_final_state=use_cache,
188
+ cu_seqlens=cu_seqlens,
189
+ head_first=False,
190
+ )
191
+ elif mode == 'fused_chunk':
192
+ o, recurrent_state = fused_chunk_gla(
193
+ q=q,
194
+ k=k,
195
+ v=v,
196
+ g=rt_gate_log,
197
+ initial_state=recurrent_state,
198
+ output_final_state=use_cache,
199
+ head_first=False,
200
+ )
201
+ elif mode == 'chunk':
202
+ q, k, rt_gate_log = map(lambda x: x.to(v.dtype), (q, k, rt_gate_log))
203
+ o, recurrent_state = chunk_gla(
204
+ q=q,
205
+ k=k,
206
+ v=v,
207
+ g=rt_gate_log,
208
+ initial_state=recurrent_state,
209
+ output_final_state=use_cache,
210
+ cu_seqlens=cu_seqlens,
211
+ head_first=False,
212
+ )
213
+ else:
214
+ raise NotImplementedError(f"Not supported mode `{mode}`.")
215
+
216
+ rodimus_caches = None
217
+ if past_key_values is not None:
218
+ if self.block_type == 'rodimus':
219
+ past_key_values.update(
220
+ recurrent_state=recurrent_state,
221
+ conv_state=conv_state if self.use_short_conv else None,
222
+ layer_idx=self.layer_idx,
223
+ offset=q_len
224
+ )
225
+ else:
226
+ rodimus_caches = (recurrent_state, conv_state if self.use_short_conv else None)
227
+
228
+ o = (o.transpose(1, 2).squeeze(1) + (shift_hidden_states.float()
229
+ if self.residual_in_fp32 else shift_hidden_states) * self.residual_weight).to(o.dtype)
230
+
231
+ o = self.activation_norm(o, final_gate)
232
+ o = self.down_proj(o)
233
+
234
+ if attention_mask is not None:
235
+ o = pad_input(o.squeeze(0), indices, batch_size, q_len)
236
+
237
+ if self.block_type == 'rodimus':
238
+ return o, None, past_key_values
239
+ else:
240
+ return o, None, (past_key_values, rodimus_caches)
241
+
242
+
243
+ class SlidingWindowSharedKeyAttention(nn.Module):
244
+ def __init__(
245
+ self,
246
+ hidden_size: int = 2048,
247
+ num_heads: int = 32,
248
+ qkv_bias: bool = False,
249
+ qk_norm: bool = False,
250
+ window_size: int = 2048,
251
+ rope_theta: Optional[float] = 10000.,
252
+ max_position_embeddings: Optional[int] = None,
253
+ layer_idx: int = None
254
+ ):
255
+ super().__init__()
256
+
257
+ self.hidden_size = hidden_size
258
+ self.num_heads = num_heads
259
+ self.head_dim = self.hidden_size // self.num_heads
260
+ self.qkv_bias = qkv_bias
261
+ self.qk_norm = qk_norm
262
+
263
+ self.window_size = window_size
264
+ self.rope_theta = rope_theta
265
+ self.max_position_embeddings = max_position_embeddings
266
+ self.layer_idx = layer_idx
267
+
268
+ self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias)
269
+ self.k_proj = nn.Linear(self.hidden_size, self.head_dim, bias=self.qkv_bias)
270
+ self.v_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias)
271
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
272
+
273
+ if qk_norm:
274
+ self.q_norm = RMSNorm(self.head_dim)
275
+ self.k_norm = RMSNorm(self.head_dim)
276
+
277
+ self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta)
278
+
279
+ def forward(
280
+ self,
281
+ hidden_states: torch.Tensor,
282
+ attention_mask: Optional[torch.LongTensor] = None,
283
+ past_key_values: Optional[Cache] = None,
284
+ output_attentions: bool = False,
285
+ use_cache: bool = False,
286
+ **kwargs,
287
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
288
+ rodimus_caches = kwargs.get('rodimus_caches', None)
289
+
290
+ if attention_mask is not None:
291
+ assert len(attention_mask.shape) == 2, (
292
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
293
+ "for padding purposes (0 indicating padding). "
294
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
295
+ )
296
+
297
+ batch_size, q_len, _ = hidden_states.size()
298
+
299
+ q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
300
+ k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
301
+ v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
302
+
303
+ if self.qk_norm:
304
+ q, k = self.q_norm(q), self.k_norm(k)
305
+
306
+ # equivalent to cu_seqlens in `flash_attn`
307
+ cu_seqlens = kwargs.get('cu_seqlens', None)
308
+
309
+ seqlen_offset, max_seqlen = 0, q.shape[1]
310
+ if past_key_values is not None:
311
+ seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
312
+ max_seqlen = q.shape[1] + seqlen_offset
313
+
314
+ if attention_mask is not None:
315
+ # to deliminate the offsets of padding tokens
316
+ seqlen_offset = seqlen_offset + attention_mask.sum(-1) - attention_mask.shape[-1]
317
+ max_seqlen = q.shape[1] + max(seqlen_offset)
318
+
319
+ if self.max_position_embeddings is not None:
320
+ max_seqlen = max(max_seqlen, self.max_position_embeddings)
321
+ q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
322
+
323
+ if past_key_values is not None:
324
+ if rodimus_caches is not None:
325
+ recurrent_state, conv_state = rodimus_caches
326
+ else:
327
+ recurrent_state, conv_state = None, None
328
+
329
+ cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0
330
+ k_cached, v_cached = past_key_values.update(
331
+ recurrent_state=recurrent_state,
332
+ conv_state=conv_state,
333
+ attn_state=[k.flatten(-2, -1), v.flatten(-2, -1)],
334
+ layer_idx=self.layer_idx,
335
+ offset=q_len,
336
+ cache_kwargs=dict(window_size=self.window_size)
337
+ )['attn_state']
338
+ if cache_has_content:
339
+ k, v = k_cached, v_cached
340
+ k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
341
+ v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
342
+
343
+ if flash_attn_func is None:
344
+ raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first")
345
+
346
+ q, k, v = map(autocast_to_fp16, (q, k, v))
347
+ k = repeat(k, "... h d -> ... (n h) d", n=self.num_heads)
348
+ # Contains at least one padding token in the sequence
349
+ if attention_mask is not None:
350
+ q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(
351
+ q=q,
352
+ states=(k, v),
353
+ attention_mask=attention_mask[:, -max(self.window_size, q_len):],
354
+ q_len=q_len
355
+ )
356
+ cu_seqlens_q, cu_seqlens_k = cu_seqlens
357
+ max_seqlen_q, max_seqlen_k = max_seq_lens
358
+ o = flash_attn_varlen_func(
359
+ q, k, v,
360
+ cu_seqlens_q=cu_seqlens_q,
361
+ cu_seqlens_k=cu_seqlens_k,
362
+ max_seqlen_q=max_seqlen_q,
363
+ max_seqlen_k=max_seqlen_k,
364
+ causal=True,
365
+ window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
366
+ )
367
+ o = pad_input(o, indices_q, batch_size, q_len)
368
+ elif cu_seqlens is not None:
369
+ o = flash_attn_varlen_func(
370
+ q.squeeze(0), k.squeeze(0), v.squeeze(0),
371
+ cu_seqlens_q=cu_seqlens,
372
+ cu_seqlens_k=cu_seqlens,
373
+ max_seqlen_q=max_seqlen,
374
+ max_seqlen_k=max_seqlen,
375
+ causal=True,
376
+ window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
377
+ ).unsqueeze(0)
378
+ else:
379
+ o = flash_attn_func(
380
+ q, k, v,
381
+ causal=True,
382
+ window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
383
+ )
384
+ o = o.reshape(batch_size, q_len, -1)
385
+ o = self.o_proj(o.to(dtype=self.o_proj.weight.dtype))
386
+
387
+ if not output_attentions:
388
+ attentions = None
389
+
390
+ return o, attentions, past_key_values
layers/rwkv6.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ # "Eagle and Finch: RWKV with Matrix-Valued States and Dynamic Recurrence"[https://arxiv.org/abs/2404.05892]
5
+
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ import warnings
10
+ from typing import TYPE_CHECKING, Optional, Tuple
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from einops import rearrange
15
+
16
+ from fla.modules import GroupNorm
17
+ from fla.modules.activations import ACT2FN
18
+ from fla.modules.token_shift import token_shift
19
+ from fla.ops.rwkv6 import chunk_rwkv6, fused_recurrent_rwkv6
20
+
21
+ if TYPE_CHECKING:
22
+ from fla.models.utils import Cache
23
+
24
+
25
+ class RWKV6Attention(nn.Module):
26
+
27
+ def __init__(
28
+ self,
29
+ mode: str = 'chunk',
30
+ hidden_size: int = 1024,
31
+ expand_k: float = 0.5,
32
+ expand_v: float = 1.0,
33
+ num_heads: int = 4,
34
+ gate_fn: str = 'swish',
35
+ proj_low_rank_dim: int = 32,
36
+ gate_low_rank_dim: int = 64,
37
+ fuse_norm: bool = True,
38
+ elementwise_affine: Optional[bool] = True,
39
+ norm_eps: float = 1e-5,
40
+ layer_idx: int = None,
41
+ **kwargs
42
+ ) -> RWKV6Attention:
43
+ super().__init__()
44
+
45
+ self.mode = mode
46
+ self.hidden_size = hidden_size
47
+ self.expand_k = expand_k
48
+ self.expand_v = expand_v
49
+ self.num_heads = num_heads
50
+ self.proj_low_rank_dim = proj_low_rank_dim
51
+ self.gate_low_rank_dim = gate_low_rank_dim
52
+
53
+ self.key_dim = int(hidden_size * expand_k)
54
+ self.value_dim = int(hidden_size * expand_v)
55
+ self.layer_idx = layer_idx
56
+
57
+ assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
58
+ assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
59
+ assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
60
+
61
+ self.head_k_dim = self.key_dim // num_heads
62
+ self.head_v_dim = self.value_dim // num_heads
63
+
64
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
65
+ self.x_proj = nn.Sequential(
66
+ LerpLinear(hidden_size, proj_low_rank_dim * 5),
67
+ nn.Tanh(),
68
+ nn.Linear(proj_low_rank_dim * 5, hidden_size, bias=False)
69
+ )
70
+ self.x_bias = nn.Parameter(torch.zeros(5, hidden_size))
71
+
72
+ self.r_proj = DDLerpLinear(hidden_size, self.key_dim)
73
+ self.w_proj = DDLerpLinear(hidden_size, self.key_dim, low_rank_dim=gate_low_rank_dim)
74
+ self.k_proj = DDLerpLinear(hidden_size, self.key_dim)
75
+ self.v_proj = DDLerpLinear(hidden_size, self.value_dim)
76
+ self.g_proj = DDLerpLinear(hidden_size, self.value_dim)
77
+ self.bonus = nn.Parameter(torch.zeros(num_heads, self.head_k_dim))
78
+
79
+ # TODO: fuse GroupNorm and output gate
80
+ self.g_norm = GroupNorm(self.num_heads, self.value_dim, elementwise_affine=elementwise_affine, bias=True, eps=norm_eps)
81
+ self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
82
+ self.gate_fn = ACT2FN[gate_fn]
83
+
84
+ try:
85
+ from transformers.modeling_utils import _init_weights
86
+ except ImportError:
87
+ _init_weights = True
88
+ if _init_weights:
89
+ self.apply(self._initialize_weights)
90
+
91
+ warnings.warn(
92
+ "According to Bo, you are using a potentially buggy FLA implementation of RWKV. "
93
+ "If you plan to report any numbers based on this implementation, we strongly recommend "
94
+ "cross-checking with the official repo: https://github.com/BlinkDL/RWKV-LM. "
95
+ "Bo may disagree with results reported from this version."
96
+ )
97
+
98
+ def _initialize_weights(self, module: nn.Module):
99
+ if getattr(module, "_is_hf_initialized", False):
100
+ return
101
+ if isinstance(module, nn.Linear):
102
+ nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
103
+ if module.bias is not None:
104
+ nn.init.zeros_(module.bias)
105
+ if isinstance(module, nn.Parameter):
106
+ nn.init.xavier_uniform_(module, gain=2 ** -2.5)
107
+ module._is_hf_initialized = True
108
+
109
+ def forward(
110
+ self,
111
+ hidden_states: torch.Tensor,
112
+ attention_mask: Optional[torch.Tensor] = None,
113
+ past_key_values: Optional[Cache] = None,
114
+ use_cache: Optional[bool] = False,
115
+ output_attentions: Optional[bool] = False,
116
+ cu_seqlens: Optional[torch.LongTensor] = None,
117
+ **kwargs
118
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
119
+ if attention_mask is not None:
120
+ assert len(attention_mask.shape) == 2, (
121
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
122
+ "for padding purposes (0 indicating padding). "
123
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
124
+ )
125
+
126
+ batch_size, seq_len, hidden_size = hidden_states.shape
127
+ # launching the triton kernel for just one token will actually be slower
128
+ mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
129
+
130
+ last_state = None
131
+ if past_key_values is not None and len(past_key_values) > self.layer_idx:
132
+ last_state = past_key_values[self.layer_idx]
133
+
134
+ if attention_mask is not None:
135
+ hidden_states = hidden_states.mul_(attention_mask[:, -hidden_states.shape[-2]:, None])
136
+
137
+ if hidden_states.shape[1] == 1 and last_state is not None:
138
+ shifted = last_state['conv_state'].unsqueeze(1)
139
+ delta = shifted - hidden_states
140
+ elif last_state is None:
141
+ delta = token_shift(hidden_states, cu_seqlens)
142
+ else:
143
+ shifted = self.time_shift(hidden_states)
144
+ shifted[:, 0] = last_state['conv_state']
145
+ delta = shifted - hidden_states
146
+
147
+ x = self.x_proj[0](hidden_states, delta, cu_seqlens).view(batch_size, seq_len, -1, self.proj_low_rank_dim)
148
+ x = torch.einsum('b t n r, h n r-> b t n h', self.x_proj[1](x), self.x_proj[2].weight.view(hidden_size, 5, -1))
149
+
150
+ r, w, k, v, g = x.add_(self.x_bias).unbind(-2)
151
+ r = self.r_proj(hidden_states, r, delta, cu_seqlens)
152
+ w = self.w_proj(hidden_states, w, delta, cu_seqlens)
153
+ k = self.k_proj(hidden_states, k, delta, cu_seqlens)
154
+ v = self.v_proj(hidden_states, v, delta, cu_seqlens)
155
+ g = self.g_proj(hidden_states, g, delta, cu_seqlens)
156
+
157
+ # dealing with left-padding
158
+ if attention_mask is not None:
159
+ v = v.mul_(attention_mask[:, -v.shape[-2]:, None])
160
+ r, w, k = map(lambda x: rearrange(x, 'b t (h d) -> b t h d', d=self.head_k_dim), (r, w, k))
161
+ v = rearrange(v, 'b t (h d) -> b t h d', d=self.head_v_dim)
162
+ w = -torch.exp(w)
163
+ u = self.bonus
164
+
165
+ recurrent_state = last_state['recurrent_state'] if last_state is not None else None
166
+
167
+ if mode == 'fused_recurrent':
168
+ o, recurrent_state = fused_recurrent_rwkv6(
169
+ r=r,
170
+ k=k,
171
+ v=v,
172
+ w=w,
173
+ u=u,
174
+ scale=1.,
175
+ initial_state=recurrent_state,
176
+ output_final_state=use_cache,
177
+ cu_seqlens=cu_seqlens,
178
+ )
179
+ elif mode == 'chunk':
180
+ o, recurrent_state = chunk_rwkv6(
181
+ r=r,
182
+ k=k,
183
+ v=v,
184
+ w=w,
185
+ u=u,
186
+ scale=1.,
187
+ initial_state=recurrent_state,
188
+ output_final_state=use_cache,
189
+ cu_seqlens=cu_seqlens,
190
+ )
191
+ else:
192
+ raise NotImplementedError(f"Not supported mode `{mode}`.")
193
+
194
+ if past_key_values is not None:
195
+ past_key_values.update(
196
+ recurrent_state=recurrent_state,
197
+ conv_state=hidden_states[:, -1],
198
+ layer_idx=self.layer_idx,
199
+ offset=r.shape[2]
200
+ )
201
+
202
+ o = self.g_norm(rearrange(o, '... h d -> ... (h d)')) * self.gate_fn(g)
203
+ o = self.o_proj(o)
204
+
205
+ return o, None, past_key_values
206
+
207
+
208
+ class LoRA(nn.Module):
209
+
210
+ def __init__(
211
+ self,
212
+ input_dim: int,
213
+ output_dim: int,
214
+ low_rank_dim: int,
215
+ bias: Optional[bool] = True,
216
+ activation: Optional[str] = 'tanh'
217
+ ):
218
+ super().__init__()
219
+
220
+ self.input_dim = input_dim
221
+ self.output_dim = output_dim
222
+ self.low_rank_dim = low_rank_dim
223
+ self.bias = bias
224
+
225
+ if activation is None:
226
+ self.activation = nn.Identity()
227
+ elif activation == 'sigmoid':
228
+ self.activation = nn.Sigmoid()
229
+ elif activation == 'tanh':
230
+ self.activation = nn.Tanh()
231
+ elif activation == 'relu':
232
+ self.activation = nn.ReLU()
233
+ else:
234
+ raise ValueError(f"Not supported activation `{activation}`.")
235
+
236
+ self.lora = nn.Sequential(
237
+ nn.Linear(input_dim, low_rank_dim, bias=False),
238
+ self.activation,
239
+ nn.Linear(low_rank_dim, output_dim, bias=bias)
240
+ )
241
+ try:
242
+ from transformers.modeling_utils import _init_weights
243
+ except ImportError:
244
+ _init_weights = True
245
+ if _init_weights:
246
+ self.apply(self._initialize_weights)
247
+
248
+ def __repr__(self) -> str:
249
+ s = f"{self.__class__.__name__}("
250
+ s += f"input_dim={self.input_dim}, low_rank_dim={self.low_rank_dim}, output_dim={self.output_dim}"
251
+ if not self.bias:
252
+ s += f", bias={self.bias}"
253
+ s += ")"
254
+ return s
255
+
256
+ def _initialize_weights(self, module: nn.Module):
257
+ if getattr(module, "_is_hf_initialized", False):
258
+ return
259
+
260
+ # Initialize weights to zero as in original code
261
+ nn.init.zeros_(self.lora[0].weight)
262
+ original_dtype = self.lora[2].weight.dtype
263
+ shape = self.lora[2].weight.shape
264
+ # Convert to float32 for numerical stability in orthogonal init
265
+ weight_fp32 = self.lora[2].weight.float()
266
+
267
+ # Calculate gain based on dimensions
268
+ gain = math.sqrt(shape[1] / shape[0]) if shape[1] > shape[0] else 1
269
+
270
+ # Apply orthogonal initialization with scaling factor 0.1
271
+ nn.init.orthogonal_(weight_fp32, gain=gain * 0.1)
272
+
273
+ # Convert back to original dtype
274
+ self.lora[2].weight.data.copy_(weight_fp32.to(original_dtype))
275
+ # Set Lora[2] bias to zero
276
+ if self.lora[2].bias is not None:
277
+ nn.init.zeros_(self.lora[2].bias)
278
+
279
+ module._is_hf_initialized = True
280
+
281
+ def set_bias_value(self, value):
282
+ """Set bias to a specific value (for v0, w0 etc.)"""
283
+ if self.bias and self.lora[2].bias is not None:
284
+ if isinstance(value, torch.Tensor):
285
+ # Handle tensor values
286
+ self.lora[2].bias.data.copy_(value.to(self.lora[2].bias.dtype))
287
+ else:
288
+ # Handle scalar values
289
+ nn.init.constant_(self.lora[2].bias, value)
290
+
291
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
292
+ return self.lora(x)
293
+
294
+
295
+ class LerpLinear(nn.Module):
296
+
297
+ def __init__(
298
+ self,
299
+ input_dim: int,
300
+ output_dim: int,
301
+ low_rank_dim: Optional[int] = None
302
+ ):
303
+ super().__init__()
304
+
305
+ self.input_dim = input_dim
306
+ self.output_dim = output_dim
307
+ self.low_rank_dim = low_rank_dim
308
+
309
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
310
+ if low_rank_dim is None:
311
+ self.linear = nn.Linear(input_dim, output_dim, bias=False)
312
+ else:
313
+ self.linear = LoRA(input_dim, output_dim, low_rank_dim)
314
+ self.mu = nn.Parameter(torch.zeros(input_dim))
315
+
316
+ def __repr__(self) -> str:
317
+ s = f"{self.__class__.__name__}({self.input_dim}, {self.output_dim}"
318
+ if self.low_rank_dim is not None:
319
+ s += f", low_rank_dim={self.low_rank_dim}"
320
+ s += ")"
321
+ return s
322
+
323
+ def forward(self, x: torch.Tensor, delta: Optional[torch.Tensor] = None,
324
+ cu_seqlens: Optional[torch.LongTensor] = None) -> torch.Tensor:
325
+ if delta is None:
326
+ delta = token_shift(x, cu_seqlens)
327
+ return self.linear(x + delta * self.mu)
328
+
329
+
330
+ class DDLerpLinear(nn.Module):
331
+
332
+ def __init__(
333
+ self,
334
+ input_dim: int,
335
+ output_dim: int,
336
+ low_rank_dim: Optional[int] = None
337
+ ):
338
+ super().__init__()
339
+
340
+ self.input_dim = input_dim
341
+ self.output_dim = output_dim
342
+ self.low_rank_dim = low_rank_dim
343
+
344
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
345
+ if low_rank_dim is None:
346
+ self.linear = nn.Linear(input_dim, output_dim, bias=False)
347
+ else:
348
+ self.linear = LoRA(input_dim, output_dim, low_rank_dim)
349
+
350
+ def __repr__(self) -> str:
351
+ s = f"{self.__class__.__name__}({self.input_dim}, {self.output_dim}"
352
+ if self.low_rank_dim is not None:
353
+ s += f", low_rank_dim={self.low_rank_dim}"
354
+ s += ")"
355
+ return s
356
+
357
+ def forward(self, x: torch.Tensor, mu: torch.Tensor,
358
+ delta: Optional[torch.Tensor] = None,
359
+ cu_seqlens: Optional[torch.LongTensor] = None) -> torch.Tensor:
360
+ if delta is None:
361
+ delta = token_shift(x, cu_seqlens)
362
+ return self.linear(x + delta * mu)
layers/sig_tr_gka.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trace Sigma-GKA layer.
2
+
3
+ Same block interface as ``SigmaGKANet`` (projections, short conv, beta, alpha,
4
+ polynomial coefficients, output norm). ``use_mamba_init`` selects the decay:
5
+
6
+ # Mamba / KDA
7
+ g = -exp(A_log) * softplus(f_proj(x) + dt_bias) # [B, T, H, D]
8
+
9
+ # GLA
10
+ g = logsigmoid(W2 W1 x) / gate_logit_normalizer # [B, T, H, D]
11
+
12
+ ``g`` (value state) and ``gk`` (key-key state) share this gate. Both stay
13
+ non-positive.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from typing import Optional, Sequence, Tuple
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ from einops import rearrange, repeat
25
+ from torch import Tensor
26
+
27
+ from fla.models.utils import Cache
28
+ from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
29
+ from ..modules.l2norm import l2norm
30
+ # from ..ops.phi_kkt_approx_gla_trace_c16.phi_kkt_solve_trace import (
31
+ # phi_kkt_decoding_one_step,
32
+ # phi_kkt_solve_gla,
33
+ # )
34
+ # from ..ops.phi_kkt_approx_gla_trace.phi_kkt_solve_trace import (
35
+ # phi_kkt_decoding_one_step,
36
+ # phi_kkt_solve_gla,
37
+ # )
38
+ from ..ops.phi_kkt_approx_gla_trace.phi_kkt_solve_trace import (
39
+ phi_kkt_decoding_one_step,
40
+ phi_kkt_solve_gla,
41
+ )
42
+
43
+ class SigTrGKANet(nn.Module):
44
+ def __init__(
45
+ self,
46
+ mode: str = "chunk",
47
+ hidden_size: int = 2048,
48
+ head_dim: int = 128,
49
+ num_heads: int = 8,
50
+ num_q_heads: Optional[int] = None,
51
+ num_k_heads: Optional[int] = None,
52
+ num_v_heads: Optional[int] = None,
53
+ use_short_conv: bool = True,
54
+ conv_size: int = 4,
55
+ conv_bias: bool = False,
56
+ use_output_gate: bool = False,
57
+ use_beta_gate: bool = True,
58
+ use_alpha_connection: bool = False,
59
+ use_v_conv: bool = True,
60
+ use_forgetting_gate: bool = True,
61
+ use_forgetting_gate_kk: bool = True,
62
+ gla_rescale: bool = True,
63
+ gate_logit_normalizer: float = 16.0,
64
+ gate_low_rank_dim: int = 16,
65
+ clamp_min: Optional[float] = None,
66
+ use_mamba_init: bool = False,
67
+ norm_eps: float = 1e-6,
68
+ layer_idx: Optional[int] = None,
69
+ chunk_size: int = 64,
70
+ learnable_abc: Sequence[float] = (1.0, -0.5, 0.375),
71
+ random_init_abc: bool = True,
72
+ abc_requires_grad: bool = True,
73
+ lambda_lower_bound: float = 0.25,
74
+ max_cg_step_training: int = 30,
75
+ max_cg_step_decoding: int = 30,
76
+ **kwargs,
77
+ ) -> None:
78
+ super().__init__()
79
+ del lambda_lower_bound, max_cg_step_training, max_cg_step_decoding
80
+
81
+ self.mode = mode
82
+ self.hidden_size = hidden_size
83
+ self.head_dim = head_dim
84
+ self.num_heads = num_heads
85
+ self.num_q_heads = num_heads if num_q_heads is None else num_q_heads
86
+ self.num_k_heads = num_heads if num_k_heads is None else num_k_heads
87
+ self.num_v_heads = num_heads if num_v_heads is None else num_v_heads
88
+ self.expanded_num_heads = max(self.num_q_heads, self.num_k_heads, self.num_v_heads)
89
+ self.num_q_groups = self.expanded_num_heads // self.num_q_heads
90
+ self.num_k_groups = self.expanded_num_heads // self.num_k_heads
91
+ self.num_v_groups = self.expanded_num_heads // self.num_v_heads
92
+ if self.expanded_num_heads % self.num_q_heads:
93
+ raise ValueError("expanded heads must divide num_q_heads")
94
+ if self.expanded_num_heads % self.num_k_heads:
95
+ raise ValueError("expanded heads must divide num_k_heads")
96
+ if self.expanded_num_heads % self.num_v_heads:
97
+ raise ValueError("expanded heads must divide num_v_heads")
98
+
99
+ self.query_dim = self.num_q_heads * head_dim
100
+ self.key_dim = self.num_k_heads * head_dim
101
+ self.value_dim = self.num_v_heads * head_dim
102
+ self.expanded_dim = self.expanded_num_heads * head_dim
103
+
104
+ self.layer_idx = layer_idx
105
+ self.chunk_size = chunk_size
106
+ self.conv_size = conv_size
107
+ self.use_short_conv = use_short_conv
108
+ self.use_v_conv = use_v_conv
109
+ self.use_beta_gate = use_beta_gate
110
+ self.use_alpha_connection = use_alpha_connection
111
+ self.use_output_gate = use_output_gate
112
+ self.use_forgetting_gate = use_forgetting_gate
113
+ self.use_forgetting_gate_kk = use_forgetting_gate_kk
114
+ self.use_mamba_init = use_mamba_init
115
+ if layer_idx in (None, 0):
116
+ print("use_mamba_init:", use_mamba_init)
117
+ self.gate_logit_normalizer = gate_logit_normalizer
118
+ self.clamp_min = -5#clamp_min
119
+ self.gla_scale = head_dim ** -0.5 if gla_rescale else 1.0
120
+
121
+ self.q_proj = nn.Linear(hidden_size, self.query_dim, bias=False)
122
+ self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
123
+ self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
124
+ self.o_proj = nn.Linear(self.expanded_dim, hidden_size, bias=False)
125
+
126
+ if use_short_conv:
127
+ self.q_conv1d = ShortConvolution(self.query_dim, conv_size, bias=conv_bias, activation="silu")
128
+ self.k_conv1d = ShortConvolution(self.key_dim, conv_size, bias=conv_bias, activation="silu")
129
+ if use_v_conv:
130
+ self.v_conv1d = ShortConvolution(self.value_dim, conv_size, bias=conv_bias, activation="silu")
131
+
132
+ self.b_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True) if use_beta_gate else None
133
+ self.alpha_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True) if use_alpha_connection else None
134
+
135
+ # One decay, shared by the value state (g) and the key-key state (gk).
136
+ if use_forgetting_gate or use_forgetting_gate_kk:
137
+ if use_mamba_init:
138
+ # Per expanded head and per key dim, matching KDA's [H, K].
139
+ self.gate_dim = self.expanded_num_heads * self.head_dim
140
+ self.f_proj = nn.Sequential(
141
+ nn.Linear(hidden_size, 16, bias=False),
142
+ nn.Linear(16, self.gate_dim, bias=False),
143
+ )
144
+ self.A_log = nn.Parameter(
145
+ torch.log(torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(1, 16))
146
+ )
147
+ self.A_log._no_weight_decay = True
148
+ dt = torch.exp(
149
+ torch.rand(self.gate_dim, dtype=torch.float32) * (math.log(0.1) - math.log(0.001))
150
+ + math.log(0.001)
151
+ ).clamp(min=1e-4)
152
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
153
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
154
+ self.dt_bias = nn.Parameter(inv_dt)
155
+ self.dt_bias._no_weight_decay = True
156
+ else:
157
+ # GLA low-rank gate. Output is the key dim, then repeated across k groups.
158
+ self.gk_proj = nn.Sequential(
159
+ nn.Linear(hidden_size, gate_low_rank_dim, bias=False),
160
+ nn.Linear(gate_low_rank_dim, self.key_dim, bias=True),
161
+ )
162
+
163
+ coeff = torch.tensor(tuple(learnable_abc), dtype=torch.float32).reshape(-1)
164
+ n_coeff = int(coeff.numel())
165
+ if n_coeff not in (3, 4):
166
+ raise ValueError(f"learnable_abc must have 3 or 4 values, got {n_coeff}")
167
+ self.learnable_abc = nn.Parameter(
168
+ coeff.unsqueeze(0).expand(self.expanded_num_heads, n_coeff).contiguous(),
169
+ requires_grad=abc_requires_grad,
170
+ )
171
+ if random_init_abc:
172
+ # a, c ~ U(0, 2); b, d ~ U(-2, 0). Same draw as SigmaGKANet.
173
+ signs = torch.tensor([1.0, -1.0, 1.0, -1.0][:n_coeff], dtype=torch.float32)
174
+ self.learnable_abc = nn.Parameter(
175
+ 2 * (torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(),
176
+ requires_grad=abc_requires_grad,
177
+ )
178
+ print("random init abc")
179
+ print(self.learnable_abc)
180
+ print(self.learnable_abc.requires_grad)
181
+ else:
182
+ print("not random init abc")
183
+ print(self.learnable_abc)
184
+ print(self.learnable_abc.requires_grad)
185
+ self.learnable_abc._no_weight_decay = True
186
+
187
+ if use_output_gate:
188
+ self.g_proj = nn.Linear(hidden_size, self.expanded_dim, bias=False)
189
+ self.o_norm = FusedRMSNormGated(head_dim, eps=norm_eps)
190
+ else:
191
+ self.o_norm = RMSNorm(head_dim, eps=norm_eps)
192
+
193
+ def _heads(self, x: Tensor, n_heads: int) -> Tensor:
194
+ return rearrange(x, "... (h d) -> ... h d", h=n_heads)
195
+
196
+ def _repeat_heads(self, x: Tensor, groups: int) -> Tensor:
197
+ if groups == 1:
198
+ return x
199
+ return repeat(x, "... h d -> ... (h g) d", g=groups)
200
+
201
+ def _kda_decay(self, hidden_states: Tensor) -> Tensor:
202
+ """Per-key-dim KDA decay, shape [B, T, H, D], values in (-inf, 0].
203
+
204
+ ``g = -exp(A_log) * softplus(f_proj(x) + dt_bias)``, with ``A_log``
205
+ broadcast over the key dimension.
206
+ """
207
+ gate = rearrange(self.f_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim)
208
+ gate = gate.float() + self.dt_bias.view(self.expanded_num_heads, self.head_dim)
209
+ gate = -self.A_log.float().exp().unsqueeze(-1) * F.softplus(gate)
210
+ if self.clamp_min is not None:
211
+ gate = gate.clamp_min(self.clamp_min)
212
+ return gate
213
+
214
+ def _gla_decay(self, hidden_states: Tensor) -> Tensor:
215
+ """Per-dimension GLA decay, shape [B, T, H, D], values in (-inf, 0]."""
216
+ gate = self.gk_proj(hidden_states)
217
+ gate = self._repeat_heads(self._heads(gate, self.num_k_heads), self.num_k_groups)
218
+ gate = F.logsigmoid(gate) / self.gate_logit_normalizer
219
+ if self.clamp_min is not None:
220
+ gate = gate.clamp_min(self.clamp_min)
221
+ return gate
222
+
223
+ def forward(
224
+ self,
225
+ hidden_states: Tensor,
226
+ attention_mask: Optional[Tensor] = None,
227
+ past_key_values: Optional[Cache] = None,
228
+ use_cache: Optional[bool] = False,
229
+ output_attentions: Optional[bool] = False,
230
+ **kwargs,
231
+ ) -> Tuple[Tensor, Optional[Tensor], Optional[Cache]]:
232
+ del output_attentions
233
+ if attention_mask is not None and not self.training:
234
+ raise NotImplementedError("sig_tr_gka does not support varlen attention_mask.")
235
+
236
+ batch_size, q_len, _ = hidden_states.shape
237
+ del batch_size
238
+ cu_seqlens = kwargs.get("cu_seqlens", None)
239
+
240
+ last_state = None
241
+ if past_key_values is not None and len(past_key_values) > self.layer_idx:
242
+ last_state = past_key_values[self.layer_idx]
243
+ conv_state_q = conv_state_k = conv_state_v = None
244
+ if last_state is not None:
245
+ conv_state_q, conv_state_k, conv_state_v = last_state["conv_state"]
246
+
247
+ if self.use_short_conv:
248
+ q, conv_state_q = self.q_conv1d(
249
+ x=self.q_proj(hidden_states), cache=conv_state_q,
250
+ output_final_state=use_cache, cu_seqlens=cu_seqlens,
251
+ )
252
+ k, conv_state_k = self.k_conv1d(
253
+ x=self.k_proj(hidden_states), cache=conv_state_k,
254
+ output_final_state=use_cache, cu_seqlens=cu_seqlens,
255
+ )
256
+ if self.use_v_conv:
257
+ v, conv_state_v = self.v_conv1d(
258
+ x=self.v_proj(hidden_states), cache=conv_state_v,
259
+ output_final_state=use_cache, cu_seqlens=cu_seqlens,
260
+ )
261
+ else:
262
+ v = self.v_proj(hidden_states)
263
+ else:
264
+ q = self.q_proj(hidden_states)
265
+ k = self.k_proj(hidden_states)
266
+ v = self.v_proj(hidden_states)
267
+
268
+ q = self._repeat_heads(self._heads(q, self.num_q_heads), self.num_q_groups)
269
+ k = self._repeat_heads(self._heads(k, self.num_k_heads), self.num_k_groups)
270
+ v = self._repeat_heads(self._heads(v, self.num_v_heads), self.num_v_groups)
271
+ q = l2norm(q)
272
+ k = l2norm(k)
273
+ # q = q / (torch.linalg.vector_norm(q, dim=-1, keepdim=True) + 1e-6)
274
+ # k = k / (torch.linalg.vector_norm(k, dim=-1, keepdim=True) + 1e-6)
275
+
276
+ if self.use_beta_gate:
277
+ beta = torch.sqrt(self.b_proj(hidden_states).sigmoid())
278
+ # k = (beta[..., None] + 1e-6) * k
279
+ # v = (beta[..., None] + 1e-6) * v
280
+ # k = beta[..., None] * k
281
+ # v = beta[..., None] * v
282
+ # Off by default: alpha = 1, so q_mix = x and q is not added back onto the polynomial query.
283
+ alpha = self.alpha_proj(hidden_states).sigmoid() if self.use_alpha_connection else torch.ones_like(q[..., 0])
284
+
285
+ if self.use_forgetting_gate or self.use_forgetting_gate_kk:
286
+ decay = self._kda_decay(hidden_states) if self.use_mamba_init else self._gla_decay(hidden_states)
287
+ else:
288
+ decay = None
289
+ g = decay if self.use_forgetting_gate else None
290
+ gk = decay if self.use_forgetting_gate_kk else None
291
+
292
+ coeff = self.learnable_abc.to(dtype=torch.float32)
293
+ if last_state is None:
294
+ o, h_kk, h_kv = phi_kkt_solve_gla(
295
+ q=q,
296
+ k=k,
297
+ v=v,
298
+ alpha=alpha,
299
+ g=g,
300
+ gk=gk,
301
+ gla_scale=self.gla_scale,
302
+ learnable_abc=coeff,
303
+ chunk_size=self.chunk_size,
304
+ output_final_state=past_key_values is not None,
305
+ layer_idx=self.layer_idx,
306
+ )
307
+ else:
308
+ last_h_kk, last_h_kv = last_state["recurrent_state"]
309
+ o, h_kk, h_kv = phi_kkt_decoding_one_step(
310
+ q=q,
311
+ k=k,
312
+ v=v,
313
+ alpha=alpha,
314
+ g=g,
315
+ gk=gk,
316
+ gla_scale=self.gla_scale,
317
+ learnable_abc=coeff,
318
+ prev_h_kk=last_h_kk,
319
+ prev_h_kv=last_h_kv,
320
+ )
321
+
322
+ if past_key_values is not None:
323
+ past_key_values.update(
324
+ recurrent_state=(h_kk, h_kv),
325
+ conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
326
+ layer_idx=self.layer_idx,
327
+ offset=q_len,
328
+ )
329
+
330
+ if self.use_output_gate:
331
+ out_gate = rearrange(self.g_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim)
332
+ o = self.o_norm(o, out_gate)
333
+ else:
334
+ o = self.o_norm(o)
335
+ o = self.o_proj(rearrange(o, "b t h d -> b t (h d)"))
336
+ return o, None, past_key_values
layers/sigma_gka.py ADDED
@@ -0,0 +1,1212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sigma Gated KalmaNet (Sigma GKA) layer implementation with Grouped Query Attention (GQA) support.
3
+
4
+ This module implements the Sigma Gated KalmaNet layer from the paper:
5
+ "Sigma Gated KalmaNet: A Fading Memory Layer Through Test-Time Ridge Regression" (https://arxiv.org/abs/2511.21016).
6
+
7
+ Overview:
8
+ Sigma GKA is a state space model (SSM) that updates its state based on the entire history
9
+ of previously seen tokens, rather than just the current token. At each timestep t,
10
+ the optimal state S_t minimizes a ridge regression objective over all past tokens:
11
+
12
+ S_t = argmin_S { λ·||S||²_F + Σ(i=1 to t) η_i·||S·k_i - v_i||² }
13
+
14
+ where λ is the ridge regularization strength and η_i are exponentially decaying weights
15
+ controlled by forgetting gates. This has a closed-form solution:
16
+
17
+ S_t = U_t · (H_t + λI)^(-1)
18
+
19
+ where:
20
+ U_t = Σ(i=1 to t) η_i v_i k_i^T (cumulative value-key outer products)
21
+ H_t = Σ(i=1 to t) η_i k_i k_i^T (cumulative key-key covariance)
22
+
23
+ The output is computed as y_t = S_t · q_t, which reduces to solving the ridge
24
+ regression problem (H_t + λI)·x_t = q_t for x_t, then computing y_t = U_t · x_t.
25
+ This is solved numerically via the Chebyshev iteration algorithm.
26
+
27
+ The layer supports GQA-style head grouping where the number of key/value heads
28
+ can be different from the number of query heads. The hyperparameters in this module
29
+ are set so that we can initialize the module's weights from existing Attention layers.
30
+
31
+ Key Variables:
32
+ - head_dim: Head dimension (same for q/k/v)
33
+ - num_q_heads: Number of query heads
34
+ - num_k_heads: Number of key heads
35
+ - num_v_heads: Number of value heads
36
+ - expanded_num_heads: Maximum of num_q_heads, num_k_heads, num_v_heads
37
+ - num_q_groups: Repetition factor for Q heads, computed as expanded_num_heads // num_q_heads
38
+ - num_k_groups: Repetition factor for K heads, computed as expanded_num_heads // num_k_heads
39
+ - num_v_groups: Repetition factor for V heads, computed as expanded_num_heads // num_v_heads
40
+ - query_dim: Total query dimension, num_q_heads * head_dim
41
+ - key_dim: Total key dimension, num_k_heads * head_dim
42
+ - value_dim: Total value dimension, num_v_heads * head_dim
43
+ - expanded_dim: Expanded dimension, expanded_num_heads * head_dim
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ import math
49
+ from typing import TYPE_CHECKING, Any, Optional, Tuple
50
+
51
+ import torch
52
+ import torch.nn as nn
53
+ from einops import rearrange, repeat
54
+ from torch import Tensor
55
+ from torch.nn import functional as F
56
+
57
+ from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
58
+ from fla.ops.simple_gla import chunk_simple_gla
59
+ from fla.models.utils import Cache
60
+
61
+ # from ..ops.chebyshev.chunk_dk_backward_gating_sp import compute_kk_final_with_gating
62
+ # from .sequence_parallel.gka_sp_utils import (
63
+ # state_passing_gka_p2p,
64
+ # recompute_with_initial_states,
65
+ # )
66
+
67
+ # from ..ops.chebyshev.gka_chebyshev_solve import (
68
+ # gka_chebyshev_gla,
69
+ # torch_decoding_one_step,
70
+ # )
71
+ from ..ops.phi_kkt_approx_gla.phi_kkt_solve import (
72
+ phi_kkt_solve_gla,
73
+ phi_kkt_decoding_one_step,
74
+ )
75
+ from torch.nn import Sigmoid
76
+
77
+ from typing import Any, Optional
78
+
79
+ import torch
80
+ import torch.nn as nn
81
+ import torch.nn.init as init
82
+
83
+
84
+ class LinearLowRank(nn.Module):
85
+ """
86
+ Low-rank linear layer that factorizes a linear projection into two smaller ones:
87
+ y = linearB(act_fn(linearA(x)))
88
+
89
+ where linearA projects from in_features to rank, and linearB projects from rank to out_features.
90
+
91
+ linearB is zero-initialized so that the module outputs zeros at init time. This makes it safe
92
+ to use as a residual branch (e.g. added on top of a repeat/expand) without perturbing the
93
+ pretrained signal at the start of training.
94
+
95
+ Note: linearB is marked with ``_is_hf_initialized = True`` to prevent transformers'
96
+ ``post_init`` from overwriting the zero initialization with a random normal.
97
+
98
+ Args:
99
+ in_features: Input dimension.
100
+ out_features: Output dimension.
101
+ rank: Bottleneck dimension between the two linear layers.
102
+ act_fn: Optional activation applied between linearA and linearB. Defaults to Identity.
103
+ bias: Whether to include bias terms in both linear layers. Defaults to False.
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ in_features: int,
109
+ out_features: int,
110
+ rank: int,
111
+ act_fn: Optional[Any] = None,
112
+ bias: bool = False,
113
+ ):
114
+ super().__init__()
115
+ self.linearA = nn.Linear(in_features, rank, bias=bias)
116
+ self.linearB = nn.Linear(rank, out_features, bias=bias)
117
+
118
+ self.in_features = in_features
119
+ self.out_features = out_features
120
+ self.rank = rank
121
+ self.bias = bias
122
+ self.act_fn = act_fn if act_fn is not None else nn.Identity()
123
+
124
+ # Initialize B weights and bias to zero
125
+ init.zeros_(self.linearB.weight)
126
+ if self.linearB.bias is not None:
127
+ init.zeros_(self.linearB.bias)
128
+ self.linearB._is_hf_initialized = (
129
+ True
130
+ ) # prevent transformers' post_init from re-initializing
131
+
132
+ def forward(self, x: torch.Tensor):
133
+ return self.linearB(self.act_fn(self.linearA(x)))
134
+ ###调整初始化
135
+ #####我们的目标是使用(-1/2)求逆
136
+ class SigmaGKANet(nn.Module):
137
+ """
138
+ Sigma GKA layer with Chebyshev solver and GQA support.
139
+
140
+ Args:
141
+ hidden_size: The hidden size of the input. Defaults to 2048.
142
+ head_dim: The dimension of each head. Assumes q/k/v have the same head dimension.
143
+ Defaults to 128.
144
+ num_q_heads: The number of query heads. Defaults to 16.
145
+ num_k_heads: The number of key heads for GQA. If None, defaults to num_q_heads.
146
+ Defaults to None.
147
+ num_v_heads: The number of value heads for GQA. If None, defaults to num_q_heads.
148
+ Defaults to None.
149
+ use_beta_gate: Whether to use beta gating mechanism. Defaults to True.
150
+ use_alpha_connection: Whether to use alpha connection for residual paths. Defaults to True.
151
+ use_v_conv: Whether to apply convolution to value vectors. Defaults to True.
152
+ use_forgetting_gate: Whether to use forgetting gate mechanism. Defaults to True.
153
+ use_forgetting_gate_kk: Whether to use forgetting gate for key-key interactions. Defaults to True.
154
+ gla_rescale: Whether to apply GLA-style rescaling. Defaults to True.
155
+ solver_type: Solver method. Currently, we only support "chebyshev". Defaults to "chebyshev".
156
+ bp_lambda: Whether to backpropagate through lambda parameters. Defaults to True.
157
+ num_iter: Number of iterations for iterative solvers. Defaults to 30.
158
+ ridge_strength: Regularization strength for ridge regression. Defaults to 0.02.
159
+ use_gate: Whether to use output gating mechanism. Defaults to True.
160
+ conv_size: Size of the convolution kernel. Defaults to 4.
161
+ layer_idx: The index of the layer. Used for caching during inference. Defaults to None.
162
+ norm_eps: The epsilon value for the normalization layer. Defaults to 1e-6.
163
+ chunk_size: Size of chunks for parallel processing in Triton kernels. Defaults to 64.
164
+ kv_proj_rank: Rank for low-rank KV projection to expand K/V heads. If None, uses
165
+ standard GQA repeat. Defaults to None.
166
+ kv_learnable_residual: Whether to use a learnable residual for the KV head expansion
167
+ instead of a fixed repeat. Only used when kv_proj_rank is set. Defaults to False.
168
+ learnable_abc: Initial polynomial coefficients. Length 3 (abc) uses
169
+ phi(H) ~ a I + b H/F + c H^2/F^2; length 4 (abcd) adds d H^3/F^3.
170
+ Stored as an ``nn.Parameter`` of shape [H, 3] or [H, 4].
171
+ Defaults to (1.0, -0.5, 0.375).
172
+ random_init_abc: If True, initialize per-head coefficients independently instead of
173
+ broadcasting ``learnable_abc`` to all heads. ``a, c`` are drawn from ``U(0, 1)``
174
+ (positive) and ``b, d`` from ``U(-1, 0)`` (negative). Defaults to False.
175
+ """
176
+
177
+ def __init__(
178
+ self,
179
+ hidden_size: int = 2048,
180
+ head_dim: int = 128,
181
+ num_heads: int = 8,
182
+ num_q_heads: Optional[int] = None,
183
+ num_k_heads: Optional[int] = None,
184
+ num_v_heads: Optional[int] = None,
185
+ use_beta_gate: bool = True,
186
+ use_alpha_connection: bool = True,
187
+ use_v_conv: bool = True,
188
+ use_forgetting_gate: bool = True,
189
+ use_forgetting_gate_kk: bool = True,
190
+ gla_rescale: bool = True,
191
+ # solver_type: str = "chebyshev",
192
+ bp_lambda: bool = True,
193
+ num_iter: int = 30,
194
+ ridge_strength: float = 0.02,
195
+ use_gate: bool = False,
196
+ conv_size: int = 4,
197
+ layer_idx: Optional[int] = None,
198
+ norm_eps: float = 1e-6,
199
+ chunk_size: int = 64,
200
+ kv_proj_rank: Optional[int] = None,
201
+ kv_learnable_residual: bool = False,
202
+ # learnable_abc: Tuple[float, ...] = (2.3424, -2.5663, 1.2652),
203
+ # learnable_abc: Tuple[float, ...] = (2.1111, -1.5556, 0.4444),
204
+ # learnable_abc: Tuple[float, ...] = (2.0, -2.0, 0.5,-0.125),
205
+ learnable_abc: Tuple[float, ...] = (1.0, -0.5, 0.375),
206
+ random_init_abc: bool = False,
207
+ abc_requires_grad: bool = False,
208
+ **kwargs,
209
+ ) -> None:
210
+ super().__init__()
211
+
212
+ # assert solver_type == "chebyshev", f"Received {solver_type=}. Currently, Sigma GKA only supports 'chebyshev' solver."
213
+
214
+ self.hidden_size = hidden_size
215
+
216
+ self.use_gate = use_gate
217
+ self.conv_size = conv_size
218
+ self.sequence_parallel_group = None
219
+ self.chunk_size = chunk_size
220
+
221
+ self.head_dim = head_dim
222
+ self.num_heads = num_heads
223
+ self.num_q_heads = num_q_heads if num_q_heads is not None else num_heads
224
+ self.num_k_heads = num_k_heads if num_k_heads is not None else num_heads
225
+ self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads
226
+ self.expanded_num_heads = max(
227
+ self.num_q_heads, self.num_k_heads, self.num_v_heads
228
+ )
229
+ self.num_q_groups = self.expanded_num_heads // self.num_q_heads
230
+ self.num_k_groups = self.expanded_num_heads // self.num_k_heads
231
+ self.num_v_groups = self.expanded_num_heads // self.num_v_heads
232
+
233
+ self.query_dim = self.num_q_heads * self.head_dim
234
+ self.key_dim = self.num_k_heads * self.head_dim
235
+ self.value_dim = self.num_v_heads * self.head_dim
236
+ self.expanded_dim = self.expanded_num_heads * self.head_dim
237
+
238
+ self.layer_idx = layer_idx
239
+
240
+ self.ridge_strength = ridge_strength
241
+ self.num_iter = num_iter
242
+ self.use_beta_gate = use_beta_gate
243
+ self.use_alpha_connection = use_alpha_connection
244
+ # self.solver_type = solver_type
245
+ self.bp_lambda = bp_lambda
246
+ self.use_v_conv = use_v_conv
247
+ self.use_forgetting_gate = use_forgetting_gate
248
+ self.use_forgetting_gate_kk = use_forgetting_gate_kk
249
+
250
+ if gla_rescale:
251
+ self.gla_scale = self.head_dim ** -0.5
252
+ else:
253
+ self.gla_scale = 1.0
254
+
255
+ # Projection layers
256
+ self.q_proj = nn.Linear(hidden_size, self.query_dim, bias=False)
257
+ self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
258
+ self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
259
+
260
+ self.a_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=False)
261
+
262
+ self.b_proj = (
263
+ nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
264
+ if self.use_beta_gate
265
+ else None
266
+ )
267
+
268
+ if self.use_alpha_connection:
269
+ self.alpha_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
270
+
271
+ # Initialize A parameter (log scale)
272
+ A = torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(0, 16)
273
+ self.A_log = nn.Parameter(torch.log(A))
274
+ self.A_log._no_weight_decay = True
275
+
276
+ # Initialize dt bias parameter
277
+ dt_min = 0.001
278
+ dt_max = 0.1
279
+ dt_init_floor = 1e-4
280
+ dt = torch.exp(
281
+ torch.rand(self.expanded_num_heads) * (math.log(dt_max) - math.log(dt_min))
282
+ + math.log(dt_min)
283
+ )
284
+ dt = torch.clamp(dt, min=dt_init_floor)
285
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
286
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
287
+
288
+ self.dt_bias = nn.Parameter(inv_dt)
289
+ self.dt_bias._no_weight_decay = True
290
+
291
+ # Per-head polynomial coefficients: [H, 3] abc or [H, 4] abcd
292
+ init_abc = torch.tensor(learnable_abc, dtype=torch.float32).reshape(-1)
293
+ n_coeff = int(init_abc.numel())
294
+ if n_coeff not in (3, 4):
295
+ raise ValueError(
296
+ f"learnable_abc must have 3 (abc) or 4 (abcd) coefficients, got {n_coeff}"
297
+ )
298
+ self.learnable_abc = nn.Parameter(
299
+ init_abc.unsqueeze(0).expand(self.expanded_num_heads, n_coeff).contiguous(), requires_grad=abc_requires_grad
300
+ )
301
+ if random_init_abc:
302
+ # a, c ~ U(0, 1); b, d ~ U(-1, 0)
303
+ signs = torch.tensor([1.0, -1.0, 1.0, -1.0][:n_coeff], dtype=torch.float32)
304
+ self.learnable_abc = nn.Parameter(
305
+ 2*(torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad
306
+ # (torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad
307
+ # 2*(torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32).contiguous())-1.0, requires_grad=abc_requires_grad
308
+ ###make the abc to be in the range of [-1, 1]
309
+ )
310
+ print("random init abc")
311
+ print(self.learnable_abc)
312
+ print(self.learnable_abc.requires_grad)
313
+ else:
314
+ print("not random init abc")
315
+ print(self.learnable_abc)
316
+ print(self.learnable_abc.requires_grad)
317
+ self.learnable_abc._no_weight_decay = True
318
+ print('tanh')
319
+
320
+ # Short convolution layers
321
+ self.conv_size = conv_size
322
+ self.q_conv1d = ShortConvolution(
323
+ hidden_size=self.query_dim, kernel_size=conv_size, activation="silu"
324
+ )
325
+ self.k_conv1d = ShortConvolution(
326
+ hidden_size=self.key_dim, kernel_size=conv_size, activation="silu"
327
+ )
328
+ if self.use_v_conv:
329
+ self.v_conv1d = ShortConvolution(
330
+ hidden_size=self.value_dim, kernel_size=conv_size, activation="silu"
331
+ )
332
+
333
+ # Output gating and normalization
334
+ if use_gate:
335
+ self.g_proj = nn.Linear(hidden_size, self.expanded_dim, bias=False)
336
+ self.o_norm = FusedRMSNormGated(self.head_dim, eps=norm_eps)
337
+ else:
338
+ self.o_norm = RMSNorm(self.head_dim, eps=norm_eps)
339
+ self.o_proj = nn.Linear(self.expanded_dim, hidden_size, bias=False)
340
+
341
+ # Optional KV projection for GQA
342
+ self.kv_proj_rank = kv_proj_rank
343
+ self.kv_learnable_residual = kv_learnable_residual
344
+ if self.kv_proj_rank is not None:
345
+ act_fn = nn.SiLU()
346
+ self.proj_k = LinearLowRank(
347
+ in_features=self.key_dim,
348
+ out_features=self.expanded_num_heads * self.head_dim,
349
+ rank=self.kv_proj_rank,
350
+ act_fn=act_fn,
351
+ )
352
+ self.proj_v = LinearLowRank(
353
+ in_features=self.value_dim,
354
+ out_features=self.expanded_num_heads * self.head_dim,
355
+ rank=self.kv_proj_rank,
356
+ act_fn=act_fn,
357
+ )
358
+
359
+ if self.kv_learnable_residual:
360
+ # Learnable mixing matrices initialized to mimic repeat_kv
361
+ eye_k = torch.eye(self.num_k_heads)
362
+ ones_k = torch.ones((self.num_k_groups, 1))
363
+ self.k_rep = nn.Parameter(
364
+ torch.kron(eye_k, ones_k)
365
+ ) # [expanded_num_heads, num_k_heads]
366
+
367
+ eye_v = torch.eye(self.num_v_heads)
368
+ ones_v = torch.ones((self.num_v_groups, 1))
369
+ self.v_rep = nn.Parameter(
370
+ torch.kron(eye_v, ones_v)
371
+ ) # [expanded_num_heads, num_v_heads]
372
+
373
+ def _expand_kv(self, k: Tensor, v: Tensor) -> Tuple[Tensor, Tensor]:
374
+ """
375
+ Expand k and v from their native head counts to expanded_num_heads.
376
+
377
+ Three modes:
378
+ 1. kv_proj_rank + kv_learnable_residual: learnable mixing residual + low-rank projection
379
+ 2. kv_proj_rank without learnable residual: plain repeat residual + low-rank projection
380
+ 3. No projection: simple repeat (or rearrange if groups == 1). This is the standard GQA repeat.
381
+
382
+ Args:
383
+ k: [B, L, Dk] raw key tensor (flat, not yet reshaped to heads)
384
+ v: [B, L, Dv] raw value tensor (flat, not yet reshaped to heads)
385
+
386
+ Returns:
387
+ k: [B, L, H, D] expanded keys
388
+ v: [B, L, H, D] expanded values
389
+ """
390
+ if self.kv_proj_rank is not None and (
391
+ self.num_k_groups > 1 or self.num_v_groups > 1
392
+ ):
393
+ # Build residual
394
+ if self.kv_learnable_residual:
395
+ k_heads = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
396
+ k_res = torch.einsum("eh,blhd->bled", self.k_rep, k_heads)
397
+ v_heads = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
398
+ v_res = torch.einsum("eh,blhd->bled", self.v_rep, v_heads)
399
+ else:
400
+ k_res = repeat(
401
+ rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads),
402
+ "... h d -> ... (h g) d",
403
+ g=self.num_k_groups,
404
+ )
405
+ v_res = repeat(
406
+ rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads),
407
+ "... h d -> ... (h g) d",
408
+ g=self.num_v_groups,
409
+ )
410
+
411
+ # Low-rank projection to expanded dim + add residual
412
+ k = (
413
+ rearrange(
414
+ self.proj_k(k), "... (h d) -> ... h d", h=self.expanded_num_heads
415
+ )
416
+ + k_res
417
+ )
418
+ v = (
419
+ rearrange(
420
+ self.proj_v(v), "... (h d) -> ... h d", h=self.expanded_num_heads
421
+ )
422
+ + v_res
423
+ )
424
+ else:
425
+ # Plain rearrange + repeat
426
+ k = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
427
+ v = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
428
+ if self.num_k_groups > 1:
429
+ k = repeat(k, "... h d -> ... (h g) d", g=self.num_k_groups)
430
+ if self.num_v_groups > 1:
431
+ v = repeat(v, "... h d -> ... (h g) d", g=self.num_v_groups)
432
+
433
+ return k, v
434
+
435
+ def forward(
436
+ self,
437
+ hidden_states: Tensor,
438
+ attention_mask: Optional[Tensor] = None,
439
+ past_key_values: Optional[Cache] = None,
440
+ use_cache: Optional[bool] = False,
441
+ output_attentions: Optional[bool] = False,
442
+ **kwargs,
443
+ ) -> Tuple[Tensor, Optional[Tensor], Optional[Cache]]:
444
+ """
445
+ Sigma GKA forward pass with optional caching.
446
+
447
+ NOTE: We use the following variables for tensor shape hints:
448
+ - B: Input batch size
449
+ - L: Sequence length (full sequence length before SP distribution)
450
+ - Dh: Hidden dimension (self.hidden_size)
451
+ - H: Expanded number of heads (self.expanded_num_heads)
452
+ - Hq: Number of query heads (self.num_q_heads)
453
+ - Hk: Number of key heads (self.num_k_heads)
454
+ - Hv: Number of value heads (self.num_v_heads)
455
+ - D: Head dimension (self.head_dim)
456
+ - Dq: Query dimension (self.query_dim)
457
+ - Dk: Key dimension (self.key_dim)
458
+ - Dv: Value dimension (self.value_dim)
459
+ - Dexp: Expanded dimension (self.expanded_dim)
460
+ - C: Convolution size (self.conv_size)
461
+ - SP: Sequence parallel size. 1 if not using sequence parallel
462
+
463
+ - B_sp: Batch size after SP reordering. B_sp = B*2 if self.sequence_parallel_group else B_sp = B
464
+ - L_sp: Sequence length after SP reordering. L_sp = L/(SP*2) + C-1 if self.sequence_parallel_group else L_sp = L/SP
465
+ - Lp: Sequence length after SP reordering and conv padding removal. Lp = L/(SP*2) if self.sequence_parallel_group else Lp = L/SP
466
+
467
+ Args:
468
+ hidden_states: Input tensor with shape [B, L/SP, Dh].
469
+ attention_mask: Optional 0-1 mask. Not used.
470
+ past_key_values: Optional cache containing conv_state and recurrent_state
471
+ for inference. When provided, performs incremental decoding.
472
+ use_cache: Whether to return updated cache states. Defaults to False.
473
+ output_attentions: Whether to return attention weights (not used). Defaults to False.
474
+ **kwargs: Additional keyword arguments, may include cu_seqlens for packed sequences.
475
+
476
+ Returns:
477
+ Tuple of (output, attention_weights, past_key_values) where:
478
+ - output: Output tensor with same shape as hidden_states [B, L, Dh]
479
+ - attention_weights: None (not computed for GKA)
480
+ - past_key_values: Updated cache (same as input if provided, else None)
481
+ """
482
+ # During inference, if attention_mask is not None, throw an error
483
+ if attention_mask is not None and not self.training:
484
+ raise NotImplementedError(
485
+ "Sigma GKA kernels currently do not support varlen inputs."
486
+ )
487
+
488
+ batch_size, q_len, _ = hidden_states.shape
489
+ # print(hidden_states.dtype)
490
+
491
+ last_state = None
492
+ if past_key_values is not None and len(past_key_values) > self.layer_idx:
493
+ last_state = past_key_values[self.layer_idx]
494
+
495
+ cu_seqlens = kwargs.get("cu_seqlens", None)
496
+
497
+ # Apply P2P reordering to hidden_states first for custom zigzag SP
498
+ # if self.sequence_parallel_group is not None:
499
+ # assert (
500
+ # cu_seqlens is None
501
+ # ), "SP not implemented for cu_seqlens (variable length samples in a batch)."
502
+ # sp_size = torch.distributed.get_world_size(
503
+ # group=self.sequence_parallel_group
504
+ # )
505
+ # sp_rank = torch.distributed.get_rank(group=self.sequence_parallel_group)
506
+
507
+ # hidden_states = reorder_for_ssm_p2p(
508
+ # hidden_states,
509
+ # self.sequence_parallel_group,
510
+ # torch.cuda.Stream(),
511
+ # sp_size,
512
+ # sp_rank,
513
+ # self.conv_size,
514
+ # )
515
+ # # hidden_states: [B_sp, L_sp, Dh]
516
+
517
+ # Apply projections and convolutions
518
+ conv_state_q, conv_state_k, conv_state_v = None, None, None
519
+ if last_state is not None:
520
+ conv_state_q, conv_state_k, conv_state_v = last_state["conv_state"]
521
+
522
+ q, conv_state_q = self.q_conv1d(
523
+ x=self.q_proj(hidden_states),
524
+ cache=conv_state_q,
525
+ output_final_state=use_cache,
526
+ cu_seqlens=cu_seqlens,
527
+ )
528
+ # q: [B_sp, L_sp, Dq]
529
+ # conv_state_q: [B, Dq, C] or None
530
+
531
+ k, conv_state_k = self.k_conv1d(
532
+ x=self.k_proj(hidden_states),
533
+ cache=conv_state_k,
534
+ output_final_state=use_cache,
535
+ cu_seqlens=cu_seqlens,
536
+ )
537
+ # k: [B_sp, L_sp, Dk]
538
+ # conv_state_k: [B, Dk, C] or None
539
+
540
+ if self.use_v_conv:
541
+ v, conv_state_v = self.v_conv1d(
542
+ x=self.v_proj(hidden_states),
543
+ cache=conv_state_v,
544
+ output_final_state=use_cache,
545
+ cu_seqlens=cu_seqlens,
546
+ )
547
+ # v: [B_sp, L_sp, Dv]
548
+ # conv_state_v: [B, Dv, C] or None
549
+ else:
550
+ v = self.v_proj(hidden_states) # [B_sp, L_sp, Dv]
551
+ conv_state_v = None
552
+
553
+ # Remove padding for custom zigzag SP (first conv_size-1 tokens added by P2P)
554
+ # if self.sequence_parallel_group is not None:
555
+ # q = q[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dq]
556
+ # k = k[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dk]
557
+ # if self.use_v_conv:
558
+ # v = v[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dv]
559
+ # # Also remove padding from hidden_states so beta/alpha/g/gk match seq length
560
+ # hidden_states = hidden_states[
561
+ # :, self.conv_size - 1 :, :
562
+ # ].contiguous() # [B_sp, Lp, Dh]
563
+
564
+ # Reshape q to heads and expand k/v (handles projection + residual if configured)
565
+ q = rearrange(
566
+ q, "... (h d) -> ... h d", h=self.num_q_heads
567
+ ) # [B_sp, Lp, Hq, D]
568
+ k, v = self._expand_kv(k, v) # [B_sp, Lp, H, D] each
569
+
570
+ # Apply GQA/head repeats for q to match expanded_num_heads
571
+ if self.num_q_groups > 1:
572
+ q = repeat(q, "... h d -> ... (h g) d", g=self.num_q_groups)
573
+ # q: [B_sp, Lp, H, D]
574
+
575
+ # Get recurrent state from cache
576
+ last_h_kk, last_h_kv = (
577
+ last_state["recurrent_state"] if last_state is not None else (None, None)
578
+ )
579
+
580
+ # Normalize queries and keys,question q k 需要norm嘛,没有明确感觉需要
581
+ qk_norm_eps = 1e-6
582
+ q = q / (
583
+ torch.linalg.vector_norm(q, dim=-1, keepdim=True).to(q) + qk_norm_eps
584
+ ) # [B_sp, Lp, H, D]
585
+ k = k / (
586
+ torch.linalg.vector_norm(k, dim=-1, keepdim=True).to(k) + qk_norm_eps
587
+ ) # [B_sp, Lp, H, D]
588
+
589
+ # Apply beta gating if enabled
590
+ if self.use_beta_gate:
591
+ beta = self.b_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
592
+ eps = 1e-6
593
+ k = ((beta[..., None] + eps) * k).to(k.dtype) # [B_sp, Lp, H, D]
594
+ v = ((beta[..., None] + eps) * v).to(v.dtype) # [B_sp, Lp, H, D]
595
+
596
+ # Compute alpha connection parameter
597
+ if self.use_alpha_connection:
598
+ alpha = self.alpha_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
599
+ else:
600
+ alpha = torch.ones_like(q[..., 0]) # [B_sp, Lp, H]
601
+
602
+ # Compute forgetting gate
603
+ if self.use_forgetting_gate:
604
+ g = -self.A_log.float().exp() * F.softplus(
605
+ self.a_proj(hidden_states).float() + self.dt_bias
606
+ ) # [B_sp, Lp, H]
607
+ else:
608
+ g = None
609
+
610
+ gk = g if self.use_forgetting_gate_kk else None
611
+
612
+ # Backward kernels require sequence length to be divisible by chunk size
613
+ if gk is None and self.training:
614
+ seq_len = hidden_states.shape[1]
615
+ assert (
616
+ seq_len % self.chunk_size == 0
617
+ ), f"Triton chunk size must divide the sequence length. Got seq_len={seq_len}, chunk_size={self.chunk_size}"
618
+ # sig_learnable_abc = (2*torch.sigmoid(self.learnable_abc)-1.0).to(torch.float32)
619
+ # sig_learnable_abc = torch.tanh(self.learnable_abc).to(torch.float32)
620
+ sig_learnable_abc = self.learnable_abc.to(torch.float32)
621
+ if last_state is None:
622
+ o, h_kk, h_kv = phi_kkt_solve_gla(
623
+ q=q,
624
+ k=k,
625
+ v=v,
626
+ alpha=alpha,###this alpha_connect
627
+ g=g,
628
+ gk=gk,
629
+ gla_scale=self.gla_scale,
630
+ learnable_abc=sig_learnable_abc.to(torch.float32),
631
+ chunk_size=self.chunk_size,
632
+ )
633
+ else:
634
+ o, h_kk, h_kv = phi_kkt_decoding_one_step(
635
+ q=q,
636
+ k=k,
637
+ v=v,
638
+ alpha=alpha,
639
+ g=g,
640
+ gk=gk,
641
+ gla_scale=self.gla_scale,
642
+ learnable_abc=sig_learnable_abc.to(torch.float32),
643
+ prev_h_kk=last_h_kk,
644
+ prev_h_kv=last_h_kv,
645
+ )
646
+
647
+ # Update cache
648
+ if past_key_values is not None:
649
+ past_key_values.update(
650
+ recurrent_state=(h_kk, h_kv),
651
+ conv_state=(conv_state_q, conv_state_k, conv_state_v),
652
+ layer_idx=self.layer_idx,
653
+ offset=q_len,
654
+ )
655
+
656
+ # Apply output gating and normalization
657
+ if self.use_gate:
658
+ g = rearrange(
659
+ self.g_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim
660
+ ) # [B_sp, Lp, H, D]
661
+ o = self.o_norm(o, g) # [B_sp, Lp, H, D]
662
+ else:
663
+ o = self.o_norm(o) # [B_sp, Lp, H, D]
664
+
665
+ # Reshape and project output
666
+ o = rearrange(o, "b t h d -> b t (h d)") # [B_sp, Lp, Dexp]
667
+ o = self.o_proj(o) # [B_sp, Lp, Dh]
668
+
669
+ # Scatter sequence if using sequence parallel
670
+ # if self.sequence_parallel_group is not None:
671
+ # # Recombine zigzag chunks to contiguous
672
+ # bz, len_o, dim = o.shape
673
+ # if bz == 2:
674
+ # o = o.view(bz // 2, len_o * 2, dim)
675
+ # else:
676
+ # o = torch.cat([o[: bz // 2], o[bz // 2 :]], dim=1).contiguous()
677
+ # o: [B, L/SP, Dh]
678
+
679
+ return o, None, past_key_values
680
+
681
+ # #####我们的目标是使用(-1/2)求逆
682
+ # class SigmaGKANet(nn.Module):
683
+ # """
684
+ # Sigma GKA layer with Chebyshev solver and GQA support.
685
+
686
+ # Args:
687
+ # hidden_size: The hidden size of the input. Defaults to 2048.
688
+ # head_dim: The dimension of each head. Assumes q/k/v have the same head dimension.
689
+ # Defaults to 128.
690
+ # num_q_heads: The number of query heads. Defaults to 16.
691
+ # num_k_heads: The number of key heads for GQA. If None, defaults to num_q_heads.
692
+ # Defaults to None.
693
+ # num_v_heads: The number of value heads for GQA. If None, defaults to num_q_heads.
694
+ # Defaults to None.
695
+ # use_beta_gate: Whether to use beta gating mechanism. Defaults to True.
696
+ # use_alpha_connection: Whether to use alpha connection for residual paths. Defaults to True.
697
+ # use_v_conv: Whether to apply convolution to value vectors. Defaults to True.
698
+ # use_forgetting_gate: Whether to use forgetting gate mechanism. Defaults to True.
699
+ # use_forgetting_gate_kk: Whether to use forgetting gate for key-key interactions. Defaults to True.
700
+ # gla_rescale: Whether to apply GLA-style rescaling. Defaults to True.
701
+ # solver_type: Solver method. Currently, we only support "chebyshev". Defaults to "chebyshev".
702
+ # bp_lambda: Whether to backpropagate through lambda parameters. Defaults to True.
703
+ # num_iter: Number of iterations for iterative solvers. Defaults to 30.
704
+ # ridge_strength: Regularization strength for ridge regression. Defaults to 0.02.
705
+ # use_gate: Whether to use output gating mechanism. Defaults to True.
706
+ # conv_size: Size of the convolution kernel. Defaults to 4.
707
+ # layer_idx: The index of the layer. Used for caching during inference. Defaults to None.
708
+ # norm_eps: The epsilon value for the normalization layer. Defaults to 1e-6.
709
+ # chunk_size: Size of chunks for parallel processing in Triton kernels. Defaults to 64.
710
+ # kv_proj_rank: Rank for low-rank KV projection to expand K/V heads. If None, uses
711
+ # standard GQA repeat. Defaults to None.
712
+ # kv_learnable_residual: Whether to use a learnable residual for the KV head expansion
713
+ # instead of a fixed repeat. Only used when kv_proj_rank is set. Defaults to False.
714
+ # learnable_abc: Initial polynomial coefficients. Length 3 (abc) uses
715
+ # phi(H) ~ a I + b H/F + c H^2/F^2; length 4 (abcd) adds d H^3/F^3.
716
+ # Stored as an ``nn.Parameter`` of shape [H, 3] or [H, 4].
717
+ # Defaults to (1.0, -0.5, 0.375).
718
+ # random_init_abc: If True, initialize per-head coefficients independently instead of
719
+ # broadcasting ``learnable_abc`` to all heads. ``a, c`` are drawn from ``U(0, 1)``
720
+ # (positive) and ``b, d`` from ``U(-1, 0)`` (negative). Defaults to False.
721
+ # """
722
+
723
+ # def __init__(
724
+ # self,
725
+ # hidden_size: int = 2048,
726
+ # head_dim: int = 128,
727
+ # num_heads: int = 8,
728
+ # num_q_heads: Optional[int] = None,
729
+ # num_k_heads: Optional[int] = None,
730
+ # num_v_heads: Optional[int] = None,
731
+ # use_beta_gate: bool = True,
732
+ # use_alpha_connection: bool = True,
733
+ # use_v_conv: bool = True,
734
+ # use_forgetting_gate: bool = True,
735
+ # use_forgetting_gate_kk: bool = True,
736
+ # gla_rescale: bool = True,
737
+ # # solver_type: str = "chebyshev",
738
+ # bp_lambda: bool = True,
739
+ # num_iter: int = 30,
740
+ # ridge_strength: float = 0.02,
741
+ # use_gate: bool = False,
742
+ # conv_size: int = 4,
743
+ # layer_idx: Optional[int] = None,
744
+ # norm_eps: float = 1e-6,
745
+ # chunk_size: int = 64,
746
+ # kv_proj_rank: Optional[int] = None,
747
+ # kv_learnable_residual: bool = False,
748
+ # learnable_abc: Tuple[float, ...] = (2.3424, -2.5663, 1.2652),
749
+ # # learnable_abc: Tuple[float, ...] = (2.1111, -1.5556, 0.4444),
750
+ # # learnable_abc: Tuple[float, ...] = (2.0, -2.0, 0.5,-0.125),
751
+ # random_init_abc: bool = True,
752
+ # abc_requires_grad: bool = True,
753
+ # **kwargs,
754
+ # ) -> None:
755
+ # super().__init__()
756
+
757
+ # # assert solver_type == "chebyshev", f"Received {solver_type=}. Currently, Sigma GKA only supports 'chebyshev' solver."
758
+
759
+ # self.hidden_size = hidden_size
760
+
761
+ # self.use_gate = use_gate
762
+ # self.conv_size = conv_size
763
+ # self.sequence_parallel_group = None
764
+ # self.chunk_size = chunk_size
765
+
766
+ # self.head_dim = head_dim
767
+ # self.num_heads = num_heads
768
+ # self.num_q_heads = num_q_heads if num_q_heads is not None else num_heads
769
+ # self.num_k_heads = num_k_heads if num_k_heads is not None else num_heads
770
+ # self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads
771
+ # self.expanded_num_heads = max(
772
+ # self.num_q_heads, self.num_k_heads, self.num_v_heads
773
+ # )
774
+ # self.num_q_groups = self.expanded_num_heads // self.num_q_heads
775
+ # self.num_k_groups = self.expanded_num_heads // self.num_k_heads
776
+ # self.num_v_groups = self.expanded_num_heads // self.num_v_heads
777
+
778
+ # self.query_dim = self.num_q_heads * self.head_dim
779
+ # self.key_dim = self.num_k_heads * self.head_dim
780
+ # self.value_dim = self.num_v_heads * self.head_dim
781
+ # self.expanded_dim = self.expanded_num_heads * self.head_dim
782
+
783
+ # self.layer_idx = layer_idx
784
+
785
+ # self.ridge_strength = ridge_strength
786
+ # self.num_iter = num_iter
787
+ # self.use_beta_gate = use_beta_gate
788
+ # self.use_alpha_connection = use_alpha_connection
789
+ # # self.solver_type = solver_type
790
+ # self.bp_lambda = bp_lambda
791
+ # self.use_v_conv = use_v_conv
792
+ # self.use_forgetting_gate = use_forgetting_gate
793
+ # self.use_forgetting_gate_kk = use_forgetting_gate_kk
794
+
795
+ # if gla_rescale:
796
+ # self.gla_scale = self.head_dim ** -0.5
797
+ # else:
798
+ # self.gla_scale = 1.0
799
+
800
+ # # Projection layers
801
+ # self.q_proj = nn.Linear(hidden_size, self.query_dim, bias=False)
802
+ # self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
803
+ # self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
804
+
805
+ # self.a_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=False)
806
+
807
+ # self.b_proj = (
808
+ # nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
809
+ # if self.use_beta_gate
810
+ # else None
811
+ # )
812
+
813
+ # if self.use_alpha_connection:
814
+ # self.alpha_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
815
+
816
+ # # Initialize A parameter (log scale)
817
+ # A = torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(0, 16)
818
+ # self.A_log = nn.Parameter(torch.log(A))
819
+ # self.A_log._no_weight_decay = True
820
+
821
+ # # Initialize dt bias parameter
822
+ # dt_min = 0.001
823
+ # dt_max = 0.1
824
+ # dt_init_floor = 1e-4
825
+ # dt = torch.exp(
826
+ # torch.rand(self.expanded_num_heads) * (math.log(dt_max) - math.log(dt_min))
827
+ # + math.log(dt_min)
828
+ # )
829
+ # dt = torch.clamp(dt, min=dt_init_floor)
830
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
831
+ # inv_dt = dt + torch.log(-torch.expm1(-dt))
832
+
833
+ # self.dt_bias = nn.Parameter(inv_dt)
834
+ # self.dt_bias._no_weight_decay = True
835
+
836
+ # # Per-head polynomial coefficients: [H, 3] abc or [H, 4] abcd
837
+ # init_abc = torch.tensor(learnable_abc, dtype=torch.float32).reshape(-1)
838
+ # n_coeff = int(init_abc.numel())
839
+ # if n_coeff not in (3, 4):
840
+ # raise ValueError(
841
+ # f"learnable_abc must have 3 (abc) or 4 (abcd) coefficients, got {n_coeff}"
842
+ # )
843
+ # self.learnable_abc = nn.Parameter(
844
+ # init_abc.unsqueeze(0).expand(self.expanded_num_heads, n_coeff).contiguous()
845
+ # )
846
+ # if random_init_abc:
847
+ # # a, c ~ U(0, 1); b, d ~ U(-1, 0)
848
+ # signs = torch.tensor([1.0, -1.0, 1.0, -1.0][:n_coeff], dtype=torch.float32)
849
+ # self.learnable_abc = nn.Parameter(
850
+ # # 2*(torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad
851
+ # # (torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad
852
+ # 2*(torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32).contiguous()-1.0), requires_grad=abc_requires_grad
853
+ # )
854
+ # print("random init abc")
855
+ # print(self.learnable_abc)
856
+ # print(self.learnable_abc.requires_grad)
857
+ # else:
858
+ # print("not random init abc")
859
+ # print(self.learnable_abc)
860
+ # print(self.learnable_abc.requires_grad)
861
+ # self.learnable_abc._no_weight_decay = True
862
+
863
+ # # Short convolution layers
864
+ # self.conv_size = conv_size
865
+ # self.q_conv1d = ShortConvolution(
866
+ # hidden_size=self.query_dim, kernel_size=conv_size, activation="silu"
867
+ # )
868
+ # self.k_conv1d = ShortConvolution(
869
+ # hidden_size=self.key_dim, kernel_size=conv_size, activation="silu"
870
+ # )
871
+ # if self.use_v_conv:
872
+ # self.v_conv1d = ShortConvolution(
873
+ # hidden_size=self.value_dim, kernel_size=conv_size, activation="silu"
874
+ # )
875
+
876
+ # # Output gating and normalization
877
+ # if use_gate:
878
+ # self.g_proj = nn.Linear(hidden_size, self.expanded_dim, bias=False)
879
+ # self.o_norm = FusedRMSNormGated(self.head_dim, eps=norm_eps)
880
+ # else:
881
+ # self.o_norm = RMSNorm(self.head_dim, eps=norm_eps)
882
+ # self.o_proj = nn.Linear(self.expanded_dim, hidden_size, bias=False)
883
+
884
+ # # Optional KV projection for GQA
885
+ # self.kv_proj_rank = kv_proj_rank
886
+ # self.kv_learnable_residual = kv_learnable_residual
887
+ # if self.kv_proj_rank is not None:
888
+ # act_fn = nn.SiLU()
889
+ # self.proj_k = LinearLowRank(
890
+ # in_features=self.key_dim,
891
+ # out_features=self.expanded_num_heads * self.head_dim,
892
+ # rank=self.kv_proj_rank,
893
+ # act_fn=act_fn,
894
+ # )
895
+ # self.proj_v = LinearLowRank(
896
+ # in_features=self.value_dim,
897
+ # out_features=self.expanded_num_heads * self.head_dim,
898
+ # rank=self.kv_proj_rank,
899
+ # act_fn=act_fn,
900
+ # )
901
+
902
+ # if self.kv_learnable_residual:
903
+ # # Learnable mixing matrices initialized to mimic repeat_kv
904
+ # eye_k = torch.eye(self.num_k_heads)
905
+ # ones_k = torch.ones((self.num_k_groups, 1))
906
+ # self.k_rep = nn.Parameter(
907
+ # torch.kron(eye_k, ones_k)
908
+ # ) # [expanded_num_heads, num_k_heads]
909
+
910
+ # eye_v = torch.eye(self.num_v_heads)
911
+ # ones_v = torch.ones((self.num_v_groups, 1))
912
+ # self.v_rep = nn.Parameter(
913
+ # torch.kron(eye_v, ones_v)
914
+ # ) # [expanded_num_heads, num_v_heads]
915
+
916
+ # def _expand_kv(self, k: Tensor, v: Tensor) -> Tuple[Tensor, Tensor]:
917
+ # """
918
+ # Expand k and v from their native head counts to expanded_num_heads.
919
+
920
+ # Three modes:
921
+ # 1. kv_proj_rank + kv_learnable_residual: learnable mixing residual + low-rank projection
922
+ # 2. kv_proj_rank without learnable residual: plain repeat residual + low-rank projection
923
+ # 3. No projection: simple repeat (or rearrange if groups == 1). This is the standard GQA repeat.
924
+
925
+ # Args:
926
+ # k: [B, L, Dk] raw key tensor (flat, not yet reshaped to heads)
927
+ # v: [B, L, Dv] raw value tensor (flat, not yet reshaped to heads)
928
+
929
+ # Returns:
930
+ # k: [B, L, H, D] expanded keys
931
+ # v: [B, L, H, D] expanded values
932
+ # """
933
+ # if self.kv_proj_rank is not None and (
934
+ # self.num_k_groups > 1 or self.num_v_groups > 1
935
+ # ):
936
+ # # Build residual
937
+ # if self.kv_learnable_residual:
938
+ # k_heads = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
939
+ # k_res = torch.einsum("eh,blhd->bled", self.k_rep, k_heads)
940
+ # v_heads = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
941
+ # v_res = torch.einsum("eh,blhd->bled", self.v_rep, v_heads)
942
+ # else:
943
+ # k_res = repeat(
944
+ # rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads),
945
+ # "... h d -> ... (h g) d",
946
+ # g=self.num_k_groups,
947
+ # )
948
+ # v_res = repeat(
949
+ # rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads),
950
+ # "... h d -> ... (h g) d",
951
+ # g=self.num_v_groups,
952
+ # )
953
+
954
+ # # Low-rank projection to expanded dim + add residual
955
+ # k = (
956
+ # rearrange(
957
+ # self.proj_k(k), "... (h d) -> ... h d", h=self.expanded_num_heads
958
+ # )
959
+ # + k_res
960
+ # )
961
+ # v = (
962
+ # rearrange(
963
+ # self.proj_v(v), "... (h d) -> ... h d", h=self.expanded_num_heads
964
+ # )
965
+ # + v_res
966
+ # )
967
+ # else:
968
+ # # Plain rearrange + repeat
969
+ # k = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
970
+ # v = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
971
+ # if self.num_k_groups > 1:
972
+ # k = repeat(k, "... h d -> ... (h g) d", g=self.num_k_groups)
973
+ # if self.num_v_groups > 1:
974
+ # v = repeat(v, "... h d -> ... (h g) d", g=self.num_v_groups)
975
+
976
+ # return k, v
977
+
978
+ # def forward(
979
+ # self,
980
+ # hidden_states: Tensor,
981
+ # attention_mask: Optional[Tensor] = None,
982
+ # past_key_values: Optional[Cache] = None,
983
+ # use_cache: Optional[bool] = False,
984
+ # output_attentions: Optional[bool] = False,
985
+ # **kwargs,
986
+ # ) -> Tuple[Tensor, Optional[Tensor], Optional[Cache]]:
987
+ # """
988
+ # Sigma GKA forward pass with optional caching.
989
+
990
+ # NOTE: We use the following variables for tensor shape hints:
991
+ # - B: Input batch size
992
+ # - L: Sequence length (full sequence length before SP distribution)
993
+ # - Dh: Hidden dimension (self.hidden_size)
994
+ # - H: Expanded number of heads (self.expanded_num_heads)
995
+ # - Hq: Number of query heads (self.num_q_heads)
996
+ # - Hk: Number of key heads (self.num_k_heads)
997
+ # - Hv: Number of value heads (self.num_v_heads)
998
+ # - D: Head dimension (self.head_dim)
999
+ # - Dq: Query dimension (self.query_dim)
1000
+ # - Dk: Key dimension (self.key_dim)
1001
+ # - Dv: Value dimension (self.value_dim)
1002
+ # - Dexp: Expanded dimension (self.expanded_dim)
1003
+ # - C: Convolution size (self.conv_size)
1004
+ # - SP: Sequence parallel size. 1 if not using sequence parallel
1005
+
1006
+ # - B_sp: Batch size after SP reordering. B_sp = B*2 if self.sequence_parallel_group else B_sp = B
1007
+ # - L_sp: Sequence length after SP reordering. L_sp = L/(SP*2) + C-1 if self.sequence_parallel_group else L_sp = L/SP
1008
+ # - Lp: Sequence length after SP reordering and conv padding removal. Lp = L/(SP*2) if self.sequence_parallel_group else Lp = L/SP
1009
+
1010
+ # Args:
1011
+ # hidden_states: Input tensor with shape [B, L/SP, Dh].
1012
+ # attention_mask: Optional 0-1 mask. Not used.
1013
+ # past_key_values: Optional cache containing conv_state and recurrent_state
1014
+ # for inference. When provided, performs incremental decoding.
1015
+ # use_cache: Whether to return updated cache states. Defaults to False.
1016
+ # output_attentions: Whether to return attention weights (not used). Defaults to False.
1017
+ # **kwargs: Additional keyword arguments, may include cu_seqlens for packed sequences.
1018
+
1019
+ # Returns:
1020
+ # Tuple of (output, attention_weights, past_key_values) where:
1021
+ # - output: Output tensor with same shape as hidden_states [B, L, Dh]
1022
+ # - attention_weights: None (not computed for GKA)
1023
+ # - past_key_values: Updated cache (same as input if provided, else None)
1024
+ # """
1025
+ # # During inference, if attention_mask is not None, throw an error
1026
+ # if attention_mask is not None and not self.training:
1027
+ # raise NotImplementedError(
1028
+ # "Sigma GKA kernels currently do not support varlen inputs."
1029
+ # )
1030
+
1031
+ # batch_size, q_len, _ = hidden_states.shape
1032
+ # # print(hidden_states.dtype)
1033
+
1034
+ # last_state = None
1035
+ # if past_key_values is not None:
1036
+ # last_state = past_key_values[self.layer_idx]
1037
+
1038
+ # cu_seqlens = kwargs.get("cu_seqlens", None)
1039
+
1040
+ # # Apply P2P reordering to hidden_states first for custom zigzag SP
1041
+ # # if self.sequence_parallel_group is not None:
1042
+ # # assert (
1043
+ # # cu_seqlens is None
1044
+ # # ), "SP not implemented for cu_seqlens (variable length samples in a batch)."
1045
+ # # sp_size = torch.distributed.get_world_size(
1046
+ # # group=self.sequence_parallel_group
1047
+ # # )
1048
+ # # sp_rank = torch.distributed.get_rank(group=self.sequence_parallel_group)
1049
+
1050
+ # # hidden_states = reorder_for_ssm_p2p(
1051
+ # # hidden_states,
1052
+ # # self.sequence_parallel_group,
1053
+ # # torch.cuda.Stream(),
1054
+ # # sp_size,
1055
+ # # sp_rank,
1056
+ # # self.conv_size,
1057
+ # # )
1058
+ # # # hidden_states: [B_sp, L_sp, Dh]
1059
+
1060
+ # # Apply projections and convolutions
1061
+ # conv_state_q, conv_state_k, conv_state_v = None, None, None
1062
+ # if last_state is not None:
1063
+ # conv_state_q, conv_state_k, conv_state_v = last_state["conv_state"]
1064
+
1065
+ # q, conv_state_q = self.q_conv1d(
1066
+ # x=self.q_proj(hidden_states),
1067
+ # cache=conv_state_q,
1068
+ # output_final_state=use_cache,
1069
+ # cu_seqlens=cu_seqlens,
1070
+ # )
1071
+ # # q: [B_sp, L_sp, Dq]
1072
+ # # conv_state_q: [B, Dq, C] or None
1073
+
1074
+ # k, conv_state_k = self.k_conv1d(
1075
+ # x=self.k_proj(hidden_states),
1076
+ # cache=conv_state_k,
1077
+ # output_final_state=use_cache,
1078
+ # cu_seqlens=cu_seqlens,
1079
+ # )
1080
+ # # k: [B_sp, L_sp, Dk]
1081
+ # # conv_state_k: [B, Dk, C] or None
1082
+
1083
+ # if self.use_v_conv:
1084
+ # v, conv_state_v = self.v_conv1d(
1085
+ # x=self.v_proj(hidden_states),
1086
+ # cache=conv_state_v,
1087
+ # output_final_state=use_cache,
1088
+ # cu_seqlens=cu_seqlens,
1089
+ # )
1090
+ # # v: [B_sp, L_sp, Dv]
1091
+ # # conv_state_v: [B, Dv, C] or None
1092
+ # else:
1093
+ # v = self.v_proj(hidden_states) # [B_sp, L_sp, Dv]
1094
+ # conv_state_v = None
1095
+
1096
+ # # Remove padding for custom zigzag SP (first conv_size-1 tokens added by P2P)
1097
+ # # if self.sequence_parallel_group is not None:
1098
+ # # q = q[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dq]
1099
+ # # k = k[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dk]
1100
+ # # if self.use_v_conv:
1101
+ # # v = v[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dv]
1102
+ # # # Also remove padding from hidden_states so beta/alpha/g/gk match seq length
1103
+ # # hidden_states = hidden_states[
1104
+ # # :, self.conv_size - 1 :, :
1105
+ # # ].contiguous() # [B_sp, Lp, Dh]
1106
+
1107
+ # # Reshape q to heads and expand k/v (handles projection + residual if configured)
1108
+ # q = rearrange(
1109
+ # q, "... (h d) -> ... h d", h=self.num_q_heads
1110
+ # ) # [B_sp, Lp, Hq, D]
1111
+ # k, v = self._expand_kv(k, v) # [B_sp, Lp, H, D] each
1112
+
1113
+ # # Apply GQA/head repeats for q to match expanded_num_heads
1114
+ # if self.num_q_groups > 1:
1115
+ # q = repeat(q, "... h d -> ... (h g) d", g=self.num_q_groups)
1116
+ # # q: [B_sp, Lp, H, D]
1117
+
1118
+ # # Get recurrent state from cache
1119
+ # last_h_kk, last_h_kv = (
1120
+ # last_state["recurrent_state"] if last_state is not None else (None, None)
1121
+ # )
1122
+
1123
+ # # Normalize queries and keys,question q k 需要norm嘛,没有明确感觉需要
1124
+ # qk_norm_eps = 1e-6
1125
+ # q = q / (
1126
+ # torch.linalg.vector_norm(q, dim=-1, keepdim=True).to(q) + qk_norm_eps
1127
+ # ) # [B_sp, Lp, H, D]
1128
+ # k = k / (
1129
+ # torch.linalg.vector_norm(k, dim=-1, keepdim=True).to(k) + qk_norm_eps
1130
+ # ) # [B_sp, Lp, H, D]
1131
+
1132
+ # # Apply beta gating if enabled
1133
+ # if self.use_beta_gate:
1134
+ # beta = self.b_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
1135
+ # eps = 1e-6
1136
+ # k = ((beta[..., None] + eps) * k).to(k.dtype) # [B_sp, Lp, H, D]
1137
+ # v = ((beta[..., None] + eps) * v).to(v.dtype) # [B_sp, Lp, H, D]
1138
+
1139
+ # # Compute alpha connection parameter
1140
+ # if self.use_alpha_connection:
1141
+ # alpha = self.alpha_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
1142
+ # else:
1143
+ # alpha = torch.ones_like(q[..., 0]) # [B_sp, Lp, H]
1144
+
1145
+ # # Compute forgetting gate
1146
+ # if self.use_forgetting_gate:
1147
+ # g = -self.A_log.float().exp() * F.softplus(
1148
+ # self.a_proj(hidden_states).float() + self.dt_bias
1149
+ # ) # [B_sp, Lp, H]
1150
+ # else:
1151
+ # g = None
1152
+
1153
+ # gk = g if self.use_forgetting_gate_kk else None
1154
+
1155
+ # # Backward kernels require sequence length to be divisible by chunk size
1156
+ # if gk is None and self.training:
1157
+ # seq_len = hidden_states.shape[1]
1158
+ # assert (
1159
+ # seq_len % self.chunk_size == 0
1160
+ # ), f"Triton chunk size must divide the sequence length. Got seq_len={seq_len}, chunk_size={self.chunk_size}"
1161
+ # # sig_learnable_abc = (2*torch.sigmoid(self.learnable_abc)-1.0).to(torch.float32)
1162
+ # # sig_learnable_abc = torch.tanh(self.learnable_abc).to(torch.float32)
1163
+ # sig_learnable_abc = self.learnable_abc.to(torch.float32)
1164
+ # o, h_kk, h_kv = phi_kkt_solve_gla(
1165
+ # q=q,
1166
+ # k=k,
1167
+ # v=v,
1168
+ # alpha=alpha,###this alpha_connect
1169
+ # g=g,
1170
+ # gk=gk,
1171
+ # gla_scale=self.gla_scale,
1172
+ # learnable_abc=sig_learnable_abc.to(torch.float32),
1173
+ # chunk_size=self.chunk_size,
1174
+ # h0_kk=last_h_kk,
1175
+ # h0_kv=last_h_kv,
1176
+ # output_final_state=bool(use_cache),
1177
+ # )
1178
+
1179
+ # # Update cache
1180
+ # if past_key_values is not None:
1181
+ # past_key_values.update(
1182
+ # recurrent_state=(h_kk, h_kv),
1183
+ # conv_state=(conv_state_q, conv_state_k, conv_state_v),
1184
+ # layer_idx=self.layer_idx,
1185
+ # offset=q_len,
1186
+ # )
1187
+
1188
+ # # Apply output gating and normalization
1189
+ # if self.use_gate:
1190
+ # g = rearrange(
1191
+ # self.g_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim
1192
+ # ) # [B_sp, Lp, H, D]
1193
+ # o = self.o_norm(o, g) # [B_sp, Lp, H, D]
1194
+ # else:
1195
+ # o = self.o_norm(o) # [B_sp, Lp, H, D]
1196
+
1197
+ # # Reshape and project output
1198
+ # o = rearrange(o, "b t h d -> b t (h d)") # [B_sp, Lp, Dexp]
1199
+ # o = self.o_proj(o) # [B_sp, Lp, Dh]
1200
+
1201
+ # # Scatter sequence if using sequence parallel
1202
+ # # if self.sequence_parallel_group is not None:
1203
+ # # # Recombine zigzag chunks to contiguous
1204
+ # # bz, len_o, dim = o.shape
1205
+ # # if bz == 2:
1206
+ # # o = o.view(bz // 2, len_o * 2, dim)
1207
+ # # else:
1208
+ # # o = torch.cat([o[: bz // 2], o[bz // 2 :]], dim=1).contiguous()
1209
+ # # o: [B, L/SP, Dh]
1210
+
1211
+ # return o, None, past_key_values
1212
+
layers/simple_gla.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import TYPE_CHECKING, Optional, Tuple
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from einops import rearrange, repeat
12
+
13
+ from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
14
+ from fla.modules.activations import ACT2FN
15
+ from fla.ops.simple_gla import chunk_simple_gla, fused_recurrent_simple_gla
16
+
17
+ if TYPE_CHECKING:
18
+ from fla.models.utils import Cache
19
+
20
+
21
+ class SimpleGatedLinearAttention(nn.Module):
22
+ r"""
23
+ The layer implementaion for [Gated Linear Attention Transformers with Hardware-Efficient Training](https://arxiv.org/abs/2312.06635). # noqa
24
+ This layer calls the simplified GLA kernel in which the gating is head-wise instead of elementwise.
25
+
26
+ Args:
27
+ mode (str, Optional):
28
+ Which GLA kernel to use.
29
+ Currently available: `chunk`.
30
+ Default: `chunk`.
31
+ hidden_size (int, Optional):
32
+ The hidden size of the input. Default: 1024.
33
+ expand_k (float, Optional):
34
+ The expansion ratio for the key dim. Default: 1.0.
35
+ expand_v (float, Optional):
36
+ The expansion ratio for the value dim. Default: 1.0.
37
+ num_heads (int, Optional):
38
+ The number of heads. Default: 4.
39
+ num_kv_heads (int, Optional):
40
+ The number of key/value heads, used for MQA. Default: None.
41
+ feature_map (str, Optional):
42
+ Feature map function applied to queries/keys. Default: None.
43
+ use_short_conv (bool, Optional):
44
+ Whether to use short convolutions. Default: `False`.
45
+ conv_size (int, Optional):
46
+ The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4.
47
+ conv_bias (bool, Optional):
48
+ Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`.
49
+ gate_fn (str, Optional):
50
+ The activation function for the output gate. Default: `swish`.
51
+ elementwise_affine (bool, Optional):
52
+ If `True`, applies elementwise affine to LayerNorm with learnable parameters. Default: `True`.
53
+ norm_eps (float, Optional):
54
+ The epsilon value for the layernorm/rmsnorm layer. Default: 1e-5.
55
+ gate_logit_normalizer (int, Optional):
56
+ The normalizer for the gate logits, appied after `logsigmoid`. Default: 16.
57
+ fuse_norm (bool, Optional):
58
+ Whether to fuse the norm and the output gate for better memory footprint. Default: `True`.
59
+ layer_idx (int, Optional):
60
+ The index of the layer. Default: None.
61
+ """
62
+
63
+ def __init__(
64
+ self,
65
+ mode: str = 'chunk',
66
+ hidden_size: int = 1024,
67
+ expand_k: float = 1.,
68
+ expand_v: float = 1.,
69
+ num_heads: int = 4,
70
+ num_kv_heads: Optional[int] = None,
71
+ feature_map: Optional[str] = None,
72
+ use_short_conv: bool = True,
73
+ conv_size: int = 4,
74
+ conv_bias: bool = False,
75
+ gate_fn: str = 'swish',
76
+ elementwise_affine: Optional[bool] = True,
77
+ norm_eps: float = 1e-5,
78
+ gate_logit_normalizer: int = 16,
79
+ fuse_norm: bool = True,
80
+ layer_idx: int = None,
81
+ ) -> SimpleGatedLinearAttention:
82
+ super().__init__()
83
+
84
+ self.mode = mode
85
+ self.hidden_size = hidden_size
86
+ self.expand_k = expand_k
87
+ self.expand_v = expand_v
88
+ self.num_heads = num_heads
89
+ self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
90
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
91
+ self.feature_map_fn = ACT2FN[feature_map] if feature_map is not None else None
92
+
93
+ self.use_short_conv = use_short_conv
94
+ self.conv_size = conv_size
95
+ self.conv_bias = conv_bias
96
+
97
+ self.key_dim = int(hidden_size * expand_k)
98
+ self.value_dim = int(hidden_size * expand_v)
99
+ self.key_dim_per_group = self.key_dim // self.num_kv_groups
100
+ self.value_dim_per_group = self.value_dim // self.num_kv_groups
101
+ self.layer_idx = layer_idx
102
+
103
+ assert mode in ['chunk', "fused_recurrent"], f"Not supported mode `{mode}`."
104
+ assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
105
+ assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
106
+
107
+ self.head_k_dim = self.key_dim // num_heads
108
+ self.head_v_dim = self.value_dim // num_heads
109
+
110
+ self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
111
+ self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False)
112
+ self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False)
113
+ self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
114
+
115
+ if use_short_conv:
116
+ self.conv_size = conv_size
117
+ self.q_conv1d = ShortConvolution(
118
+ hidden_size=self.key_dim,
119
+ kernel_size=conv_size,
120
+ bias=conv_bias,
121
+ activation='silu',
122
+ )
123
+ self.k_conv1d = ShortConvolution(
124
+ hidden_size=self.key_dim_per_group,
125
+ kernel_size=conv_size,
126
+ bias=conv_bias,
127
+ activation='silu',
128
+ )
129
+ self.v_conv1d = ShortConvolution(
130
+ hidden_size=self.value_dim_per_group,
131
+ kernel_size=conv_size,
132
+ bias=conv_bias,
133
+ activation='silu',
134
+ )
135
+
136
+ self.gk_proj = nn.Linear(hidden_size, self.num_heads)
137
+
138
+ if gate_fn == 'swish' and fuse_norm:
139
+ self.g_norm_swish_gate = FusedRMSNormGated(
140
+ hidden_size=self.head_v_dim,
141
+ elementwise_affine=elementwise_affine,
142
+ eps=norm_eps
143
+ )
144
+ self.fuse_norm_and_gate = True
145
+ else:
146
+ self.fuse_norm_and_gate = False
147
+ self.g_norm = RMSNorm(
148
+ hidden_size=self.head_v_dim,
149
+ elementwise_affine=elementwise_affine,
150
+ eps=norm_eps
151
+ )
152
+ self.gate_fn = ACT2FN[gate_fn]
153
+ self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
154
+
155
+ self.gate_logit_normalizer = gate_logit_normalizer
156
+
157
+ def forward(
158
+ self,
159
+ hidden_states: torch.Tensor,
160
+ attention_mask: Optional[torch.Tensor] = None,
161
+ past_key_values: Optional[Cache] = None,
162
+ use_cache: Optional[bool] = False,
163
+ output_attentions: Optional[bool] = False,
164
+ **kwargs
165
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
166
+ if attention_mask is not None:
167
+ assert len(attention_mask.shape) == 2, (
168
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
169
+ "for padding purposes (0 indicating padding). "
170
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
171
+ )
172
+
173
+ # launching the triton kernel for just one token will actually be slower
174
+ mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
175
+
176
+ last_state = None
177
+ if past_key_values is not None and len(past_key_values) > self.layer_idx:
178
+ last_state = past_key_values[self.layer_idx]
179
+
180
+ cu_seqlens = kwargs.get('cu_seqlens', None)
181
+ if self.use_short_conv:
182
+ conv_state_q, conv_state_k, conv_state_v = None, None, None
183
+ if last_state is not None:
184
+ conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
185
+ conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None
186
+ q, conv_state_q = self.q_conv1d(
187
+ x=self.q_proj(hidden_states),
188
+ mask=conv_mask,
189
+ cache=conv_state_q,
190
+ output_final_state=use_cache,
191
+ cu_seqlens=cu_seqlens
192
+ )
193
+ k, conv_state_k = self.k_conv1d(
194
+ x=self.k_proj(hidden_states),
195
+ mask=conv_mask,
196
+ cache=conv_state_k,
197
+ output_final_state=use_cache,
198
+ cu_seqlens=cu_seqlens
199
+ )
200
+ v, conv_state_v = self.v_conv1d(
201
+ x=self.v_proj(hidden_states),
202
+ mask=conv_mask,
203
+ cache=conv_state_v,
204
+ output_final_state=use_cache,
205
+ cu_seqlens=cu_seqlens
206
+ )
207
+ else:
208
+ q = self.q_proj(hidden_states)
209
+ k = self.k_proj(hidden_states)
210
+ v = self.v_proj(hidden_states)
211
+ gk = self.gk_proj(hidden_states)
212
+
213
+ if self.feature_map_fn is not None:
214
+ q, k = map(self.feature_map_fn, (q, k))
215
+ # dealing with left-padding
216
+ if attention_mask is not None:
217
+ v = v.mul_(attention_mask[:, -v.shape[-2]:, None])
218
+ q = rearrange(q, '... (h d) -> ... h d', h=self.num_heads)
219
+ if self.num_kv_groups > 1:
220
+ k, v = (repeat(x, '... (h d) -> ... (h g) d', h=self.num_kv_heads, g=self.num_kv_groups) for x in (k, v))
221
+ else:
222
+ k, v = (rearrange(x, '... (h d) -> ... h d', h=self.num_kv_heads) for x in (k, v))
223
+ gk = F.logsigmoid(gk) / self.gate_logit_normalizer
224
+
225
+ recurrent_state = last_state['recurrent_state'] if last_state is not None else None
226
+ if mode == 'chunk':
227
+ o, recurrent_state = chunk_simple_gla(
228
+ q=q,
229
+ k=k,
230
+ v=v,
231
+ g=gk,
232
+ initial_state=recurrent_state,
233
+ output_final_state=use_cache,
234
+ cu_seqlens=cu_seqlens,
235
+ )
236
+ elif mode == 'fused_recurrent':
237
+ o, recurrent_state = fused_recurrent_simple_gla(
238
+ q=q,
239
+ k=k,
240
+ v=v,
241
+ g=gk,
242
+ initial_state=recurrent_state,
243
+ output_final_state=use_cache,
244
+ cu_seqlens=cu_seqlens,
245
+ )
246
+ else:
247
+ raise NotImplementedError(f"Not supported mode `{mode}`.")
248
+
249
+ if past_key_values is not None:
250
+ past_key_values.update(
251
+ recurrent_state=recurrent_state,
252
+ conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
253
+ layer_idx=self.layer_idx,
254
+ offset=q.shape[1]
255
+ )
256
+
257
+ g = self.g_proj(hidden_states)
258
+ if self.fuse_norm_and_gate:
259
+ g = rearrange(g, 'b t (h d) -> b t h d', h=self.num_heads)
260
+ o = self.g_norm_swish_gate(o, g)
261
+ o = rearrange(o, 'b t h d -> b t (h d)')
262
+ else:
263
+ o = rearrange(self.g_norm(o), 'b t h d -> b t (h d)')
264
+ o = o * self.gate_fn(g)
265
+ o = self.o_proj(o)
266
+
267
+ return o, None, past_key_values
268
+
269
+ def state_size(self, **kwargs) -> int:
270
+ state_size = self.key_dim * self.head_v_dim
271
+ for module in self.children():
272
+ if isinstance(module, ShortConvolution):
273
+ state_size += module.state_size
274
+ return state_size
layers/state_org.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import TYPE_CHECKING, Dict, Optional, Tuple
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from einops import rearrange, repeat
13
+
14
+ from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
15
+ from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
16
+ from fla.modules.activations import ACT2FN
17
+ # from ..ops.state_org import chunk_state_org, fused_chunk_state_org, fused_recurrent_state_org
18
+ from fla.ops.gla import chunk_gla, fused_chunk_gla, fused_recurrent_gla
19
+ if TYPE_CHECKING:
20
+ from transformers.processing_utils import Unpack
21
+
22
+ from fla.models.utils import Cache
23
+
24
+
25
+ class StateOrg(nn.Module):
26
+ r"""
27
+ The layer implementaion for [Gated Linear Attention Transformers with Hardware-Efficient Training](https://arxiv.org/abs/2312.06635). # noqa
28
+
29
+ Args:
30
+ mode (str, Optional):
31
+ Which GLA kernel to use.
32
+ Currently available: `chunk`, `fused_recurrent`, and `fused_chunk`.
33
+ Default: `chunk`.
34
+ hidden_size (int, Optional):
35
+ The hidden size of the input. Default: 1024.
36
+ expand_k (float, Optional):
37
+ The expansion ratio for the key dim. Default: 0.5.
38
+ expand_v (float, Optional):
39
+ The expansion ratio for the value dim. Default: 1.0.
40
+ num_heads (int, Optional):
41
+ The number of heads. Default: 4.
42
+ num_kv_heads (int, Optional):
43
+ The number of key/value heads, used for MQA. Default: None.
44
+ feature_map (str, Optional):
45
+ Feature map function applied to queries/keys. Default: None.
46
+ use_short_conv (bool, Optional):
47
+ Whether to use short convolutions. Default: `False`.
48
+ conv_size (int, Optional):
49
+ The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4.
50
+ conv_bias (bool, Optional):
51
+ Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`.
52
+ use_output_gate (bool, Optional):
53
+ Whether to use output gate. Default: `True`.
54
+ gate_fn (str, Optional):
55
+ The activation function for the output gate. Default: `swish`.
56
+ elementwise_affine (bool, Optional):
57
+ If `True`, applies elementwise affine to LayerNorm with learnable parameters. Default: `True`.
58
+ norm_eps (float, Optional):
59
+ The epsilon value for the layernorm/rmsnorm layer. Default: 1e-5.
60
+ gate_logit_normalizer (int, Optional):
61
+ The normalizer for the gate logits, appied after `logsigmoid`. Default: 16.
62
+ gate_low_rank_dim (int, Optional):
63
+ The low rank dim for the gate projection. Default: 16.
64
+ clamp_min (float, Optional):
65
+ The minimum value for the gate logits. Default: None.
66
+ fuse_norm (bool, Optional):
67
+ Whether to fuse the norm and the output gate for better memory footprint. Default: `True`.
68
+ layer_idx (int, Optional):
69
+ The index of the layer. Default: None.
70
+ """
71
+
72
+ def __init__(
73
+ self,
74
+ mode: str = 'chunk',
75
+ hidden_size: int = 1024,
76
+ expand_k: float = 0.5,
77
+ expand_v: float = 1.0,
78
+ num_heads: int = 4,
79
+ num_kv_heads: Optional[int] = None,
80
+ feature_map: Optional[str] = None,
81
+ use_short_conv: bool = False,
82
+ conv_size: int = 4,
83
+ conv_bias: bool = False,
84
+ use_output_gate: bool = True,
85
+ gate_fn: str = 'swish',
86
+ elementwise_affine: Optional[bool] = True,
87
+ norm_eps: float = 1e-5,
88
+ gate_logit_normalizer: int = 16,
89
+ gate_low_rank_dim: int = 16,
90
+ clamp_min: Optional[float] = None,
91
+ fuse_norm: bool = True,
92
+ layer_idx: int = None,
93
+ ) -> StateOrg:
94
+ super().__init__()
95
+
96
+ self.mode = mode
97
+ self.hidden_size = hidden_size
98
+ self.expand_k = expand_k
99
+ self.expand_v = expand_v
100
+ self.num_heads = num_heads
101
+ self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
102
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
103
+ self.feature_map_fn = ACT2FN[feature_map] if feature_map is not None else None
104
+
105
+ self.use_short_conv = use_short_conv
106
+ self.conv_size = conv_size
107
+ self.conv_bias = conv_bias
108
+ self.use_output_gate = use_output_gate
109
+
110
+ self.key_dim = int(hidden_size * expand_k)
111
+ self.value_dim = int(hidden_size * expand_v)
112
+ self.key_dim_per_group = self.key_dim // self.num_kv_groups
113
+ self.value_dim_per_group = self.value_dim // self.num_kv_groups
114
+ self.clamp_min = clamp_min
115
+ self.layer_idx = layer_idx
116
+
117
+ assert mode in ['chunk', 'fused_recurrent', 'fused_chunk'], f"Not supported mode `{mode}`."
118
+ assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
119
+ assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
120
+
121
+ self.head_k_dim = self.key_dim // num_heads
122
+ self.head_v_dim = self.value_dim // num_heads
123
+
124
+ self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
125
+ self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False)
126
+ self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False)
127
+ if self.use_output_gate:
128
+ self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
129
+
130
+ if use_short_conv:
131
+ self.conv_size = conv_size
132
+ self.q_conv1d = ShortConvolution(
133
+ hidden_size=self.key_dim,
134
+ kernel_size=conv_size,
135
+ bias=conv_bias,
136
+ activation='silu',
137
+ )
138
+ self.k_conv1d = ShortConvolution(
139
+ hidden_size=self.key_dim_per_group,
140
+ kernel_size=conv_size,
141
+ bias=conv_bias,
142
+ activation='silu',
143
+ )
144
+ self.v_conv1d = ShortConvolution(
145
+ hidden_size=self.value_dim_per_group,
146
+ kernel_size=conv_size,
147
+ bias=conv_bias,
148
+ activation='silu',
149
+ )
150
+
151
+ self.gk_proj = nn.Sequential(nn.Linear(hidden_size, gate_low_rank_dim, bias=False),
152
+ nn.Linear(gate_low_rank_dim, self.key_dim_per_group, bias=True))
153
+ self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
154
+
155
+ if gate_fn == 'swish' and fuse_norm and use_output_gate:
156
+ self.g_norm_swish_gate = FusedRMSNormGated(
157
+ hidden_size=self.head_v_dim,
158
+ elementwise_affine=elementwise_affine,
159
+ eps=norm_eps
160
+ )
161
+ self.fuse_norm_and_gate = True
162
+ else:
163
+ self.fuse_norm_and_gate = False
164
+ self.g_norm = RMSNorm(
165
+ hidden_size=self.head_v_dim,
166
+ elementwise_affine=elementwise_affine,
167
+ eps=norm_eps
168
+ )
169
+ self.gate_fn = ACT2FN[gate_fn]
170
+
171
+ self.gate_logit_normalizer = gate_logit_normalizer
172
+ self.chunk_size = 128
173
+
174
+ def forward(
175
+ self,
176
+ hidden_states: torch.Tensor,
177
+ attention_mask: Optional[torch.Tensor] = None,
178
+ past_key_values: Optional[Cache] = None,
179
+ use_cache: Optional[bool] = False,
180
+ output_attentions: Optional[bool] = False,
181
+ **kwargs: Unpack[Dict]
182
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
183
+ if attention_mask is not None:
184
+ assert len(attention_mask.shape) == 2, (
185
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
186
+ "for padding purposes (0 indicating padding). "
187
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
188
+ )
189
+
190
+ batch_size, q_len, _ = hidden_states.shape
191
+ mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
192
+
193
+ last_state = None
194
+ if past_key_values is not None and len(past_key_values) > self.layer_idx:
195
+ last_state = past_key_values[self.layer_idx]
196
+
197
+ cu_seqlens = kwargs.get('cu_seqlens', None)
198
+ # if attention_mask is not None:
199
+ # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
200
+ # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
201
+
202
+ if self.use_short_conv:
203
+ conv_state_q, conv_state_k, conv_state_v = None, None, None
204
+ if last_state is not None:
205
+ conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
206
+ q, conv_state_q = self.q_conv1d(
207
+ x=self.q_proj(hidden_states),
208
+ cache=conv_state_q,
209
+ output_final_state=use_cache,
210
+ cu_seqlens=cu_seqlens
211
+ )
212
+ k, conv_state_k = self.k_conv1d(
213
+ x=self.k_proj(hidden_states),
214
+ cache=conv_state_k,
215
+ output_final_state=use_cache,
216
+ cu_seqlens=cu_seqlens
217
+ )
218
+ v, conv_state_v = self.v_conv1d(
219
+ x=self.v_proj(hidden_states),
220
+ cache=conv_state_v,
221
+ output_final_state=use_cache,
222
+ cu_seqlens=cu_seqlens
223
+ )
224
+ else:
225
+ q = self.q_proj(hidden_states)
226
+ k = self.k_proj(hidden_states)
227
+ v = self.v_proj(hidden_states)
228
+ gk = self.gk_proj(hidden_states)
229
+
230
+ if self.feature_map_fn is not None:
231
+ q, k = map(self.feature_map_fn, (q, k))
232
+ q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim)
233
+ if self.num_kv_groups > 1:
234
+ k, gk = (repeat(x, '... (h d) -> ... (h g) d', g=self.num_kv_groups, d=self.head_k_dim) for x in (k, gk))
235
+ v = repeat(v, '... (h d) -> ... (h g) d', g=self.num_kv_groups, d=self.head_v_dim)
236
+ else:
237
+ k, gk = (rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim) for x in (k, gk))
238
+ v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
239
+ gk = F.logsigmoid(gk) / self.gate_logit_normalizer
240
+
241
+ if self.clamp_min is not None:
242
+ gk = torch.clamp_min(gk, self.clamp_min)
243
+
244
+ recurrent_state = last_state['recurrent_state'] if last_state is not None else None
245
+ # if mode == 'fused_recurrent':
246
+ # o, recurrent_state = fused_recurrent_gla(
247
+ # q=q,
248
+ # k=k,
249
+ # v=v,
250
+ # gk=gk,
251
+ # initial_state=recurrent_state,
252
+ # output_final_state=use_cache,
253
+ # cu_seqlens=cu_seqlens,
254
+ # )
255
+ # elif mode == 'fused_chunk':
256
+ # o, recurrent_state = fused_chunk_gla(
257
+ # q=q,
258
+ # k=k,
259
+ # v=v,
260
+ # g=gk,
261
+ # initial_state=recurrent_state,
262
+ # output_final_state=use_cache,
263
+ # )
264
+ # elif mode == 'chunk':
265
+ # o, recurrent_state = chunk_gla(
266
+ # q=q,
267
+ # k=k,
268
+ # v=v,
269
+ # g=gk,
270
+ # initial_state=recurrent_state,
271
+ # output_final_state=use_cache,
272
+ # cu_seqlens=cu_seqlens,
273
+ # )
274
+ # else:
275
+ # raise NotImplementedError(f"Not supported mode `{mode}`.")
276
+ ####input q, k, v, g, scale, initial_state, output_final_state, cu_seqlens
277
+ q,k,v,gk = map(lambda x: rearrange(x, 'b (n c) ...-> b n c ...', c=self.chunk_size), (q,k,v,gk))
278
+ o = []
279
+ for i in range(q.shape[1]):
280
+ o_i, recurrent_state = chunk_gla(
281
+ q=q[:, i],
282
+ k=k[:, i],
283
+ v=v[:, i],
284
+ g=gk[:, i],
285
+ initial_state=recurrent_state,
286
+ output_final_state=True,
287
+ cu_seqlens=None,
288
+ )
289
+ o.append(o_i)
290
+ #####为recurrent进行正则化操作###recurrent_state shape B,H,DK,DV
291
+ for j in range(recurrent_state.shape[1]):
292
+ if j == 0:###对state进行muon正则化
293
+ state = recurrent_state[j]
294
+ ###计算F范数
295
+ f_norm = ((state**2).sum(axis=(-2,-1),keepdim=True)+1e-20)**0.5
296
+ state = state / f_norm
297
+
298
+
299
+ if j == 1:###对state进行clip,remove占据小的特征值
300
+
301
+ recurrent_state = recurrent_state.contiguous()
302
+
303
+
304
+
305
+
306
+ o = torch.cat(o, dim=1)
307
+ if past_key_values is not None:
308
+ past_key_values.update(
309
+ recurrent_state=recurrent_state,
310
+ conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
311
+ layer_idx=self.layer_idx,
312
+ offset=q_len
313
+ )
314
+
315
+ if self.use_output_gate:
316
+ g = self.g_proj(hidden_states)
317
+ if self.fuse_norm_and_gate:
318
+ g = rearrange(g, '... (h d) -> ... h d', d=self.head_v_dim)
319
+ o = self.g_norm_swish_gate(o, g)
320
+ o = rearrange(o, '... h d -> ... (h d)')
321
+ else:
322
+ o = rearrange(self.g_norm(o), '... h d -> ... (h d)')
323
+ o = o * self.gate_fn(g)
324
+ else:
325
+ o = rearrange(self.g_norm(o), '... h d -> ... (h d)')
326
+ o = self.o_proj(o)
327
+ if attention_mask is not None:
328
+ o = pad_input(o.squeeze(0), indices, batch_size, q_len)
329
+
330
+ return o, None, past_key_values
models/forgetting_transformer/configuration_forgetting_transformer.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class ForgettingTransformerConfig(PretrainedConfig):
10
+
11
+ model_type = 'forgetting_transformer'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ hidden_size: int = 2048,
17
+ num_hidden_layers: int = 24,
18
+ num_heads: int = 32,
19
+ num_kv_heads: Optional[int] = None,
20
+ qkv_bias: bool = False,
21
+ qk_norm: bool = False,
22
+ window_size: Optional[int] = None,
23
+ use_output_gate: bool = False,
24
+ hidden_ratio: Optional[int] = 4,
25
+ intermediate_size: Optional[int] = None,
26
+ hidden_act: str = "swish",
27
+ initializer_range: float = 0.02,
28
+ elementwise_affine: Optional[bool] = True,
29
+ norm_eps: float = 1e-6,
30
+ use_cache: bool = True,
31
+ pad_token_id: Optional[int] = None,
32
+ bos_token_id: int = 1,
33
+ eos_token_id: int = 2,
34
+ tie_word_embeddings: bool = False,
35
+ fuse_norm: bool = True,
36
+ fuse_swiglu: bool = True,
37
+ fuse_cross_entropy: bool = True,
38
+ fuse_linear_cross_entropy: bool = False,
39
+ use_l2warp: bool = False,
40
+ vocab_size: int = 32000,
41
+ **kwargs,
42
+ ):
43
+ self.hidden_size = hidden_size
44
+ self.num_hidden_layers = num_hidden_layers
45
+ self.num_heads = num_heads
46
+ self.num_kv_heads = num_kv_heads
47
+ self.qkv_bias = qkv_bias
48
+ self.qk_norm = qk_norm
49
+ self.window_size = window_size
50
+ self.use_output_gate = use_output_gate
51
+ self.hidden_ratio = hidden_ratio
52
+ self.intermediate_size = intermediate_size
53
+ self.hidden_act = hidden_act
54
+
55
+ self.initializer_range = initializer_range
56
+ self.elementwise_affine = elementwise_affine
57
+ self.norm_eps = norm_eps
58
+ self.use_cache = use_cache
59
+
60
+ self.fuse_norm = fuse_norm
61
+ self.fuse_swiglu = fuse_swiglu
62
+ self.fuse_cross_entropy = fuse_cross_entropy
63
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
64
+ self.use_l2warp = use_l2warp
65
+ self.vocab_size = vocab_size
66
+
67
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
68
+ raise ValueError(
69
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
70
+ )
71
+ if fuse_linear_cross_entropy:
72
+ warnings.warn(
73
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
74
+ "at the potential cost of reduced precision. "
75
+ "If you observe issues like loss divergence, consider disabling this setting."
76
+ )
77
+
78
+ super().__init__(
79
+ pad_token_id=pad_token_id,
80
+ bos_token_id=bos_token_id,
81
+ eos_token_id=eos_token_id,
82
+ tie_word_embeddings=tie_word_embeddings,
83
+ **kwargs,
84
+ )
models/gated_deltanet/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.gated_deltanet.configuration_gated_deltanet import GatedDeltaNetConfig
6
+ from fla.models.gated_deltanet.modeling_gated_deltanet import GatedDeltaNetForCausalLM, GatedDeltaNetModel
7
+
8
+ AutoConfig.register(GatedDeltaNetConfig.model_type, GatedDeltaNetConfig, exist_ok=True)
9
+ AutoModel.register(GatedDeltaNetConfig, GatedDeltaNetModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(GatedDeltaNetConfig, GatedDeltaNetForCausalLM, exist_ok=True)
11
+
12
+ __all__ = ['GatedDeltaNetConfig', 'GatedDeltaNetForCausalLM', 'GatedDeltaNetModel']
models/gated_deltaproduct/modeling_gated_deltaproduct.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.layers.gated_deltaproduct import GatedDeltaProduct
18
+ from fla.models.gated_deltaproduct.configuration_gated_deltaproduct import GatedDeltaProductConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as GatedDeltaProductMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class GatedDeltaProductBlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: GatedDeltaProductConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = GatedDeltaProduct(
59
+ mode=config.attn_mode,
60
+ hidden_size=config.hidden_size,
61
+ expand_v=config.expand_v,
62
+ head_dim=config.head_dim,
63
+ num_heads=config.num_heads,
64
+ use_output_gate=config.use_output_gate,
65
+ use_forget_gate=config.use_forget_gate,
66
+ use_short_conv=config.use_short_conv,
67
+ conv_size=config.conv_size,
68
+ norm_eps=config.norm_eps,
69
+ allow_neg_eigval=config.allow_neg_eigval,
70
+ num_householder=config.num_householder,
71
+ layer_idx=layer_idx
72
+ )
73
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
74
+ self.mlp = GatedDeltaProductMLP(
75
+ hidden_size=config.hidden_size,
76
+ hidden_ratio=config.hidden_ratio,
77
+ intermediate_size=config.intermediate_size,
78
+ hidden_act=config.hidden_act,
79
+ fuse_swiglu=config.fuse_swiglu
80
+ )
81
+
82
+ def forward(
83
+ self,
84
+ hidden_states: torch.Tensor,
85
+ attention_mask: Optional[torch.Tensor] = None,
86
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
87
+ use_cache: Optional[bool] = False,
88
+ output_attentions: Optional[bool] = False,
89
+ **kwargs: Unpack[Dict]
90
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
91
+ residual = hidden_states
92
+ hidden_states = self.attn_norm(hidden_states)
93
+ hidden_states, attentions, past_key_values = self.attn(
94
+ hidden_states=hidden_states,
95
+ attention_mask=attention_mask,
96
+ past_key_values=past_key_values,
97
+ use_cache=use_cache,
98
+ output_attentions=output_attentions,
99
+ **kwargs
100
+ )
101
+ if self.config.fuse_norm:
102
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
103
+ else:
104
+ hidden_states = residual + hidden_states
105
+ residual = hidden_states
106
+ hidden_states = self.mlp_norm(hidden_states)
107
+ hidden_states = self.mlp(hidden_states, **kwargs)
108
+ hidden_states = residual + hidden_states
109
+
110
+ outputs = (hidden_states, attentions, past_key_values)
111
+
112
+ return outputs
113
+
114
+
115
+ class GatedDeltaProductPreTrainedModel(PreTrainedModel):
116
+
117
+ config_class = GatedDeltaProductConfig
118
+ base_model_prefix = 'model'
119
+ supports_gradient_checkpointing = True
120
+ _no_split_modules = ['GatedDeltaProductBlock']
121
+ _supports_cache_class = True
122
+
123
+ def __init__(self, *inputs, **kwargs):
124
+ super().__init__(*inputs, **kwargs)
125
+
126
+ def _init_weights(
127
+ self,
128
+ module: nn.Module,
129
+ prenorm_residual_strategy: Optional[str] = None,
130
+ num_residuals_per_layer: int = 2,
131
+ ):
132
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
133
+ # Slightly different from the TF version which uses truncated_normal for initialization
134
+ # cf https://github.com/pytorch/pytorch/pull/5617
135
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
136
+ if module.bias is not None:
137
+ nn.init.zeros_(module.bias)
138
+ elif isinstance(module, nn.Embedding):
139
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
140
+ elif hasattr(module, 'reset_parameters'):
141
+ module.reset_parameters()
142
+
143
+ if prenorm_residual_strategy is not None:
144
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
145
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
146
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
147
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
148
+ #
149
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
150
+ p = None
151
+ if hasattr(module, 'o_proj'):
152
+ p = module.o_proj.weight
153
+ elif hasattr(module, 'down_proj'):
154
+ p = module.down_proj.weight
155
+ if p is not None:
156
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
157
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
158
+ # We need to reinit p since this code could be called multiple times
159
+ # Having just p *= scale would repeatedly scale it down
160
+ if prenorm_residual_strategy == 'rescale':
161
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
162
+ with torch.no_grad():
163
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
164
+ elif prenorm_residual_strategy == 'zero':
165
+ nn.init.zeros_(p)
166
+ else:
167
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
168
+
169
+
170
+ class GatedDeltaProductModel(GatedDeltaProductPreTrainedModel):
171
+
172
+ def __init__(self, config: GatedDeltaProductConfig):
173
+ super().__init__(config)
174
+ self.padding_idx = config.pad_token_id
175
+ self.vocab_size = config.vocab_size
176
+
177
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
178
+ self.layers = nn.ModuleList([
179
+ GatedDeltaProductBlock(config, layer_idx)
180
+ for layer_idx in range(config.num_hidden_layers)
181
+ ])
182
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
183
+
184
+ self.gradient_checkpointing = False
185
+
186
+ self.post_init()
187
+
188
+ def get_input_embeddings(self):
189
+ return self.embeddings
190
+
191
+ def set_input_embeddings(self, value):
192
+ self.embeddings = value
193
+
194
+ def forward(
195
+ self,
196
+ input_ids: Optional[torch.LongTensor] = None,
197
+ attention_mask: Optional[torch.Tensor] = None,
198
+ inputs_embeds: Optional[torch.FloatTensor] = None,
199
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
200
+ use_cache: Optional[bool] = None,
201
+ output_attentions: Optional[bool] = None,
202
+ output_hidden_states: Optional[bool] = None,
203
+ return_dict: Optional[bool] = None,
204
+ **kwargs: Unpack[Dict]
205
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
206
+ if output_attentions:
207
+ warnings.warn("`GatedDeltaProductModel` does not `output_attentions` now, setting it to `False`.")
208
+ output_attentions = False
209
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
210
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
211
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
212
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
213
+
214
+ # retrieve input_ids and inputs_embeds
215
+ if input_ids is not None and inputs_embeds is not None:
216
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
217
+ if input_ids is None and inputs_embeds is None:
218
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
219
+
220
+ if inputs_embeds is None:
221
+ inputs_embeds = self.embeddings(input_ids)
222
+ hidden_states = inputs_embeds
223
+
224
+ if use_cache and not isinstance(past_key_values, Cache):
225
+ past_key_values = Cache.from_legacy_cache(past_key_values)
226
+
227
+ all_hidden_states = () if output_hidden_states else None
228
+ all_attns = () if output_attentions else None
229
+ for layer in self.layers:
230
+ if output_hidden_states:
231
+ all_hidden_states += (hidden_states,)
232
+
233
+ hidden_states, attentions, past_key_values = layer(
234
+ hidden_states,
235
+ attention_mask=attention_mask,
236
+ past_key_values=past_key_values,
237
+ use_cache=use_cache,
238
+ output_attentions=output_attentions,
239
+ **kwargs
240
+ )
241
+
242
+ if output_attentions:
243
+ all_attns += (attentions,)
244
+
245
+ hidden_states = self.norm(hidden_states)
246
+
247
+ # add hidden states from the last decoder layer
248
+ if output_hidden_states:
249
+ all_hidden_states += (hidden_states,)
250
+
251
+ if not return_dict:
252
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
253
+ return BaseModelOutputWithPast(
254
+ last_hidden_state=hidden_states,
255
+ past_key_values=past_key_values,
256
+ hidden_states=all_hidden_states,
257
+ attentions=all_attns
258
+ )
259
+
260
+
261
+ class GatedDeltaProductForCausalLM(GatedDeltaProductPreTrainedModel, FLAGenerationMixin):
262
+
263
+ _tied_weights_keys = ["lm_head.weight"]
264
+
265
+ def __init__(self, config):
266
+ super().__init__(config)
267
+ self.model = GatedDeltaProductModel(config)
268
+ self.vocab_size = config.vocab_size
269
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
270
+ self.criterion = None
271
+
272
+ # Initialize weights and apply final processing
273
+ self.post_init()
274
+
275
+ def get_input_embeddings(self):
276
+ return self.model.embeddings
277
+
278
+ def set_input_embeddings(self, value):
279
+ self.model.embeddings = value
280
+
281
+ def get_output_embeddings(self):
282
+ return self.lm_head
283
+
284
+ def set_output_embeddings(self, new_embeddings):
285
+ self.lm_head = new_embeddings
286
+
287
+ def set_decoder(self, decoder):
288
+ self.model = decoder
289
+
290
+ def get_decoder(self):
291
+ return self.model
292
+
293
+ def generate(self, *args, **kwargs):
294
+ try:
295
+ return super().generate(*args, **kwargs)
296
+ except AttributeError as exception:
297
+ if 'past_key_values' in str(exception):
298
+ raise AttributeError(
299
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
300
+ f"which is not supported for {self.__class__.__name__}. "
301
+ f"Try another generation strategy instead. "
302
+ f"For the available generation strategies, check this doc: "
303
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
304
+ )
305
+ else:
306
+ raise exception
307
+
308
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
309
+ def forward(
310
+ self,
311
+ input_ids: torch.LongTensor = None,
312
+ attention_mask: Optional[torch.Tensor] = None,
313
+ inputs_embeds: Optional[torch.Tensor] = None,
314
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
315
+ labels: Optional[torch.LongTensor] = None,
316
+ use_cache: Optional[bool] = None,
317
+ output_attentions: Optional[bool] = None,
318
+ output_hidden_states: Optional[bool] = None,
319
+ return_dict: Optional[bool] = None,
320
+ logits_to_keep: Optional[int] = 0,
321
+ **kwargs: Unpack[Dict]
322
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
323
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
324
+ output_hidden_states = (
325
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
326
+ )
327
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
328
+
329
+ outputs = self.model(
330
+ input_ids=input_ids,
331
+ attention_mask=attention_mask,
332
+ inputs_embeds=inputs_embeds,
333
+ past_key_values=past_key_values,
334
+ use_cache=use_cache,
335
+ output_attentions=output_attentions,
336
+ output_hidden_states=output_hidden_states,
337
+ return_dict=return_dict,
338
+ **kwargs
339
+ )
340
+
341
+ hidden_states = outputs[0]
342
+
343
+ loss, logits = None, None
344
+ if not self.config.fuse_linear_cross_entropy or labels is None:
345
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
346
+ if labels is not None:
347
+ if getattr(self, 'criterion', None) is None:
348
+ if self.config.fuse_linear_cross_entropy:
349
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
350
+ elif self.config.fuse_cross_entropy:
351
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
352
+ else:
353
+ criterion = nn.CrossEntropyLoss()
354
+ else:
355
+ criterion = self.criterion
356
+ labels = labels.to(hidden_states.device)
357
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
358
+ if self.config.fuse_linear_cross_entropy:
359
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
360
+ else:
361
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
362
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
363
+
364
+ if not return_dict:
365
+ output = (logits,) + outputs[1:]
366
+ return (loss,) + output if loss is not None else output
367
+
368
+ return CausalLMOutputWithPast(
369
+ loss=loss,
370
+ logits=logits,
371
+ past_key_values=outputs.past_key_values,
372
+ hidden_states=outputs.hidden_states,
373
+ attentions=outputs.attentions,
374
+ )
models/gka_attn/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from .configuration_gka_attn import GKAAttentionConfig
6
+ from .modeling_gka_attn import GKAAttentionForCausalLM, GKAAttentionModel
7
+
8
+ AutoConfig.register(GKAAttentionConfig.model_type, GKAAttentionConfig, exist_ok=True)
9
+ AutoModel.register(GKAAttentionConfig, GKAAttentionModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(GKAAttentionConfig, GKAAttentionForCausalLM, exist_ok=True)
11
+
12
+ __all__ = ['GKAAttentionConfig', 'GKAAttentionForCausalLM', 'GKAAttentionModel']
models/gka_attn/modeling_gka_attn.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from ...layers.gka_attn import GKAAttention
18
+ from .configuration_gka_attn import GKAAttentionConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as GKAAttentionMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ from transformers.processing_utils import Unpack
28
+
29
+
30
+ try:
31
+ from transformers.modeling_layers import GradientCheckpointingLayer
32
+ except ImportError:
33
+ from fla.models.modeling_layers import GradientCheckpointingLayer
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ class GKAAttentionBlock(GradientCheckpointingLayer):
39
+
40
+ def __init__(self, config: GKAAttentionConfig, layer_idx: int):
41
+ super().__init__()
42
+
43
+ self.config = config
44
+ self.layer_idx = layer_idx
45
+
46
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
47
+ if config.attn is not None and layer_idx in config.attn['layers']:
48
+ self.attn = Attention(
49
+ hidden_size=config.hidden_size,
50
+ num_heads=config.attn['num_heads'],
51
+ num_kv_heads=config.attn['num_kv_heads'],
52
+ qkv_bias=config.attn['qkv_bias'],
53
+ window_size=config.attn['window_size'],
54
+ rope_theta=config.attn['rope_theta'],
55
+ max_position_embeddings=config.max_position_embeddings,
56
+ layer_idx=layer_idx
57
+ )
58
+ else:
59
+ self.attn = GKAAttention(
60
+ mode=config.attn_mode,
61
+ hidden_size=config.hidden_size,
62
+ num_heads=config.num_heads,
63
+ head_dim=config.head_dim,
64
+ use_output_gate=config.use_output_gate,
65
+ use_short_conv=config.use_short_conv,
66
+ conv_size=config.conv_size,
67
+ norm_eps=config.norm_eps,
68
+ lambda_lower_bound=config.lambda_lower_bound,
69
+ layer_idx=layer_idx,
70
+ max_cg_step_training=config.max_cg_step_training,
71
+ max_cg_step_decoding=config.max_cg_step_decoding
72
+ )
73
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
74
+ self.mlp = GKAAttentionMLP(
75
+ hidden_size=config.hidden_size,
76
+ hidden_ratio=config.hidden_ratio,
77
+ intermediate_size=config.intermediate_size,
78
+ hidden_act=config.hidden_act,
79
+ fuse_swiglu=config.fuse_swiglu
80
+ )
81
+
82
+ def forward(
83
+ self,
84
+ hidden_states: torch.Tensor,
85
+ attention_mask: Optional[torch.Tensor] = None,
86
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
87
+ use_cache: Optional[bool] = False,
88
+ output_attentions: Optional[bool] = False,
89
+ **kwargs: Unpack[Dict]
90
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
91
+ residual = hidden_states
92
+ hidden_states = self.attn_norm(hidden_states)
93
+ hidden_states, attentions, past_key_values = self.attn(
94
+ hidden_states=hidden_states,
95
+ attention_mask=attention_mask,
96
+ past_key_values=past_key_values,
97
+ use_cache=use_cache,
98
+ output_attentions=output_attentions,
99
+ **kwargs
100
+ )
101
+ if self.config.fuse_norm:
102
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
103
+ else:
104
+ hidden_states = residual + hidden_states
105
+ residual = hidden_states
106
+ hidden_states = self.mlp_norm(hidden_states)
107
+ hidden_states = self.mlp(hidden_states, **kwargs)
108
+ hidden_states = residual + hidden_states
109
+
110
+ outputs = (hidden_states, attentions, past_key_values)
111
+
112
+ return outputs
113
+
114
+
115
+ class GKAAttentionPreTrainedModel(PreTrainedModel):
116
+
117
+ config_class = GKAAttentionConfig
118
+ base_model_prefix = 'model'
119
+ supports_gradient_checkpointing = True
120
+ _no_split_modules = ['GKAAttentionBlock']
121
+ _supports_cache_class = True
122
+
123
+ def __init__(self, *inputs, **kwargs):
124
+ super().__init__(*inputs, **kwargs)
125
+
126
+ def _init_weights(
127
+ self,
128
+ module: nn.Module,
129
+ prenorm_residual_strategy: Optional[str] = None,
130
+ num_residuals_per_layer: int = 2,
131
+ ):
132
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
133
+ # Slightly different from the TF version which uses truncated_normal for initialization
134
+ # cf https://github.com/pytorch/pytorch/pull/5617
135
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
136
+ if module.bias is not None:
137
+ nn.init.zeros_(module.bias)
138
+ elif isinstance(module, nn.Embedding):
139
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
140
+ elif hasattr(module, 'reset_parameters'):
141
+ module.reset_parameters()
142
+
143
+ if prenorm_residual_strategy is not None:
144
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
145
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
146
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
147
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
148
+ #
149
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
150
+ p = None
151
+ if hasattr(module, 'o_proj'):
152
+ p = module.o_proj.weight
153
+ elif hasattr(module, 'down_proj'):
154
+ p = module.down_proj.weight
155
+ if p is not None:
156
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
157
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
158
+ # We need to reinit p since this code could be called multiple times
159
+ # Having just p *= scale would repeatedly scale it down
160
+ if prenorm_residual_strategy == 'rescale':
161
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
162
+ with torch.no_grad():
163
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
164
+ elif prenorm_residual_strategy == 'zero':
165
+ nn.init.zeros_(p)
166
+ else:
167
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
168
+
169
+
170
+ class GKAAttentionModel(GKAAttentionPreTrainedModel):
171
+
172
+ def __init__(self, config: GKAAttentionConfig):
173
+ super().__init__(config)
174
+ self.padding_idx = config.pad_token_id
175
+ self.vocab_size = config.vocab_size
176
+
177
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
178
+ self.layers = nn.ModuleList([GKAAttentionBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
179
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
180
+
181
+ self.gradient_checkpointing = False
182
+
183
+ self.post_init()
184
+
185
+ def get_input_embeddings(self):
186
+ return self.embeddings
187
+
188
+ def set_input_embeddings(self, value):
189
+ self.embeddings = value
190
+
191
+ def forward(
192
+ self,
193
+ input_ids: Optional[torch.LongTensor] = None,
194
+ attention_mask: Optional[torch.Tensor] = None, # noqa
195
+ inputs_embeds: Optional[torch.FloatTensor] = None,
196
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
197
+ use_cache: Optional[bool] = None,
198
+ output_attentions: Optional[bool] = None,
199
+ output_hidden_states: Optional[bool] = None,
200
+ return_dict: Optional[bool] = None,
201
+ **kwargs: Unpack[Dict]
202
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
203
+ if output_attentions:
204
+ warnings.warn("`GKAAttentionModel` does not `output_attentions` now, setting it to `False`.")
205
+ output_attentions = False
206
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
207
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
208
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
209
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
210
+
211
+ # retrieve input_ids and inputs_embeds
212
+ if input_ids is not None and inputs_embeds is not None:
213
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
214
+ if input_ids is None and inputs_embeds is None:
215
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
216
+
217
+ if inputs_embeds is None:
218
+ inputs_embeds = self.embeddings(input_ids)
219
+ hidden_states = inputs_embeds
220
+
221
+ if use_cache and not isinstance(past_key_values, Cache):
222
+ past_key_values = Cache.from_legacy_cache(past_key_values)
223
+
224
+ all_hidden_states = () if output_hidden_states else None
225
+ all_attns = () if output_attentions else None
226
+ for layer in self.layers:
227
+ if output_hidden_states:
228
+ all_hidden_states += (hidden_states,)
229
+
230
+ hidden_states, attentions, past_key_values = layer(
231
+ hidden_states,
232
+ attention_mask=attention_mask,
233
+ past_key_values=past_key_values,
234
+ use_cache=use_cache,
235
+ output_attentions=output_attentions,
236
+ **kwargs
237
+ )
238
+
239
+ if output_attentions:
240
+ all_attns += (attentions,)
241
+
242
+ hidden_states = self.norm(hidden_states)
243
+
244
+ # add hidden states from the last decoder layer
245
+ if output_hidden_states:
246
+ all_hidden_states += (hidden_states,)
247
+
248
+ if not return_dict:
249
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
250
+ return BaseModelOutputWithPast(
251
+ last_hidden_state=hidden_states,
252
+ past_key_values=past_key_values,
253
+ hidden_states=all_hidden_states,
254
+ attentions=all_attns
255
+ )
256
+
257
+
258
+ class GKAAttentionForCausalLM(GKAAttentionPreTrainedModel, FLAGenerationMixin):
259
+
260
+ _tied_weights_keys = ["lm_head.weight"]
261
+
262
+ def __init__(self, config):
263
+ super().__init__(config)
264
+ self.model = GKAAttentionModel(config)
265
+ self.vocab_size = config.vocab_size
266
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
267
+ self.criterion = None
268
+
269
+ # Initialize weights and apply final processing
270
+ self.post_init()
271
+
272
+ def get_input_embeddings(self):
273
+ return self.model.embeddings
274
+
275
+ def set_input_embeddings(self, value):
276
+ self.model.embeddings = value
277
+
278
+ def get_output_embeddings(self):
279
+ return self.lm_head
280
+
281
+ def set_output_embeddings(self, new_embeddings):
282
+ self.lm_head = new_embeddings
283
+
284
+ def set_decoder(self, decoder):
285
+ self.model = decoder
286
+
287
+ def get_decoder(self):
288
+ return self.model
289
+
290
+ def generate(self, *args, **kwargs):
291
+ try:
292
+ return super().generate(*args, **kwargs)
293
+ except AttributeError as exception:
294
+ if 'past_key_values' in str(exception):
295
+ raise AttributeError(
296
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
297
+ f"which is not supported for {self.__class__.__name__}. "
298
+ f"Try another generation strategy instead. "
299
+ f"For the available generation strategies, check this doc: "
300
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
301
+ )
302
+ else:
303
+ raise exception
304
+
305
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
306
+ def forward(
307
+ self,
308
+ input_ids: torch.LongTensor = None,
309
+ attention_mask: Optional[torch.Tensor] = None,
310
+ inputs_embeds: Optional[torch.Tensor] = None,
311
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
312
+ labels: Optional[torch.LongTensor] = None,
313
+ use_cache: Optional[bool] = None,
314
+ output_attentions: Optional[bool] = None,
315
+ output_hidden_states: Optional[bool] = None,
316
+ return_dict: Optional[bool] = None,
317
+ logits_to_keep: Optional[int] = 0,
318
+ **kwargs: Unpack[Dict]
319
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
320
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
321
+ output_hidden_states = (
322
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
323
+ )
324
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
325
+
326
+ outputs = self.model(
327
+ input_ids=input_ids,
328
+ attention_mask=attention_mask,
329
+ inputs_embeds=inputs_embeds,
330
+ past_key_values=past_key_values,
331
+ use_cache=use_cache,
332
+ output_attentions=output_attentions,
333
+ output_hidden_states=output_hidden_states,
334
+ return_dict=return_dict,
335
+ **kwargs
336
+ )
337
+
338
+ hidden_states = outputs[0]
339
+
340
+ loss, logits = None, None
341
+ if not self.config.fuse_linear_cross_entropy or labels is None:
342
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
343
+ if labels is not None:
344
+ if getattr(self, 'criterion', None) is None:
345
+ if self.config.fuse_linear_cross_entropy:
346
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
347
+ elif self.config.fuse_cross_entropy:
348
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
349
+ else:
350
+ criterion = nn.CrossEntropyLoss()
351
+ else:
352
+ criterion = self.criterion
353
+ labels = labels.to(hidden_states.device)
354
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
355
+ if self.config.fuse_linear_cross_entropy:
356
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
357
+ else:
358
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
359
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
360
+
361
+ if not return_dict:
362
+ output = (logits,) + outputs[1:]
363
+ return (loss,) + output if loss is not None else output
364
+
365
+ return CausalLMOutputWithPast(
366
+ loss=loss,
367
+ logits=logits,
368
+ past_key_values=outputs.past_key_values,
369
+ hidden_states=outputs.hidden_states,
370
+ attentions=outputs.attentions,
371
+ )
models/gka_net/configuration_gka_net.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class GKANetConfig(PretrainedConfig):
10
+ model_type = 'gka_net'
11
+ keys_to_ignore_at_inference = ['past_key_values']
12
+
13
+ def __init__(
14
+ self,
15
+ attn_mode: str = "chunk",
16
+ hidden_size: int = 2048,
17
+ use_output_gate: bool = False,
18
+ use_short_conv: bool = True,
19
+ conv_size: int = 4,
20
+ num_heads: int = 16,
21
+ head_dim: int = 128,
22
+ lambda_lower_bound: float = 0.25,
23
+ max_position_embeddings: int = 2048,
24
+ hidden_ratio: Optional[int] = 4,
25
+ intermediate_size: Optional[int] = None,
26
+ hidden_act: str = "swish",
27
+ num_hidden_layers: int = 24,
28
+ norm_eps: float = 1e-6,
29
+ attn: Optional[Dict] = None,
30
+ use_cache: bool = True,
31
+ pad_token_id: Optional[int] = None,
32
+ bos_token_id: int = 1,
33
+ eos_token_id: int = 2,
34
+ tie_word_embeddings: bool = False,
35
+ initializer_range: float = 0.02,
36
+ fuse_norm: bool = True,
37
+ fuse_swiglu: bool = True,
38
+ fuse_cross_entropy: bool = True,
39
+ fuse_linear_cross_entropy: bool = False,
40
+ use_l2warp: bool = False,
41
+ vocab_size: int = 32000,
42
+ max_cg_step_training: int = 30,
43
+ max_cg_step_decoding: int = 30,
44
+ **kwargs
45
+ ):
46
+ self.attn_mode = attn_mode
47
+ self.hidden_size = hidden_size
48
+ self.use_output_gate = use_output_gate
49
+ self.use_short_conv = use_short_conv
50
+ self.conv_size = conv_size
51
+ self.num_heads = num_heads
52
+ self.head_dim = head_dim
53
+ self.max_position_embeddings = max_position_embeddings
54
+
55
+ self.hidden_ratio = hidden_ratio
56
+ self.intermediate_size = intermediate_size
57
+ self.hidden_act = hidden_act
58
+ self.num_hidden_layers = num_hidden_layers
59
+ self.norm_eps = norm_eps
60
+ self.attn = attn
61
+ self.use_cache = use_cache
62
+ self.initializer_range = initializer_range
63
+ self.lambda_lower_bound = lambda_lower_bound
64
+
65
+ self.fuse_norm = fuse_norm
66
+ self.fuse_swiglu = fuse_swiglu
67
+ self.fuse_cross_entropy = fuse_cross_entropy
68
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
69
+ self.use_l2warp = use_l2warp
70
+ self.vocab_size = vocab_size
71
+ self.max_cg_step_training = max_cg_step_training
72
+ self.max_cg_step_decoding = max_cg_step_decoding
73
+
74
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
75
+ raise ValueError(
76
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
77
+ )
78
+ if fuse_linear_cross_entropy:
79
+ warnings.warn(
80
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
81
+ "at the potential cost of reduced precision. "
82
+ "If you observe issues like loss divergence, consider disabling this setting."
83
+ )
84
+
85
+ if attn is not None:
86
+ if not isinstance(attn, Dict):
87
+ raise ValueError("attn must be a dictionary")
88
+ if 'layers' not in attn:
89
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
90
+ if 'num_heads' not in attn:
91
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
92
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
93
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
94
+ attn['window_size'] = attn.get('window_size', None)
95
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
96
+
97
+ super().__init__(
98
+ pad_token_id=pad_token_id,
99
+ bos_token_id=bos_token_id,
100
+ eos_token_id=eos_token_id,
101
+ tie_word_embeddings=tie_word_embeddings,
102
+ **kwargs,
103
+ )
models/gka_net/modeling_gka_net.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from ...layers.gka import GKANet
18
+ from .configuration_gka_net import GKANetConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as GKANetMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class GKANetBlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: GKANetConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = GKANet(
59
+ mode=config.attn_mode,
60
+ hidden_size=config.hidden_size,
61
+ num_heads=config.num_heads,
62
+ head_dim=config.head_dim,
63
+ use_output_gate=config.use_output_gate,
64
+ use_short_conv=config.use_short_conv,
65
+ conv_size=config.conv_size,
66
+ norm_eps=config.norm_eps,
67
+ lambda_lower_bound=config.lambda_lower_bound,
68
+ layer_idx=layer_idx,
69
+ max_cg_step_training=config.max_cg_step_training,
70
+ max_cg_step_decoding=config.max_cg_step_decoding
71
+ )
72
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
73
+ self.mlp = GKANetMLP(
74
+ hidden_size=config.hidden_size,
75
+ hidden_ratio=config.hidden_ratio,
76
+ intermediate_size=config.intermediate_size,
77
+ hidden_act=config.hidden_act,
78
+ fuse_swiglu=config.fuse_swiglu
79
+ )
80
+
81
+ def forward(
82
+ self,
83
+ hidden_states: torch.Tensor,
84
+ attention_mask: Optional[torch.Tensor] = None,
85
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
86
+ use_cache: Optional[bool] = False,
87
+ output_attentions: Optional[bool] = False,
88
+ **kwargs: Unpack[Dict]
89
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
90
+ residual = hidden_states
91
+ hidden_states = self.attn_norm(hidden_states)
92
+ hidden_states, attentions, past_key_values = self.attn(
93
+ hidden_states=hidden_states,
94
+ attention_mask=attention_mask,
95
+ past_key_values=past_key_values,
96
+ use_cache=use_cache,
97
+ output_attentions=output_attentions,
98
+ **kwargs
99
+ )
100
+ if self.config.fuse_norm:
101
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
102
+ else:
103
+ hidden_states = residual + hidden_states
104
+ residual = hidden_states
105
+ hidden_states = self.mlp_norm(hidden_states)
106
+ hidden_states = self.mlp(hidden_states, **kwargs)
107
+ hidden_states = residual + hidden_states
108
+
109
+ outputs = (hidden_states, attentions, past_key_values)
110
+
111
+ return outputs
112
+
113
+
114
+ class GKANetPreTrainedModel(PreTrainedModel):
115
+
116
+ config_class = GKANetConfig
117
+ base_model_prefix = 'model'
118
+ supports_gradient_checkpointing = True
119
+ _no_split_modules = ['GKANetBlock']
120
+ _supports_cache_class = True
121
+
122
+ def __init__(self, *inputs, **kwargs):
123
+ super().__init__(*inputs, **kwargs)
124
+
125
+ def _init_weights(
126
+ self,
127
+ module: nn.Module,
128
+ prenorm_residual_strategy: Optional[str] = None,
129
+ num_residuals_per_layer: int = 2,
130
+ ):
131
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
132
+ # Slightly different from the TF version which uses truncated_normal for initialization
133
+ # cf https://github.com/pytorch/pytorch/pull/5617
134
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
135
+ if module.bias is not None:
136
+ nn.init.zeros_(module.bias)
137
+ elif isinstance(module, nn.Embedding):
138
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
139
+ elif hasattr(module, 'reset_parameters'):
140
+ module.reset_parameters()
141
+
142
+ if prenorm_residual_strategy is not None:
143
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
144
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
145
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
146
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
147
+ #
148
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
149
+ p = None
150
+ if hasattr(module, 'o_proj'):
151
+ p = module.o_proj.weight
152
+ elif hasattr(module, 'down_proj'):
153
+ p = module.down_proj.weight
154
+ if p is not None:
155
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
156
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
157
+ # We need to reinit p since this code could be called multiple times
158
+ # Having just p *= scale would repeatedly scale it down
159
+ if prenorm_residual_strategy == 'rescale':
160
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
161
+ with torch.no_grad():
162
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
163
+ elif prenorm_residual_strategy == 'zero':
164
+ nn.init.zeros_(p)
165
+ else:
166
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
167
+
168
+
169
+ class GKANetModel(GKANetPreTrainedModel):
170
+
171
+ def __init__(self, config: GKANetConfig):
172
+ super().__init__(config)
173
+ self.padding_idx = config.pad_token_id
174
+ self.vocab_size = config.vocab_size
175
+
176
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
177
+ self.layers = nn.ModuleList([GKANetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
178
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
179
+
180
+ self.gradient_checkpointing = False
181
+
182
+ self.post_init()
183
+
184
+ def get_input_embeddings(self):
185
+ return self.embeddings
186
+
187
+ def set_input_embeddings(self, value):
188
+ self.embeddings = value
189
+
190
+ def forward(
191
+ self,
192
+ input_ids: Optional[torch.LongTensor] = None,
193
+ attention_mask: Optional[torch.Tensor] = None, # noqa
194
+ inputs_embeds: Optional[torch.FloatTensor] = None,
195
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
196
+ use_cache: Optional[bool] = None,
197
+ output_attentions: Optional[bool] = None,
198
+ output_hidden_states: Optional[bool] = None,
199
+ return_dict: Optional[bool] = None,
200
+ **kwargs: Unpack[Dict]
201
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
202
+ if output_attentions:
203
+ warnings.warn("`GKANetModel` does not `output_attentions` now, setting it to `False`.")
204
+ output_attentions = False
205
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
206
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
207
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
208
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
209
+
210
+ # retrieve input_ids and inputs_embeds
211
+ if input_ids is not None and inputs_embeds is not None:
212
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
213
+ if input_ids is None and inputs_embeds is None:
214
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
215
+
216
+ if inputs_embeds is None:
217
+ inputs_embeds = self.embeddings(input_ids)
218
+ hidden_states = inputs_embeds
219
+
220
+ if use_cache and not isinstance(past_key_values, Cache):
221
+ past_key_values = Cache.from_legacy_cache(past_key_values)
222
+
223
+ all_hidden_states = () if output_hidden_states else None
224
+ all_attns = () if output_attentions else None
225
+ for layer in self.layers:
226
+ if output_hidden_states:
227
+ all_hidden_states += (hidden_states,)
228
+
229
+ hidden_states, attentions, past_key_values = layer(
230
+ hidden_states,
231
+ attention_mask=attention_mask,
232
+ past_key_values=past_key_values,
233
+ use_cache=use_cache,
234
+ output_attentions=output_attentions,
235
+ **kwargs
236
+ )
237
+
238
+ if output_attentions:
239
+ all_attns += (attentions,)
240
+
241
+ hidden_states = self.norm(hidden_states)
242
+
243
+ # add hidden states from the last decoder layer
244
+ if output_hidden_states:
245
+ all_hidden_states += (hidden_states,)
246
+
247
+ if not return_dict:
248
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
249
+ return BaseModelOutputWithPast(
250
+ last_hidden_state=hidden_states,
251
+ past_key_values=past_key_values,
252
+ hidden_states=all_hidden_states,
253
+ attentions=all_attns
254
+ )
255
+
256
+
257
+ class GKANetForCausalLM(GKANetPreTrainedModel, FLAGenerationMixin):
258
+
259
+ _tied_weights_keys = ["lm_head.weight"]
260
+
261
+ def __init__(self, config):
262
+ super().__init__(config)
263
+ self.model = GKANetModel(config)
264
+ self.vocab_size = config.vocab_size
265
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
266
+ self.criterion = None
267
+
268
+ # Initialize weights and apply final processing
269
+ self.post_init()
270
+
271
+ def get_input_embeddings(self):
272
+ return self.model.embeddings
273
+
274
+ def set_input_embeddings(self, value):
275
+ self.model.embeddings = value
276
+
277
+ def get_output_embeddings(self):
278
+ return self.lm_head
279
+
280
+ def set_output_embeddings(self, new_embeddings):
281
+ self.lm_head = new_embeddings
282
+
283
+ def set_decoder(self, decoder):
284
+ self.model = decoder
285
+
286
+ def get_decoder(self):
287
+ return self.model
288
+
289
+ def generate(self, *args, **kwargs):
290
+ try:
291
+ return super().generate(*args, **kwargs)
292
+ except AttributeError as exception:
293
+ if 'past_key_values' in str(exception):
294
+ raise AttributeError(
295
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
296
+ f"which is not supported for {self.__class__.__name__}. "
297
+ f"Try another generation strategy instead. "
298
+ f"For the available generation strategies, check this doc: "
299
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
300
+ )
301
+ else:
302
+ raise exception
303
+
304
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
305
+ def forward(
306
+ self,
307
+ input_ids: torch.LongTensor = None,
308
+ attention_mask: Optional[torch.Tensor] = None,
309
+ inputs_embeds: Optional[torch.Tensor] = None,
310
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
311
+ labels: Optional[torch.LongTensor] = None,
312
+ use_cache: Optional[bool] = None,
313
+ output_attentions: Optional[bool] = None,
314
+ output_hidden_states: Optional[bool] = None,
315
+ return_dict: Optional[bool] = None,
316
+ logits_to_keep: Optional[int] = 0,
317
+ **kwargs: Unpack[Dict]
318
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
319
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
320
+ output_hidden_states = (
321
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
322
+ )
323
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
324
+
325
+ outputs = self.model(
326
+ input_ids=input_ids,
327
+ attention_mask=attention_mask,
328
+ inputs_embeds=inputs_embeds,
329
+ past_key_values=past_key_values,
330
+ use_cache=use_cache,
331
+ output_attentions=output_attentions,
332
+ output_hidden_states=output_hidden_states,
333
+ return_dict=return_dict,
334
+ **kwargs
335
+ )
336
+
337
+ hidden_states = outputs[0]
338
+
339
+ loss, logits = None, None
340
+ if not self.config.fuse_linear_cross_entropy or labels is None:
341
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
342
+ if labels is not None:
343
+ if getattr(self, 'criterion', None) is None:
344
+ if self.config.fuse_linear_cross_entropy:
345
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
346
+ elif self.config.fuse_cross_entropy:
347
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
348
+ else:
349
+ criterion = nn.CrossEntropyLoss()
350
+ else:
351
+ criterion = self.criterion
352
+ labels = labels.to(hidden_states.device)
353
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
354
+ if self.config.fuse_linear_cross_entropy:
355
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
356
+ else:
357
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
358
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
359
+
360
+ if not return_dict:
361
+ output = (logits,) + outputs[1:]
362
+ return (loss,) + output if loss is not None else output
363
+
364
+ return CausalLMOutputWithPast(
365
+ loss=loss,
366
+ logits=logits,
367
+ past_key_values=outputs.past_key_values,
368
+ hidden_states=outputs.hidden_states,
369
+ attentions=outputs.attentions,
370
+ )
models/gla/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.gla.configuration_gla import GLAConfig
6
+ from fla.models.gla.modeling_gla import GLAForCausalLM, GLAModel
7
+
8
+ AutoConfig.register(GLAConfig.model_type, GLAConfig, exist_ok=True)
9
+ AutoModel.register(GLAConfig, GLAModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(GLAConfig, GLAForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['GLAConfig', 'GLAForCausalLM', 'GLAModel']
models/gla/configuration_gla.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class GLAConfig(PretrainedConfig):
10
+
11
+ model_type = 'gla'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ hidden_size: int = 2048,
17
+ expand_k: float = 0.5,
18
+ expand_v: float = 1.,
19
+ hidden_ratio: Optional[int] = 4,
20
+ intermediate_size: Optional[int] = None,
21
+ num_hidden_layers: int = 24,
22
+ num_heads: int = 4,
23
+ num_kv_heads: Optional[int] = None,
24
+ feature_map: Optional[str] = None,
25
+ attn_mode: str = "chunk",
26
+ use_short_conv: bool = False,
27
+ conv_size: int = 4,
28
+ use_output_gate: bool = True,
29
+ clamp_min: Optional[float] = None,
30
+ hidden_act: str = "swish",
31
+ max_position_embeddings: int = 2048,
32
+ elementwise_affine: Optional[bool] = True,
33
+ norm_eps: float = 1e-6,
34
+ use_gk: bool = True,
35
+ use_gv: bool = False,
36
+ attn: Optional[Dict] = None,
37
+ use_cache: bool = True,
38
+ pad_token_id: Optional[int] = None,
39
+ bos_token_id: int = 1,
40
+ eos_token_id: int = 2,
41
+ tie_word_embeddings: bool = False,
42
+ initializer_range: float = 0.02,
43
+ fuse_norm: bool = True,
44
+ fuse_swiglu: bool = True,
45
+ fuse_cross_entropy: bool = True,
46
+ fuse_linear_cross_entropy: bool = False,
47
+ use_l2warp: bool = False,
48
+ vocab_size: int = 32000,
49
+ **kwargs
50
+ ):
51
+ self.hidden_size = hidden_size
52
+ self.expand_k = expand_k
53
+ self.expand_v = expand_v
54
+ self.hidden_ratio = hidden_ratio
55
+ self.intermediate_size = intermediate_size
56
+ self.num_hidden_layers = num_hidden_layers
57
+ self.num_heads = num_heads
58
+ self.num_kv_heads = num_kv_heads
59
+ self.feature_map = feature_map
60
+ self.attn_mode = attn_mode
61
+ self.use_short_conv = use_short_conv
62
+ self.conv_size = conv_size
63
+ self.use_output_gate = use_output_gate
64
+ self.clamp_min = clamp_min
65
+ self.hidden_act = hidden_act
66
+ self.max_position_embeddings = max_position_embeddings
67
+ self.elementwise_affine = elementwise_affine
68
+ self.norm_eps = norm_eps
69
+ self.use_gk = use_gk
70
+ self.use_gv = use_gv
71
+ self.attn = attn
72
+ self.use_cache = use_cache
73
+ self.initializer_range = initializer_range
74
+
75
+ self.fuse_norm = fuse_norm
76
+ self.fuse_swiglu = fuse_swiglu
77
+ self.fuse_cross_entropy = fuse_cross_entropy
78
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
79
+ self.use_l2warp = use_l2warp
80
+ self.vocab_size = vocab_size
81
+
82
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
83
+ raise ValueError(
84
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
85
+ )
86
+ if fuse_linear_cross_entropy:
87
+ warnings.warn(
88
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
89
+ "at the potential cost of reduced precision. "
90
+ "If you observe issues like loss divergence, consider disabling this setting."
91
+ )
92
+
93
+ if attn is not None:
94
+ if not isinstance(attn, Dict):
95
+ raise ValueError("attn must be a dictionary")
96
+ if 'layers' not in attn:
97
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
98
+ if 'num_heads' not in attn:
99
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
100
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
101
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
102
+ attn['window_size'] = attn.get('window_size', None)
103
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
104
+
105
+ super().__init__(
106
+ pad_token_id=pad_token_id,
107
+ bos_token_id=bos_token_id,
108
+ eos_token_id=eos_token_id,
109
+ tie_word_embeddings=tie_word_embeddings,
110
+ **kwargs,
111
+ )
models/gla/modeling_gla.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.layers.gla import GatedLinearAttention
18
+ from fla.models.gla.configuration_gla import GLAConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as GLAMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class GLABlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: GLAConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = GatedLinearAttention(
59
+ mode=config.attn_mode,
60
+ hidden_size=config.hidden_size,
61
+ expand_k=config.expand_k,
62
+ expand_v=config.expand_v,
63
+ num_heads=config.num_heads,
64
+ num_kv_heads=config.num_kv_heads,
65
+ feature_map=config.feature_map,
66
+ use_short_conv=config.use_short_conv,
67
+ conv_size=config.conv_size,
68
+ use_output_gate=config.use_output_gate,
69
+ gate_fn=config.hidden_act,
70
+ elementwise_affine=config.elementwise_affine,
71
+ norm_eps=config.norm_eps,
72
+ clamp_min=config.clamp_min,
73
+ fuse_norm=config.fuse_norm,
74
+ layer_idx=layer_idx
75
+ )
76
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
77
+ self.mlp = GLAMLP(
78
+ hidden_size=config.hidden_size,
79
+ hidden_ratio=config.hidden_ratio,
80
+ intermediate_size=config.intermediate_size,
81
+ hidden_act=config.hidden_act,
82
+ fuse_swiglu=config.fuse_swiglu
83
+ )
84
+
85
+ def forward(
86
+ self,
87
+ hidden_states: torch.Tensor,
88
+ attention_mask: Optional[torch.Tensor] = None,
89
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
90
+ use_cache: Optional[bool] = False,
91
+ output_attentions: Optional[bool] = False,
92
+ **kwargs: Unpack[Dict]
93
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
94
+ residual = hidden_states
95
+ hidden_states = self.attn_norm(hidden_states)
96
+ hidden_states, attentions, past_key_values = self.attn(
97
+ hidden_states=hidden_states,
98
+ attention_mask=attention_mask,
99
+ past_key_values=past_key_values,
100
+ use_cache=use_cache,
101
+ output_attentions=output_attentions,
102
+ **kwargs
103
+ )
104
+ if self.config.fuse_norm:
105
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
106
+ else:
107
+ hidden_states = residual + hidden_states
108
+ residual = hidden_states
109
+ hidden_states = self.mlp_norm(hidden_states)
110
+ hidden_states = self.mlp(hidden_states, **kwargs)
111
+ hidden_states = residual + hidden_states
112
+
113
+ outputs = (hidden_states, attentions, past_key_values)
114
+
115
+ return outputs
116
+
117
+
118
+ class GLAPreTrainedModel(PreTrainedModel):
119
+
120
+ config_class = GLAConfig
121
+ base_model_prefix = 'model'
122
+ supports_gradient_checkpointing = True
123
+ _no_split_modules = ['GLABlock']
124
+ _supports_cache_class = True
125
+
126
+ def __init__(self, *inputs, **kwargs):
127
+ super().__init__(*inputs, **kwargs)
128
+
129
+ def _init_weights(
130
+ self,
131
+ module: nn.Module,
132
+ prenorm_residual_strategy: Optional[str] = None,
133
+ num_residuals_per_layer: int = 2,
134
+ ):
135
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
136
+ # Slightly different from the TF version which uses truncated_normal for initialization
137
+ # cf https://github.com/pytorch/pytorch/pull/5617
138
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
139
+ if module.bias is not None:
140
+ nn.init.zeros_(module.bias)
141
+ elif isinstance(module, nn.Embedding):
142
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
143
+ elif hasattr(module, 'reset_parameters'):
144
+ module.reset_parameters()
145
+
146
+ if prenorm_residual_strategy is not None:
147
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
148
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
149
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
150
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
151
+ #
152
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
153
+ p = None
154
+ if hasattr(module, 'o_proj'):
155
+ p = module.o_proj.weight
156
+ elif hasattr(module, 'down_proj'):
157
+ p = module.down_proj.weight
158
+ if p is not None:
159
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
160
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
161
+ # We need to reinit p since this code could be called multiple times
162
+ # Having just p *= scale would repeatedly scale it down
163
+ if prenorm_residual_strategy == 'rescale':
164
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
165
+ with torch.no_grad():
166
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
167
+ elif prenorm_residual_strategy == 'zero':
168
+ nn.init.zeros_(p)
169
+ else:
170
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
171
+
172
+
173
+ class GLAModel(GLAPreTrainedModel):
174
+
175
+ def __init__(self, config: GLAConfig):
176
+ super().__init__(config)
177
+ self.padding_idx = config.pad_token_id
178
+ self.vocab_size = config.vocab_size
179
+
180
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
181
+ self.layers = nn.ModuleList([GLABlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
182
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
183
+
184
+ self.gradient_checkpointing = False
185
+
186
+ self.post_init()
187
+
188
+ def get_input_embeddings(self):
189
+ return self.embeddings
190
+
191
+ def set_input_embeddings(self, value):
192
+ self.embeddings = value
193
+
194
+ def forward(
195
+ self,
196
+ input_ids: Optional[torch.LongTensor] = None,
197
+ attention_mask: Optional[torch.Tensor] = None, # noqa
198
+ inputs_embeds: Optional[torch.FloatTensor] = None,
199
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
200
+ use_cache: Optional[bool] = None,
201
+ output_attentions: Optional[bool] = None,
202
+ output_hidden_states: Optional[bool] = None,
203
+ return_dict: Optional[bool] = None,
204
+ **kwargs: Unpack[Dict]
205
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
206
+ if output_attentions:
207
+ warnings.warn("`GLAModel` does not `output_attentions` now, setting it to `False`.")
208
+ output_attentions = False
209
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
210
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
211
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
212
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
213
+
214
+ # retrieve input_ids and inputs_embeds
215
+ if input_ids is not None and inputs_embeds is not None:
216
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
217
+ if input_ids is None and inputs_embeds is None:
218
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
219
+
220
+ if inputs_embeds is None:
221
+ inputs_embeds = self.embeddings(input_ids)
222
+ hidden_states = inputs_embeds
223
+
224
+ if use_cache and not isinstance(past_key_values, Cache):
225
+ past_key_values = Cache.from_legacy_cache(past_key_values)
226
+
227
+ all_hidden_states = () if output_hidden_states else None
228
+ all_attns = () if output_attentions else None
229
+ for layer in self.layers:
230
+ if output_hidden_states:
231
+ all_hidden_states += (hidden_states,)
232
+
233
+ hidden_states, attentions, past_key_values = layer(
234
+ hidden_states,
235
+ attention_mask=attention_mask,
236
+ past_key_values=past_key_values,
237
+ use_cache=use_cache,
238
+ output_attentions=output_attentions,
239
+ **kwargs
240
+ )
241
+
242
+ if output_attentions:
243
+ all_attns += (attentions,)
244
+
245
+ hidden_states = self.norm(hidden_states)
246
+
247
+ # add hidden states from the last decoder layer
248
+ if output_hidden_states:
249
+ all_hidden_states += (hidden_states,)
250
+
251
+ if not return_dict:
252
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
253
+ return BaseModelOutputWithPast(
254
+ last_hidden_state=hidden_states,
255
+ past_key_values=past_key_values,
256
+ hidden_states=all_hidden_states,
257
+ attentions=all_attns
258
+ )
259
+
260
+
261
+ class GLAForCausalLM(GLAPreTrainedModel, FLAGenerationMixin):
262
+
263
+ _tied_weights_keys = ["lm_head.weight"]
264
+
265
+ def __init__(self, config):
266
+ super().__init__(config)
267
+ self.model = GLAModel(config)
268
+ self.vocab_size = config.vocab_size
269
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
270
+ self.criterion = None
271
+
272
+ # Initialize weights and apply final processing
273
+ self.post_init()
274
+
275
+ def get_input_embeddings(self):
276
+ return self.model.embeddings
277
+
278
+ def set_input_embeddings(self, value):
279
+ self.model.embeddings = value
280
+
281
+ def get_output_embeddings(self):
282
+ return self.lm_head
283
+
284
+ def set_output_embeddings(self, new_embeddings):
285
+ self.lm_head = new_embeddings
286
+
287
+ def set_decoder(self, decoder):
288
+ self.model = decoder
289
+
290
+ def get_decoder(self):
291
+ return self.model
292
+
293
+ def generate(self, *args, **kwargs):
294
+ try:
295
+ return super().generate(*args, **kwargs)
296
+ except AttributeError as exception:
297
+ if 'past_key_values' in str(exception):
298
+ raise AttributeError(
299
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
300
+ f"which is not supported for {self.__class__.__name__}. "
301
+ f"Try another generation strategy instead. "
302
+ f"For the available generation strategies, check this doc: "
303
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
304
+ )
305
+ else:
306
+ raise exception
307
+
308
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
309
+ def forward(
310
+ self,
311
+ input_ids: torch.LongTensor = None,
312
+ attention_mask: Optional[torch.Tensor] = None,
313
+ inputs_embeds: Optional[torch.Tensor] = None,
314
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
315
+ labels: Optional[torch.LongTensor] = None,
316
+ use_cache: Optional[bool] = None,
317
+ output_attentions: Optional[bool] = None,
318
+ output_hidden_states: Optional[bool] = None,
319
+ return_dict: Optional[bool] = None,
320
+ logits_to_keep: Optional[int] = 0,
321
+ **kwargs: Unpack[Dict]
322
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
323
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
324
+ output_hidden_states = (
325
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
326
+ )
327
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
328
+
329
+ outputs = self.model(
330
+ input_ids=input_ids,
331
+ attention_mask=attention_mask,
332
+ inputs_embeds=inputs_embeds,
333
+ past_key_values=past_key_values,
334
+ use_cache=use_cache,
335
+ output_attentions=output_attentions,
336
+ output_hidden_states=output_hidden_states,
337
+ return_dict=return_dict,
338
+ **kwargs
339
+ )
340
+
341
+ hidden_states = outputs[0]
342
+
343
+ loss, logits = None, None
344
+ if not self.config.fuse_linear_cross_entropy or labels is None:
345
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
346
+ if labels is not None:
347
+ if getattr(self, 'criterion', None) is None:
348
+ if self.config.fuse_linear_cross_entropy:
349
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
350
+ elif self.config.fuse_cross_entropy:
351
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
352
+ else:
353
+ criterion = nn.CrossEntropyLoss()
354
+ else:
355
+ criterion = self.criterion
356
+ labels = labels.to(hidden_states.device)
357
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
358
+ if self.config.fuse_linear_cross_entropy:
359
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
360
+ else:
361
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
362
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
363
+
364
+ if not return_dict:
365
+ output = (logits,) + outputs[1:]
366
+ return (loss,) + output if loss is not None else output
367
+
368
+ return CausalLMOutputWithPast(
369
+ loss=loss,
370
+ logits=logits,
371
+ past_key_values=outputs.past_key_values,
372
+ hidden_states=outputs.hidden_states,
373
+ attentions=outputs.attentions,
374
+ )
models/gsa/configuration_gsa.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class GSAConfig(PretrainedConfig):
10
+
11
+ model_type = 'gsa'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ hidden_size: int = 2048,
17
+ gate_logit_normalizer: Optional[int] = 8,
18
+ clamp_min: Optional[float] = None,
19
+ clamp_max: Optional[float] = None,
20
+ hidden_ratio: Optional[int] = 4,
21
+ intermediate_size: Optional[int] = None,
22
+ num_hidden_layers: int = 24,
23
+ num_heads: int = 4,
24
+ num_kv_heads: Optional[int] = None,
25
+ num_slots: Optional[int] = 64,
26
+ use_short_conv: bool = False,
27
+ conv_size: int = 4,
28
+ exapnd_k: float = 1,
29
+ exapnd_v: float = 1,
30
+ feature_map: str = 'swish',
31
+ use_output_gate: bool = False,
32
+ use_norm: bool = True,
33
+ max_position_embeddings: int = 2048,
34
+ hidden_act: str = "swish",
35
+ elementwise_affine: Optional[bool] = True,
36
+ norm_eps: float = 1e-6,
37
+ attn: Optional[Dict] = None,
38
+ use_cache: bool = True,
39
+ pad_token_id: Optional[int] = None,
40
+ bos_token_id: int = 1,
41
+ eos_token_id: int = 2,
42
+ initializer_range: float = 0.02,
43
+ tie_word_embeddings: bool = False,
44
+ fuse_norm: bool = True,
45
+ fuse_swiglu: bool = True,
46
+ fuse_cross_entropy: bool = True,
47
+ fuse_linear_cross_entropy: bool = False,
48
+ use_l2warp: bool = False,
49
+ vocab_size: int = 32000,
50
+ **kwargs
51
+ ):
52
+ self.hidden_size = hidden_size
53
+ self.gate_logit_normalizer = gate_logit_normalizer
54
+ self.clamp_min = clamp_min
55
+ self.clamp_max = clamp_max
56
+ self.hidden_ratio = hidden_ratio
57
+ self.intermediate_size = intermediate_size
58
+ self.num_hidden_layers = num_hidden_layers
59
+ self.num_heads = num_heads
60
+ self.num_kv_heads = num_kv_heads
61
+ self.num_slots = num_slots
62
+ self.use_short_conv = use_short_conv
63
+ self.conv_size = conv_size
64
+ self.expand_k = exapnd_k
65
+ self.expand_v = exapnd_v
66
+ self.feature_map = feature_map
67
+ self.use_output_gate = use_output_gate
68
+ self.use_norm = use_norm
69
+ self.max_position_embeddings = max_position_embeddings
70
+ self.hidden_act = hidden_act
71
+ self.elementwise_affine = elementwise_affine
72
+ self.norm_eps = norm_eps
73
+ self.attn = attn
74
+ self.use_cache = use_cache
75
+ self.initializer_range = initializer_range
76
+
77
+ self.fuse_norm = fuse_norm
78
+ self.fuse_swiglu = fuse_swiglu
79
+ self.fuse_cross_entropy = fuse_cross_entropy
80
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
81
+ self.use_l2warp = use_l2warp
82
+ self.vocab_size = vocab_size
83
+
84
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
85
+ raise ValueError(
86
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
87
+ )
88
+ if fuse_linear_cross_entropy:
89
+ warnings.warn(
90
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
91
+ "at the potential cost of reduced precision. "
92
+ "If you observe issues like loss divergence, consider disabling this setting."
93
+ )
94
+
95
+ if attn is not None:
96
+ if not isinstance(attn, Dict):
97
+ raise ValueError("attn must be a dictionary")
98
+ if 'layers' not in attn:
99
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
100
+ if 'num_heads' not in attn:
101
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
102
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
103
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
104
+ attn['window_size'] = attn.get('window_size', None)
105
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
106
+
107
+ super().__init__(
108
+ pad_token_id=pad_token_id,
109
+ bos_token_id=bos_token_id,
110
+ eos_token_id=eos_token_id,
111
+ tie_word_embeddings=tie_word_embeddings,
112
+ **kwargs,
113
+ )
models/gsa/modeling_gsa.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.layers.gsa import GatedSlotAttention
18
+ from fla.models.gsa.configuration_gsa import GSAConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as GSAMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class GSABlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: GSAConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = GatedSlotAttention(
59
+ hidden_size=config.hidden_size,
60
+ expand_k=config.expand_k,
61
+ expand_v=config.expand_v,
62
+ num_heads=config.num_heads,
63
+ num_kv_heads=config.num_kv_heads,
64
+ num_slots=config.num_slots,
65
+ use_short_conv=config.use_short_conv,
66
+ conv_size=config.conv_size,
67
+ feature_map=config.feature_map,
68
+ use_output_gate=config.use_output_gate,
69
+ use_norm=config.use_norm,
70
+ gate_fn=config.hidden_act,
71
+ gate_logit_normalizer=config.gate_logit_normalizer,
72
+ elementwise_affine=config.elementwise_affine,
73
+ norm_eps=config.norm_eps,
74
+ fuse_norm=config.fuse_norm,
75
+ layer_idx=layer_idx
76
+ )
77
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
78
+ self.mlp = GSAMLP(
79
+ hidden_size=config.hidden_size,
80
+ hidden_ratio=config.hidden_ratio,
81
+ intermediate_size=config.intermediate_size,
82
+ hidden_act=config.hidden_act,
83
+ fuse_swiglu=config.fuse_swiglu
84
+ )
85
+
86
+ def forward(
87
+ self,
88
+ hidden_states: torch.Tensor,
89
+ attention_mask: Optional[torch.Tensor] = None,
90
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
91
+ use_cache: Optional[bool] = False,
92
+ output_attentions: Optional[bool] = False,
93
+ **kwargs: Unpack[Dict]
94
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
95
+ residual = hidden_states
96
+ hidden_states = self.attn_norm(hidden_states)
97
+ hidden_states, attentions, past_key_values = self.attn(
98
+ hidden_states=hidden_states,
99
+ attention_mask=attention_mask,
100
+ past_key_values=past_key_values,
101
+ use_cache=use_cache,
102
+ output_attentions=output_attentions,
103
+ **kwargs
104
+ )
105
+ if self.config.fuse_norm:
106
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
107
+ else:
108
+ hidden_states = residual + hidden_states
109
+ residual = hidden_states
110
+ hidden_states = self.mlp_norm(hidden_states)
111
+ hidden_states = self.mlp(hidden_states, **kwargs)
112
+ hidden_states = residual + hidden_states
113
+
114
+ outputs = (hidden_states, attentions, past_key_values)
115
+
116
+ return outputs
117
+
118
+
119
+ class GSAPreTrainedModel(PreTrainedModel):
120
+
121
+ config_class = GSAConfig
122
+ base_model_prefix = 'model'
123
+ supports_gradient_checkpointing = True
124
+ _no_split_modules = ['GSABlock']
125
+ _supports_cache_class = True
126
+
127
+ def __init__(self, *inputs, **kwargs):
128
+ super().__init__(*inputs, **kwargs)
129
+
130
+ def _init_weights(
131
+ self,
132
+ module: nn.Module,
133
+ prenorm_residual_strategy: Optional[str] = None,
134
+ num_residuals_per_layer: int = 2,
135
+ ):
136
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
137
+ # Slightly different from the TF version which uses truncated_normal for initialization
138
+ # cf https://github.com/pytorch/pytorch/pull/5617
139
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
140
+ if module.bias is not None:
141
+ nn.init.zeros_(module.bias)
142
+ elif isinstance(module, nn.Embedding):
143
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
144
+ elif hasattr(module, 'reset_parameters'):
145
+ module.reset_parameters()
146
+
147
+ if prenorm_residual_strategy is not None:
148
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
149
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
150
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
151
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
152
+ #
153
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
154
+ p = None
155
+ if hasattr(module, 'o_proj'):
156
+ p = module.o_proj.weight
157
+ elif hasattr(module, 'down_proj'):
158
+ p = module.down_proj.weight
159
+ if p is not None:
160
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
161
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
162
+ # We need to reinit p since this code could be called multiple times
163
+ # Having just p *= scale would repeatedly scale it down
164
+ if prenorm_residual_strategy == 'rescale':
165
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
166
+ with torch.no_grad():
167
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
168
+ elif prenorm_residual_strategy == 'zero':
169
+ nn.init.zeros_(p)
170
+ else:
171
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
172
+
173
+
174
+ class GSAModel(GSAPreTrainedModel):
175
+
176
+ def __init__(self, config: GSAConfig):
177
+ super().__init__(config)
178
+ self.padding_idx = config.pad_token_id
179
+ self.vocab_size = config.vocab_size
180
+
181
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
182
+ self.layers = nn.ModuleList([GSABlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
183
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
184
+
185
+ self.gradient_checkpointing = False
186
+
187
+ self.post_init()
188
+
189
+ def get_input_embeddings(self):
190
+ return self.embeddings
191
+
192
+ def set_input_embeddings(self, value):
193
+ self.embeddings = value
194
+
195
+ def forward(
196
+ self,
197
+ input_ids: Optional[torch.LongTensor] = None,
198
+ attention_mask: Optional[torch.Tensor] = None, # noqa
199
+ inputs_embeds: Optional[torch.FloatTensor] = None,
200
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
201
+ use_cache: Optional[bool] = None,
202
+ output_attentions: Optional[bool] = None,
203
+ output_hidden_states: Optional[bool] = None,
204
+ return_dict: Optional[bool] = None,
205
+ **kwargs: Unpack[Dict]
206
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
207
+ if output_attentions:
208
+ warnings.warn("`GSAModel` does not `output_attentions` now, setting it to `False`.")
209
+ output_attentions = False
210
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
211
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
212
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
213
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
214
+
215
+ # retrieve input_ids and inputs_embeds
216
+ if input_ids is not None and inputs_embeds is not None:
217
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
218
+ if input_ids is None and inputs_embeds is None:
219
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
220
+
221
+ if inputs_embeds is None:
222
+ inputs_embeds = self.embeddings(input_ids)
223
+ hidden_states = inputs_embeds
224
+
225
+ if use_cache and not isinstance(past_key_values, Cache):
226
+ past_key_values = Cache.from_legacy_cache(past_key_values)
227
+
228
+ all_hidden_states = () if output_hidden_states else None
229
+ all_attns = () if output_attentions else None
230
+ for layer in self.layers:
231
+ if output_hidden_states:
232
+ all_hidden_states += (hidden_states,)
233
+
234
+ hidden_states, attentions, past_key_values = layer(
235
+ hidden_states,
236
+ attention_mask=attention_mask,
237
+ past_key_values=past_key_values,
238
+ use_cache=use_cache,
239
+ output_attentions=output_attentions,
240
+ **kwargs
241
+ )
242
+
243
+ if output_attentions:
244
+ all_attns += (attentions,)
245
+
246
+ hidden_states = self.norm(hidden_states)
247
+
248
+ # add hidden states from the last decoder layer
249
+ if output_hidden_states:
250
+ all_hidden_states += (hidden_states,)
251
+
252
+ if not return_dict:
253
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
254
+ return BaseModelOutputWithPast(
255
+ last_hidden_state=hidden_states,
256
+ past_key_values=past_key_values,
257
+ hidden_states=all_hidden_states,
258
+ attentions=all_attns
259
+ )
260
+
261
+
262
+ class GSAForCausalLM(GSAPreTrainedModel, FLAGenerationMixin):
263
+
264
+ _tied_weights_keys = ["lm_head.weight"]
265
+
266
+ def __init__(self, config):
267
+
268
+ super().__init__(config)
269
+ self.model = GSAModel(config)
270
+ self.vocab_size = config.vocab_size
271
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
272
+ self.criterion = None
273
+
274
+ # Initialize weights and apply final processing
275
+ self.post_init()
276
+
277
+ def get_input_embeddings(self):
278
+ return self.model.embeddings
279
+
280
+ def set_input_embeddings(self, value):
281
+ self.model.embeddings = value
282
+
283
+ def get_output_embeddings(self):
284
+ return self.lm_head
285
+
286
+ def set_output_embeddings(self, new_embeddings):
287
+ self.lm_head = new_embeddings
288
+
289
+ def set_decoder(self, decoder):
290
+ self.model = decoder
291
+
292
+ def get_decoder(self):
293
+ return self.model
294
+
295
+ def generate(self, *args, **kwargs):
296
+ try:
297
+ return super().generate(*args, **kwargs)
298
+ except AttributeError as exception:
299
+ if 'past_key_values' in str(exception):
300
+ raise AttributeError(
301
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
302
+ f"which is not supported for {self.__class__.__name__}. "
303
+ f"Try another generation strategy instead. "
304
+ f"For the available generation strategies, check this doc: "
305
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
306
+ )
307
+ else:
308
+ raise exception
309
+
310
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
311
+ def forward(
312
+ self,
313
+ input_ids: torch.LongTensor = None,
314
+ attention_mask: Optional[torch.Tensor] = None,
315
+ inputs_embeds: Optional[torch.Tensor] = None,
316
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
317
+ labels: Optional[torch.LongTensor] = None,
318
+ use_cache: Optional[bool] = None,
319
+ output_attentions: Optional[bool] = None,
320
+ output_hidden_states: Optional[bool] = None,
321
+ return_dict: Optional[bool] = None,
322
+ logits_to_keep: Optional[int] = 0,
323
+ **kwargs: Unpack[Dict]
324
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
325
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
326
+ output_hidden_states = (
327
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
328
+ )
329
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
330
+
331
+ outputs = self.model(
332
+ input_ids=input_ids,
333
+ attention_mask=attention_mask,
334
+ inputs_embeds=inputs_embeds,
335
+ past_key_values=past_key_values,
336
+ use_cache=use_cache,
337
+ output_attentions=output_attentions,
338
+ output_hidden_states=output_hidden_states,
339
+ return_dict=return_dict,
340
+ **kwargs
341
+ )
342
+
343
+ hidden_states = outputs[0]
344
+
345
+ loss, logits = None, None
346
+ if not self.config.fuse_linear_cross_entropy or labels is None:
347
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
348
+ if labels is not None:
349
+ if getattr(self, 'criterion', None) is None:
350
+ if self.config.fuse_linear_cross_entropy:
351
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
352
+ elif self.config.fuse_cross_entropy:
353
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
354
+ else:
355
+ criterion = nn.CrossEntropyLoss()
356
+ else:
357
+ criterion = self.criterion
358
+ # Enable model parallelism
359
+ labels = labels.to(hidden_states.device)
360
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
361
+ if self.config.fuse_linear_cross_entropy:
362
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
363
+ else:
364
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
365
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
366
+
367
+ if not return_dict:
368
+ output = (logits,) + outputs[1:]
369
+ return (loss,) + output if loss is not None else output
370
+
371
+ return CausalLMOutputWithPast(
372
+ loss=loss,
373
+ logits=logits,
374
+ past_key_values=outputs.past_key_values,
375
+ hidden_states=outputs.hidden_states,
376
+ attentions=outputs.attentions,
377
+ )
models/hgrn/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.hgrn.configuration_hgrn import HGRNConfig
6
+ from fla.models.hgrn.modeling_hgrn import HGRNForCausalLM, HGRNModel
7
+
8
+ AutoConfig.register(HGRNConfig.model_type, HGRNConfig, exist_ok=True)
9
+ AutoModel.register(HGRNConfig, HGRNModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(HGRNConfig, HGRNForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['HGRNConfig', 'HGRNForCausalLM', 'HGRNModel']
models/hgrn2/modeling_hgrn2.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.layers.hgrn2 import HGRN2Attention
18
+ from fla.models.hgrn2.configuration_hgrn2 import HGRN2Config
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as HGRN2MLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class HGRN2Block(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: HGRN2Config, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = HGRN2Attention(
59
+ mode=config.attn_mode,
60
+ hidden_size=config.hidden_size,
61
+ num_heads=config.num_heads,
62
+ expand_ratio=config.expand_ratio,
63
+ use_short_conv=config.use_short_conv,
64
+ conv_size=config.conv_size,
65
+ elementwise_affine=config.elementwise_affine,
66
+ norm_eps=config.norm_eps,
67
+ layer_idx=layer_idx
68
+ )
69
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
70
+ self.mlp = HGRN2MLP(
71
+ hidden_size=config.hidden_size,
72
+ hidden_ratio=config.hidden_ratio,
73
+ intermediate_size=config.intermediate_size,
74
+ hidden_act=config.hidden_act,
75
+ fuse_swiglu=config.fuse_swiglu
76
+ )
77
+
78
+ def forward(
79
+ self,
80
+ hidden_states: torch.Tensor,
81
+ attention_mask: Optional[torch.Tensor] = None,
82
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
83
+ use_cache: Optional[bool] = False,
84
+ output_attentions: Optional[bool] = False,
85
+ lower_bound: Optional[torch.Tensor] = False,
86
+ **kwargs: Unpack[Dict]
87
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
88
+ residual = hidden_states
89
+ hidden_states = self.attn_norm(hidden_states)
90
+ hidden_states, attentions, past_key_values = self.attn(
91
+ hidden_states=hidden_states,
92
+ attention_mask=attention_mask,
93
+ past_key_values=past_key_values,
94
+ use_cache=use_cache,
95
+ output_attentions=output_attentions,
96
+ lower_bound=lower_bound,
97
+ **kwargs
98
+ )
99
+ if self.config.fuse_norm:
100
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
101
+ else:
102
+ hidden_states = residual + hidden_states
103
+ residual = hidden_states
104
+ hidden_states = self.mlp_norm(hidden_states)
105
+ hidden_states = self.mlp(hidden_states, **kwargs)
106
+ hidden_states = residual + hidden_states
107
+
108
+ outputs = (hidden_states, attentions, past_key_values)
109
+
110
+ return outputs
111
+
112
+
113
+ class HGRN2PreTrainedModel(PreTrainedModel):
114
+
115
+ config_class = HGRN2Config
116
+ base_model_prefix = 'model'
117
+ supports_gradient_checkpointing = True
118
+ _no_split_modules = ['HGRN2Block']
119
+ _supports_cache_class = True
120
+
121
+ def __init__(self, *inputs, **kwargs):
122
+ super().__init__(*inputs, **kwargs)
123
+
124
+ def _init_weights(
125
+ self,
126
+ module: nn.Module,
127
+ prenorm_residual_strategy: Optional[str] = None,
128
+ num_residuals_per_layer: int = 2,
129
+ ):
130
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
131
+ # Slightly different from the TF version which uses truncated_normal for initialization
132
+ # cf https://github.com/pytorch/pytorch/pull/5617
133
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
134
+ if module.bias is not None:
135
+ nn.init.zeros_(module.bias)
136
+ elif isinstance(module, nn.Embedding):
137
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
138
+ elif hasattr(module, 'reset_parameters'):
139
+ module.reset_parameters()
140
+
141
+ if prenorm_residual_strategy is not None:
142
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
143
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
144
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
145
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
146
+ #
147
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
148
+ p = None
149
+ if hasattr(module, 'o_proj'):
150
+ p = module.o_proj.weight
151
+ elif hasattr(module, 'down_proj'):
152
+ p = module.down_proj.weight
153
+ if p is not None:
154
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
155
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
156
+ # We need to reinit p since this code could be called multiple times
157
+ # Having just p *= scale would repeatedly scale it down
158
+ if prenorm_residual_strategy == 'rescale':
159
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
160
+ with torch.no_grad():
161
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
162
+ elif prenorm_residual_strategy == 'zero':
163
+ nn.init.zeros_(p)
164
+ else:
165
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
166
+
167
+
168
+ class HGRN2Model(HGRN2PreTrainedModel):
169
+
170
+ def __init__(self, config: HGRN2Config):
171
+ super().__init__(config)
172
+ self.padding_idx = config.pad_token_id
173
+ self.vocab_size = config.vocab_size
174
+
175
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
176
+ if config.use_lower_bound:
177
+ self.lower_bounds = nn.Parameter(torch.zeros(config.num_hidden_layers, config.hidden_size))
178
+ self.layers = nn.ModuleList([HGRN2Block(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
179
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
180
+
181
+ self.gradient_checkpointing = False
182
+
183
+ self.post_init()
184
+
185
+ def get_input_embeddings(self):
186
+ return self.embeddings
187
+
188
+ def set_input_embeddings(self, value):
189
+ self.embeddings = value
190
+
191
+ def forward(
192
+ self,
193
+ input_ids: Optional[torch.LongTensor] = None,
194
+ attention_mask: Optional[torch.Tensor] = None, # noqa
195
+ inputs_embeds: Optional[torch.FloatTensor] = None,
196
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
197
+ use_cache: Optional[bool] = None,
198
+ output_attentions: Optional[bool] = None,
199
+ output_hidden_states: Optional[bool] = None,
200
+ return_dict: Optional[bool] = None,
201
+ **kwargs: Unpack[Dict]
202
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
203
+ if output_attentions:
204
+ warnings.warn("`HGRN2Model` does not `output_attentions` now, setting it to `False`.")
205
+ output_attentions = False
206
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
207
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
208
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
209
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
210
+
211
+ # retrieve input_ids and inputs_embeds
212
+ if input_ids is not None and inputs_embeds is not None:
213
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
214
+ if input_ids is None and inputs_embeds is None:
215
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
216
+
217
+ if inputs_embeds is None:
218
+ inputs_embeds = self.embeddings(input_ids)
219
+ hidden_states = inputs_embeds
220
+
221
+ if use_cache and not isinstance(past_key_values, Cache):
222
+ past_key_values = Cache.from_legacy_cache(past_key_values)
223
+
224
+ all_hidden_states = () if output_hidden_states else None
225
+ all_attns = () if output_attentions else None
226
+
227
+ if self.config.use_lower_bound:
228
+ lower_bounds = self.lower_bounds.softmax(0, dtype=torch.float)
229
+ lower_bounds = lower_bounds.cumsum(0) - lower_bounds[0]
230
+ for i, layer in enumerate(self.layers):
231
+ if output_hidden_states:
232
+ all_hidden_states += (hidden_states,)
233
+
234
+ lower_bound = lower_bounds[i] if self.config.use_lower_bound else None
235
+ hidden_states, attentions, past_key_values = layer(
236
+ hidden_states,
237
+ attention_mask=attention_mask,
238
+ past_key_values=past_key_values,
239
+ use_cache=use_cache,
240
+ output_attentions=output_attentions,
241
+ lower_bound=lower_bound,
242
+ **kwargs
243
+ )
244
+
245
+ if output_attentions:
246
+ all_attns += (attentions,)
247
+
248
+ hidden_states = self.norm(hidden_states)
249
+
250
+ # add hidden states from the last decoder layer
251
+ if output_hidden_states:
252
+ all_hidden_states += (hidden_states,)
253
+
254
+ if not return_dict:
255
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
256
+ return BaseModelOutputWithPast(
257
+ last_hidden_state=hidden_states,
258
+ past_key_values=past_key_values,
259
+ hidden_states=all_hidden_states,
260
+ attentions=all_attns
261
+ )
262
+
263
+
264
+ class HGRN2ForCausalLM(HGRN2PreTrainedModel, FLAGenerationMixin):
265
+
266
+ _tied_weights_keys = ["lm_head.weight"]
267
+
268
+ def __init__(self, config):
269
+ super().__init__(config)
270
+ self.model = HGRN2Model(config)
271
+ self.vocab_size = config.vocab_size
272
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
273
+ self.criterion = None
274
+
275
+ # Initialize weights and apply final processing
276
+ self.post_init()
277
+
278
+ def get_input_embeddings(self):
279
+ return self.model.embeddings
280
+
281
+ def set_input_embeddings(self, value):
282
+ self.model.embeddings = value
283
+
284
+ def get_output_embeddings(self):
285
+ return self.lm_head
286
+
287
+ def set_output_embeddings(self, new_embeddings):
288
+ self.lm_head = new_embeddings
289
+
290
+ def set_decoder(self, decoder):
291
+ self.model = decoder
292
+
293
+ def get_decoder(self):
294
+ return self.model
295
+
296
+ def generate(self, *args, **kwargs):
297
+ try:
298
+ return super().generate(*args, **kwargs)
299
+ except AttributeError as exception:
300
+ if 'past_key_values' in str(exception):
301
+ raise AttributeError(
302
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
303
+ f"which is not supported for {self.__class__.__name__}. "
304
+ f"Try another generation strategy instead. "
305
+ f"For the available generation strategies, check this doc: "
306
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
307
+ )
308
+ else:
309
+ raise exception
310
+
311
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
312
+ def forward(
313
+ self,
314
+ input_ids: torch.LongTensor = None,
315
+ attention_mask: Optional[torch.Tensor] = None,
316
+ inputs_embeds: Optional[torch.Tensor] = None,
317
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
318
+ labels: Optional[torch.LongTensor] = None,
319
+ use_cache: Optional[bool] = None,
320
+ output_attentions: Optional[bool] = None,
321
+ output_hidden_states: Optional[bool] = None,
322
+ return_dict: Optional[bool] = None,
323
+ logits_to_keep: Optional[int] = 0,
324
+ **kwargs: Unpack[Dict]
325
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
326
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
327
+ output_hidden_states = (
328
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
329
+ )
330
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
331
+
332
+ outputs = self.model(
333
+ input_ids=input_ids,
334
+ attention_mask=attention_mask,
335
+ inputs_embeds=inputs_embeds,
336
+ past_key_values=past_key_values,
337
+ use_cache=use_cache,
338
+ output_attentions=output_attentions,
339
+ output_hidden_states=output_hidden_states,
340
+ return_dict=return_dict,
341
+ **kwargs
342
+ )
343
+
344
+ hidden_states = outputs[0]
345
+
346
+ loss, logits = None, None
347
+ if not self.config.fuse_linear_cross_entropy or labels is None:
348
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
349
+ if labels is not None:
350
+ if getattr(self, 'criterion', None) is None:
351
+ if self.config.fuse_linear_cross_entropy:
352
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
353
+ elif self.config.fuse_cross_entropy:
354
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
355
+ else:
356
+ criterion = nn.CrossEntropyLoss()
357
+ else:
358
+ criterion = self.criterion
359
+ labels = labels.to(hidden_states.device)
360
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
361
+ if self.config.fuse_linear_cross_entropy:
362
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
363
+ else:
364
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
365
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
366
+
367
+ if not return_dict:
368
+ output = (logits,) + outputs[1:]
369
+ return (loss,) + output if loss is not None else output
370
+
371
+ return CausalLMOutputWithPast(
372
+ loss=loss,
373
+ logits=logits,
374
+ past_key_values=outputs.past_key_values,
375
+ hidden_states=outputs.hidden_states,
376
+ attentions=outputs.attentions,
377
+ )
models/linear_attn/configuration_linear_attn.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class LinearAttentionConfig(PretrainedConfig):
10
+
11
+ model_type = 'linear_attn'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ attn_mode: str = "fused_chunk",
17
+ hidden_size: int = 2048,
18
+ expand_k: float = 1.0,
19
+ expand_v: float = 1.0,
20
+ hidden_ratio: Optional[int] = 4,
21
+ intermediate_size: Optional[int] = None,
22
+ num_hidden_layers: int = 24,
23
+ num_heads: int = 4,
24
+ num_kv_heads: Optional[int] = None,
25
+ feature_map: str = "elementwise_product",
26
+ tie_feature_map_qk: bool = False,
27
+ norm_q: bool = False,
28
+ norm_k: bool = False,
29
+ norm_feature_map: bool = False,
30
+ hidden_act: str = "swish",
31
+ max_position_embeddings: int = 2048,
32
+ elementwise_affine: Optional[bool] = True,
33
+ norm_eps: float = 1e-6,
34
+ attn: Optional[Dict] = None,
35
+ use_cache: bool = True,
36
+ pad_token_id: Optional[int] = None,
37
+ bos_token_id: int = 1,
38
+ eos_token_id: int = 2,
39
+ tie_word_embeddings: bool = False,
40
+ initializer_range: float = 0.02,
41
+ fuse_norm: bool = True,
42
+ fuse_swiglu: bool = True,
43
+ fuse_cross_entropy: bool = True,
44
+ fuse_linear_cross_entropy: bool = False,
45
+ use_l2warp: bool = False,
46
+ vocab_size: int = 32000,
47
+ **kwargs
48
+ ):
49
+ self.attn_mode = attn_mode
50
+ self.hidden_size = hidden_size
51
+ self.expand_k = expand_k
52
+ self.expand_v = expand_v
53
+ self.hidden_ratio = hidden_ratio
54
+ self.intermediate_size = intermediate_size
55
+ self.num_hidden_layers = num_hidden_layers
56
+ self.num_heads = num_heads
57
+ self.num_kv_heads = num_kv_heads
58
+ self.feature_map = feature_map
59
+ self.tie_feature_map_qk = tie_feature_map_qk
60
+ self.norm_q = norm_q
61
+ self.norm_k = norm_k
62
+ self.norm_feature_map = norm_feature_map
63
+ self.hidden_act = hidden_act
64
+ self.max_position_embeddings = max_position_embeddings
65
+ self.elementwise_affine = elementwise_affine
66
+ self.norm_eps = norm_eps
67
+ self.attn = attn
68
+ self.use_cache = use_cache
69
+ self.initializer_range = initializer_range
70
+
71
+ self.fuse_norm = fuse_norm
72
+ self.fuse_swiglu = fuse_swiglu
73
+ self.fuse_cross_entropy = fuse_cross_entropy
74
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
75
+ self.use_l2warp = use_l2warp
76
+ self.vocab_size = vocab_size
77
+
78
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
79
+ raise ValueError(
80
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
81
+ )
82
+ if fuse_linear_cross_entropy:
83
+ warnings.warn(
84
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
85
+ "at the potential cost of reduced precision. "
86
+ "If you observe issues like loss divergence, consider disabling this setting."
87
+ )
88
+
89
+ if attn is not None:
90
+ if not isinstance(attn, Dict):
91
+ raise ValueError("attn must be a dictionary")
92
+ if 'layers' not in attn:
93
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
94
+ if 'num_heads' not in attn:
95
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
96
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
97
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
98
+ attn['window_size'] = attn.get('window_size', None)
99
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
100
+
101
+ super().__init__(
102
+ pad_token_id=pad_token_id,
103
+ bos_token_id=bos_token_id,
104
+ eos_token_id=eos_token_id,
105
+ tie_word_embeddings=tie_word_embeddings,
106
+ **kwargs,
107
+ )
models/log_linear_mamba2/configuration_log_linear_mamba2.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fla.models.mamba2 import Mamba2Config
2
+
3
+
4
+ class LogLinearMamba2Config(Mamba2Config):
5
+
6
+ model_type = "log_linear_mamba2"
7
+
8
+ def __init__(
9
+ self,
10
+ residual_in_fp32: bool = False,
11
+ chunk_size: int = 64,
12
+ **kwargs,
13
+ ):
14
+ super().__init__(
15
+ residual_in_fp32=residual_in_fp32,
16
+ chunk_size=chunk_size,
17
+ **kwargs,
18
+ )
models/rwkv6/modeling_rwkv6.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.layers.rwkv6 import LerpLinear, RWKV6Attention
18
+ from fla.models.rwkv6.configuration_rwkv6 import RWKV6Config
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss, LayerNorm
21
+ from fla.modules.activations import ACT2FN
22
+ from fla.modules.l2warp import l2_warp
23
+ from fla.modules.token_shift import token_shift
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class RWKV6FeedForward(nn.Module):
38
+
39
+ def __init__(
40
+ self,
41
+ hidden_size: int,
42
+ hidden_ratio: Optional[int] = None,
43
+ intermediate_size: Optional[int] = None,
44
+ hidden_act: str = 'sqrelu',
45
+ layer_idx: int = None
46
+ ) -> RWKV6FeedForward:
47
+ super().__init__()
48
+
49
+ self.hidden_size = hidden_size
50
+ if hidden_ratio is None:
51
+ hidden_ratio = 3.5
52
+ if intermediate_size is None:
53
+ intermediate_size = int(hidden_size * hidden_ratio)
54
+ intermediate_size = 32 * ((intermediate_size + 32 - 1) // 32)
55
+ self.hidden_ratio = hidden_ratio
56
+ self.intermediate_size = intermediate_size
57
+
58
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
59
+
60
+ self.key = LerpLinear(hidden_size, intermediate_size)
61
+ self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
62
+ self.receptance = LerpLinear(hidden_size, hidden_size)
63
+ self.act_fn = ACT2FN[hidden_act]
64
+
65
+ self.layer_idx = layer_idx
66
+
67
+ def forward(
68
+ self,
69
+ x: torch.Tensor,
70
+ attention_mask: Optional[torch.Tensor] = None,
71
+ state: Optional[Cache] = None,
72
+ cu_seqlens: Optional[torch.LongTensor] = None,
73
+ **kwargs
74
+ ) -> torch.Tensor:
75
+ if attention_mask is not None:
76
+ x = x.mul_(attention_mask[:, -x.shape[-2]:, None])
77
+ if x.shape[1] == 1 and state is not None and state[self.layer_idx]['ffn_state'] is not None:
78
+ shifted = state[self.layer_idx]['ffn_state'].unsqueeze(1)
79
+ delta = shifted - x
80
+ elif state is not None and state[self.layer_idx]['ffn_state'] is not None:
81
+ shifted = self.time_shift(x)
82
+ if state is not None and state[self.layer_idx]['ffn_state'] is not None:
83
+ shifted[:, 0] = state[self.layer_idx]['ffn_state']
84
+ delta = shifted - x
85
+ else:
86
+ delta = token_shift(x, cu_seqlens)
87
+ key = self.act_fn(self.key(x, delta))
88
+ value = self.value(key)
89
+ receptance = self.receptance(x, delta)
90
+
91
+ if state is not None:
92
+ # no need to update the offset twice
93
+ state.update(ffn_state=x[:, -1], layer_idx=self.layer_idx, offset=0)
94
+ return receptance.sigmoid() * value, state
95
+
96
+
97
+ class RWKV6Block(GradientCheckpointingLayer):
98
+
99
+ def __init__(self, config: RWKV6Config, layer_idx: int):
100
+ super().__init__()
101
+
102
+ self.config = config
103
+ self.layer_idx = layer_idx
104
+
105
+ if config.norm_first and layer_idx == 0:
106
+ self.pre_norm = (LayerNorm if config.fuse_norm else nn.LayerNorm)(
107
+ config.hidden_size,
108
+ bias=config.norm_bias,
109
+ eps=config.norm_eps
110
+ )
111
+ self.attn_norm = (LayerNorm if config.fuse_norm else nn.LayerNorm)(
112
+ config.hidden_size,
113
+ bias=config.norm_bias,
114
+ eps=config.norm_eps
115
+ )
116
+ if config.attn is not None and layer_idx in config.attn['layers']:
117
+ self.attn = Attention(
118
+ hidden_size=config.hidden_size,
119
+ num_heads=config.attn['num_heads'],
120
+ num_kv_heads=config.attn['num_kv_heads'],
121
+ qkv_bias=config.attn['qkv_bias'],
122
+ window_size=config.attn['window_size'],
123
+ rope_theta=config.attn['rope_theta'],
124
+ max_position_embeddings=config.max_position_embeddings,
125
+ layer_idx=layer_idx
126
+ )
127
+ else:
128
+ self.attn = RWKV6Attention(
129
+ mode=config.attn_mode,
130
+ hidden_size=config.hidden_size,
131
+ expand_k=config.expand_k,
132
+ expand_v=config.expand_v,
133
+ num_heads=config.num_heads,
134
+ proj_low_rank_dim=config.proj_low_rank_dim,
135
+ gate_low_rank_dim=config.gate_low_rank_dim,
136
+ norm_eps=config.norm_eps,
137
+ fuse_norm=config.fuse_norm,
138
+ layer_idx=layer_idx
139
+ )
140
+ self.ffn_norm = (LayerNorm if config.fuse_norm else nn.LayerNorm)(
141
+ config.hidden_size,
142
+ bias=config.norm_bias,
143
+ eps=config.norm_eps
144
+ )
145
+ self.ffn = RWKV6FeedForward(
146
+ hidden_size=config.hidden_size,
147
+ hidden_ratio=config.hidden_ratio,
148
+ intermediate_size=config.intermediate_size,
149
+ hidden_act=config.hidden_act,
150
+ layer_idx=layer_idx
151
+ )
152
+
153
+ def forward(
154
+ self,
155
+ hidden_states: torch.Tensor,
156
+ attention_mask: Optional[torch.Tensor] = None,
157
+ past_key_values: Optional[Cache] = None,
158
+ use_cache: Optional[bool] = False,
159
+ output_attentions: Optional[bool] = False,
160
+ cu_seqlens: Optional[torch.LongTensor] = None,
161
+ **kwargs,
162
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
163
+ residual = self.pre_norm(hidden_states) if hasattr(self, 'pre_norm') else hidden_states
164
+ hidden_states = self.attn_norm(residual)
165
+ hidden_states, attentions, past_key_values = self.attn(
166
+ hidden_states=hidden_states,
167
+ attention_mask=attention_mask,
168
+ past_key_values=past_key_values,
169
+ use_cache=use_cache,
170
+ output_attentions=output_attentions,
171
+ cu_seqlens=cu_seqlens,
172
+ **kwargs
173
+ )
174
+ if self.config.fuse_norm:
175
+ hidden_states, residual = self.ffn_norm(hidden_states, residual, True)
176
+ else:
177
+ hidden_states = residual + hidden_states
178
+ residual = hidden_states
179
+ hidden_states = self.ffn_norm(hidden_states)
180
+ hidden_states, past_key_values = self.ffn(
181
+ hidden_states, attention_mask, past_key_values, cu_seqlens, **kwargs
182
+ )
183
+ hidden_states = residual + hidden_states
184
+
185
+ outputs = (hidden_states, attentions, past_key_values)
186
+
187
+ return outputs
188
+
189
+
190
+ class RWKV6PreTrainedModel(PreTrainedModel):
191
+
192
+ config_class = RWKV6Config
193
+ base_model_prefix = 'model'
194
+ supports_gradient_checkpointing = True
195
+ _no_split_modules = ['RWKV6Block']
196
+ _supports_cache_class = True
197
+
198
+ def __init__(self, *inputs, **kwargs):
199
+ super().__init__(*inputs, **kwargs)
200
+
201
+ def _init_weights(
202
+ self,
203
+ module: nn.Module,
204
+ rescale_prenorm_residual: bool = True,
205
+ num_residuals_per_layer: int = 2,
206
+ ):
207
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
208
+ # Slightly different from the TF version which uses truncated_normal for initialization
209
+ # cf https://github.com/pytorch/pytorch/pull/5617
210
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
211
+ if module.bias is not None:
212
+ nn.init.zeros_(module.bias)
213
+ elif isinstance(module, nn.Parameter):
214
+ nn.init.normal_(module, mean=0.0, std=self.config.initializer_range)
215
+ elif isinstance(module, nn.Embedding):
216
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
217
+ elif hasattr(module, 'reset_parameters'):
218
+ module.reset_parameters()
219
+
220
+ if rescale_prenorm_residual:
221
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
222
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
223
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
224
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
225
+ #
226
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
227
+ p = None
228
+ if hasattr(module, 'o_proj'):
229
+ p = module.o_proj.weight
230
+ elif hasattr(module, 'down_proj'):
231
+ p = module.down_proj.weight
232
+ if p is not None:
233
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
234
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
235
+ # We need to reinit p since this code could be called multiple times
236
+ # Having just p *= scale would repeatedly scale it down
237
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
238
+ with torch.no_grad():
239
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
240
+
241
+
242
+ class RWKV6Model(RWKV6PreTrainedModel):
243
+
244
+ def __init__(self, config: RWKV6Config):
245
+ super().__init__(config)
246
+ self.padding_idx = config.pad_token_id
247
+ self.vocab_size = config.vocab_size
248
+
249
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
250
+ self.layers = nn.ModuleList([RWKV6Block(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
251
+ self.norm = (LayerNorm if config.fuse_norm else nn.LayerNorm)(
252
+ config.hidden_size,
253
+ bias=config.norm_bias,
254
+ eps=config.norm_eps
255
+ )
256
+
257
+ self.gradient_checkpointing = False
258
+
259
+ self.post_init()
260
+
261
+ def get_input_embeddings(self):
262
+ return self.embeddings
263
+
264
+ def set_input_embeddings(self, value):
265
+ self.embeddings = value
266
+
267
+ def forward(
268
+ self,
269
+ input_ids: Optional[torch.LongTensor] = None,
270
+ attention_mask: Optional[torch.Tensor] = None, # noqa
271
+ inputs_embeds: Optional[torch.FloatTensor] = None,
272
+ past_key_values: Optional[Cache] = None,
273
+ use_cache: Optional[bool] = None,
274
+ output_attentions: Optional[bool] = None,
275
+ output_hidden_states: Optional[bool] = None,
276
+ return_dict: Optional[bool] = None,
277
+ cu_seqlens: Optional[torch.LongTensor] = None,
278
+ **kwargs: Unpack[Dict]
279
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
280
+ if output_attentions:
281
+ warnings.warn("`RWKV6Model` does not `output_attentions` now, setting it to `False`.")
282
+ output_attentions = False
283
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
284
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
285
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
286
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
287
+
288
+ # retrieve input_ids and inputs_embeds
289
+ if input_ids is not None and inputs_embeds is not None:
290
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
291
+ if input_ids is None and inputs_embeds is None:
292
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
293
+
294
+ if inputs_embeds is None:
295
+ inputs_embeds = self.embeddings(input_ids)
296
+ hidden_states = inputs_embeds
297
+
298
+ if use_cache and not isinstance(past_key_values, Cache):
299
+ past_key_values = Cache.from_legacy_cache(past_key_values)
300
+
301
+ all_hidden_states = () if output_hidden_states else None
302
+ all_attns = () if output_attentions else None
303
+ for layer in self.layers:
304
+ if output_hidden_states:
305
+ all_hidden_states += (hidden_states,)
306
+
307
+ hidden_states, attentions, past_key_values = layer(
308
+ hidden_states,
309
+ attention_mask=attention_mask,
310
+ past_key_values=past_key_values,
311
+ use_cache=use_cache,
312
+ output_attentions=output_attentions,
313
+ cu_seqlens=cu_seqlens,
314
+ **kwargs
315
+ )
316
+
317
+ if output_attentions:
318
+ all_attns += (attentions,)
319
+
320
+ hidden_states = self.norm(hidden_states)
321
+
322
+ # add hidden states from the last decoder layer
323
+ if output_hidden_states:
324
+ all_hidden_states += (hidden_states,)
325
+
326
+ if not return_dict:
327
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
328
+ return BaseModelOutputWithPast(
329
+ last_hidden_state=hidden_states,
330
+ past_key_values=past_key_values,
331
+ hidden_states=all_hidden_states,
332
+ attentions=all_attns
333
+ )
334
+
335
+
336
+ class RWKV6ForCausalLM(RWKV6PreTrainedModel, FLAGenerationMixin):
337
+
338
+ _tied_weights_keys = ["lm_head.weight"]
339
+
340
+ def __init__(self, config):
341
+ super().__init__(config)
342
+ self.model = RWKV6Model(config)
343
+ self.vocab_size = config.vocab_size
344
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
345
+ self.criterion = None
346
+
347
+ # Initialize weights and apply final processing
348
+ self.post_init()
349
+
350
+ def get_input_embeddings(self):
351
+ return self.model.embeddings
352
+
353
+ def set_input_embeddings(self, value):
354
+ self.model.embeddings = value
355
+
356
+ def get_output_embeddings(self):
357
+ return self.lm_head
358
+
359
+ def set_output_embeddings(self, new_embeddings):
360
+ self.lm_head = new_embeddings
361
+
362
+ def set_decoder(self, decoder):
363
+ self.model = decoder
364
+
365
+ def get_decoder(self):
366
+ return self.model
367
+
368
+ def generate(self, *args, **kwargs):
369
+ try:
370
+ return super().generate(*args, **kwargs)
371
+ except AttributeError as exception:
372
+ if 'past_key_values' in str(exception):
373
+ raise AttributeError(
374
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
375
+ f"which is not supported for {self.__class__.__name__}. "
376
+ f"Try another generation strategy instead. "
377
+ f"For the available generation strategies, check this doc: "
378
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
379
+ )
380
+ else:
381
+ raise exception
382
+
383
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
384
+ def forward(
385
+ self,
386
+ input_ids: torch.LongTensor = None,
387
+ attention_mask: Optional[torch.Tensor] = None,
388
+ inputs_embeds: Optional[torch.Tensor] = None,
389
+ past_key_values: Optional[Cache] = None,
390
+ labels: Optional[torch.LongTensor] = None,
391
+ use_cache: Optional[bool] = None,
392
+ output_attentions: Optional[bool] = None,
393
+ output_hidden_states: Optional[bool] = None,
394
+ return_dict: Optional[bool] = None,
395
+ logits_to_keep: Optional[int] = 0,
396
+ **kwargs: Unpack[Dict]
397
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
398
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
399
+ output_hidden_states = (
400
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
401
+ )
402
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
403
+
404
+ outputs = self.model(
405
+ input_ids=input_ids,
406
+ attention_mask=attention_mask,
407
+ inputs_embeds=inputs_embeds,
408
+ past_key_values=past_key_values,
409
+ use_cache=use_cache,
410
+ output_attentions=output_attentions,
411
+ output_hidden_states=output_hidden_states,
412
+ return_dict=return_dict,
413
+ **kwargs
414
+ )
415
+
416
+ hidden_states = outputs[0]
417
+
418
+ loss, logits = None, None
419
+ if not self.config.fuse_linear_cross_entropy or labels is None:
420
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
421
+ if labels is not None:
422
+ if getattr(self, 'criterion', None) is None:
423
+ if self.config.fuse_linear_cross_entropy:
424
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
425
+ elif self.config.fuse_cross_entropy:
426
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
427
+ else:
428
+ criterion = nn.CrossEntropyLoss()
429
+ else:
430
+ criterion = self.criterion
431
+ labels = labels.to(hidden_states.device)
432
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
433
+ if self.config.fuse_linear_cross_entropy:
434
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
435
+ else:
436
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
437
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
438
+
439
+ if not return_dict:
440
+ output = (logits,) + outputs[1:]
441
+ return (loss,) + output if loss is not None else output
442
+
443
+ return CausalLMOutputWithPast(
444
+ loss=loss,
445
+ logits=logits,
446
+ past_key_values=outputs.past_key_values,
447
+ hidden_states=outputs.hidden_states,
448
+ attentions=outputs.attentions,
449
+ )
models/samba/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.samba.configuration_samba import SambaConfig
6
+ from fla.models.samba.modeling_samba import SambaBlock, SambaForCausalLM, SambaModel
7
+
8
+ AutoConfig.register(SambaConfig.model_type, SambaConfig, exist_ok=True)
9
+ AutoModel.register(SambaConfig, SambaModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(SambaConfig, SambaForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['SambaConfig', 'SambaForCausalLM', 'SambaModel', 'SambaBlock']
models/samba/modeling_samba.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
8
+
9
+ import torch
10
+ from torch import nn
11
+ from transformers.modeling_utils import PreTrainedModel
12
+ from transformers.utils import ModelOutput, logging
13
+ from transformers.utils.deprecation import deprecate_kwarg
14
+
15
+ from fla.layers.attn import Attention
16
+ from fla.layers.mamba import Mamba
17
+ from fla.models.mamba.modeling_mamba import MambaCache
18
+ from fla.models.samba.configuration_samba import SambaConfig
19
+ from fla.models.utils import FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as SambaMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class SambaBlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config, layer_idx):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.mixer_norm = RMSNorm(hidden_size=config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.mixer = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.mixer = Mamba(
59
+ hidden_size=config.hidden_size,
60
+ state_size=config.state_size,
61
+ conv_kernel=config.conv_kernel,
62
+ intermediate_size=config.intermediate_size,
63
+ time_step_rank=config.time_step_rank,
64
+ use_bias=config.use_bias,
65
+ layer_idx=layer_idx
66
+ )
67
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
68
+ self.mlp = SambaMLP(
69
+ hidden_size=config.hidden_size,
70
+ hidden_ratio=config.hidden_ratio,
71
+ hidden_act=config.hidden_act,
72
+ fuse_swiglu=config.fuse_swiglu
73
+ )
74
+
75
+ def forward(
76
+ self,
77
+ hidden_states: torch.Tensor,
78
+ cache_params: Optional[Tuple[torch.Tensor]] = None,
79
+ **kwargs: Unpack[Dict]
80
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
81
+
82
+ residual = hidden_states
83
+ hidden_states = self.mixer_norm(hidden_states)
84
+ if isinstance(self.mixer, Mamba):
85
+ hidden_states = self.mixer(hidden_states, cache_params=cache_params, **kwargs)
86
+ else:
87
+ hidden_states, _, cache_params = self.mixer(hidden_states=hidden_states, past_key_values=cache_params, **kwargs)
88
+ if self.config.fuse_norm:
89
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
90
+ else:
91
+ hidden_states = residual + hidden_states
92
+ residual = hidden_states
93
+ hidden_states = self.mlp_norm(hidden_states)
94
+ hidden_states = self.mlp(hidden_states, **kwargs)
95
+ hidden_states = residual + hidden_states
96
+ return hidden_states
97
+
98
+
99
+ class SambaPreTrainedModel(PreTrainedModel):
100
+ """
101
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
102
+ models.
103
+ """
104
+
105
+ config_class = SambaConfig
106
+ base_model_prefix = "backbone"
107
+ _no_split_modules = ["SambaBlock"]
108
+ supports_gradient_checkpointing = True
109
+
110
+ def _init_weights(self, module):
111
+ """Initialize the weights."""
112
+ if isinstance(module, nn.Linear):
113
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
114
+ if module.bias is not None:
115
+ if not getattr(module.bias, "_no_reinit", False):
116
+ nn.init.zeros_(module.bias)
117
+ elif isinstance(module, Mamba):
118
+ module.A_log._no_weight_decay = True
119
+ module.D._no_weight_decay = True
120
+
121
+ dt_init_std = self.config.time_step_rank**-0.5 * self.config.time_step_scale
122
+ if self.config.time_step_init_scheme == "constant":
123
+ nn.init.constant_(module.dt_proj.weight, dt_init_std)
124
+ elif self.config.time_step_init_scheme == "random":
125
+ nn.init.uniform_(module.dt_proj.weight, -dt_init_std, dt_init_std)
126
+
127
+ dt = torch.exp(
128
+ torch.rand(self.config.intermediate_size)
129
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
130
+ + math.log(self.config.time_step_min)
131
+ ).clamp(min=self.config.time_step_floor)
132
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
133
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
134
+ with torch.no_grad():
135
+ module.dt_proj.bias.data = nn.Parameter(inv_dt.to(module.dt_proj.bias.device))
136
+ module.dt_proj.bias._no_reinit = True
137
+ elif isinstance(module, nn.Embedding):
138
+ nn.init.normal_(module.weight, std=self.config.initializer_range)
139
+ elif hasattr(module, 'reset_parameters'):
140
+ module.reset_parameters()
141
+
142
+ if self.config.rescale_prenorm_residual:
143
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
144
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
145
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
146
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
147
+ #
148
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
149
+ for name, p in module.named_parameters():
150
+ if name in ["out_proj.weight"]:
151
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
152
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
153
+ # We need to reinit p since this code could be called multiple times
154
+ # Having just p *= scale would repeatedly scale it down
155
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
156
+ with torch.no_grad():
157
+ p /= math.sqrt(self.config.num_layers)
158
+
159
+
160
+ @dataclass
161
+ class SambaOutput(ModelOutput):
162
+ """
163
+ Class for the Samba model outputs.
164
+
165
+ Args:
166
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
167
+ Sequence of hidden-states at the output of the last layer of the model.
168
+ cache_params (`MambaCache`):
169
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
170
+ avoid providing the old `input_ids`.
171
+
172
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
173
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*,
174
+ returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
175
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
176
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
177
+
178
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
179
+ """
180
+
181
+ last_hidden_state: Optional[torch.FloatTensor] = None
182
+ cache_params: Optional[MambaCache] = None
183
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
184
+
185
+
186
+ @dataclass
187
+ class SambaCausalLMOutput(ModelOutput):
188
+ """
189
+ Base class for causal language model (or autoregressive) outputs.
190
+
191
+ Args:
192
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
193
+ Language modeling loss (for next-token prediction).
194
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
195
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
196
+ cache_params (`MambaCache`):
197
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
198
+ avoid providing the old `input_ids`.
199
+
200
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
201
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*,
202
+ returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
203
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
204
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
205
+
206
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
207
+ """
208
+
209
+ loss: Optional[torch.FloatTensor] = None
210
+ logits: Optional[torch.FloatTensor] = None
211
+ cache_params: Optional[MambaCache] = None
212
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
213
+
214
+
215
+ class SambaModel(SambaPreTrainedModel):
216
+ def __init__(self, config):
217
+ super().__init__(config)
218
+
219
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
220
+ self.layers = nn.ModuleList([SambaBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
221
+
222
+ self.gradient_checkpointing = False
223
+ self.norm_f = RMSNorm(config.hidden_size, eps=config.norm_eps)
224
+ # Initialize weights and apply final processing
225
+ self.post_init()
226
+
227
+ def get_input_embeddings(self):
228
+ return self.embeddings
229
+
230
+ def set_input_embeddings(self, new_embeddings):
231
+ self.embeddings = new_embeddings
232
+
233
+ def forward(
234
+ self,
235
+ input_ids: Optional[torch.LongTensor] = None,
236
+ inputs_embeds: Optional[torch.LongTensor] = None,
237
+ cache_params: Optional[MambaCache] = None,
238
+ use_cache: Optional[bool] = None,
239
+ output_hidden_states: Optional[bool] = None,
240
+ return_dict: Optional[bool] = None,
241
+ **kwargs: Unpack[Dict]
242
+ ) -> Union[Tuple, SambaOutput]:
243
+ output_hidden_states = (
244
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
245
+ )
246
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
247
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
248
+
249
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
250
+ raise ValueError(
251
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
252
+ )
253
+
254
+ if inputs_embeds is None:
255
+ inputs_embeds = self.embeddings(input_ids)
256
+
257
+ if cache_params is None and use_cache:
258
+ cache_params = MambaCache(
259
+ self.config, inputs_embeds.size(0), device=inputs_embeds.device, dtype=inputs_embeds.dtype
260
+ )
261
+
262
+ hidden_states = inputs_embeds
263
+ all_hidden_states = () if output_hidden_states else None
264
+ for mixer_block in self.layers:
265
+ hidden_states = mixer_block(
266
+ hidden_states,
267
+ cache_params=cache_params,
268
+ **kwargs
269
+ )
270
+
271
+ if output_hidden_states:
272
+ all_hidden_states = all_hidden_states + (hidden_states,)
273
+
274
+ if use_cache:
275
+ cache_params.seqlen_offset += inputs_embeds.shape[1]
276
+
277
+ hidden_states = self.norm_f(hidden_states)
278
+
279
+ if output_hidden_states:
280
+ all_hidden_states = all_hidden_states + (hidden_states,)
281
+
282
+ if not return_dict:
283
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
284
+
285
+ return SambaOutput(
286
+ last_hidden_state=hidden_states,
287
+ cache_params=cache_params if use_cache else None,
288
+ hidden_states=all_hidden_states,
289
+ )
290
+
291
+
292
+ class SambaForCausalLM(SambaPreTrainedModel, FLAGenerationMixin):
293
+
294
+ _tied_weights_keys = ["lm_head.weight"]
295
+
296
+ def __init__(self, config):
297
+ super().__init__(config)
298
+ self.backbone = SambaModel(config)
299
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
300
+ self.criterion = None
301
+
302
+ # Initialize weights and apply final processing
303
+ self.post_init()
304
+
305
+ def get_output_embeddings(self):
306
+ return self.lm_head
307
+
308
+ def set_output_embeddings(self, new_embeddings):
309
+ self.lm_head = new_embeddings
310
+
311
+ def get_input_embeddings(self):
312
+ return self.backbone.get_input_embeddings()
313
+
314
+ def set_input_embeddings(self, new_embeddings):
315
+ return self.backbone.set_input_embeddings(new_embeddings)
316
+
317
+ def _update_model_kwargs_for_generation(
318
+ self, outputs: ModelOutput, model_kwargs: Dict[str, Any], **kwargs
319
+ ) -> Dict[str, Any]:
320
+ model_kwargs["cache_params"] = outputs.get("cache_params", None)
321
+ return model_kwargs
322
+
323
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
324
+ def forward(
325
+ self,
326
+ input_ids: Optional[torch.LongTensor] = None,
327
+ attention_mask: Optional[torch.Tensor] = None, # noqa
328
+ inputs_embeds: Optional[torch.FloatTensor] = None,
329
+ cache_params: Optional[MambaCache] = None,
330
+ labels: Optional[torch.LongTensor] = None,
331
+ output_hidden_states: Optional[bool] = None,
332
+ return_dict: Optional[bool] = None,
333
+ use_cache: Optional[bool] = None,
334
+ logits_to_keep: Optional[int] = 0,
335
+ **kwargs: Unpack[Dict]
336
+ ) -> Union[Tuple, SambaCausalLMOutput]:
337
+ r"""
338
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
339
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
340
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
341
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
342
+ """
343
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
344
+
345
+ outputs = self.backbone(
346
+ input_ids,
347
+ cache_params=cache_params,
348
+ inputs_embeds=inputs_embeds,
349
+ output_hidden_states=output_hidden_states,
350
+ return_dict=return_dict,
351
+ use_cache=use_cache,
352
+ **kwargs
353
+ )
354
+ hidden_states = outputs[0]
355
+
356
+ loss, logits = None, None
357
+ if not self.config.fuse_linear_cross_entropy or labels is None:
358
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
359
+ if labels is not None:
360
+ if getattr(self, 'criterion', None) is None:
361
+ if self.config.fuse_linear_cross_entropy:
362
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
363
+ elif self.config.fuse_cross_entropy:
364
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
365
+ else:
366
+ criterion = nn.CrossEntropyLoss()
367
+ else:
368
+ criterion = self.criterion
369
+ labels = labels.to(hidden_states.device)
370
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
371
+ if self.config.fuse_linear_cross_entropy:
372
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
373
+ else:
374
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
375
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
376
+
377
+ if not return_dict:
378
+ output = (logits,) + outputs[1:]
379
+ return (loss,) + output if loss is not None else output
380
+
381
+ return SambaCausalLMOutput(
382
+ loss=loss,
383
+ logits=logits,
384
+ cache_params=outputs.cache_params,
385
+ hidden_states=outputs.hidden_states,
386
+ )
models/sig_tr_gka_net/modeling_sig_tr_gka_net.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from ...layers.sig_tr_gka import SigTrGKANet
18
+ from .configuration_sig_tr_gka_net import SigTrGKANetConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as SigTrGKANetMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class SigTrGKANetBlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: SigTrGKANetConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = SigTrGKANet(
59
+ mode=config.attn_mode,
60
+ hidden_size=config.hidden_size,
61
+ num_heads=config.num_heads,
62
+ head_dim=config.head_dim,
63
+ use_output_gate=config.use_output_gate,
64
+ use_short_conv=config.use_short_conv,
65
+ conv_size=config.conv_size,
66
+ norm_eps=config.norm_eps,
67
+ lambda_lower_bound=config.lambda_lower_bound,
68
+ use_mamba_init=config.use_mamba_init,
69
+ layer_idx=layer_idx,
70
+ max_cg_step_training=config.max_cg_step_training,
71
+ max_cg_step_decoding=config.max_cg_step_decoding
72
+ )
73
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
74
+ self.mlp = SigTrGKANetMLP(
75
+ hidden_size=config.hidden_size,
76
+ hidden_ratio=config.hidden_ratio,
77
+ intermediate_size=config.intermediate_size,
78
+ hidden_act=config.hidden_act,
79
+ fuse_swiglu=config.fuse_swiglu
80
+ )
81
+
82
+ def forward(
83
+ self,
84
+ hidden_states: torch.Tensor,
85
+ attention_mask: Optional[torch.Tensor] = None,
86
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
87
+ use_cache: Optional[bool] = False,
88
+ output_attentions: Optional[bool] = False,
89
+ **kwargs: Unpack[Dict]
90
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
91
+ residual = hidden_states
92
+ hidden_states = self.attn_norm(hidden_states)
93
+ hidden_states, attentions, past_key_values = self.attn(
94
+ hidden_states=hidden_states,
95
+ attention_mask=attention_mask,
96
+ past_key_values=past_key_values,
97
+ use_cache=use_cache,
98
+ output_attentions=output_attentions,
99
+ **kwargs
100
+ )
101
+ if self.config.fuse_norm:
102
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
103
+ else:
104
+ hidden_states = residual + hidden_states
105
+ residual = hidden_states
106
+ hidden_states = self.mlp_norm(hidden_states)
107
+ hidden_states = self.mlp(hidden_states, **kwargs)
108
+ hidden_states = residual + hidden_states
109
+
110
+ outputs = (hidden_states, attentions, past_key_values)
111
+
112
+ return outputs
113
+
114
+
115
+ class SigTrGKANetPreTrainedModel(PreTrainedModel):
116
+
117
+ config_class = SigTrGKANetConfig
118
+ base_model_prefix = 'model'
119
+ supports_gradient_checkpointing = True
120
+ _no_split_modules = ['SigTrGKANetBlock']
121
+ _supports_cache_class = True
122
+ # Keep polynomial coefficients in fp32 under HF dtype casts (torch_dtype=bf16, .to(bf16)).
123
+ _keep_in_fp32_modules = ['learnable_abc']
124
+
125
+ def __init__(self, *inputs, **kwargs):
126
+ super().__init__(*inputs, **kwargs)
127
+
128
+ def _init_weights(
129
+ self,
130
+ module: nn.Module,
131
+ prenorm_residual_strategy: Optional[str] = None,
132
+ num_residuals_per_layer: int = 2,
133
+ ):
134
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
135
+ # Slightly different from the TF version which uses truncated_normal for initialization
136
+ # cf https://github.com/pytorch/pytorch/pull/5617
137
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
138
+ if module.bias is not None:
139
+ nn.init.zeros_(module.bias)
140
+ elif isinstance(module, nn.Embedding):
141
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
142
+ elif hasattr(module, 'reset_parameters'):
143
+ module.reset_parameters()
144
+
145
+ if prenorm_residual_strategy is not None:
146
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
147
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
148
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
149
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
150
+ #
151
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
152
+ p = None
153
+ if hasattr(module, 'o_proj'):
154
+ p = module.o_proj.weight
155
+ elif hasattr(module, 'down_proj'):
156
+ p = module.down_proj.weight
157
+ if p is not None:
158
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
159
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
160
+ # We need to reinit p since this code could be called multiple times
161
+ # Having just p *= scale would repeatedly scale it down
162
+ if prenorm_residual_strategy == 'rescale':
163
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
164
+ with torch.no_grad():
165
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
166
+ elif prenorm_residual_strategy == 'zero':
167
+ nn.init.zeros_(p)
168
+ else:
169
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
170
+
171
+
172
+ class SigTrGKANetModel(SigTrGKANetPreTrainedModel):
173
+
174
+ def __init__(self, config: SigTrGKANetConfig):
175
+ super().__init__(config)
176
+ self.padding_idx = config.pad_token_id
177
+ self.vocab_size = config.vocab_size
178
+
179
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
180
+ self.layers = nn.ModuleList([SigTrGKANetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
181
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
182
+
183
+ self.gradient_checkpointing = False
184
+
185
+ self.post_init()
186
+
187
+ def get_input_embeddings(self):
188
+ return self.embeddings
189
+
190
+ def set_input_embeddings(self, value):
191
+ self.embeddings = value
192
+
193
+ def forward(
194
+ self,
195
+ input_ids: Optional[torch.LongTensor] = None,
196
+ attention_mask: Optional[torch.Tensor] = None, # noqa
197
+ inputs_embeds: Optional[torch.FloatTensor] = None,
198
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
199
+ use_cache: Optional[bool] = None,
200
+ output_attentions: Optional[bool] = None,
201
+ output_hidden_states: Optional[bool] = None,
202
+ return_dict: Optional[bool] = None,
203
+ **kwargs: Unpack[Dict]
204
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
205
+ if output_attentions:
206
+ warnings.warn("`SigTrGKANetModel` does not `output_attentions` now, setting it to `False`.")
207
+ output_attentions = False
208
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
209
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
210
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
211
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
212
+
213
+ # retrieve input_ids and inputs_embeds
214
+ if input_ids is not None and inputs_embeds is not None:
215
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
216
+ if input_ids is None and inputs_embeds is None:
217
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
218
+
219
+ if inputs_embeds is None:
220
+ inputs_embeds = self.embeddings(input_ids)
221
+ hidden_states = inputs_embeds
222
+
223
+ if use_cache and not isinstance(past_key_values, Cache):
224
+ past_key_values = Cache.from_legacy_cache(past_key_values)
225
+
226
+ all_hidden_states = () if output_hidden_states else None
227
+ all_attns = () if output_attentions else None
228
+ for layer in self.layers:
229
+ if output_hidden_states:
230
+ all_hidden_states += (hidden_states,)
231
+
232
+ hidden_states, attentions, past_key_values = layer(
233
+ hidden_states,
234
+ attention_mask=attention_mask,
235
+ past_key_values=past_key_values,
236
+ use_cache=use_cache,
237
+ output_attentions=output_attentions,
238
+ **kwargs
239
+ )
240
+
241
+ if output_attentions:
242
+ all_attns += (attentions,)
243
+
244
+ hidden_states = self.norm(hidden_states)
245
+
246
+ # add hidden states from the last decoder layer
247
+ if output_hidden_states:
248
+ all_hidden_states += (hidden_states,)
249
+
250
+ if not return_dict:
251
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
252
+ return BaseModelOutputWithPast(
253
+ last_hidden_state=hidden_states,
254
+ past_key_values=past_key_values,
255
+ hidden_states=all_hidden_states,
256
+ attentions=all_attns
257
+ )
258
+
259
+
260
+ class SigTrGKANetForCausalLM(SigTrGKANetPreTrainedModel, FLAGenerationMixin):
261
+
262
+ _tied_weights_keys = ["lm_head.weight"]
263
+
264
+ def __init__(self, config):
265
+ super().__init__(config)
266
+ self.model = SigTrGKANetModel(config)
267
+ self.vocab_size = config.vocab_size
268
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
269
+ self.criterion = None
270
+
271
+ # Initialize weights and apply final processing
272
+ self.post_init()
273
+
274
+ def get_input_embeddings(self):
275
+ return self.model.embeddings
276
+
277
+ def set_input_embeddings(self, value):
278
+ self.model.embeddings = value
279
+
280
+ def get_output_embeddings(self):
281
+ return self.lm_head
282
+
283
+ def set_output_embeddings(self, new_embeddings):
284
+ self.lm_head = new_embeddings
285
+
286
+ def set_decoder(self, decoder):
287
+ self.model = decoder
288
+
289
+ def get_decoder(self):
290
+ return self.model
291
+
292
+ def generate(self, *args, **kwargs):
293
+ try:
294
+ return super().generate(*args, **kwargs)
295
+ except AttributeError as exception:
296
+ if 'past_key_values' in str(exception):
297
+ raise AttributeError(
298
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
299
+ f"which is not supported for {self.__class__.__name__}. "
300
+ f"Try another generation strategy instead. "
301
+ f"For the available generation strategies, check this doc: "
302
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
303
+ )
304
+ else:
305
+ raise exception
306
+
307
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
308
+ def forward(
309
+ self,
310
+ input_ids: torch.LongTensor = None,
311
+ attention_mask: Optional[torch.Tensor] = None,
312
+ inputs_embeds: Optional[torch.Tensor] = None,
313
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
314
+ labels: Optional[torch.LongTensor] = None,
315
+ use_cache: Optional[bool] = None,
316
+ output_attentions: Optional[bool] = None,
317
+ output_hidden_states: Optional[bool] = None,
318
+ return_dict: Optional[bool] = None,
319
+ logits_to_keep: Optional[int] = 0,
320
+ **kwargs: Unpack[Dict]
321
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
322
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
323
+ output_hidden_states = (
324
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
325
+ )
326
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
327
+
328
+ outputs = self.model(
329
+ input_ids=input_ids,
330
+ attention_mask=attention_mask,
331
+ inputs_embeds=inputs_embeds,
332
+ past_key_values=past_key_values,
333
+ use_cache=use_cache,
334
+ output_attentions=output_attentions,
335
+ output_hidden_states=output_hidden_states,
336
+ return_dict=return_dict,
337
+ **kwargs
338
+ )
339
+
340
+ hidden_states = outputs[0]
341
+
342
+ loss, logits = None, None
343
+ if not self.config.fuse_linear_cross_entropy or labels is None:
344
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
345
+ if labels is not None:
346
+ if getattr(self, 'criterion', None) is None:
347
+ if self.config.fuse_linear_cross_entropy:
348
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
349
+ elif self.config.fuse_cross_entropy:
350
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
351
+ else:
352
+ criterion = nn.CrossEntropyLoss()
353
+ else:
354
+ criterion = self.criterion
355
+ labels = labels.to(hidden_states.device)
356
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
357
+ if self.config.fuse_linear_cross_entropy:
358
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
359
+ else:
360
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
361
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
362
+
363
+ if not return_dict:
364
+ output = (logits,) + outputs[1:]
365
+ return (loss,) + output if loss is not None else output
366
+
367
+ return CausalLMOutputWithPast(
368
+ loss=loss,
369
+ logits=logits,
370
+ past_key_values=outputs.past_key_values,
371
+ hidden_states=outputs.hidden_states,
372
+ attentions=outputs.attentions,
373
+ )
models/sigma_gka_net/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from .configuration_sigma_gka_net import SigmaGKANetConfig
6
+ from .modeling_sigma_gka_net import SigmaGKANetForCausalLM, SigmaGKANetModel
7
+
8
+ AutoConfig.register(SigmaGKANetConfig.model_type, SigmaGKANetConfig, exist_ok=True)
9
+ AutoModel.register(SigmaGKANetConfig, SigmaGKANetModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(SigmaGKANetConfig, SigmaGKANetForCausalLM, exist_ok=True)
11
+
12
+ __all__ = ['SigmaGKANetConfig', 'SigmaGKANetForCausalLM', 'SigmaGKANetModel']
models/sigma_gka_net/modeling_sigma_gka_net.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from ...layers.sigma_gka import SigmaGKANet
18
+ from .configuration_sigma_gka_net import SigmaGKANetConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as SigmaGKANetMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class SigmaGKANetBlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: SigmaGKANetConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = SigmaGKANet(
59
+ mode=config.attn_mode,
60
+ hidden_size=config.hidden_size,
61
+ num_heads=config.num_heads,
62
+ head_dim=config.head_dim,
63
+ use_output_gate=config.use_output_gate,
64
+ use_short_conv=config.use_short_conv,
65
+ conv_size=config.conv_size,
66
+ norm_eps=config.norm_eps,
67
+ lambda_lower_bound=config.lambda_lower_bound,
68
+ layer_idx=layer_idx,
69
+ max_cg_step_training=config.max_cg_step_training,
70
+ max_cg_step_decoding=config.max_cg_step_decoding
71
+ )
72
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
73
+ self.mlp = SigmaGKANetMLP(
74
+ hidden_size=config.hidden_size,
75
+ hidden_ratio=config.hidden_ratio,
76
+ intermediate_size=config.intermediate_size,
77
+ hidden_act=config.hidden_act,
78
+ fuse_swiglu=config.fuse_swiglu
79
+ )
80
+
81
+ def forward(
82
+ self,
83
+ hidden_states: torch.Tensor,
84
+ attention_mask: Optional[torch.Tensor] = None,
85
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
86
+ use_cache: Optional[bool] = False,
87
+ output_attentions: Optional[bool] = False,
88
+ **kwargs: Unpack[Dict]
89
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
90
+ residual = hidden_states
91
+ hidden_states = self.attn_norm(hidden_states)
92
+ hidden_states, attentions, past_key_values = self.attn(
93
+ hidden_states=hidden_states,
94
+ attention_mask=attention_mask,
95
+ past_key_values=past_key_values,
96
+ use_cache=use_cache,
97
+ output_attentions=output_attentions,
98
+ **kwargs
99
+ )
100
+ if self.config.fuse_norm:
101
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
102
+ else:
103
+ hidden_states = residual + hidden_states
104
+ residual = hidden_states
105
+ hidden_states = self.mlp_norm(hidden_states)
106
+ hidden_states = self.mlp(hidden_states, **kwargs)
107
+ hidden_states = residual + hidden_states
108
+
109
+ outputs = (hidden_states, attentions, past_key_values)
110
+
111
+ return outputs
112
+
113
+
114
+ class SigmaGKANetPreTrainedModel(PreTrainedModel):
115
+
116
+ config_class = SigmaGKANetConfig
117
+ base_model_prefix = 'model'
118
+ supports_gradient_checkpointing = True
119
+ _no_split_modules = ['SigmaGKANetBlock']
120
+ _supports_cache_class = True
121
+ # Keep polynomial coefficients in fp32 under HF dtype casts (torch_dtype=bf16, .to(bf16)).
122
+ _keep_in_fp32_modules = ['learnable_abc']
123
+
124
+ def __init__(self, *inputs, **kwargs):
125
+ super().__init__(*inputs, **kwargs)
126
+
127
+ def _init_weights(
128
+ self,
129
+ module: nn.Module,
130
+ prenorm_residual_strategy: Optional[str] = None,
131
+ num_residuals_per_layer: int = 2,
132
+ ):
133
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
134
+ # Slightly different from the TF version which uses truncated_normal for initialization
135
+ # cf https://github.com/pytorch/pytorch/pull/5617
136
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
137
+ if module.bias is not None:
138
+ nn.init.zeros_(module.bias)
139
+ elif isinstance(module, nn.Embedding):
140
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
141
+ elif hasattr(module, 'reset_parameters'):
142
+ module.reset_parameters()
143
+
144
+ if prenorm_residual_strategy is not None:
145
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
146
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
147
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
148
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
149
+ #
150
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
151
+ p = None
152
+ if hasattr(module, 'o_proj'):
153
+ p = module.o_proj.weight
154
+ elif hasattr(module, 'down_proj'):
155
+ p = module.down_proj.weight
156
+ if p is not None:
157
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
158
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
159
+ # We need to reinit p since this code could be called multiple times
160
+ # Having just p *= scale would repeatedly scale it down
161
+ if prenorm_residual_strategy == 'rescale':
162
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
163
+ with torch.no_grad():
164
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
165
+ elif prenorm_residual_strategy == 'zero':
166
+ nn.init.zeros_(p)
167
+ else:
168
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
169
+
170
+
171
+ class SigmaGKANetModel(SigmaGKANetPreTrainedModel):
172
+
173
+ def __init__(self, config: SigmaGKANetConfig):
174
+ super().__init__(config)
175
+ self.padding_idx = config.pad_token_id
176
+ self.vocab_size = config.vocab_size
177
+
178
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
179
+ self.layers = nn.ModuleList([SigmaGKANetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
180
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
181
+
182
+ self.gradient_checkpointing = False
183
+
184
+ self.post_init()
185
+
186
+ def get_input_embeddings(self):
187
+ return self.embeddings
188
+
189
+ def set_input_embeddings(self, value):
190
+ self.embeddings = value
191
+
192
+ def forward(
193
+ self,
194
+ input_ids: Optional[torch.LongTensor] = None,
195
+ attention_mask: Optional[torch.Tensor] = None, # noqa
196
+ inputs_embeds: Optional[torch.FloatTensor] = None,
197
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
198
+ use_cache: Optional[bool] = None,
199
+ output_attentions: Optional[bool] = None,
200
+ output_hidden_states: Optional[bool] = None,
201
+ return_dict: Optional[bool] = None,
202
+ **kwargs: Unpack[Dict]
203
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
204
+ if output_attentions:
205
+ warnings.warn("`SigmaGKANetModel` does not `output_attentions` now, setting it to `False`.")
206
+ output_attentions = False
207
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
208
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
209
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
210
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
211
+
212
+ # retrieve input_ids and inputs_embeds
213
+ if input_ids is not None and inputs_embeds is not None:
214
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
215
+ if input_ids is None and inputs_embeds is None:
216
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
217
+
218
+ if inputs_embeds is None:
219
+ inputs_embeds = self.embeddings(input_ids)
220
+ hidden_states = inputs_embeds
221
+
222
+ if use_cache and not isinstance(past_key_values, Cache):
223
+ past_key_values = Cache.from_legacy_cache(past_key_values)
224
+
225
+ all_hidden_states = () if output_hidden_states else None
226
+ all_attns = () if output_attentions else None
227
+ for layer in self.layers:
228
+ if output_hidden_states:
229
+ all_hidden_states += (hidden_states,)
230
+
231
+ hidden_states, attentions, past_key_values = layer(
232
+ hidden_states,
233
+ attention_mask=attention_mask,
234
+ past_key_values=past_key_values,
235
+ use_cache=use_cache,
236
+ output_attentions=output_attentions,
237
+ **kwargs
238
+ )
239
+
240
+ if output_attentions:
241
+ all_attns += (attentions,)
242
+
243
+ hidden_states = self.norm(hidden_states)
244
+
245
+ # add hidden states from the last decoder layer
246
+ if output_hidden_states:
247
+ all_hidden_states += (hidden_states,)
248
+
249
+ if not return_dict:
250
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
251
+ return BaseModelOutputWithPast(
252
+ last_hidden_state=hidden_states,
253
+ past_key_values=past_key_values,
254
+ hidden_states=all_hidden_states,
255
+ attentions=all_attns
256
+ )
257
+
258
+
259
+ class SigmaGKANetForCausalLM(SigmaGKANetPreTrainedModel, FLAGenerationMixin):
260
+
261
+ _tied_weights_keys = ["lm_head.weight"]
262
+
263
+ def __init__(self, config):
264
+ super().__init__(config)
265
+ self.model = SigmaGKANetModel(config)
266
+ self.vocab_size = config.vocab_size
267
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
268
+ self.criterion = None
269
+
270
+ # Initialize weights and apply final processing
271
+ self.post_init()
272
+
273
+ def get_input_embeddings(self):
274
+ return self.model.embeddings
275
+
276
+ def set_input_embeddings(self, value):
277
+ self.model.embeddings = value
278
+
279
+ def get_output_embeddings(self):
280
+ return self.lm_head
281
+
282
+ def set_output_embeddings(self, new_embeddings):
283
+ self.lm_head = new_embeddings
284
+
285
+ def set_decoder(self, decoder):
286
+ self.model = decoder
287
+
288
+ def get_decoder(self):
289
+ return self.model
290
+
291
+ def generate(self, *args, **kwargs):
292
+ try:
293
+ return super().generate(*args, **kwargs)
294
+ except AttributeError as exception:
295
+ if 'past_key_values' in str(exception):
296
+ raise AttributeError(
297
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
298
+ f"which is not supported for {self.__class__.__name__}. "
299
+ f"Try another generation strategy instead. "
300
+ f"For the available generation strategies, check this doc: "
301
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
302
+ )
303
+ else:
304
+ raise exception
305
+
306
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
307
+ def forward(
308
+ self,
309
+ input_ids: torch.LongTensor = None,
310
+ attention_mask: Optional[torch.Tensor] = None,
311
+ inputs_embeds: Optional[torch.Tensor] = None,
312
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
313
+ labels: Optional[torch.LongTensor] = None,
314
+ use_cache: Optional[bool] = None,
315
+ output_attentions: Optional[bool] = None,
316
+ output_hidden_states: Optional[bool] = None,
317
+ return_dict: Optional[bool] = None,
318
+ logits_to_keep: Optional[int] = 0,
319
+ **kwargs: Unpack[Dict]
320
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
321
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
322
+ output_hidden_states = (
323
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
324
+ )
325
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
326
+
327
+ outputs = self.model(
328
+ input_ids=input_ids,
329
+ attention_mask=attention_mask,
330
+ inputs_embeds=inputs_embeds,
331
+ past_key_values=past_key_values,
332
+ use_cache=use_cache,
333
+ output_attentions=output_attentions,
334
+ output_hidden_states=output_hidden_states,
335
+ return_dict=return_dict,
336
+ **kwargs
337
+ )
338
+
339
+ hidden_states = outputs[0]
340
+
341
+ loss, logits = None, None
342
+ if not self.config.fuse_linear_cross_entropy or labels is None:
343
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
344
+ if labels is not None:
345
+ if getattr(self, 'criterion', None) is None:
346
+ if self.config.fuse_linear_cross_entropy:
347
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
348
+ elif self.config.fuse_cross_entropy:
349
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
350
+ else:
351
+ criterion = nn.CrossEntropyLoss()
352
+ else:
353
+ criterion = self.criterion
354
+ labels = labels.to(hidden_states.device)
355
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
356
+ if self.config.fuse_linear_cross_entropy:
357
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
358
+ else:
359
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
360
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
361
+
362
+ if not return_dict:
363
+ output = (logits,) + outputs[1:]
364
+ return (loss,) + output if loss is not None else output
365
+
366
+ return CausalLMOutputWithPast(
367
+ loss=loss,
368
+ logits=logits,
369
+ past_key_values=outputs.past_key_values,
370
+ hidden_states=outputs.hidden_states,
371
+ attentions=outputs.attentions,
372
+ )
models/transformer/configuration_transformer.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class TransformerConfig(PretrainedConfig):
10
+
11
+ model_type = 'transformer'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ hidden_size: int = 2048,
17
+ num_hidden_layers: int = 24,
18
+ num_heads: int = 32,
19
+ num_kv_heads: Optional[int] = None,
20
+ qkv_bias: bool = False,
21
+ qk_norm: bool = False,
22
+ window_size: Optional[int] = None,
23
+ rope_theta: Optional[float] = 10000.,
24
+ max_position_embeddings: int = 2048,
25
+ hidden_ratio: Optional[int] = 4,
26
+ intermediate_size: Optional[int] = None,
27
+ hidden_act: str = "swish",
28
+ initializer_range: float = 0.02,
29
+ elementwise_affine: Optional[bool] = True,
30
+ norm_eps: float = 1e-6,
31
+ use_cache: bool = True,
32
+ pad_token_id: Optional[int] = None,
33
+ bos_token_id: int = 1,
34
+ eos_token_id: int = 2,
35
+ tie_word_embeddings: bool = False,
36
+ fuse_norm: bool = True,
37
+ fuse_swiglu: bool = True,
38
+ fuse_cross_entropy: bool = True,
39
+ fuse_linear_cross_entropy: bool = False,
40
+ use_l2warp: bool = False,
41
+ vocab_size: int = 32000,
42
+ **kwargs,
43
+ ):
44
+ self.hidden_size = hidden_size
45
+ self.num_hidden_layers = num_hidden_layers
46
+ self.num_heads = num_heads
47
+ self.num_kv_heads = num_kv_heads
48
+ self.qkv_bias = qkv_bias
49
+ self.qk_norm = qk_norm
50
+ self.window_size = window_size
51
+ self.rope_theta = rope_theta
52
+ self.max_position_embeddings = max_position_embeddings
53
+
54
+ self.hidden_ratio = hidden_ratio
55
+ self.intermediate_size = intermediate_size
56
+ self.hidden_act = hidden_act
57
+
58
+ self.initializer_range = initializer_range
59
+ self.elementwise_affine = elementwise_affine
60
+ self.norm_eps = norm_eps
61
+ self.use_cache = use_cache
62
+
63
+ self.fuse_norm = fuse_norm
64
+ self.fuse_swiglu = fuse_swiglu
65
+ self.fuse_cross_entropy = fuse_cross_entropy
66
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
67
+ self.use_l2warp = use_l2warp
68
+ self.vocab_size = vocab_size
69
+
70
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
71
+ raise ValueError(
72
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
73
+ )
74
+ if fuse_linear_cross_entropy:
75
+ warnings.warn(
76
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
77
+ "at the potential cost of reduced precision. "
78
+ "If you observe issues like loss divergence, consider disabling this setting."
79
+ )
80
+
81
+ super().__init__(
82
+ pad_token_id=pad_token_id,
83
+ bos_token_id=bos_token_id,
84
+ eos_token_id=eos_token_id,
85
+ tie_word_embeddings=tie_word_embeddings,
86
+ **kwargs,
87
+ )
models/transformer/modeling_transformer.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.models.transformer.configuration_transformer import TransformerConfig
18
+ from fla.models.utils import Cache, FLAGenerationMixin
19
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
20
+ from fla.modules import GatedMLP as TransformerMLP
21
+ from fla.modules import RMSNorm
22
+ from fla.modules.l2warp import l2_warp
23
+
24
+ if TYPE_CHECKING:
25
+ from transformers.processing_utils import Unpack
26
+
27
+
28
+ try:
29
+ from transformers.modeling_layers import GradientCheckpointingLayer
30
+ except ImportError:
31
+ from fla.models.modeling_layers import GradientCheckpointingLayer
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ class TransformerBlock(GradientCheckpointingLayer):
37
+
38
+ def __init__(self, config: TransformerConfig, layer_idx: int):
39
+ super().__init__()
40
+
41
+ self.config = config
42
+ self.layer_idx = layer_idx
43
+
44
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
45
+ self.attn = Attention(
46
+ hidden_size=config.hidden_size,
47
+ num_heads=config.num_heads,
48
+ num_kv_heads=config.num_kv_heads,
49
+ qkv_bias=config.qkv_bias,
50
+ qk_norm=config.qk_norm,
51
+ window_size=config.window_size,
52
+ rope_theta=config.rope_theta,
53
+ max_position_embeddings=config.max_position_embeddings,
54
+ layer_idx=layer_idx
55
+ )
56
+
57
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
58
+ self.mlp = TransformerMLP(
59
+ hidden_size=config.hidden_size,
60
+ hidden_ratio=config.hidden_ratio,
61
+ intermediate_size=config.intermediate_size,
62
+ hidden_act=config.hidden_act,
63
+ fuse_swiglu=config.fuse_swiglu
64
+ )
65
+
66
+ def forward(
67
+ self,
68
+ hidden_states: torch.Tensor,
69
+ attention_mask: Optional[torch.Tensor] = None,
70
+ past_key_values: Optional[Tuple[torch.Tensor]] = None,
71
+ output_attentions: Optional[bool] = False,
72
+ use_cache: Optional[bool] = False,
73
+ **kwargs: Unpack[Any]
74
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
75
+
76
+ residual = hidden_states
77
+ hidden_states = self.attn_norm(hidden_states)
78
+ hidden_states, attentions, past_key_values = self.attn(
79
+ hidden_states=hidden_states,
80
+ attention_mask=attention_mask,
81
+ past_key_values=past_key_values,
82
+ use_cache=use_cache,
83
+ output_attentions=output_attentions,
84
+ **kwargs
85
+ )
86
+ if self.config.fuse_norm:
87
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
88
+ else:
89
+ hidden_states = residual + hidden_states
90
+ residual = hidden_states
91
+ hidden_states = self.mlp_norm(hidden_states)
92
+ hidden_states = self.mlp(hidden_states, **kwargs)
93
+ hidden_states = residual + hidden_states
94
+
95
+ outputs = (hidden_states,)
96
+
97
+ if output_attentions:
98
+ outputs += (attentions,)
99
+
100
+ if use_cache:
101
+ outputs += (past_key_values,)
102
+
103
+ return outputs
104
+
105
+
106
+ class TransformerPreTrainedModel(PreTrainedModel):
107
+
108
+ config_class = TransformerConfig
109
+ base_model_prefix = 'model'
110
+ supports_gradient_checkpointing = True
111
+ _no_split_modules = ['TransformerBlock']
112
+ _supports_cache_class = True
113
+
114
+ def __init__(self, *inputs, **kwargs):
115
+ super().__init__(*inputs, **kwargs)
116
+
117
+ def _init_weights(
118
+ self,
119
+ module: nn.Module,
120
+ rescale_prenorm_residual: bool = False,
121
+ num_residuals_per_layer: int = 2,
122
+ ):
123
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
124
+ # Slightly different from the TF version which uses truncated_normal for initialization
125
+ # cf https://github.com/pytorch/pytorch/pull/5617
126
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
127
+ if module.bias is not None:
128
+ nn.init.zeros_(module.bias)
129
+ elif isinstance(module, nn.Embedding):
130
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
131
+ elif hasattr(module, 'reset_parameters'):
132
+ module.reset_parameters()
133
+
134
+ if rescale_prenorm_residual:
135
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
136
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
137
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
138
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
139
+ #
140
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
141
+ p = None
142
+ if hasattr(module, 'o_proj'):
143
+ p = module.o_proj.weight
144
+ elif hasattr(module, 'down_proj'):
145
+ p = module.down_proj.weight
146
+ if p is not None:
147
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
148
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
149
+ # We need to reinit p since this code could be called multiple times
150
+ # Having just p *= scale would repeatedly scale it down
151
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
152
+ with torch.no_grad():
153
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
154
+
155
+
156
+ class TransformerModel(TransformerPreTrainedModel):
157
+
158
+ def __init__(
159
+ self,
160
+ config: TransformerConfig
161
+ ) -> TransformerModel:
162
+ super().__init__(config)
163
+ self.padding_idx = config.pad_token_id
164
+ self.vocab_size = config.vocab_size
165
+
166
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
167
+ self.layers = nn.ModuleList([TransformerBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
168
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
169
+
170
+ self.gradient_checkpointing = False
171
+
172
+ self.post_init()
173
+
174
+ def get_input_embeddings(self):
175
+ return self.embeddings
176
+
177
+ def set_input_embeddings(self, value):
178
+ self.embeddings = value
179
+
180
+ def forward(
181
+ self,
182
+ input_ids: Optional[torch.LongTensor] = None,
183
+ attention_mask: Optional[torch.Tensor] = None,
184
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
185
+ inputs_embeds: Optional[torch.FloatTensor] = None,
186
+ use_cache: Optional[bool] = None,
187
+ output_attentions: Optional[bool] = None,
188
+ output_hidden_states: Optional[bool] = None,
189
+ return_dict: Optional[bool] = None,
190
+ **kwargs: Unpack[Any]
191
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
192
+ if output_attentions:
193
+ warnings.warn(
194
+ "`TransformerModel` does not support output attention weights now, so `output_attentions` is set to `False`."
195
+ )
196
+ output_attentions = False
197
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
198
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
199
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
200
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
201
+
202
+ # retrieve input_ids and inputs_embeds
203
+ if input_ids is not None and inputs_embeds is not None:
204
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
205
+ elif input_ids is None and inputs_embeds is None:
206
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
207
+
208
+ if use_cache and not isinstance(past_key_values, Cache):
209
+ past_key_values = Cache.from_legacy_cache(past_key_values)
210
+
211
+ if inputs_embeds is None:
212
+ inputs_embeds = self.embeddings(input_ids)
213
+
214
+ # embed positions
215
+ hidden_states = inputs_embeds
216
+
217
+ all_hidden_states = () if output_hidden_states else None
218
+ all_attns = () if output_attentions else None
219
+ next_cache = None
220
+
221
+ for layer in self.layers:
222
+ if output_hidden_states:
223
+ all_hidden_states += (hidden_states,)
224
+
225
+ layer_outputs = layer(
226
+ hidden_states,
227
+ attention_mask=attention_mask,
228
+ past_key_values=past_key_values,
229
+ output_attentions=output_attentions,
230
+ use_cache=use_cache,
231
+ **kwargs
232
+ )
233
+
234
+ hidden_states = layer_outputs[0]
235
+
236
+ if use_cache:
237
+ next_cache = layer_outputs[2 if output_attentions else 1]
238
+
239
+ if output_attentions:
240
+ all_attns += (layer_outputs[1],)
241
+
242
+ hidden_states = self.norm(hidden_states)
243
+
244
+ # add hidden states from the last decoder layer
245
+ if output_hidden_states:
246
+ all_hidden_states += (hidden_states,)
247
+
248
+ if not return_dict:
249
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_attns] if v is not None)
250
+
251
+ return BaseModelOutputWithPast(
252
+ last_hidden_state=hidden_states,
253
+ past_key_values=next_cache,
254
+ hidden_states=all_hidden_states,
255
+ attentions=all_attns
256
+ )
257
+
258
+
259
+ class TransformerForCausalLM(TransformerPreTrainedModel, FLAGenerationMixin):
260
+
261
+ _tied_weights_keys = ["lm_head.weight"]
262
+
263
+ def __init__(self, config):
264
+ super().__init__(config)
265
+ self.model = TransformerModel(config)
266
+ self.vocab_size = config.vocab_size
267
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
268
+ self.criterion = None
269
+
270
+ # Initialize weights and apply final processing
271
+ self.post_init()
272
+
273
+ def get_input_embeddings(self):
274
+ return self.model.embeddings
275
+
276
+ def set_input_embeddings(self, value):
277
+ self.model.embeddings = value
278
+
279
+ def get_output_embeddings(self):
280
+ return self.lm_head
281
+
282
+ def set_output_embeddings(self, new_embeddings):
283
+ self.lm_head = new_embeddings
284
+
285
+ def set_decoder(self, decoder):
286
+ self.model = decoder
287
+
288
+ def get_decoder(self):
289
+ return self.model
290
+
291
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
292
+ def forward(
293
+ self,
294
+ input_ids: torch.LongTensor = None,
295
+ attention_mask: Optional[torch.Tensor] = None,
296
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
297
+ inputs_embeds: Optional[torch.FloatTensor] = None,
298
+ labels: Optional[torch.LongTensor] = None,
299
+ use_cache: Optional[bool] = None,
300
+ output_attentions: Optional[bool] = None,
301
+ output_hidden_states: Optional[bool] = None,
302
+ return_dict: Optional[bool] = None,
303
+ logits_to_keep: Optional[int] = 0,
304
+ **kwargs: Unpack[Any]
305
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
306
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
307
+ output_hidden_states = (
308
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
309
+ )
310
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
311
+
312
+ outputs = self.model(
313
+ input_ids=input_ids,
314
+ attention_mask=attention_mask,
315
+ past_key_values=past_key_values,
316
+ inputs_embeds=inputs_embeds,
317
+ use_cache=use_cache,
318
+ output_attentions=output_attentions,
319
+ output_hidden_states=output_hidden_states,
320
+ return_dict=return_dict,
321
+ **kwargs
322
+ )
323
+
324
+ hidden_states = outputs[0]
325
+
326
+ logits = None if self.config.fuse_linear_cross_entropy else self.lm_head(hidden_states[:, -logits_to_keep:])
327
+
328
+ loss = None
329
+ if labels is not None:
330
+ if getattr(self, 'criterion', None) is None:
331
+ if self.config.fuse_linear_cross_entropy:
332
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
333
+ elif self.config.fuse_cross_entropy:
334
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
335
+ else:
336
+ criterion = nn.CrossEntropyLoss()
337
+ else:
338
+ criterion = self.criterion
339
+ # Enable model parallelism
340
+ labels = labels.to(hidden_states.device)
341
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
342
+ if self.config.fuse_linear_cross_entropy:
343
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
344
+ else:
345
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
346
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
347
+
348
+ if not return_dict:
349
+ output = (logits,) + outputs[1:]
350
+ return (loss,) + output if loss is not None else output
351
+
352
+ return CausalLMOutputWithPast(
353
+ loss=loss,
354
+ logits=logits,
355
+ past_key_values=outputs.past_key_values,
356
+ hidden_states=outputs.hidden_states,
357
+ attentions=outputs.attentions,
358
+ )
modules/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from fla.modules.convolution import ImplicitLongConvolution, LongConvolution, ShortConvolution
4
+ from fla.modules.fused_bitlinear import BitLinear, FusedBitLinear
5
+ from fla.modules.fused_cross_entropy import FusedCrossEntropyLoss
6
+ from fla.modules.fused_kl_div import FusedKLDivLoss
7
+ from fla.modules.fused_linear_cross_entropy import FusedLinearCrossEntropyLoss
8
+ from fla.modules.fused_norm_gate import (
9
+ FusedLayerNormGated,
10
+ FusedLayerNormSwishGate,
11
+ FusedLayerNormSwishGateLinear,
12
+ FusedRMSNormGated,
13
+ FusedRMSNormSwishGate,
14
+ FusedRMSNormSwishGateLinear
15
+ )
16
+ from fla.modules.l2norm import L2Norm
17
+ from fla.modules.layernorm import GroupNorm, GroupNormLinear, LayerNorm, LayerNormLinear, RMSNorm, RMSNormLinear
18
+ from fla.modules.mlp import GatedMLP
19
+ from fla.modules.rotary import RotaryEmbedding
20
+ from fla.modules.token_shift import TokenShift
21
+
22
+ __all__ = [
23
+ 'ImplicitLongConvolution', 'LongConvolution', 'ShortConvolution',
24
+ 'BitLinear', 'FusedBitLinear',
25
+ 'FusedCrossEntropyLoss', 'FusedLinearCrossEntropyLoss', 'FusedKLDivLoss',
26
+ 'L2Norm',
27
+ 'GroupNorm', 'GroupNormLinear', 'LayerNorm', 'LayerNormLinear', 'RMSNorm', 'RMSNormLinear',
28
+ 'FusedLayerNormGated', 'FusedLayerNormSwishGate', 'FusedLayerNormSwishGateLinear',
29
+ 'FusedRMSNormGated', 'FusedRMSNormSwishGate', 'FusedRMSNormSwishGateLinear',
30
+ 'GatedMLP',
31
+ 'RotaryEmbedding',
32
+ 'TokenShift'
33
+ ]
modules/activations.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Tri Dao, Yu Zhang, Songlin Yang.
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+ import triton
7
+ import triton.language as tl
8
+
9
+ from fla.ops.utils.op import exp, log
10
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, autotune_cache_kwargs, input_guard, is_amd
11
+
12
+ try:
13
+ from torch.distributed.tensor import DTensor
14
+ except (ImportError, AttributeError):
15
+ DTensor = None
16
+
17
+ NUM_WARPS_AUTOTUNE = [1, 2, 4, 8, 16] if is_amd else [1, 2, 4, 8, 16, 32]
18
+
19
+
20
+ @triton.autotune(
21
+ configs=[
22
+ triton.Config({'B': bs}, num_warps=num_warps)
23
+ for bs in [512, 1024, 2048, 4096, 8192]
24
+ for num_warps in NUM_WARPS_AUTOTUNE
25
+ ],
26
+ key=['D'],
27
+ **autotune_cache_kwargs
28
+ )
29
+ @triton.jit(do_not_specialize=['T'])
30
+ def sigmoid_fwd_kernel(
31
+ x, y,
32
+ T,
33
+ B: tl.constexpr,
34
+ D: tl.constexpr
35
+ ):
36
+ pid = tl.program_id(0)
37
+ offs = pid * B + tl.arange(0, B)
38
+ mask = offs < T
39
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
40
+ y_val = 1.0 / (1.0 + exp(-x_val))
41
+ tl.store(y + offs, y_val.to(y.dtype.element_ty), mask=mask)
42
+
43
+
44
+ @triton.autotune(
45
+ configs=[
46
+ triton.Config({'B': bs}, num_warps=num_warps)
47
+ for bs in [512, 1024, 2048, 4096, 8192]
48
+ for num_warps in NUM_WARPS_AUTOTUNE
49
+ ],
50
+ key=['D'],
51
+ **autotune_cache_kwargs
52
+ )
53
+ @triton.jit(do_not_specialize=['T'])
54
+ def sigmoid_bwd_kernel(
55
+ x, dy, dx,
56
+ T,
57
+ B: tl.constexpr,
58
+ D: tl.constexpr
59
+ ):
60
+ pid = tl.program_id(0)
61
+ offs = pid * B + tl.arange(0, B)
62
+ mask = offs < T
63
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
64
+ g_val = tl.load(dy + offs, mask=mask, other=0.).to(tl.float32)
65
+ s = 1.0 / (1.0 + exp(-x_val))
66
+ dx_val = g_val * s * (1.0 - s)
67
+ tl.store(dx + offs, dx_val.to(dx.dtype.element_ty), mask=mask)
68
+
69
+
70
+ def sigmoid_fwd(x: torch.Tensor) -> torch.Tensor:
71
+ T, D = x.numel(), x.shape[-1]
72
+ y = torch.empty_like(x)
73
+ sigmoid_fwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, y, T=T, D=D)
74
+ return y
75
+
76
+
77
+ def sigmoid_bwd(x: torch.Tensor, dy: torch.Tensor) -> torch.Tensor:
78
+ T, D = x.numel(), x.shape[-1]
79
+ dx = torch.empty_like(x)
80
+ sigmoid_bwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, dy, dx, T=T, D=D)
81
+ return dx
82
+
83
+
84
+ class SigmoidFunction(torch.autograd.Function):
85
+
86
+ @staticmethod
87
+ def forward(ctx, x):
88
+ ctx.save_for_backward(x)
89
+ return sigmoid_fwd(x)
90
+
91
+ @staticmethod
92
+ def backward(ctx, dout):
93
+ x, = ctx.saved_tensors
94
+ return sigmoid_bwd(x, dout)
95
+
96
+
97
+ sigmoid = SigmoidFunction.apply
98
+
99
+
100
+ @triton.autotune(
101
+ configs=[
102
+ triton.Config({'B': bs}, num_warps=num_warps)
103
+ for bs in [512, 1024, 2048, 4096, 8192]
104
+ for num_warps in NUM_WARPS_AUTOTUNE
105
+ ],
106
+ key=['D'],
107
+ **autotune_cache_kwargs
108
+ )
109
+ @triton.jit(do_not_specialize=['T'])
110
+ def logsigmoid_fwd_kernel(
111
+ x,
112
+ y,
113
+ temperature,
114
+ T,
115
+ B: tl.constexpr,
116
+ D: tl.constexpr
117
+ ):
118
+ i = tl.program_id(0)
119
+ o_i = i * B + tl.arange(0, B)
120
+ m_i = o_i < T
121
+
122
+ b_x = tl.load(x + o_i, mask=m_i, other=0.).to(tl.float32)
123
+ b_m = tl.minimum(0., b_x)
124
+ b_z = 1. + exp(-tl.abs(b_x))
125
+ b_y = (b_m - log(b_z)) / temperature
126
+ tl.store(y + o_i, b_y.to(y.dtype.element_ty), mask=m_i)
127
+
128
+
129
+ @triton.autotune(
130
+ configs=[
131
+ triton.Config({'B': bs}, num_warps=num_warps)
132
+ for bs in [512, 1024, 2048, 4096, 8192]
133
+ for num_warps in NUM_WARPS_AUTOTUNE
134
+ ],
135
+ key=['D'],
136
+ **autotune_cache_kwargs
137
+ )
138
+ @triton.jit(do_not_specialize=['T'])
139
+ def logsigmoid_bwd_kernel(
140
+ x,
141
+ dx,
142
+ dy,
143
+ temperature,
144
+ T,
145
+ B: tl.constexpr,
146
+ D: tl.constexpr
147
+ ):
148
+ i = tl.program_id(0)
149
+ o_i = i * B + tl.arange(0, B)
150
+ m_i = o_i < T
151
+
152
+ b_x = tl.load(x + o_i, mask=m_i, other=0.).to(tl.float32)
153
+ b_dy = tl.load(dy + o_i, mask=m_i, other=0.).to(tl.float32)
154
+ b_dx = b_dy * ((1. - tl.sigmoid(b_x)) / temperature)
155
+ tl.store(dx + o_i, b_dx.to(dx.dtype.element_ty), mask=m_i)
156
+
157
+
158
+ def logsigmoid_fwd(x: torch.Tensor, temperature: float = 1.) -> torch.Tensor:
159
+ T, D = x.numel(), x.shape[-1]
160
+ y = torch.empty_like(x)
161
+ logsigmoid_fwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](
162
+ x=x,
163
+ y=y,
164
+ temperature=temperature,
165
+ T=T,
166
+ D=D,
167
+ )
168
+ return y
169
+
170
+
171
+ def logsigmoid_bwd(x: torch.Tensor, dy: torch.Tensor, temperature: float = 1.) -> torch.Tensor:
172
+ T, D = x.numel(), x.shape[-1]
173
+ dx = torch.empty_like(x)
174
+ logsigmoid_bwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](
175
+ x=x,
176
+ dx=dx,
177
+ dy=dy,
178
+ temperature=temperature,
179
+ T=T,
180
+ D=D,
181
+ )
182
+ return dx
183
+
184
+
185
+ class LogSigmoidFunction(torch.autograd.Function):
186
+
187
+ @staticmethod
188
+ @input_guard
189
+ def forward(ctx, x, temperature):
190
+ ctx.save_for_backward(x,)
191
+ ctx.temperature = temperature
192
+ return logsigmoid_fwd(x, temperature)
193
+
194
+ @staticmethod
195
+ @input_guard
196
+ def backward(ctx, dy):
197
+ x, = ctx.saved_tensors
198
+ return logsigmoid_bwd(x, dy, ctx.temperature), None
199
+
200
+
201
+ def logsigmoid(x: torch.Tensor, temperature: float = 1.) -> torch.Tensor:
202
+ return LogSigmoidFunction.apply(x, temperature)
203
+
204
+
205
+ @triton.autotune(
206
+ configs=[
207
+ triton.Config({'B': bs}, num_warps=num_warps)
208
+ for bs in [512, 1024, 2048, 4096, 8192]
209
+ for num_warps in NUM_WARPS_AUTOTUNE
210
+ ],
211
+ key=['D'],
212
+ **autotune_cache_kwargs
213
+ )
214
+ @triton.jit(do_not_specialize=['T'])
215
+ def swish_fwd_kernel(
216
+ x, y,
217
+ T,
218
+ B: tl.constexpr,
219
+ D: tl.constexpr
220
+ ):
221
+ pid = tl.program_id(0)
222
+ offs = pid * B + tl.arange(0, B)
223
+ mask = offs < T
224
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
225
+ s = 1.0 / (1.0 + exp(-x_val))
226
+ y_val = x_val * s
227
+ tl.store(y + offs, y_val.to(y.dtype.element_ty), mask=mask)
228
+
229
+
230
+ @triton.autotune(
231
+ configs=[
232
+ triton.Config({'B': bs}, num_warps=num_warps)
233
+ for bs in [512, 1024, 2048, 4096, 8192]
234
+ for num_warps in NUM_WARPS_AUTOTUNE
235
+ ],
236
+ key=['D'],
237
+ **autotune_cache_kwargs
238
+ )
239
+ @triton.jit(do_not_specialize=['T'])
240
+ def swish_bwd_kernel(
241
+ x, dy, dx,
242
+ T,
243
+ B: tl.constexpr,
244
+ D: tl.constexpr
245
+ ):
246
+ pid = tl.program_id(0)
247
+ offs = pid * B + tl.arange(0, B)
248
+ mask = offs < T
249
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
250
+ g_val = tl.load(dy + offs, mask=mask, other=0.).to(tl.float32)
251
+ s = 1.0 / (1.0 + exp(-x_val))
252
+ dx_val = g_val * s * (1.0 + x_val * (1.0 - s))
253
+ tl.store(dx + offs, dx_val.to(dx.dtype.element_ty), mask=mask)
254
+
255
+
256
+ def swish_fwd(x: torch.Tensor) -> torch.Tensor:
257
+ T, D = x.numel(), x.shape[-1]
258
+ y = torch.empty_like(x)
259
+ swish_fwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, y, T=T, D=D)
260
+ return y
261
+
262
+
263
+ def swish_bwd(x: torch.Tensor, dy: torch.Tensor) -> torch.Tensor:
264
+ T, D = x.numel(), x.shape[-1]
265
+ dx = torch.empty_like(x)
266
+ swish_bwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, dy, dx, T=T, D=D)
267
+ return dx
268
+
269
+
270
+ class SwishFunction(torch.autograd.Function):
271
+
272
+ @staticmethod
273
+ def forward(ctx, x):
274
+ ctx.save_for_backward(x)
275
+ return swish_fwd(x)
276
+
277
+ @staticmethod
278
+ def backward(ctx, dout):
279
+ x, = ctx.saved_tensors
280
+ return swish_bwd(x, dout)
281
+
282
+
283
+ swish = SwishFunction.apply
284
+
285
+ # 1/sqrt(2*pi)-> 0.3989423
286
+ # 1/sqrt(2) -> 0.70710678
287
+ # sqrt(2/pi) -> 0.79788456
288
+
289
+
290
+ # this function is tanh approximation of gelu
291
+ # actual gelu is:
292
+ # x * 0.5 * (1.0 + torch.erf(x * 0.70710678))
293
+ @torch.compile
294
+ def bias_gelu(y, bias):
295
+ x = bias + y
296
+ return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=y.dtype)
297
+
298
+
299
+ # gradient of tanh approximation of gelu
300
+ # gradient of actual gelu is:
301
+ # 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x)
302
+ @torch.compile
303
+ def bias_gelu_bwd(g, y, bias):
304
+ """Assume that y has shape (B, D=D) and bias has shape (D)"""
305
+ x = bias + y
306
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
307
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
308
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (
309
+ 1 + tanh_out
310
+ )
311
+ grad_y = ff * g
312
+ return grad_y.to(dtype=y.dtype), grad_y.sum(dim=(0), dtype=bias.dtype)
313
+
314
+
315
+ class GeLUFunction(torch.autograd.Function):
316
+
317
+ @staticmethod
318
+ # bias is an optional argument
319
+ def forward(ctx, input, bias):
320
+ ctx.save_for_backward(input, bias)
321
+ return bias_gelu(input, bias)
322
+
323
+ @staticmethod
324
+ def backward(ctx, grad_output):
325
+ input, bias = ctx.saved_tensors
326
+ tmp = bias_gelu_bwd(grad_output, input, bias)
327
+ return tmp, tmp
328
+
329
+
330
+ bias_gelu_impl = GeLUFunction.apply
331
+
332
+
333
+ # this function is tanh approximation of gelu
334
+ # actual gelu is:
335
+ # x * 0.5 * (1.0 + torch.erf(x * 0.70710678))
336
+ @torch.compile
337
+ def gelu_fwd(x):
338
+ return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=x.dtype)
339
+
340
+
341
+ # gradient of tanh approximation of gelu
342
+ # gradient of actual gelu is:
343
+ # 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x)
344
+ @torch.compile
345
+ def gelu_bwd(g, x):
346
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
347
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
348
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (
349
+ 1 + tanh_out
350
+ )
351
+ return (ff * g).to(dtype=x.dtype)
352
+
353
+
354
+ class FastGeLUFunction(torch.autograd.Function):
355
+ @staticmethod
356
+ # bias is an optional argument
357
+ def forward(ctx, input):
358
+ ctx.save_for_backward(input)
359
+ return gelu_fwd(input)
360
+
361
+ @staticmethod
362
+ def backward(ctx, grad_output):
363
+ (input,) = ctx.saved_tensors
364
+ tmp = gelu_bwd(grad_output, input)
365
+ return tmp
366
+
367
+
368
+ fast_gelu_impl = FastGeLUFunction.apply
369
+
370
+
371
+ @torch.compile
372
+ def relu_bwd(g, x):
373
+ return torch.where(x >= 0, g, 0.0).to(dtype=x.dtype)
374
+
375
+
376
+ @torch.compile
377
+ def sqrelu_fwd(x):
378
+ r = F.relu(x.float())
379
+ return (r * r).to(dtype=x.dtype)
380
+
381
+
382
+ @torch.compile
383
+ def sqrelu_bwd(g, x):
384
+ return (2.0 * g * F.relu(x.float())).to(dtype=x.dtype)
385
+
386
+
387
+ class SquaredReLUFunction(torch.autograd.Function):
388
+
389
+ @staticmethod
390
+ def forward(ctx, input):
391
+ ctx.save_for_backward(input)
392
+ return sqrelu_fwd(input)
393
+
394
+ @staticmethod
395
+ def backward(ctx, grad_output):
396
+ input, = ctx.saved_tensors
397
+ return sqrelu_bwd(grad_output, input)
398
+
399
+
400
+ sqrelu = SquaredReLUFunction.apply
401
+
402
+
403
+ @triton.autotune(
404
+ configs=[
405
+ triton.Config({'B': bs}, num_warps=num_warps)
406
+ for bs in [512, 1024, 2048, 4096, 8192]
407
+ for num_warps in NUM_WARPS_AUTOTUNE
408
+ ],
409
+ key=['D'],
410
+ **autotune_cache_kwargs
411
+ )
412
+ @triton.jit(do_not_specialize=['T'])
413
+ def swiglu_fwd_kernel(
414
+ x, y, z,
415
+ T,
416
+ B: tl.constexpr,
417
+ D: tl.constexpr
418
+ ):
419
+ pid = tl.program_id(0)
420
+ offs = pid * B + tl.arange(0, B)
421
+ mask = offs < T
422
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
423
+ y_val = tl.load(y + offs, mask=mask, other=0.).to(tl.float32)
424
+ s = 1.0 / (1.0 + exp(-x_val))
425
+ z_val = x_val * s * y_val
426
+ tl.store(z + offs, z_val.to(z.dtype.element_ty), mask=mask)
427
+
428
+
429
+ @triton.heuristics({
430
+ 'HAS_WEIGHT': lambda args: args['z'] is not None,
431
+ })
432
+ @triton.autotune(
433
+ configs=[
434
+ triton.Config({'B': bs}, num_warps=num_warps)
435
+ for bs in [512, 1024, 2048, 4096, 8192]
436
+ for num_warps in NUM_WARPS_AUTOTUNE
437
+ ],
438
+ key=['D'],
439
+ **autotune_cache_kwargs
440
+ )
441
+ @triton.jit(do_not_specialize=['T'])
442
+ def swiglu_fwdbwd_kernel(
443
+ x, y, g, dx, dy, z,
444
+ T,
445
+ B: tl.constexpr,
446
+ D: tl.constexpr,
447
+ HAS_WEIGHT: tl.constexpr
448
+ ):
449
+ pid = tl.program_id(0)
450
+ offs = pid * B + tl.arange(0, B)
451
+ mask = offs < T
452
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
453
+ y_val = tl.load(y + offs, mask=mask, other=0.).to(tl.float32)
454
+ g_val = tl.load(g + offs, mask=mask, other=0.).to(tl.float32)
455
+
456
+ s = 1.0 / (1.0 + exp(-x_val))
457
+ x_s = x_val * s
458
+ dx_val = g_val * s * (1.0 + x_val * (1.0 - s)) * y_val
459
+ dy_val = g_val * x_s
460
+
461
+ tl.store(dx + offs, dx_val.to(dx.dtype.element_ty), mask=mask)
462
+ tl.store(dy + offs, dy_val.to(dy.dtype.element_ty), mask=mask)
463
+ if HAS_WEIGHT:
464
+ z_val = x_s * y_val
465
+ tl.store(z + offs, z_val.to(z.dtype.element_ty), mask=mask)
466
+
467
+
468
+ def swiglu_fwd(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
469
+ T, D = x.numel(), x.shape[-1]
470
+ z = torch.empty_like(x)
471
+ swiglu_fwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, y, z, T=T, D=D)
472
+ return z
473
+
474
+
475
+ def swiglu_fwdbwd(x: torch.Tensor, y: torch.Tensor, g: torch.Tensor, use_weight: bool = False):
476
+ T, D = x.numel(), x.shape[-1]
477
+ dx = torch.empty_like(x)
478
+ dy = torch.empty_like(x)
479
+ if use_weight:
480
+ # recomputed for weight grad
481
+ z = torch.empty_like(x)
482
+ else:
483
+ z = None
484
+ swiglu_fwdbwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, y, g, dx, dy, z, T=T, D=D)
485
+ if use_weight:
486
+ return dx, dy, z
487
+ return dx, dy
488
+
489
+
490
+ class SwiGLUFunction(torch.autograd.Function):
491
+ r"""
492
+ Swish-Gated Linear Unit (SwiGLU) function.
493
+
494
+ .. math::
495
+ \text{SwiGLU}(x, y) = swish(x) * y = \frac{x}{1 + \exp(-x)} * y
496
+ """
497
+
498
+ @staticmethod
499
+ def forward(ctx, x, y):
500
+ ctx.save_for_backward(x, y)
501
+ return swiglu_fwd(x, y)
502
+
503
+ @staticmethod
504
+ def backward(ctx, dout):
505
+ x, y = ctx.saved_tensors
506
+ return swiglu_fwdbwd(x, y, dout)
507
+
508
+
509
+ class SwiGLULinearFunction(torch.autograd.Function):
510
+ r"""
511
+ Swish-Gated Linear Unit (SwiGLU) function followed by a linear transformation.
512
+
513
+ .. math::
514
+ \text{SwiGLULinear}(x, y, W, b) = (swish(x) * y) W + b
515
+
516
+ This simple wrap discards the intermediate results of SwiGLU(x, y) to save memory.
517
+ """
518
+
519
+ @staticmethod
520
+ @autocast_custom_fwd
521
+ def forward(ctx, x, y, weight, bias):
522
+ z = swiglu_fwd(x, y)
523
+ out = F.linear(z, weight, bias)
524
+ # We don't store z, will be recomputed in the backward pass to save memory
525
+ ctx.save_for_backward(x, y, weight)
526
+ ctx.linear_bias_is_none = bias is None
527
+ return out
528
+
529
+ @staticmethod
530
+ @autocast_custom_bwd
531
+ def backward(ctx, dout, *args):
532
+ x, y, weight = ctx.saved_tensors
533
+ dout = dout.reshape(-1, dout.shape[-1])
534
+ dz = F.linear(dout, weight.t()).view_as(x)
535
+ dx, dy, z = swiglu_fwdbwd(x, y, dz, use_weight=True)
536
+ dlinear_weight = torch.einsum("bo,bi->oi", dout, z.reshape(-1, z.shape[-1]))
537
+ dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0)
538
+ return dx, dy, dlinear_weight, dlinear_bias
539
+
540
+
541
+ swiglu = SwiGLUFunction.apply
542
+
543
+
544
+ swiglu_linear = SwiGLULinearFunction.apply
545
+
546
+
547
+ ACT2FN = {
548
+ 'relu': F.relu,
549
+ 'sigmoid': sigmoid,
550
+ 'logsigmoid': logsigmoid,
551
+ 'silu': swish,
552
+ 'swish': swish,
553
+ 'sqrelu': sqrelu,
554
+ 'gelu': fast_gelu_impl,
555
+ 'bias_gelu': bias_gelu_impl,
556
+ }
modules/convolution.py ADDED
@@ -0,0 +1,1168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ import math
5
+ import warnings
6
+ from typing import Optional, Tuple
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ import triton
12
+ import triton.language as tl
13
+ from einops import rearrange
14
+
15
+ from fla.ops.utils import prepare_chunk_indices, prepare_sequence_ids
16
+ from fla.utils import autotune_cache_kwargs, get_multiprocessor_count, input_guard, is_amd
17
+
18
+ NUM_WARPS_AUTOTUNE = [2, 4, 8, 16] if is_amd else [4, 8, 16, 32]
19
+ STATIC_WARPS = 32 if not is_amd else 16
20
+
21
+
22
+ try:
23
+ from causal_conv1d import causal_conv1d_fn
24
+ from causal_conv1d import causal_conv1d_update as causal_conv1d_update_cuda
25
+ except ImportError:
26
+ causal_conv1d_fn = None
27
+ causal_conv1d_update_cuda = None
28
+
29
+
30
+ @triton.heuristics({
31
+ 'HAS_WEIGHT': lambda args: args['weight'] is not None,
32
+ 'HAS_BIAS': lambda args: args['bias'] is not None,
33
+ 'HAS_RESIDUAL': lambda args: args['residual'] is not None,
34
+ 'USE_INITIAL_STATE': lambda args: args['initial_state'] is not None,
35
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
36
+ })
37
+ @triton.autotune(
38
+ configs=[
39
+ triton.Config({'BD': BD}, num_warps=num_warps)
40
+ for BD in [16, 32, 64, 128]
41
+ for num_warps in NUM_WARPS_AUTOTUNE
42
+ ],
43
+ key=['D', 'W', 'NB'],
44
+ **autotune_cache_kwargs
45
+ )
46
+ @triton.jit
47
+ def causal_conv1d_fwd_kernel(
48
+ x,
49
+ y,
50
+ weight,
51
+ bias,
52
+ residual,
53
+ cu_seqlens,
54
+ initial_state,
55
+ chunk_indices,
56
+ B,
57
+ T,
58
+ D: tl.constexpr,
59
+ W: tl.constexpr,
60
+ BT: tl.constexpr,
61
+ BW: tl.constexpr,
62
+ BD: tl.constexpr,
63
+ NB: tl.constexpr,
64
+ ACTIVATION: tl.constexpr,
65
+ HAS_WEIGHT: tl.constexpr,
66
+ HAS_BIAS: tl.constexpr,
67
+ HAS_RESIDUAL: tl.constexpr,
68
+ USE_INITIAL_STATE: tl.constexpr,
69
+ IS_VARLEN: tl.constexpr,
70
+ ):
71
+ i_d, i_t, i_b = tl.program_id(0), tl.program_id(1), tl.program_id(2)
72
+
73
+ if IS_VARLEN:
74
+ 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)
75
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
76
+ T = eos - bos
77
+ else:
78
+ i_n = i_b
79
+ bos, eos = i_b * T, i_b * T + T
80
+
81
+ o_d = i_d * BD + tl.arange(0, BD)
82
+ o_w = tl.arange(0, BW) + W - BW
83
+ m_d = o_d < D
84
+ m_w = o_w >= 0
85
+
86
+ if HAS_WEIGHT:
87
+ # [BD, BW]
88
+ b_w = tl.load(weight + o_d[:, None] * W + o_w, mask=m_d[:, None] & m_w, other=0).to(tl.float32)
89
+
90
+ b_y = tl.zeros((BT, BD), dtype=tl.float32)
91
+ if not USE_INITIAL_STATE:
92
+ for i_w in tl.static_range(-W + 1, 1):
93
+ p_yi = tl.make_block_ptr(x + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
94
+ # [BT, BD]
95
+ b_yi = tl.load(p_yi, boundary_check=(0, 1)).to(tl.float32)
96
+ if HAS_WEIGHT:
97
+ b_yi *= tl.sum(b_w * (o_w == (i_w + W - 1)), 1)
98
+ b_y += b_yi
99
+ elif i_t * BT >= W:
100
+ # to make Triton compiler happy, we need to copy codes
101
+ for i_w in tl.static_range(-W + 1, 1):
102
+ p_yi = tl.make_block_ptr(x + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
103
+ # [BT, BD]
104
+ b_yi = tl.load(p_yi, boundary_check=(0, 1)).to(tl.float32)
105
+ if HAS_WEIGHT:
106
+ b_yi *= tl.sum(b_w * (o_w == (i_w + W - 1)), 1)
107
+ b_y += b_yi
108
+ else:
109
+ o_t = i_t * BT + tl.arange(0, BT)
110
+ for i_w in tl.static_range(-W + 1, 1):
111
+ o_x = o_t + i_w
112
+ m_x = ((o_x >= 0) & (o_x < T))[:, None] & m_d
113
+ m_c = ((o_x + W >= 0) & (o_x < 0))[:, None] & m_d
114
+
115
+ b_yi = tl.load(x + bos * D + o_x[:, None] * D + o_d, mask=m_x, other=0).to(tl.float32)
116
+
117
+ b_yi += tl.load(initial_state + i_n * D*W + o_d * W + (o_x + W)[:, None], mask=m_c, other=0).to(tl.float32)
118
+
119
+ if HAS_WEIGHT:
120
+ b_yi *= tl.sum(b_w * (o_w == (i_w + W - 1)), 1)
121
+ b_y += b_yi
122
+
123
+ if HAS_BIAS:
124
+ b_y += tl.load(bias + o_d, mask=m_d).to(tl.float32)
125
+
126
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
127
+ b_y = b_y * tl.sigmoid(b_y)
128
+
129
+ if HAS_RESIDUAL:
130
+ p_residual = tl.make_block_ptr(residual + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
131
+ b_residual = tl.load(p_residual, boundary_check=(0, 1))
132
+ b_y += b_residual
133
+
134
+ p_y = tl.make_block_ptr(y + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
135
+ tl.store(p_y, tl.cast(b_y, dtype=p_y.dtype.element_ty, fp_downcast_rounding='rtne'), boundary_check=(0, 1))
136
+
137
+
138
+ @triton.heuristics({
139
+ 'HAS_WEIGHT': lambda args: args['dw'] is not None,
140
+ 'HAS_BIAS': lambda args: args['db'] is not None,
141
+ 'USE_INITIAL_STATE': lambda args: args['dh0'] is not None,
142
+ 'USE_FINAL_STATE': lambda args: args['dht'] is not None,
143
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
144
+ })
145
+ @triton.autotune(
146
+ configs=[
147
+ triton.Config({'BD': BD}, num_warps=num_warps)
148
+ for BD in [16, 32, 64, 128]
149
+ for num_warps in [4, 8, 16, 32]
150
+ ],
151
+ key=['D', 'W', 'NB'],
152
+ **autotune_cache_kwargs
153
+ )
154
+ @triton.jit
155
+ def causal_conv1d_bwd_kernel(
156
+ x,
157
+ y,
158
+ weight,
159
+ initial_state,
160
+ dh0,
161
+ dht,
162
+ dy,
163
+ dx,
164
+ dw,
165
+ db,
166
+ cu_seqlens,
167
+ chunk_indices,
168
+ B,
169
+ T,
170
+ D: tl.constexpr,
171
+ W: tl.constexpr,
172
+ BT: tl.constexpr,
173
+ BW: tl.constexpr,
174
+ BD: tl.constexpr,
175
+ NB: tl.constexpr,
176
+ ACTIVATION: tl.constexpr,
177
+ HAS_WEIGHT: tl.constexpr,
178
+ HAS_BIAS: tl.constexpr,
179
+ USE_INITIAL_STATE: tl.constexpr,
180
+ USE_FINAL_STATE: tl.constexpr,
181
+ IS_VARLEN: tl.constexpr,
182
+ ):
183
+ i_d, i_t, i_b = tl.program_id(0), tl.program_id(1), tl.program_id(2)
184
+ if IS_VARLEN:
185
+ i_tg = i_t
186
+ 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)
187
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
188
+ T = eos - bos
189
+ else:
190
+ i_tg = i_b * tl.num_programs(1) + i_t
191
+ i_n = i_b
192
+ bos, eos = i_b * T, i_b * T + T
193
+
194
+ o_d = i_d * BD + tl.arange(0, BD)
195
+ o_w = tl.arange(0, BW) + W - BW
196
+ m_d = o_d < D
197
+ m_w = o_w >= 0
198
+
199
+ if HAS_WEIGHT:
200
+ p_x = tl.make_block_ptr(x + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
201
+ b_x = tl.load(p_x, boundary_check=(0, 1))
202
+ # [BD, BW]
203
+ b_w = tl.load(weight + o_d[:, None] * W + o_w, mask=m_d[:, None] & m_w, other=0)
204
+
205
+ b_dx = tl.zeros((BT, BD), dtype=tl.float32)
206
+ if HAS_BIAS:
207
+ b_db = tl.zeros((BD,), dtype=tl.float32)
208
+
209
+ if not USE_FINAL_STATE:
210
+ for i_w in tl.static_range(0, W):
211
+ p_dy = tl.make_block_ptr(dy + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
212
+ # [BT, BD]
213
+ b_dy = tl.load(p_dy, boundary_check=(0, 1)).to(tl.float32)
214
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
215
+ p_y = tl.make_block_ptr(y + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
216
+ b_y = tl.load(p_y, boundary_check=(0, 1)).to(tl.float32)
217
+ b_ys = tl.sigmoid(b_y)
218
+ b_dy = b_dy * b_ys * (1 + b_y * (1 - b_ys))
219
+ b_wdy = b_dy
220
+ if HAS_WEIGHT:
221
+ # [BT, BD]
222
+ b_wdy = b_wdy * tl.sum(b_w * (o_w == (W - i_w - 1)), 1)
223
+ # [BD]
224
+ b_dw = tl.sum(b_dy * b_x, 0)
225
+ tl.store(dw + i_tg * D*W + o_d * W + W - i_w - 1, b_dw.to(dw.dtype.element_ty), mask=m_d)
226
+ if HAS_BIAS and i_w == 0:
227
+ b_db += tl.sum(b_dy, 0)
228
+ b_dx += b_wdy
229
+ elif i_t * BT >= W:
230
+ # to make Triton compiler happy, we need to copy codes
231
+ for i_w in tl.static_range(0, W):
232
+ p_dy = tl.make_block_ptr(dy + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
233
+ # [BT, BD]
234
+ b_dy = tl.load(p_dy, boundary_check=(0, 1)).to(tl.float32)
235
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
236
+ p_y = tl.make_block_ptr(y + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
237
+ b_y = tl.load(p_y, boundary_check=(0, 1)).to(tl.float32)
238
+ b_ys = tl.sigmoid(b_y)
239
+ b_dy = b_dy * b_ys * (1 + b_y * (1 - b_ys))
240
+ b_wdy = b_dy
241
+ if HAS_WEIGHT:
242
+ # [BT, BD]
243
+ b_wdy = b_wdy * tl.sum(b_w * (o_w == (W - i_w - 1)), 1)
244
+ # [BD]
245
+ b_dw = tl.sum(b_dy * b_x, 0)
246
+ tl.store(dw + i_tg * D*W + o_d * W + W - i_w - 1, b_dw.to(dw.dtype.element_ty), mask=m_d)
247
+ if HAS_BIAS and i_w == 0:
248
+ b_db += tl.sum(b_dy, 0)
249
+ b_dx += b_wdy
250
+ else:
251
+ # which may use initial state
252
+ o_t = i_t * BT + tl.arange(0, BT)
253
+ for i_w in tl.static_range(0, W):
254
+ p_dy = tl.make_block_ptr(dy + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
255
+ b_dy_shift = tl.load(p_dy, boundary_check=(0, 1)).to(tl.float32)
256
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
257
+ p_y = tl.make_block_ptr(y + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
258
+ b_y_shift = tl.load(p_y, boundary_check=(0, 1)).to(tl.float32)
259
+ b_ys = tl.sigmoid(b_y_shift)
260
+ b_dy_shift = b_dy_shift * b_ys * (1 + b_y_shift * (1 - b_ys))
261
+ if HAS_WEIGHT:
262
+ # gradient comes from x:sum_t dy[t+i_w] * x[t]
263
+ b_dw = tl.sum(b_dy_shift * b_x, 0)
264
+ # index of cache:c = W - i_w + t
265
+ if USE_INITIAL_STATE:
266
+ mask_head_rows = (o_t < i_w)
267
+ # dy_head = dy[t]
268
+ b_dy_head = tl.load(dy + bos * D + o_t[:, None] * D + o_d, mask=(mask_head_rows[:, None] & m_d[None, :]),
269
+ other=0.0).to(tl.float32)
270
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
271
+ # use y[t] (not y[t+i_w])
272
+ b_y_head = tl.load(y + bos * D + o_t[:, None] * D + o_d,
273
+ mask=(mask_head_rows[:, None] & m_d[None, :]), other=0.0).to(tl.float32)
274
+ b_ys_head = tl.sigmoid(b_y_head)
275
+ b_dy_head = b_dy_head * b_ys_head * (1 + b_y_head * (1 - b_ys_head))
276
+ o_c = W - i_w + o_t
277
+ # index 0 is padding 0
278
+ mask_c = (mask_head_rows & (o_c >= 1) & (o_c < W))
279
+ b_xc = tl.load(initial_state + i_n * D * W + o_d[None, :] * W + o_c[:, None],
280
+ mask=(mask_c[:, None] & m_d[None, :]), other=0.0).to(tl.float32)
281
+ # add the gradient comes from initial_state
282
+ b_dw += tl.sum(b_dy_head * b_xc, 0)
283
+ tl.store(dw + i_tg * D * W + o_d * W + W - i_w - 1, b_dw.to(dw.dtype.element_ty), mask=m_d)
284
+
285
+ if HAS_BIAS and i_w == 0:
286
+ b_db += tl.sum(b_dy_shift, 0)
287
+ b_wdy = b_dy_shift if not HAS_WEIGHT else (b_dy_shift * tl.sum(b_w * (o_w == (W - i_w - 1)), 1))
288
+ b_dx += b_wdy
289
+
290
+ if USE_INITIAL_STATE:
291
+ p_dy0 = tl.make_block_ptr(dy + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
292
+ b_dy0 = tl.load(p_dy0, boundary_check=(0, 1)).to(tl.float32)
293
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
294
+ p_y0 = tl.make_block_ptr(y + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
295
+ b_y0 = tl.load(p_y0, boundary_check=(0, 1)).to(tl.float32)
296
+ b_ys0 = tl.sigmoid(b_y0)
297
+ b_dy0 = b_dy0 * b_ys0 * (1 + b_y0 * (1 - b_ys0))
298
+ # index 0 is padding 0, skip calculation
299
+ for i_w in tl.static_range(1, W):
300
+ m_rows = (o_t < i_w)
301
+ if HAS_WEIGHT:
302
+ # [BT]
303
+ w_idx_rows = i_w - 1 - o_t
304
+ # [BT, BW]
305
+ w_mask = (o_w[None, :] == w_idx_rows[:, None])
306
+ w_pick = tl.sum(b_w[None, :, :] * w_mask[:, None, :], 2)
307
+ else:
308
+ w_pick = 1.0
309
+ contrib = (b_dy0 * w_pick).to(tl.float32)
310
+ contrib = tl.where(m_rows[:, None] & m_d[None, :], contrib, 0.0)
311
+ # [BD]
312
+ b_dh0_s = tl.sum(contrib, 0)
313
+ # dh0: [NT, B, D, W]
314
+ tl.store(dh0 + i_t * B * D * W + i_n * D * W + o_d * W + i_w,
315
+ b_dh0_s.to(dh0.dtype.element_ty, fp_downcast_rounding='rtne'), mask=m_d)
316
+
317
+ if HAS_BIAS:
318
+ b_db = tl.cast(b_db, dtype=db.dtype.element_ty, fp_downcast_rounding='rtne')
319
+ tl.store(db + i_tg * D + o_d, b_db, mask=m_d)
320
+
321
+ if USE_FINAL_STATE:
322
+ if i_t * BT + BT >= T-W:
323
+ start_tok = max(0, T - (W - 1))
324
+ offset = i_t * BT + tl.arange(0, BT)
325
+ tok_idx = offset - start_tok
326
+ mask = (offset >= start_tok) & (offset < T)
327
+ w_idx = 1 + tok_idx
328
+ dht_off = i_n * D * W + o_d[None, :] * W + w_idx[:, None]
329
+ b_dht = tl.load(dht + dht_off, mask=mask[:, None] & m_d[None, :], other=0.).to(tl.float32)
330
+ b_dx += b_dht
331
+
332
+ p_dx = tl.make_block_ptr(dx + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
333
+ tl.store(p_dx, tl.cast(b_dx, dtype=p_dx.dtype.element_ty, fp_downcast_rounding='rtne'), boundary_check=(0, 1))
334
+
335
+
336
+ @triton.heuristics({
337
+ 'USE_INITIAL_STATE': lambda args: args['cache'] is not None,
338
+ 'HAS_WEIGHT': lambda args: args['weight'] is not None,
339
+ 'HAS_BIAS': lambda args: args['bias'] is not None,
340
+ 'HAS_RESIDUAL': lambda args: args['residual'] is not None,
341
+ })
342
+ @triton.jit
343
+ def causal_conv1d_update_kernel(
344
+ x,
345
+ cache,
346
+ residual,
347
+ y,
348
+ weight,
349
+ bias,
350
+ D: tl.constexpr,
351
+ W: tl.constexpr,
352
+ BD: tl.constexpr,
353
+ BW: tl.constexpr,
354
+ ACTIVATION: tl.constexpr,
355
+ USE_INITIAL_STATE: tl.constexpr,
356
+ HAS_WEIGHT: tl.constexpr,
357
+ HAS_BIAS: tl.constexpr,
358
+ HAS_RESIDUAL: tl.constexpr,
359
+ ):
360
+ i_d, i_n = tl.program_id(0), tl.program_id(1)
361
+
362
+ o_d = i_d * BD + tl.arange(0, BD)
363
+ o_w = tl.arange(0, BW) + W - BW
364
+ m_d = o_d < D
365
+ m_w = o_w >= 0
366
+ m_c = o_w < W - 1
367
+
368
+ # [BD]
369
+ b_x = tl.load(x + i_n * D + o_d, mask=m_d, other=0).to(tl.float32)
370
+
371
+ if USE_INITIAL_STATE:
372
+ # shift the cache by 1 with the last one being discarded
373
+ p_cache = tl.make_block_ptr(cache + i_n * D*W, (D, W), (W, 1), (i_d * BD, W - BW + 1), (BD, BW), (1, 0))
374
+ # [BD, BW]
375
+ b_cache = tl.load(p_cache, boundary_check=(0, 1)).to(tl.float32)
376
+ b_cache = tl.where(m_c[None, :], b_cache, b_x[:, None])
377
+ else:
378
+ b_cache = tl.zeros((BD, BW), dtype=tl.float32)
379
+
380
+ if HAS_WEIGHT:
381
+ b_w = tl.load(weight + o_d[:, None] * W + o_w, mask=m_d[:, None] & m_w, other=0)
382
+ b_y = tl.sum(b_cache * b_w, 1)
383
+ else:
384
+ b_y = tl.sum(b_cache, 1)
385
+ if HAS_BIAS:
386
+ b_y += tl.load(bias + o_d, mask=m_d)
387
+
388
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
389
+ b_y = b_y * tl.sigmoid(b_y)
390
+
391
+ if HAS_RESIDUAL:
392
+ b_y += tl.load(residual + i_n * D + o_d, mask=m_d, other=0)
393
+
394
+ tl.store(y + i_n * D + o_d, tl.cast(b_y, dtype=y.dtype.element_ty, fp_downcast_rounding='rtne'), mask=m_d)
395
+
396
+ if USE_INITIAL_STATE:
397
+ b_cache = tl.cast(b_cache, dtype=cache.dtype.element_ty, fp_downcast_rounding='rtne')
398
+ # update the cache in-place
399
+ p_cache = tl.make_block_ptr(cache + i_n * D*W, (D, W), (W, 1), (i_d * BD, W - BW), (BD, BW), (1, 0))
400
+ tl.store(p_cache, b_cache, boundary_check=(0, 1))
401
+
402
+
403
+ def causal_conv1d_fwd(
404
+ x: torch.Tensor,
405
+ weight: torch.Tensor,
406
+ bias: torch.Tensor,
407
+ residual: torch.Tensor,
408
+ initial_state: Optional[torch.Tensor] = None,
409
+ output_final_state: bool = False,
410
+ activation: Optional[str] = None,
411
+ cu_seqlens: Optional[torch.Tensor] = None,
412
+ ) -> torch.Tensor:
413
+ shape = x.shape
414
+ if x.shape[-1] != weight.shape[0]:
415
+ x = rearrange(x, 'b t ... -> b t (...)')
416
+ B, T, D, W = *x.shape, weight.shape[1]
417
+ BT = min(64, triton.next_power_of_2(triton.cdiv(max(16, B*T), get_multiprocessor_count(x.device.index))))
418
+ BW = triton.next_power_of_2(W)
419
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
420
+ NT = len(chunk_indices) if cu_seqlens is not None else triton.cdiv(T, BT)
421
+ NB = triton.cdiv(B*T, 1024)
422
+
423
+ y = torch.empty_like(x)
424
+ def grid(meta): return (triton.cdiv(D, meta['BD']), NT, B)
425
+ causal_conv1d_fwd_kernel[grid](
426
+ x=x,
427
+ y=y,
428
+ weight=weight,
429
+ bias=bias,
430
+ residual=residual,
431
+ cu_seqlens=cu_seqlens,
432
+ initial_state=initial_state,
433
+ chunk_indices=chunk_indices,
434
+ B=B,
435
+ T=T,
436
+ D=D,
437
+ W=W,
438
+ BT=BT,
439
+ BW=BW,
440
+ NB=NB,
441
+ ACTIVATION=activation,
442
+ )
443
+ final_state = None
444
+ if output_final_state:
445
+ final_state = causal_conv1d_update_states(
446
+ x=x,
447
+ state_len=W,
448
+ initial_state=initial_state,
449
+ cu_seqlens=cu_seqlens,
450
+ )
451
+ return y.view(shape), final_state
452
+
453
+
454
+ def causal_conv1d_bwd(
455
+ x: torch.Tensor,
456
+ dy: torch.Tensor,
457
+ dht: torch.Tensor,
458
+ weight: Optional[torch.Tensor] = None,
459
+ bias: Optional[torch.Tensor] = None,
460
+ residual: Optional[torch.Tensor] = None,
461
+ initial_state: Optional[torch.Tensor] = None,
462
+ activation: Optional[str] = None,
463
+ cu_seqlens: Optional[torch.Tensor] = None,
464
+ ):
465
+ shape = x.shape
466
+ if x.shape[-1] != weight.shape[0]:
467
+ x = rearrange(x, 'b t ... -> b t (...)')
468
+ B, T, D = x.shape
469
+ W = weight.shape[1] if weight is not None else None
470
+ BT = min(64, triton.next_power_of_2(triton.cdiv(max(16, B*T), get_multiprocessor_count(x.device.index))))
471
+ BW = triton.next_power_of_2(W)
472
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
473
+ NT = len(chunk_indices) if cu_seqlens is not None else triton.cdiv(T, BT)
474
+ NB = triton.cdiv(B*T, 1024)
475
+
476
+ y = None
477
+ if activation is not None:
478
+ y, _ = causal_conv1d_fwd(
479
+ x=x,
480
+ weight=weight,
481
+ bias=bias,
482
+ residual=None,
483
+ initial_state=initial_state,
484
+ activation=None,
485
+ cu_seqlens=cu_seqlens,
486
+ output_final_state=False
487
+ )
488
+ dx = torch.empty_like(x)
489
+ dw = weight.new_empty(B*NT, *weight.shape, dtype=torch.float) if weight is not None else None
490
+ db = bias.new_empty(B*NT, *bias.shape, dtype=torch.float) if bias is not None else None
491
+ dr = dy if residual is not None else None
492
+ dh0 = initial_state.new_zeros(min(NT, triton.cdiv(W, BT)), *initial_state.shape) if initial_state is not None else None
493
+
494
+ def grid(meta): return (triton.cdiv(D, meta['BD']), NT, B)
495
+ causal_conv1d_bwd_kernel[grid](
496
+ x=x,
497
+ y=y,
498
+ weight=weight,
499
+ initial_state=initial_state,
500
+ dh0=dh0,
501
+ dht=dht,
502
+ dy=dy,
503
+ dx=dx,
504
+ dw=dw,
505
+ db=db,
506
+ cu_seqlens=cu_seqlens,
507
+ chunk_indices=chunk_indices,
508
+ B=B,
509
+ T=T,
510
+ D=D,
511
+ W=W,
512
+ BT=BT,
513
+ BW=BW,
514
+ NB=NB,
515
+ ACTIVATION=activation,
516
+ )
517
+ if weight is not None:
518
+ dw = dw.sum(0).to(weight)
519
+ if bias is not None:
520
+ db = db.sum(0).to(bias)
521
+ if initial_state is not None:
522
+ dh0 = dh0.sum(0, dtype=torch.float32).to(initial_state)
523
+
524
+ return dx.view(shape), dw, db, dr, dh0
525
+
526
+
527
+ @triton.heuristics({
528
+ 'USE_INITIAL_STATE': lambda args: args['initial_state'] is not None,
529
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
530
+ })
531
+ @triton.jit
532
+ def causal_conv1d_states_fwd_kernel(
533
+ x,
534
+ initial_state,
535
+ final_state,
536
+ cu_seqlens,
537
+ T,
538
+ D,
539
+ W,
540
+ BD: tl.constexpr,
541
+ BW: tl.constexpr,
542
+ USE_INITIAL_STATE: tl.constexpr,
543
+ IS_VARLEN: tl.constexpr,
544
+ ):
545
+ i_d, i_n = tl.program_id(0), tl.program_id(1)
546
+ if IS_VARLEN:
547
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
548
+ T = eos - bos
549
+ else:
550
+ bos, eos = i_n * T, i_n * T + T
551
+
552
+ o_t = eos - BW + tl.arange(0, BW)
553
+ o_d = i_d * BD + tl.arange(0, BD)
554
+ o_w = W - BW + tl.arange(0, BW)
555
+ m_t = (o_t >= tl.maximum(bos, eos - W))
556
+ m_d = o_d < D
557
+ m_w = (o_w >= 0) & (o_w < W)
558
+
559
+ b_x = tl.load(x + o_t * D + o_d[:, None], mask=(m_t & m_d[:, None]), other=0)
560
+ if USE_INITIAL_STATE:
561
+ if T < BW:
562
+ o_c = W - (BW - T) + tl.arange(0, BW)
563
+ m_c = (o_c >= 0) & (o_c < W)
564
+ b_cache = tl.load(initial_state + i_n * D*W + o_d[:, None] * W + o_c, mask=m_d[:, None] & m_c, other=0)
565
+ b_x += b_cache
566
+
567
+ tl.store(final_state + i_n * D*W + o_d[:, None] * W + o_w, b_x, mask=m_d[:, None] & m_w)
568
+
569
+
570
+ @input_guard
571
+ def causal_conv1d_update_states(
572
+ x: torch.Tensor,
573
+ state_len: int,
574
+ initial_state: Optional[torch.Tensor] = None,
575
+ cu_seqlens: Optional[torch.Tensor] = None,
576
+ ) -> torch.Tensor:
577
+ B, T, D, W = *x.shape, state_len
578
+ N = len(cu_seqlens) - 1 if cu_seqlens is not None else B
579
+
580
+ final_state = torch.empty(N, D, W, dtype=x.dtype, device=x.device)
581
+ BD = min(triton.next_power_of_2(D), 256)
582
+ BW = triton.next_power_of_2(W)
583
+ grid = (triton.cdiv(D, BD), N)
584
+ causal_conv1d_states_fwd_kernel[grid](
585
+ x=x,
586
+ initial_state=initial_state,
587
+ final_state=final_state,
588
+ cu_seqlens=cu_seqlens,
589
+ T=T,
590
+ D=D,
591
+ W=W,
592
+ BW=BW,
593
+ BD=BD
594
+ )
595
+ return final_state
596
+
597
+
598
+ @input_guard
599
+ def causal_conv1d_update(
600
+ x: torch.Tensor,
601
+ cache: torch.Tensor,
602
+ residual: Optional[torch.Tensor] = None,
603
+ weight: Optional[torch.Tensor] = None,
604
+ bias: Optional[torch.Tensor] = None,
605
+ activation: Optional[str] = None
606
+ ) -> torch.Tensor:
607
+ shape = x.shape
608
+ if weight is not None and x.shape[-1] != weight.shape[0]:
609
+ x = rearrange(x, 'b t ... -> b t (...)')
610
+ *_, D = x.shape
611
+ N = x.numel() // D
612
+ W = weight.shape[1] if weight is not None else None
613
+ BD = 8
614
+ BW = triton.next_power_of_2(W)
615
+
616
+ y = torch.empty_like(x)
617
+ # NOTE: autotuning is disabled as cache is updated in-place
618
+ def grid(meta): return (triton.cdiv(D, meta['BD']), N)
619
+ causal_conv1d_update_kernel[grid](
620
+ x=x,
621
+ cache=cache,
622
+ residual=residual,
623
+ y=y,
624
+ weight=weight,
625
+ bias=bias,
626
+ D=D,
627
+ W=W,
628
+ BD=BD,
629
+ BW=BW,
630
+ ACTIVATION=activation,
631
+ num_warps=STATIC_WARPS,
632
+ )
633
+ return y.view(shape), cache
634
+
635
+
636
+ class CausalConv1dFunction(torch.autograd.Function):
637
+
638
+ @staticmethod
639
+ @input_guard
640
+ def forward(
641
+ ctx,
642
+ x: torch.Tensor,
643
+ weight: Optional[torch.Tensor] = None,
644
+ bias: Optional[torch.Tensor] = None,
645
+ residual: Optional[torch.Tensor] = None,
646
+ initial_state: Optional[torch.Tensor] = None,
647
+ output_final_state: Optional[bool] = False,
648
+ activation: Optional[str] = None,
649
+ cu_seqlens: Optional[torch.Tensor] = None,
650
+ ):
651
+ ctx.activation = activation
652
+ ctx.cu_seqlens = cu_seqlens
653
+ ctx.save_for_backward(x, weight, bias, residual, initial_state)
654
+ y, final_state = causal_conv1d_fwd(
655
+ x=x,
656
+ weight=weight,
657
+ bias=bias,
658
+ residual=residual,
659
+ initial_state=initial_state,
660
+ output_final_state=output_final_state,
661
+ activation=activation,
662
+ cu_seqlens=cu_seqlens,
663
+ )
664
+ return y, final_state
665
+
666
+ @staticmethod
667
+ @input_guard
668
+ def backward(ctx, dy: torch.Tensor, dht: Optional[torch.Tensor] = None):
669
+ x, weight, bias, residual, initial_state = ctx.saved_tensors
670
+ dx, dw, db, dr, dh0 = causal_conv1d_bwd(
671
+ x=x,
672
+ dy=dy,
673
+ dht=dht,
674
+ weight=weight,
675
+ bias=bias,
676
+ residual=residual,
677
+ initial_state=initial_state,
678
+ activation=ctx.activation,
679
+ cu_seqlens=ctx.cu_seqlens,
680
+ )
681
+ return dx, dw, db, dr, dh0, None, None, None
682
+
683
+
684
+ @input_guard
685
+ def causal_conv1d(
686
+ x: torch.Tensor,
687
+ weight: Optional[torch.Tensor] = None,
688
+ bias: Optional[torch.Tensor] = None,
689
+ residual: Optional[torch.Tensor] = None,
690
+ initial_state: Optional[torch.Tensor] = None,
691
+ output_final_state: Optional[bool] = False,
692
+ activation: Optional[str] = None,
693
+ backend: Optional[str] = 'triton',
694
+ cu_seqlens: Optional[torch.Tensor] = None,
695
+ **kwargs,
696
+ ):
697
+ """
698
+ A causal 1D convolution implementation that powers Mamba/Mamba2 and DeltaNet architectures.
699
+
700
+ When a residual connection is provided, this implements the Canon operation
701
+ described in the paper at https://papers.ssrn.com/sol3/papers.cfm?abstract_id=5240330.
702
+
703
+ Args:
704
+ x (torch.Tensor):
705
+ Input tensor of shape [B, T, D].
706
+ weight (Optional[torch.Tensor]):
707
+ Weight tensor of shape [D, W]. Default: `None`.
708
+ bias (Optional[torch.Tensor]):
709
+ Bias tensor of shape [D]. Default: `None`.
710
+ residual (Optional[torch.Tensor]):
711
+ Residual tensor of shape [B, T, D]. Default: `None`.
712
+ initial_state (Optional[torch.Tensor]):
713
+ Initial state tensor of shape [N, D, W],
714
+ where `N` is the number of sequences in the batch and `W` is the kernel size.
715
+ If provided, the initial state is used to initialize the cache. Default: `None`.
716
+ output_final_state (Optional[bool]):
717
+ Whether to output the final state of shape [N, D, W]. Default: `False`.
718
+ activation (Optional[str]):
719
+ Activations applied to output, only `swish`/`silu` or `None` (i.e., no activation) are supported.
720
+ Default: `None`.
721
+ backend (Optional[str]):
722
+ Specifies the backend to use for the convolution operation. Supported values are `'cuda'` and `'triton'`.
723
+ Default: `'triton'`.
724
+ cu_seqlens (Optional[torch.Tensor]):
725
+ Cumulative sequence lengths (optional)
726
+
727
+ Returns:
728
+ Tuple of (output, final_state).
729
+ If `output_final_state` is `False`, the final state is `None`.
730
+ """
731
+
732
+ if backend == 'triton':
733
+ y, final_state = CausalConv1dFunction.apply(
734
+ x,
735
+ weight,
736
+ bias,
737
+ residual,
738
+ initial_state,
739
+ output_final_state,
740
+ activation,
741
+ cu_seqlens,
742
+ )
743
+ return y, final_state
744
+
745
+ B, _, D, W = *x.shape, weight.shape[-1]
746
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
747
+ x = rearrange(x, 'b t d -> b d t')
748
+
749
+ # check if cu_seqlens and cache are both provided
750
+ # Sequence index for each token. Used for varlen.
751
+ # Suppose a batch consists of two sequences with lengths 3 and 4,
752
+ # seq_idx=[0, 0, 0, 1, 1, 1, 1] for this batch.
753
+ # NOTE: No need to provide this arg if `cu_seqlens` is passed.
754
+ # This arg is just for BC, and will be removed in the future.
755
+ # [B, T]
756
+ seq_idx = kwargs.get('seq_idx', None)
757
+ if cu_seqlens is not None and seq_idx is None:
758
+ seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
759
+
760
+ # equivalent to:
761
+ # y = _conv_forward(x, weight, bias)[..., :x.shape[-1]]
762
+ # if activation is not None:
763
+ # y = ACT2FN[activation](x)
764
+
765
+ cache, initial_state = initial_state, None
766
+ if cache is not None:
767
+ # To make causal-conv1d happy
768
+ initial_state = (
769
+ cache[:, :, -(W-1):] # [N, D, W-1]
770
+ .transpose(1, 2).contiguous() # [N, W-1, D] and stride(2)==1
771
+ .transpose(1, 2) # [N, D, W-1] and stride(1)==1
772
+ )
773
+
774
+ result = causal_conv1d_fn(
775
+ x=x,
776
+ weight=weight,
777
+ bias=bias,
778
+ activation=activation,
779
+ seq_idx=seq_idx,
780
+ initial_states=initial_state,
781
+ return_final_states=output_final_state,
782
+ )
783
+ y, final_state = result if output_final_state else (result, None)
784
+ y = rearrange(y, 'b d t -> b t d')
785
+ if output_final_state:
786
+ cache = x.new_zeros(N, D, W)
787
+ cache[:, :, -W+1:].copy_(final_state[:, :, -W+1:])
788
+ if residual is not None:
789
+ y.add_(residual)
790
+
791
+ return y, cache
792
+
793
+
794
+ class ShortConvolution(nn.Conv1d):
795
+ """Short convolution layer for efficient causal convolution operations.
796
+
797
+ This class implements a depthwise separable 1D convolution with causal padding,
798
+ designed for efficient sequence processing. It supports multiple backends (Triton/CUDA)
799
+ and optional activation functions.
800
+
801
+ Args:
802
+ hidden_size (int): Number of input/output channels (must be equal for depthwise conv)
803
+ kernel_size (int): Size of the convolution kernel
804
+ bias (bool, optional): Whether to include learnable bias. Defaults to False.
805
+ activation (Optional[str], optional): Activation function ('silu' or 'swish'). Defaults to 'silu'.
806
+ backend (Optional[str], optional): Backend implementation ('triton' or 'cuda'). Defaults to 'triton'.
807
+ device (Optional[torch.device], optional): Device to place the layer on. Defaults to None.
808
+ dtype (Optional[torch.dtype], optional): Data type for layer parameters. Defaults to None.
809
+ **kwargs: Additional keyword arguments (deprecated 'use_fast_conv1d' supported for compatibility)
810
+
811
+ Attributes:
812
+ hidden_size (int): Number of channels
813
+ activation (Optional[str]): Selected activation function
814
+ backend (str): Actual backend being used (may differ from input due to availability)
815
+
816
+ Note:
817
+ - Uses depthwise convolution (groups=hidden_size) for efficiency
818
+ - Applies causal padding (kernel_size-1) to ensure no future information leakage
819
+ - Falls back to Triton backend if CUDA backend is unavailable
820
+ """
821
+
822
+ def __init__(
823
+ self,
824
+ hidden_size: int,
825
+ kernel_size: int,
826
+ bias: bool = False,
827
+ activation: Optional[str] = 'silu',
828
+ backend: Optional[str] = 'triton',
829
+ device: Optional[torch.device] = None,
830
+ dtype: Optional[torch.dtype] = None,
831
+ **kwargs,
832
+ ):
833
+ super().__init__(
834
+ in_channels=hidden_size,
835
+ out_channels=hidden_size,
836
+ kernel_size=kernel_size,
837
+ groups=hidden_size,
838
+ bias=bias,
839
+ padding=kernel_size - 1,
840
+ device=device,
841
+ dtype=dtype,
842
+ )
843
+
844
+ self.hidden_size = hidden_size
845
+ self.activation = None
846
+
847
+ if activation is not None:
848
+ assert activation in ['silu', 'swish'], f"Activation `{activation}` not supported yet."
849
+ self.activation = activation
850
+
851
+ if 'use_fast_conv1d' in kwargs:
852
+ warnings.warn(
853
+ "The `use_fast_conv1d` parameter is deprecated and will be ignored. "
854
+ "Please use the `backend` parameter instead."
855
+ )
856
+ import os
857
+ self.backend = os.environ.get('FLA_CONV_BACKEND', backend)
858
+ if backend not in ['cuda', 'triton']:
859
+ raise ValueError(f"Invalid backend: {backend}, must be one of ['cuda', 'triton']")
860
+ if backend == 'cuda':
861
+ if causal_conv1d_fn is None:
862
+ warnings.warn(
863
+ "The `backend` parameter is set to `cuda`, but `causal_conv1d_fn` is not available. "
864
+ "Switching to the Triton implementation instead. "
865
+ "Consider installing `causal_conv1d` to enable the CUDA backend."
866
+ )
867
+ self.backend = 'triton'
868
+
869
+ def extra_repr(self):
870
+ s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}'
871
+ ', stride={stride}')
872
+ if self.padding != (0,) * len(self.padding):
873
+ s += ', padding={padding}'
874
+ if self.dilation != (1,) * len(self.dilation):
875
+ s += ', dilation={dilation}'
876
+ if self.output_padding != (0,) * len(self.output_padding):
877
+ s += ', output_padding={output_padding}'
878
+ if self.groups != 1:
879
+ s += ', groups={groups}'
880
+ if self.bias is None:
881
+ s += ', bias=False'
882
+ if self.padding_mode != 'zeros':
883
+ s += ', padding_mode={padding_mode}'
884
+ if self.activation is not None:
885
+ s += ', activation={activation}'
886
+ s += f', backend={self.backend}'
887
+ return s.format(**self.__dict__)
888
+
889
+ def forward(
890
+ self,
891
+ x: torch.Tensor,
892
+ residual: Optional[torch.Tensor] = None,
893
+ mask: Optional[torch.Tensor] = None,
894
+ cache: Optional[torch.Tensor] = None,
895
+ output_final_state: bool = False,
896
+ cu_seqlens: Optional[torch.LongTensor] = None,
897
+ **kwargs,
898
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
899
+ """
900
+ Args:
901
+ x (`torch.Tensor`):
902
+ Tensor of shape `[B, T, D]`. `B` must be 1 if `seq_idx` is provided.
903
+ residual (`Optional[torch.Tensor]`):
904
+ Residual tensor of shape `[B, T, D]`. Default: `None`.
905
+ mask (`Optional[torch.Tensor]`):
906
+ Attention mask dealing with padded positions.
907
+ cache (`Optional[torch.Tensor]`):
908
+ Previous cache tensor of shape `[N, D, W]`, where `W` is the kernel size.
909
+ If provided, the cache is updated **inplace**.
910
+ output_final_state (Optional[bool]):
911
+ Whether to output the final state of shape `[N, D, W]`. Default: `False`.
912
+ cu_seqlens (Optional[torch.LongTensor]):
913
+ Cumulative sequence lengths for each batch. Used for varlen. Default: `None`.
914
+ Shape: [B+1]
915
+
916
+ Returns:
917
+ Tensor of shape `[B, T, D]`.
918
+ """
919
+
920
+ B, T, *_ = x.shape
921
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
922
+ if mask is not None:
923
+ if cu_seqlens is not None:
924
+ raise ValueError("`mask` and `cu_seqlens` cannot be provided at the same time")
925
+ x = x.mul_(mask.unsqueeze(-1))
926
+
927
+ # in decoding phase, the cache (if provided) is updated inplace
928
+ if B * T == N:
929
+ y, cache = self.step(
930
+ x=x,
931
+ residual=residual,
932
+ cache=cache,
933
+ output_final_state=output_final_state,
934
+ cu_seqlens=cu_seqlens
935
+ )
936
+ return y, cache
937
+
938
+ # cuda backend do not support:
939
+ # 1. both `cu_seqlens` and `cache` being provided
940
+ # 2. both `cu_seqlens` and `output_final_state` being provided
941
+ if self.backend == 'cuda' and (
942
+ (cu_seqlens is not None and cache is not None) or
943
+ (cu_seqlens is not None and output_final_state)
944
+ ):
945
+ warnings.warn(
946
+ "The CUDA backend does not support both `cu_seqlens` and `cache` being provided, "
947
+ "or both `cu_seqlens` and `output_final_state` being provided. "
948
+ "Switching to the Triton backend instead. ",
949
+ stacklevel=2
950
+ )
951
+ self.backend = 'triton'
952
+
953
+ return causal_conv1d(
954
+ x=x,
955
+ weight=rearrange(self.weight, "d 1 w -> d w"),
956
+ bias=self.bias,
957
+ residual=residual,
958
+ initial_state=cache,
959
+ output_final_state=output_final_state,
960
+ activation=self.activation,
961
+ backend=self.backend,
962
+ cu_seqlens=cu_seqlens,
963
+ **kwargs
964
+ )
965
+
966
+ def step(
967
+ self,
968
+ x: torch.Tensor,
969
+ residual: torch.Tensor,
970
+ cache: torch.Tensor,
971
+ output_final_state: bool = False,
972
+ cu_seqlens: Optional[torch.LongTensor] = None
973
+ ):
974
+ B, _, D, W = *x.shape, self.kernel_size[0]
975
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
976
+ if output_final_state and cache is None:
977
+ cache = x.new_zeros(N, D, W)
978
+ # NOTE: we follow the fast mode that updates the cache in-place
979
+ if self.backend == 'triton':
980
+ return causal_conv1d_update(
981
+ x=x,
982
+ cache=cache,
983
+ residual=residual,
984
+ weight=rearrange(self.weight, "d 1 w -> d w"),
985
+ bias=self.bias,
986
+ activation=self.activation,
987
+ )
988
+
989
+ shape = x.shape
990
+ x = x.squeeze(0) if cu_seqlens is not None else x.squeeze(1)
991
+ # equivalent to:
992
+ # cache.copy_(cache.roll(shifts=-1, dims=-1))
993
+ # cache[:, :, -1] = x
994
+ # y = torch.sum(cache * rearrange(self.weight, "d 1 w -> d w"), dim=-1)
995
+ y = causal_conv1d_update_cuda(
996
+ x=x,
997
+ conv_state=cache,
998
+ weight=rearrange(self.weight, "d 1 w -> d w"),
999
+ bias=self.bias,
1000
+ activation=self.activation,
1001
+ )
1002
+ y = y.view(shape)
1003
+ if residual is not None:
1004
+ y.add_(residual)
1005
+ return y, cache
1006
+
1007
+ @property
1008
+ def state_size(self) -> int:
1009
+ return self.hidden_size * self.kernel_size
1010
+
1011
+
1012
+ def fft_conv(u, k, dropout_mask, gelu=True, k_rev=None):
1013
+ seqlen = u.shape[-1]
1014
+ fft_size = 2 * seqlen
1015
+ k_f = torch.fft.rfft(k, n=fft_size) / fft_size
1016
+ if k_rev is not None:
1017
+ k_rev_f = torch.fft.rfft(k_rev, n=fft_size) / fft_size
1018
+ k_f = k_f + k_rev_f.conj()
1019
+ u_f = torch.fft.rfft(u.to(dtype=k.dtype), n=fft_size)
1020
+
1021
+ if len(u.shape) > 3:
1022
+ k_f = k_f.unsqueeze(1)
1023
+ y = torch.fft.irfft(u_f * k_f, n=fft_size, norm="forward")[..., :seqlen]
1024
+
1025
+ out = y + u
1026
+ if gelu:
1027
+ out = F.gelu(out)
1028
+ if dropout_mask is not None:
1029
+ return (out * rearrange(dropout_mask, "b H -> b H 1")).to(dtype=u.dtype)
1030
+ else:
1031
+ return out.to(dtype=u.dtype)
1032
+
1033
+
1034
+ class LongConvolution(nn.Module):
1035
+ """
1036
+ LongConvolution applies a convolution operation on the input tensor using a fixed
1037
+ filter of length max_len.
1038
+ The filter is learned during training and is applied using FFT convolution.
1039
+
1040
+ Args:
1041
+ hidden_size (int): The number of expected features in the input and output.
1042
+ max_len (int): The maximum sequence length.
1043
+
1044
+ Returns:
1045
+ y: [batch_size, seq_len, hidden_size] tensor
1046
+ """
1047
+
1048
+ def __init__(
1049
+ self,
1050
+ hidden_size: int,
1051
+ max_len: int,
1052
+ **kwargs,
1053
+ ):
1054
+ """
1055
+ Initializes the LongConvolution module.
1056
+ Args:
1057
+ hidden_size (int): The number of expected features in the input and output.
1058
+ max_len (int): The maximum sequence length.
1059
+ """
1060
+ super().__init__()
1061
+ self.hidden_size = hidden_size
1062
+ self.filter = nn.Parameter(torch.randn(self.hidden_size, max_len), requires_grad=True)
1063
+
1064
+ def forward(self, x: torch.Tensor, *args, **kwargs):
1065
+ """
1066
+ Applies the LongConvolution operation on the input tensor.
1067
+ Args:
1068
+ x: [batch_size, seq_len, hidden_size] tensor
1069
+ Returns:
1070
+ y: [batch_size, seq_len, hidden_size] tensor
1071
+ """
1072
+ x = x.transpose(1, 2)
1073
+ y = fft_conv(x, self.filter, dropout_mask=None, gelu=False)
1074
+ y = y.transpose(1, 2)
1075
+ return y.to(dtype=x.dtype)
1076
+
1077
+
1078
+ class PositionalEmbedding(nn.Module):
1079
+ def __init__(self, emb_dim: int, seq_len: int, **kwargs):
1080
+ """Complex exponential positional embeddings for implicit long convolution filters."""
1081
+ super().__init__()
1082
+
1083
+ self.seq_len = seq_len
1084
+ # The time embedding fed to the filteres is normalized so that t_f = 1
1085
+ t = torch.linspace(0, 1, self.seq_len)[None, :, None] # 1, L, 1
1086
+
1087
+ if emb_dim > 1:
1088
+ bands = (emb_dim - 1) // 2
1089
+ # To compute the right embeddings we use the "proper" linspace
1090
+ t_rescaled = torch.linspace(0, seq_len - 1, seq_len)[None, :, None]
1091
+ w = 2 * math.pi * t_rescaled / seq_len # 1, L, 1
1092
+
1093
+ f = torch.linspace(1e-4, bands - 1, bands)[None, None]
1094
+ z = torch.exp(-1j * f * w)
1095
+ z = torch.cat([t, z.real, z.imag], dim=-1)
1096
+ self.z = nn.Parameter(z, requires_grad=False)
1097
+
1098
+ def forward(self, L):
1099
+ return self.z[:, :L]
1100
+
1101
+
1102
+ class ImplicitLongConvolution(nn.Module):
1103
+ """
1104
+ Long convolution with implicit filter parameterized by an MLP.
1105
+
1106
+ Args:
1107
+ hidden_size (int):
1108
+ The number of expected features in the input and output.
1109
+ max_len (int):
1110
+ The maximum sequence length.
1111
+ d_emb (Optional[int]):
1112
+ The dimension of the positional embeddings. Must be odd and greater or equal to 3 (time, sine and cosine).
1113
+ Defaults to 3.
1114
+ d_hidden (Optional[int]):
1115
+ The number of features in the hidden layer of the MLP. Defaults to 16.
1116
+
1117
+ Attributes:
1118
+ pos_emb (`PositionalEmbedding`): The positional embedding layer.
1119
+ mlp (`nn.Sequential`): The MLP that parameterizes the implicit filter.
1120
+
1121
+ """
1122
+
1123
+ def __init__(
1124
+ self,
1125
+ hidden_size: int,
1126
+ max_len: int,
1127
+ d_emb: int = 3,
1128
+ d_hidden: int = 16,
1129
+ **kwargs,
1130
+ ):
1131
+ """
1132
+ Long convolution with implicit filter parameterized by an MLP.
1133
+
1134
+
1135
+ """
1136
+ super().__init__()
1137
+ self.hidden_size = hidden_size
1138
+ self.d_emb = d_emb
1139
+
1140
+ assert (
1141
+ d_emb % 2 != 0 and d_emb >= 3
1142
+ ), "d_emb must be odd and greater or equal to 3 (time, sine and cosine)"
1143
+ self.pos_emb = PositionalEmbedding(d_emb, max_len)
1144
+
1145
+ # final linear layer
1146
+ self.mlp = nn.Sequential(
1147
+ nn.Linear(d_emb, d_hidden),
1148
+ torch.nn.ReLU(),
1149
+ nn.Linear(d_hidden, hidden_size),
1150
+ )
1151
+
1152
+ def filter(self, seq_len: int, *args, **kwargs):
1153
+ return self.mlp(self.pos_emb(seq_len)).transpose(1, 2)
1154
+
1155
+ def forward(self, x: torch.Tensor, *args, **kwargs):
1156
+ """
1157
+ Args:
1158
+ x: [batch_size, seq_len, hidden_size] tensor
1159
+
1160
+ Returns:
1161
+ y: [batch_size, seq_len, hidden_size] tensor
1162
+ """
1163
+ x = x.transpose(1, 2)
1164
+ k = self.filter(x.shape[-1])
1165
+ y = fft_conv(x, k, dropout_mask=None, gelu=False)
1166
+
1167
+ y = y.transpose(1, 2)
1168
+ return y.to(dtype=x.dtype)
modules/feature_map.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import Optional
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from torch import nn
11
+
12
+ from fla.modules.activations import fast_gelu_impl, sigmoid, sqrelu, swish
13
+ from fla.modules.layernorm import layer_norm
14
+ from fla.utils import checkpoint
15
+
16
+
17
+ @checkpoint
18
+ def flatten_diag_outer_product(x, y):
19
+ z = torch.einsum("...i,...j->...ij", x, y)
20
+ N = z.size(-1)
21
+ indicies = torch.triu_indices(N, N)
22
+ return z[..., indicies[0], indicies[1]]
23
+
24
+
25
+ @checkpoint
26
+ def flatten_diag_outer_product_off1(x, y):
27
+ z = torch.einsum("...i,...j->...ij", x, y)
28
+ N = z.size(-1)
29
+ indicies = torch.triu_indices(N, N, 1)
30
+ indices2 = torch.arange(0, N)
31
+ return z[..., indicies[0], indicies[1]], z[..., indices2, indices2]
32
+
33
+
34
+ def is_power_of_2(n):
35
+ return (n & (n - 1) == 0) and n != 0
36
+
37
+
38
+ class HedgehogFeatureMap(nn.Module):
39
+
40
+ r"""
41
+ Hedgehog feature map as introduced in
42
+ `The Hedgehog & the Porcupine: Expressive Linear Attentions with Softmax Mimicry <https://arxiv.org/abs/2402.04347>`_
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ head_dim: int
48
+ ) -> HedgehogFeatureMap:
49
+ super().__init__()
50
+ # Trainable map
51
+ self.layer = nn.Linear(head_dim, head_dim)
52
+ self.init_weights_()
53
+
54
+ def init_weights_(self):
55
+ """Initialize trainable map as identity"""
56
+ with torch.no_grad():
57
+ identity = torch.eye(*self.layer.weight.shape[-2:], dtype=torch.float)
58
+ self.layer.weight.copy_(identity.to(self.layer.weight))
59
+ nn.init.zeros_(self.layer.bias)
60
+
61
+ def forward(self, x: torch.Tensor):
62
+ x = self.layer(x) # shape b, h, l, d
63
+ return torch.cat([2*x, -2*x], dim=-1).softmax(-1)
64
+
65
+
66
+ class T2RFeatureMap(nn.Module):
67
+
68
+ r"""
69
+ Simple linear mapping feature map as in
70
+ `Finetuning Pretrained Transformers into RNNs <https://arxiv.org/abs/2103.13076>`_
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ head_dim: int,
76
+ dot_dim: int = None,
77
+ bias: Optional[bool] = False
78
+ ) -> T2RFeatureMap:
79
+ super().__init__()
80
+ # Trainable map
81
+ if dot_dim is None:
82
+ dot_dim = head_dim
83
+
84
+ self.head_dim = head_dim
85
+ self.dot_dim = dot_dim
86
+ self.bias = bias
87
+
88
+ self.layer = nn.Linear(head_dim, dot_dim, bias=bias)
89
+
90
+ def __repr__(self) -> str:
91
+ return f"{self.__class__.__name__}(head_dim={self.head_dim}, dot_dim={self.dot_dim}, bias={self.bias})"
92
+
93
+ def forward(self, x: torch.Tensor):
94
+ return self.layer(x).relu()
95
+
96
+
97
+ class DPFPFeatureMap(nn.Module):
98
+
99
+ r"""
100
+ Deterministic Parameter-Free Projection (DPFP) feature map in
101
+ `Linear Transformers Are Secretly Fast Weight Programmers <https://arxiv.org/abs/2102.11174>`_
102
+ """
103
+
104
+ def __init__(
105
+ self,
106
+ head_dim: int,
107
+ nu: int = 4
108
+ ) -> DPFPFeatureMap:
109
+ super().__init__()
110
+ self.nu = nu
111
+
112
+ def forward(self, x: torch.Tensor):
113
+ x = torch.cat([x.relu(), -x.relu()], dim=-1)
114
+ x_rolled = torch.cat([x.roll(shifts=j, dims=-1) for j in range(1, self.nu+1)], dim=-1)
115
+ x_repeat = torch.cat([x] * self.nu, dim=-1)
116
+ return x_repeat * x_rolled
117
+
118
+
119
+ class HadamardFeatureMap(nn.Module):
120
+ def __init__(
121
+ self,
122
+ head_dim: int
123
+ ) -> HadamardFeatureMap:
124
+ super().__init__()
125
+ # Trainable map
126
+ self.layer1 = nn.Linear(head_dim, head_dim)
127
+ self.layer2 = nn.Linear(head_dim, head_dim)
128
+
129
+ def forward(self, x: torch.Tensor):
130
+ return self.layer1(x) * self.layer2(x)
131
+
132
+
133
+ class LearnableOuterProductFeatureMap(nn.Module):
134
+ def __init__(
135
+ self,
136
+ head_dim: int,
137
+ feature_dim: int
138
+ ) -> LearnableOuterProductFeatureMap:
139
+ super().__init__()
140
+ # Trainable map
141
+ self.layer1 = nn.Linear(head_dim, feature_dim, bias=False)
142
+ self.layer2 = nn.Linear(head_dim, feature_dim, bias=False)
143
+ self.normalizer = feature_dim ** -0.5
144
+
145
+ def forward(self, x: torch.Tensor):
146
+ return flatten_diag_outer_product(self.layer1(x), self.layer2(x))
147
+
148
+
149
+ class LearnablePolySketchNonNegativeFeatureMap(nn.Module):
150
+
151
+ def __init__(
152
+ self,
153
+ head_dim: int,
154
+ sketch_size: Optional[int] = None,
155
+ degree: Optional[int] = 2
156
+ ) -> LearnablePolySketchNonNegativeFeatureMap:
157
+ super().__init__()
158
+
159
+ assert is_power_of_2(degree) and degree >= 2, f"The degree {degree} must be a power of 2"
160
+
161
+ self.head_dim = head_dim
162
+ self.sketch_size = sketch_size if sketch_size is not None else head_dim
163
+ self.degree = degree
164
+
165
+ self.gamma = nn.Parameter(torch.ones(head_dim))
166
+ self.beta = nn.Parameter(torch.zeros(head_dim))
167
+ # NOTE: the sketch layers defined here are quite different from the original paper
168
+ # currently we simply use linear layers without any non-linear activations
169
+ self.sketches1 = nn.ModuleList([
170
+ nn.Linear(head_dim, sketch_size, bias=False),
171
+ *[nn.Linear(sketch_size, sketch_size, bias=False) for _ in range(int(math.log2(self.degree)) - 2)]
172
+ ])
173
+ self.sketches2 = nn.ModuleList([
174
+ nn.Linear(head_dim, sketch_size, bias=False),
175
+ *[nn.Linear(sketch_size, sketch_size, bias=False) for _ in range(int(math.log2(self.degree)) - 2)]
176
+ ])
177
+
178
+ def forward(self, x: torch.Tensor):
179
+ # Section 2.1
180
+ x = layer_norm(x, self.gamma, self.beta)
181
+ # first map the input to sketch size with learnable parameters
182
+ x = self.sketches1[0](x) * self.sketches2[0](x) * self.head_dim ** -0.5
183
+ for i in range(1, int(math.log2(self.degree)) - 1):
184
+ x = self.sketches1[i](x) * self.sketches2[i](x) * self.head_dim ** -0.5
185
+ # do sketch mapping for log2(p) - 1 times in total
186
+ # do p=2 mapping to ensure non-negativity
187
+ return flatten_diag_outer_product(x, x)
188
+
189
+
190
+ class TaylorFeatureMap(nn.Module):
191
+ def __init__(
192
+ self,
193
+ head_dim: int
194
+ ) -> TaylorFeatureMap:
195
+ super().__init__()
196
+ self.head_dim = head_dim
197
+ self.r2 = math.sqrt(2)
198
+ self.rd = math.sqrt(self.head_dim)
199
+ self.rrd = math.sqrt(self.rd)
200
+
201
+ def forward(self, x: torch.Tensor):
202
+ x2_1, x2_2 = flatten_diag_outer_product_off1(x, x)
203
+ return torch.cat([torch.ones_like(x[..., 0:1]), x / self.rrd, x2_2 / (self.rd * self.r2), x2_1 / self.rd], dim=-1)
204
+
205
+
206
+ class RebasedFeatureMap(nn.Module):
207
+
208
+ def __init__(
209
+ self,
210
+ head_dim: int,
211
+ use_gamma: Optional[bool] = True,
212
+ use_beta: Optional[bool] = True,
213
+ normalize: Optional[bool] = True
214
+ ) -> RebasedFeatureMap:
215
+ super().__init__()
216
+
217
+ self.head_dim = head_dim
218
+ self.use_gamma = use_gamma
219
+ self.use_beta = use_beta
220
+ self.normalize = normalize
221
+
222
+ self.gamma = None
223
+ self.beta = None
224
+ if use_gamma:
225
+ self.gamma = nn.Parameter(torch.ones(head_dim))
226
+ if use_beta:
227
+ self.beta = nn.Parameter(torch.zeros(head_dim))
228
+
229
+ def forward(self, x: torch.Tensor, flatten: Optional[bool] = True):
230
+ if self.use_beta and self.use_gamma and self.normalize:
231
+ x = layer_norm(x, self.gamma, self.beta)
232
+ elif self.normalize:
233
+ x = F.layer_norm(x, (self.head_dim,), self.gamma, self.beta)
234
+ elif self.use_gamma and self.use_beta:
235
+ x = torch.addcmul(self.beta, x, self.gamma)
236
+ elif self.use_gamma:
237
+ x = x.mul(self.gamma)
238
+ else:
239
+ raise RuntimeError(f"Not supported combination of `use_gamma`, `use_beta` and `normalize`, "
240
+ f"which is currentlt set as (`{self.use_gamma}`, `{self.use_beta}`, `{self.normalize}`)")
241
+ if not flatten:
242
+ return x
243
+ x2_1, x2_2 = flatten_diag_outer_product_off1(x, x)
244
+ # rebased use learnable parameters to approximate any quadratic function
245
+ return torch.cat([x2_2 * self.head_dim ** -0.5, x2_1 * (2 / self.head_dim) ** 0.5], dim=-1)
246
+
247
+
248
+ class ReLUFeatureMap(nn.Module):
249
+
250
+ def __init__(
251
+ self,
252
+ ) -> ReLUFeatureMap:
253
+ super().__init__()
254
+
255
+ def forward(self, x: torch.Tensor):
256
+ return F.relu(x)
257
+
258
+
259
+ class SquaredReLUFeatureMap(nn.Module):
260
+
261
+ def __init__(
262
+ self,
263
+ ) -> SquaredReLUFeatureMap:
264
+ super().__init__()
265
+
266
+ def forward(self, x: torch.Tensor):
267
+ return sqrelu(x)
268
+
269
+
270
+ class GELUFeatureMap(nn.Module):
271
+
272
+ def __init__(
273
+ self,
274
+ ) -> GELUFeatureMap:
275
+ super().__init__()
276
+
277
+ def forward(self, x: torch.Tensor):
278
+ return fast_gelu_impl(x)
279
+
280
+
281
+ class SwishFeatureMap(nn.Module):
282
+
283
+ def __init__(
284
+ self,
285
+ ) -> SwishFeatureMap:
286
+ super().__init__()
287
+
288
+ def forward(self, x: torch.Tensor):
289
+ return swish(x)
290
+
291
+
292
+ class SigmoidFeatureMap(nn.Module):
293
+
294
+ def __init__(
295
+ self,
296
+ ) -> SigmoidFeatureMap:
297
+ super().__init__()
298
+
299
+ def forward(self, x: torch.Tensor):
300
+ return sigmoid(x)
modules/fused_bitlinear.py ADDED
@@ -0,0 +1,634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ # Implementations of BitLinear layer with fused LayerNorm and quantized Linear layer.
5
+ # [The Era of 1-bit LLMs: All Large Language Models are in 1.58 Bits](https://arxiv.org/abs/2402.17764)
6
+ # [Scalable MatMul-free Language Modeling](https://arxiv.org/abs/2406.02528)
7
+
8
+ # Code adapted from https://github.com/ridgerchu/matmulfreellm/
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ import triton
18
+ import triton.language as tl
19
+
20
+ from fla.modules.layernorm import RMSNorm
21
+ from fla.utils import autotune_cache_kwargs, get_multiprocessor_count, input_guard, is_amd, require_version
22
+
23
+ NUM_WARPS_AUTOTUNE = [1, 2, 4, 8, 16] if is_amd else [1, 2, 4, 8, 16, 32]
24
+
25
+
26
+ def activation_quant(x):
27
+ """
28
+ Per-token quantization to 8 bits. No grouping is needed for quantization.
29
+
30
+ Args:
31
+ x: An activation tensor with shape [n, d].
32
+
33
+ Returns:
34
+ A quantized activation tensor with shape [n, d].
35
+ """
36
+ # Compute the scale factor
37
+ scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp_(min=1e-5)
38
+ # Quantize and then de-quantize the tensor
39
+ y = (x * scale).round().clamp_(-128, 127) / scale
40
+ return y
41
+
42
+
43
+ def weight_quant(w):
44
+ """
45
+ Per-tensor quantization to 1.58 bits. No grouping is needed for quantization.
46
+
47
+ Args:
48
+ w: A weight tensor with shape [d, k].
49
+
50
+ Returns:
51
+ A quantized weight tensor with shape [d, k].
52
+ """
53
+ # Compute the scale factor
54
+ scale = 1.0 / w.abs().mean().clamp_(min=1e-5)
55
+ # Quantize and then de-quantize the tensor
56
+ u = (w * scale).round().clamp_(-1, 1) / scale
57
+ return u
58
+
59
+
60
+ @triton.autotune(
61
+ configs=[
62
+ triton.Config({}, num_warps=num_warps)
63
+ for num_warps in NUM_WARPS_AUTOTUNE
64
+ ],
65
+ key=["N", "HAS_RESIDUAL", "STORE_RESIDUAL_OUT", "IS_RMS_NORM", "HAS_BIAS"],
66
+ **autotune_cache_kwargs
67
+ )
68
+ @triton.jit
69
+ def layer_norm_fwd_kernel_quant(
70
+ X, # pointer to the input
71
+ Y, # pointer to the output
72
+ W, # pointer to the weights
73
+ B, # pointer to the biases
74
+ RESIDUAL, # pointer to the residual
75
+ RESIDUAL_OUT, # pointer to the residual
76
+ Mean, # pointer to the mean
77
+ Rstd, # pointer to the 1/std
78
+ stride_x_row, # how much to increase the pointer when moving by 1 row
79
+ stride_y_row,
80
+ stride_res_row,
81
+ stride_res_out_row,
82
+ N, # number of columns in X
83
+ eps, # epsilon to avoid division by zero
84
+ IS_RMS_NORM: tl.constexpr,
85
+ BLOCK_N: tl.constexpr,
86
+ HAS_RESIDUAL: tl.constexpr,
87
+ STORE_RESIDUAL_OUT: tl.constexpr,
88
+ HAS_WEIGHT: tl.constexpr,
89
+ HAS_BIAS: tl.constexpr
90
+ ):
91
+ # Map the program id to the row of X and Y it should compute.
92
+ row = tl.program_id(0)
93
+ X += row * stride_x_row
94
+ Y += row * stride_y_row
95
+ if HAS_RESIDUAL:
96
+ RESIDUAL += row * stride_res_row
97
+ if STORE_RESIDUAL_OUT:
98
+ RESIDUAL_OUT += row * stride_res_out_row
99
+ # Compute mean and variance
100
+ cols = tl.arange(0, BLOCK_N)
101
+ x = tl.load(X + cols, mask=cols < N, other=0.0).to(tl.float32)
102
+ if HAS_RESIDUAL:
103
+ residual = tl.load(RESIDUAL + cols, mask=cols < N, other=0.0).to(tl.float32)
104
+ x += residual
105
+ if STORE_RESIDUAL_OUT:
106
+ tl.store(RESIDUAL_OUT + cols, x, mask=cols < N)
107
+ if not IS_RMS_NORM:
108
+ mean = tl.sum(x, axis=0) / N
109
+ tl.store(Mean + row, mean)
110
+ xbar = tl.where(cols < N, x - mean, 0.0)
111
+ var = tl.sum(xbar * xbar, axis=0) / N
112
+ else:
113
+ xbar = tl.where(cols < N, x, 0.0)
114
+ var = tl.sum(xbar * xbar, axis=0) / N
115
+ rstd = 1 / tl.sqrt(var + eps)
116
+ tl.store(Rstd + row, rstd)
117
+ # Normalize and apply linear transformation
118
+ mask = cols < N
119
+ if HAS_WEIGHT:
120
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
121
+ if HAS_BIAS:
122
+ b = tl.load(B + cols, mask=mask).to(tl.float32)
123
+ x_hat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
124
+
125
+ y = x_hat * w if HAS_WEIGHT else x_hat
126
+ if HAS_BIAS:
127
+ y = y + b
128
+
129
+ # Aply quantization to the output
130
+ scale = 127.0 / tl.maximum(tl.max(tl.abs(y), 0), 1e-5)
131
+ # Quantize and then de-quantize the tensor
132
+ y = tl.extra.cuda.libdevice.round(y * scale)
133
+ y = tl.maximum(tl.minimum(y, 127), -128) / scale
134
+
135
+ # Write output
136
+ tl.store(Y + cols, y, mask=mask)
137
+
138
+
139
+ def layer_norm_fwd_quant(
140
+ x: torch.Tensor,
141
+ weight: torch.Tensor,
142
+ bias: torch.Tensor,
143
+ eps: float,
144
+ residual: torch.Tensor = None,
145
+ out_dtype: torch.dtype = None,
146
+ residual_dtype: torch.dtype = None,
147
+ is_rms_norm: bool = False
148
+ ):
149
+ if residual is not None:
150
+ residual_dtype = residual.dtype
151
+ M, N = x.shape
152
+ # allocate output
153
+ y = torch.empty_like(x, dtype=x.dtype if out_dtype is None else out_dtype)
154
+ if residual is not None or (residual_dtype is not None and residual_dtype != x.dtype):
155
+ residual_out = torch.empty(M, N, device=x.device, dtype=residual_dtype)
156
+ else:
157
+ residual_out = None
158
+ mean = torch.empty((M,), dtype=torch.float32, device=x.device) if not is_rms_norm else None
159
+ rstd = torch.empty((M,), dtype=torch.float32, device=x.device)
160
+ # Less than 64KB per feature: enqueue fused kernel
161
+ MAX_FUSED_SIZE = 65536 // x.element_size()
162
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
163
+ if N > BLOCK_N:
164
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
165
+ # heuristics for number of warps
166
+ layer_norm_fwd_kernel_quant[(M,)](
167
+ x,
168
+ y,
169
+ weight,
170
+ bias,
171
+ residual,
172
+ residual_out,
173
+ mean,
174
+ rstd,
175
+ x.stride(0),
176
+ y.stride(0),
177
+ residual.stride(0) if residual is not None else 0,
178
+ residual_out.stride(0) if residual_out is not None else 0,
179
+ N,
180
+ eps,
181
+ is_rms_norm,
182
+ BLOCK_N,
183
+ residual is not None,
184
+ residual_out is not None,
185
+ weight is not None,
186
+ bias is not None,
187
+ )
188
+ # residual_out is None if residual is None and residual_dtype == input_dtype
189
+ return y, mean, rstd, residual_out if residual_out is not None else x
190
+
191
+
192
+ @triton.heuristics({
193
+ "RECOMPUTE_OUTPUT": lambda args: args["Y"] is not None
194
+ })
195
+ @triton.autotune(
196
+ configs=[
197
+ triton.Config({}, num_warps=num_warps)
198
+ for num_warps in NUM_WARPS_AUTOTUNE
199
+ ],
200
+ key=["N", "HAS_DRESIDUAL", "STORE_DRESIDUAL", "IS_RMS_NORM", "HAS_BIAS"],
201
+ **autotune_cache_kwargs
202
+ )
203
+ @triton.jit
204
+ def layer_norm_bwd_kernel(
205
+ X, # pointer to the input
206
+ W, # pointer to the weights
207
+ B, # pointer to the biases
208
+ Y, # pointer to the output to be recomputed
209
+ DY, # pointer to the output gradient
210
+ DX, # pointer to the input gradient
211
+ DW, # pointer to the partial sum of weights gradient
212
+ DB, # pointer to the partial sum of biases gradient
213
+ DRESIDUAL,
214
+ DRESIDUAL_IN,
215
+ Mean, # pointer to the mean
216
+ Rstd, # pointer to the 1/std
217
+ stride_x_row, # how much to increase the pointer when moving by 1 row
218
+ stride_y_row,
219
+ stride_dy_row,
220
+ stride_dx_row,
221
+ stride_dres_row,
222
+ stride_dres_in_row,
223
+ M, # number of rows in X
224
+ N, # number of columns in X
225
+ eps, # epsilon to avoid division by zero
226
+ rows_per_program,
227
+ IS_RMS_NORM: tl.constexpr,
228
+ BLOCK_N: tl.constexpr,
229
+ HAS_DRESIDUAL: tl.constexpr,
230
+ STORE_DRESIDUAL: tl.constexpr,
231
+ HAS_WEIGHT: tl.constexpr,
232
+ HAS_BIAS: tl.constexpr,
233
+ RECOMPUTE_OUTPUT: tl.constexpr,
234
+ ):
235
+ # Map the program id to the elements of X, DX, and DY it should compute.
236
+ row_block_id = tl.program_id(0)
237
+ row_start = row_block_id * rows_per_program
238
+ cols = tl.arange(0, BLOCK_N)
239
+ mask = cols < N
240
+ X += row_start * stride_x_row
241
+ if HAS_DRESIDUAL:
242
+ DRESIDUAL += row_start * stride_dres_row
243
+ if STORE_DRESIDUAL:
244
+ DRESIDUAL_IN += row_start * stride_dres_in_row
245
+ DY += row_start * stride_dy_row
246
+ DX += row_start * stride_dx_row
247
+ if RECOMPUTE_OUTPUT:
248
+ Y += row_start * stride_y_row
249
+ if HAS_WEIGHT:
250
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
251
+ dw = tl.zeros((BLOCK_N,), dtype=tl.float32)
252
+ if RECOMPUTE_OUTPUT and HAS_BIAS:
253
+ b = tl.load(B + cols, mask=mask, other=0.0).to(tl.float32)
254
+ if HAS_BIAS:
255
+ db = tl.zeros((BLOCK_N,), dtype=tl.float32)
256
+ row_end = min((row_block_id + 1) * rows_per_program, M)
257
+ for row in range(row_start, row_end):
258
+ # Load data to SRAM
259
+ x = tl.load(X + cols, mask=mask, other=0).to(tl.float32)
260
+ dy = tl.load(DY + cols, mask=mask, other=0).to(tl.float32)
261
+ if not IS_RMS_NORM:
262
+ mean = tl.load(Mean + row)
263
+ rstd = tl.load(Rstd + row)
264
+ # Compute dx
265
+ xhat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
266
+ xhat = tl.where(mask, xhat, 0.0)
267
+ if RECOMPUTE_OUTPUT:
268
+ y = xhat * w if HAS_WEIGHT else xhat
269
+ if HAS_BIAS:
270
+ y = y + b
271
+
272
+ # Aply quantization to the output
273
+ scale = 127.0 / tl.maximum(tl.max(tl.abs(y), 0), 1e-5)
274
+ # Quantize and then de-quantize the tensor
275
+ y = tl.extra.cuda.libdevice.round(y * scale)
276
+ y = tl.maximum(tl.minimum(y, 127), -128) / scale
277
+
278
+ tl.store(Y + cols, y, mask=mask)
279
+ wdy = dy
280
+ if HAS_WEIGHT:
281
+ wdy = dy * w
282
+ dw += dy * xhat
283
+ if HAS_BIAS:
284
+ db += dy
285
+ if not IS_RMS_NORM:
286
+ c1 = tl.sum(xhat * wdy, axis=0) / N
287
+ c2 = tl.sum(wdy, axis=0) / N
288
+ dx = (wdy - (xhat * c1 + c2)) * rstd
289
+ else:
290
+ c1 = tl.sum(xhat * wdy, axis=0) / N
291
+ dx = (wdy - xhat * c1) * rstd
292
+ if HAS_DRESIDUAL:
293
+ dres = tl.load(DRESIDUAL + cols, mask=mask, other=0).to(tl.float32)
294
+ dx += dres
295
+ # Write dx
296
+ if STORE_DRESIDUAL:
297
+ tl.store(DRESIDUAL_IN + cols, dx, mask=mask)
298
+ tl.store(DX + cols, dx, mask=mask)
299
+
300
+ X += stride_x_row
301
+ if HAS_DRESIDUAL:
302
+ DRESIDUAL += stride_dres_row
303
+ if STORE_DRESIDUAL:
304
+ DRESIDUAL_IN += stride_dres_in_row
305
+ if RECOMPUTE_OUTPUT:
306
+ Y += stride_y_row
307
+ DY += stride_dy_row
308
+ DX += stride_dx_row
309
+ if HAS_WEIGHT:
310
+ tl.store(DW + row_block_id * N + cols, dw, mask=mask)
311
+ if HAS_BIAS:
312
+ tl.store(DB + row_block_id * N + cols, db, mask=mask)
313
+
314
+
315
+ def layer_norm_bwd(
316
+ dy: torch.Tensor,
317
+ x: torch.Tensor,
318
+ weight: torch.Tensor,
319
+ bias: torch.Tensor,
320
+ eps: float,
321
+ mean: torch.Tensor,
322
+ rstd: torch.Tensor,
323
+ dresidual: torch.Tensor = None,
324
+ has_residual: bool = False,
325
+ is_rms_norm: bool = False,
326
+ x_dtype: torch.dtype = None,
327
+ recompute_output: bool = False,
328
+ ):
329
+ M, N = x.shape
330
+ # allocate output
331
+ dx = torch.empty_like(x) if x_dtype is None else torch.empty(M, N, dtype=x_dtype, device=x.device)
332
+ dresidual_in = torch.empty_like(x) if has_residual and dx.dtype != x.dtype else None
333
+ y = torch.empty(M, N, dtype=dy.dtype, device=dy.device) if recompute_output else None
334
+
335
+ # Less than 64KB per feature: enqueue fused kernel
336
+ MAX_FUSED_SIZE = 65536 // x.element_size()
337
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
338
+ if N > BLOCK_N:
339
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
340
+ sm_count = get_multiprocessor_count(x.device.index)
341
+ _dw = torch.empty((sm_count, N), dtype=torch.float32, device=weight.device) if weight is not None else None
342
+ _db = torch.empty((sm_count, N), dtype=torch.float32, device=bias.device) if bias is not None else None
343
+ rows_per_program = math.ceil(M / sm_count)
344
+ grid = (sm_count,)
345
+ layer_norm_bwd_kernel[grid](
346
+ x,
347
+ weight,
348
+ bias,
349
+ y,
350
+ dy,
351
+ dx,
352
+ _dw,
353
+ _db,
354
+ dresidual,
355
+ dresidual_in,
356
+ mean,
357
+ rstd,
358
+ x.stride(0),
359
+ 0 if not recompute_output else y.stride(0),
360
+ dy.stride(0),
361
+ dx.stride(0),
362
+ dresidual.stride(0) if dresidual is not None else 0,
363
+ dresidual_in.stride(0) if dresidual_in is not None else 0,
364
+ M,
365
+ N,
366
+ eps,
367
+ rows_per_program,
368
+ is_rms_norm,
369
+ BLOCK_N,
370
+ dresidual is not None,
371
+ dresidual_in is not None,
372
+ weight is not None,
373
+ bias is not None,
374
+ )
375
+ dw = _dw.sum(0).to(weight.dtype) if weight is not None else None
376
+ db = _db.sum(0).to(bias.dtype) if bias is not None else None
377
+ # Don't need to compute dresidual_in separately in this case
378
+ if has_residual and dx.dtype == x.dtype:
379
+ dresidual_in = dx
380
+ return (dx, dw, db, dresidual_in) if not recompute_output else (dx, dw, db, dresidual_in, y)
381
+
382
+
383
+ class LayerNormLinearQuantFn(torch.autograd.Function):
384
+
385
+ @staticmethod
386
+ @input_guard
387
+ def forward(
388
+ ctx,
389
+ x,
390
+ norm_weight,
391
+ norm_bias,
392
+ linear_weight,
393
+ linear_bias,
394
+ residual=None,
395
+ eps=1e-6,
396
+ prenorm=False,
397
+ residual_in_fp32=False,
398
+ is_rms_norm=False,
399
+ ):
400
+ x_shape_og = x.shape
401
+ # reshape input data into 2D tensor
402
+ x = x.reshape(-1, x.shape[-1])
403
+ if residual is not None:
404
+ assert residual.shape == x_shape_og
405
+ residual = residual.reshape(-1, residual.shape[-1])
406
+ residual_dtype = residual.dtype if residual is not None else (torch.float32 if residual_in_fp32 else None)
407
+ y, mean, rstd, residual_out = layer_norm_fwd_quant(
408
+ x,
409
+ norm_weight,
410
+ norm_bias,
411
+ eps,
412
+ residual,
413
+ out_dtype=None if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype(),
414
+ residual_dtype=residual_dtype,
415
+ is_rms_norm=is_rms_norm,
416
+ )
417
+ y = y.reshape(x_shape_og)
418
+ dtype = torch.get_autocast_gpu_dtype() if torch.is_autocast_enabled() else y.dtype
419
+ linear_weight = weight_quant(linear_weight).to(dtype)
420
+ linear_bias = linear_bias.to(dtype) if linear_bias is not None else None
421
+ out = F.linear(y.to(linear_weight.dtype), linear_weight, linear_bias)
422
+ # We don't store y, will be recomputed in the backward pass to save memory
423
+ ctx.save_for_backward(residual_out, norm_weight, norm_bias, linear_weight, mean, rstd)
424
+ ctx.x_shape_og = x_shape_og
425
+ ctx.eps = eps
426
+ ctx.is_rms_norm = is_rms_norm
427
+ ctx.has_residual = residual is not None
428
+ ctx.prenorm = prenorm
429
+ ctx.x_dtype = x.dtype
430
+ ctx.linear_bias_is_none = linear_bias is None
431
+ return out if not prenorm else (out, residual_out.reshape(x_shape_og))
432
+
433
+ @staticmethod
434
+ @input_guard
435
+ def backward(ctx, dout, *args):
436
+ x, norm_weight, norm_bias, linear_weight, mean, rstd = ctx.saved_tensors
437
+ dout = dout.reshape(-1, dout.shape[-1])
438
+ dy = F.linear(dout, linear_weight.t())
439
+ dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0)
440
+ assert dy.shape == x.shape
441
+ if ctx.prenorm:
442
+ dresidual = args[0]
443
+ dresidual = dresidual.reshape(-1, dresidual.shape[-1])
444
+ assert dresidual.shape == x.shape
445
+ else:
446
+ dresidual = None
447
+ dx, dnorm_weight, dnorm_bias, dresidual_in, y = layer_norm_bwd(
448
+ dy,
449
+ x,
450
+ norm_weight,
451
+ norm_bias,
452
+ ctx.eps,
453
+ mean,
454
+ rstd,
455
+ dresidual,
456
+ ctx.has_residual,
457
+ ctx.is_rms_norm,
458
+ x_dtype=ctx.x_dtype,
459
+ recompute_output=True
460
+ )
461
+ dlinear_weight = torch.einsum("bo,bi->oi", dout, y)
462
+ return (
463
+ dx.reshape(ctx.x_shape_og),
464
+ dnorm_weight,
465
+ dnorm_bias,
466
+ dlinear_weight,
467
+ dlinear_bias,
468
+ dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
469
+ None,
470
+ None,
471
+ None,
472
+ None,
473
+ )
474
+
475
+
476
+ def layer_norm_linear_quant_fn(
477
+ x,
478
+ norm_weight,
479
+ norm_bias,
480
+ linear_weight,
481
+ linear_bias,
482
+ residual=None,
483
+ eps=1e-6,
484
+ prenorm=False,
485
+ residual_in_fp32=False,
486
+ is_rms_norm=False,
487
+ ):
488
+ return LayerNormLinearQuantFn.apply(
489
+ x,
490
+ norm_weight,
491
+ norm_bias,
492
+ linear_weight,
493
+ linear_bias,
494
+ residual,
495
+ eps,
496
+ prenorm,
497
+ residual_in_fp32,
498
+ is_rms_norm,
499
+ )
500
+
501
+
502
+ def rms_norm_linear_quant(
503
+ x: torch.Tensor,
504
+ norm_weight: torch.Tensor,
505
+ norm_bias: torch.Tensor,
506
+ linear_weight: torch.Tensor,
507
+ linear_bias: torch.Tensor,
508
+ residual: torch.Tensor = None,
509
+ eps: float = 1e-5,
510
+ prenorm: bool = False,
511
+ residual_in_fp32: bool = False
512
+ ):
513
+ return layer_norm_linear_quant_fn(
514
+ x=x,
515
+ norm_weight=norm_weight,
516
+ norm_bias=norm_bias,
517
+ linear_weight=linear_weight,
518
+ linear_bias=linear_bias,
519
+ residual=residual,
520
+ eps=eps,
521
+ prenorm=prenorm,
522
+ residual_in_fp32=residual_in_fp32,
523
+ is_rms_norm=True
524
+ )
525
+
526
+
527
+ @require_version("triton>=3.0", "Triton >= 3.0 is required to do online quantization.")
528
+ def bit_linear(x, weight, bias=None, norm_weight=None, norm_bias=None, eps=1e-8):
529
+ """
530
+ A functional version of BitLinear that applies quantization to activations and weights.
531
+
532
+ Args:
533
+ x: Input tensor with shape [n, d].
534
+ weight: Weight tensor with shape [out_features, in_features].
535
+ bias: Bias tensor with shape [out_features] (optional).
536
+ norm_weight: Weight tensor for RMS normalization with shape [in_features].
537
+ norm_bias: Bias tensor for RMS normalization with shape [in_features].
538
+ eps: A small constant for numerical stability in normalization.
539
+
540
+ Returns:
541
+ Output tensor with shape [n, out_features].
542
+ """
543
+ return layer_norm_linear_quant_fn(
544
+ x,
545
+ norm_weight,
546
+ norm_bias,
547
+ weight,
548
+ bias,
549
+ is_rms_norm=True
550
+ )
551
+
552
+
553
+ class BitLinear(nn.Linear):
554
+ """
555
+ A custom linear layer that applies quantization on both activations and weights.
556
+ This is primarily for training; kernel optimization is needed for efficiency in deployment.
557
+ """
558
+
559
+ def __init__(
560
+ self,
561
+ in_features: int,
562
+ out_features: int,
563
+ bias: bool = False,
564
+ norm_eps: float = 1e-8
565
+ ):
566
+ """
567
+ Initializes the BitLinear layer.
568
+
569
+ Args:
570
+ in_features: Size of each input sample.
571
+ out_features: Size of each output sample.
572
+ bias: If set to False, the layer will not learn an additive bias. Default: True.
573
+ """
574
+ # Initialize the superclass nn.Linear with the given parameters
575
+ super(BitLinear, self).__init__(in_features, out_features, bias=bias)
576
+
577
+ self.norm = RMSNorm(in_features, eps=norm_eps)
578
+
579
+ def __repr__(self) -> str:
580
+ return f"{self.__class__.__name__}({super().extra_repr()}, norm_eps={self.norm.eps})"
581
+
582
+ def forward(self, x):
583
+ """
584
+ Overrides the forward pass to include quantization.
585
+
586
+ Args:
587
+ x: An input tensor with shape [n, d].
588
+
589
+ Returns:
590
+ An output tensor with shape [n, d].
591
+ """
592
+ # Weight tensor
593
+ w = self.weight
594
+
595
+ # Apply RMS normalization to the input
596
+ x_norm = self.norm(x)
597
+
598
+ # Apply quantization to both activations and weights
599
+ # Uses Straight-Through Estimator (STE) trick with .detach() for gradient flow
600
+ x_quant = x_norm + (activation_quant(x_norm) - x_norm).detach()
601
+ w_quant = w + (weight_quant(w) - w).detach()
602
+ # Perform linear operation with quantized values
603
+ y = F.linear(x_quant, w_quant)
604
+
605
+ return y
606
+
607
+
608
+ class FusedBitLinear(BitLinear):
609
+ """
610
+ A custom linear layer that applies quantization on both activations and weights.
611
+ This is primarily for training; kernel optimization is needed for efficiency in deployment.
612
+ """
613
+
614
+ def __init__(self, in_features, out_features, bias=False):
615
+ """
616
+ Initializes the BitLinear layer.
617
+
618
+ Args:
619
+ in_features: Size of each input sample.
620
+ out_features: Size of each output sample.
621
+ bias: If set to False, the layer will not learn an additive bias. Default: True.
622
+ """
623
+ # Initialize the superclass nn.Linear with the given parameters
624
+ super(FusedBitLinear, self).__init__(in_features, out_features, bias=bias)
625
+
626
+ def forward(self, x):
627
+ return layer_norm_linear_quant_fn(
628
+ x,
629
+ self.norm.weight,
630
+ self.norm.bias,
631
+ self.weight,
632
+ self.bias,
633
+ is_rms_norm=True
634
+ )
modules/fused_cross_entropy.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright (c) 2023, Tri Dao.
4
+
5
+ from typing import Any, Tuple
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import triton
10
+ import triton.language as tl
11
+
12
+ from fla.ops.utils.op import exp, log
13
+ from fla.utils import input_guard
14
+
15
+ # `all_gather_into_tensor` and `reduce_scatter_tensor` are new placeholders for
16
+ # `_all_gather_base` and `_reduce_scatter_base`. They require the most recent
17
+ # version of PyTorch. The following 2 lines are for backward compatibility with
18
+ # older PyTorch.
19
+ if "all_gather_into_tensor" not in dir(torch.distributed):
20
+ torch.distributed.all_gather_into_tensor = torch.distributed._all_gather_base
21
+
22
+
23
+ @triton.heuristics({
24
+ "HAS_SMOOTHING": lambda args: args["label_smoothing"] > 0.0,
25
+ })
26
+ @triton.jit
27
+ def cross_entropy_fwd_kernel(
28
+ loss_ptr, # data ptrs
29
+ lse_ptr,
30
+ z_loss_ptr,
31
+ logits_ptr,
32
+ labels_ptr,
33
+ label_smoothing,
34
+ logit_scale,
35
+ lse_square_scale,
36
+ ignore_index,
37
+ total_classes,
38
+ class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes
39
+ n_cols, # shapes
40
+ n_rows,
41
+ logits_row_stride, # strides
42
+ BLOCK_SIZE: tl.constexpr,
43
+ HAS_SMOOTHING: tl.constexpr,
44
+ # if SPLIT (e.g. tensor parallel), don't include the LSE in the loss since it's not the final LSE
45
+ SPLIT: tl.constexpr,
46
+ ):
47
+ row_idx = tl.program_id(0)
48
+ col_block_idx = tl.program_id(1)
49
+ logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64)
50
+ col_offsets = col_block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
51
+ label_idx = tl.load(labels_ptr + row_idx)
52
+ logits = tl.load(logits_ptr + col_offsets, mask=col_offsets < n_cols, other=-float("inf"))
53
+ logits = logits.to(tl.float32) * logit_scale
54
+ max_logits = tl.max(logits, 0)
55
+ if HAS_SMOOTHING:
56
+ sum_logits = tl.sum(tl.where(col_offsets < n_cols, logits, 0.0), 0)
57
+ lse = log(tl.sum(exp(logits - max_logits), 0)) + max_logits
58
+ tl.store(lse_ptr + col_block_idx * n_rows + row_idx, lse)
59
+ if label_idx == ignore_index:
60
+ loss = 0.0
61
+ z_loss = 0.0
62
+ else:
63
+ label_idx -= class_start_idx
64
+ if label_idx >= col_block_idx * BLOCK_SIZE and label_idx < min(
65
+ n_cols, (col_block_idx + 1) * BLOCK_SIZE
66
+ ):
67
+ logits_label = tl.load(logits_ptr + label_idx) * logit_scale
68
+ if HAS_SMOOTHING:
69
+ loss = (
70
+ (lse if not SPLIT else 0.0)
71
+ - label_smoothing * sum_logits / total_classes
72
+ - (1 - label_smoothing) * logits_label
73
+ )
74
+ else:
75
+ loss = (lse if not SPLIT else 0.0) - logits_label
76
+ else:
77
+ # If label is out of bounds, we set the CE loss to 0.0. But we still want the label_smoothing loss
78
+ if HAS_SMOOTHING:
79
+ loss = label_smoothing * ((lse if not SPLIT else 0.0) - sum_logits / total_classes)
80
+ else:
81
+ loss = 0.0
82
+ if not SPLIT:
83
+ z_loss = lse_square_scale * lse * lse
84
+ loss += z_loss
85
+ else:
86
+ z_loss = 0.0
87
+ tl.store(loss_ptr + col_block_idx * n_rows + row_idx, loss)
88
+ if not SPLIT:
89
+ tl.store(z_loss_ptr + col_block_idx * n_rows + row_idx, z_loss)
90
+
91
+
92
+ @triton.heuristics({
93
+ "HAS_SMOOTHING": lambda args: args["label_smoothing"] > 0.0,
94
+ })
95
+ @triton.jit
96
+ def cross_entropy_bwd_kernel(
97
+ dlogits_ptr, # data ptrs
98
+ dloss_ptr,
99
+ logits_ptr,
100
+ lse_ptr,
101
+ labels_ptr,
102
+ label_smoothing,
103
+ logit_scale,
104
+ lse_square_scale,
105
+ ignore_index,
106
+ total_classes,
107
+ class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes
108
+ n_cols, # shapes
109
+ logits_row_stride, # strides
110
+ dlogits_row_stride,
111
+ dloss_row_stride,
112
+ BLOCK_SIZE: tl.constexpr,
113
+ HAS_SMOOTHING: tl.constexpr,
114
+ ):
115
+ row_idx = tl.program_id(0)
116
+ col_block_idx = tl.program_id(1)
117
+ logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64)
118
+ dlogits_ptr = dlogits_ptr + row_idx * dlogits_row_stride.to(tl.int64)
119
+ col_offsets = col_block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
120
+ label_idx = tl.load(labels_ptr + row_idx)
121
+ if label_idx != ignore_index:
122
+ dloss = tl.load(dloss_ptr + row_idx * dloss_row_stride)
123
+ else:
124
+ dloss = 0.0
125
+ logits = tl.load(logits_ptr + col_offsets, mask=col_offsets < n_cols, other=-float("inf")).to(
126
+ tl.float32
127
+ ) * logit_scale
128
+ lse = tl.load(lse_ptr + row_idx)
129
+ probs = exp(logits - lse)
130
+ probs += 2.0 * lse_square_scale * lse * probs
131
+ label_idx -= class_start_idx
132
+ if HAS_SMOOTHING:
133
+ smooth_negative = label_smoothing / total_classes
134
+ probs = tl.where(col_offsets == label_idx, probs - (1 - label_smoothing), probs) - smooth_negative
135
+ else:
136
+ probs = tl.where(col_offsets == label_idx, probs - 1.0, probs)
137
+ tl.store(dlogits_ptr + col_offsets, (dloss * logit_scale) * probs, mask=col_offsets < n_cols)
138
+
139
+
140
+ def fused_cross_entropy_forward(
141
+ logits: torch.Tensor,
142
+ target: torch.Tensor,
143
+ label_smoothing: float = 0.0,
144
+ logit_scale: float = 1.0,
145
+ lse_square_scale: float = 0.0,
146
+ ignore_index: int = -100,
147
+ process_group=None,
148
+ ):
149
+ n_rows, n_cols = logits.shape
150
+ assert target.shape == (n_rows,)
151
+ world_size = 1 if process_group is None else torch.distributed.get_world_size(process_group)
152
+ total_classes = world_size * n_cols
153
+ rank = 0 if process_group is None else torch.distributed.get_rank(process_group)
154
+ class_start_idx = rank * n_cols
155
+
156
+ if logits.stride(-1) != 1:
157
+ logits = logits.contiguous()
158
+ # Set these similar to https://github.com/openai/triton/blob/main/python/tutorials/02-fused-softmax.py
159
+ MAX_BLOCK_SIZE = 64 * 1024
160
+ BLOCK_SIZE = min(triton.next_power_of_2(n_cols), MAX_BLOCK_SIZE)
161
+ num_warps = (
162
+ 4
163
+ if BLOCK_SIZE < 2048
164
+ else (8 if BLOCK_SIZE < 8192 else (16 if BLOCK_SIZE < 128 * 1024 else 32))
165
+ )
166
+ # We may split the lse computation across multiple blocks, then do a reduction
167
+ # lse(local_lse) to get the final LSE. This is faster for large n_cols (e.g., > 64k)
168
+ # where having just one thread block processing more than 64k elements is slow.
169
+ split = world_size > 1 or n_cols > MAX_BLOCK_SIZE
170
+ n_splits = (n_cols + BLOCK_SIZE - 1) // BLOCK_SIZE
171
+ loss_shape = (n_splits, n_rows) if n_splits > 1 else (n_rows,)
172
+ losses = torch.empty(*loss_shape, dtype=torch.float, device=logits.device)
173
+ lse = torch.empty(*loss_shape, dtype=torch.float, device=logits.device)
174
+ z_losses = torch.empty(*loss_shape, dtype=torch.float, device=logits.device)
175
+
176
+ cross_entropy_fwd_kernel[(n_rows, n_splits)](
177
+ losses, # data ptrs
178
+ lse,
179
+ z_losses,
180
+ logits,
181
+ target,
182
+ label_smoothing,
183
+ logit_scale,
184
+ lse_square_scale,
185
+ ignore_index,
186
+ total_classes,
187
+ class_start_idx,
188
+ n_cols, # shapes
189
+ n_rows,
190
+ logits.stride(0), # strides
191
+ BLOCK_SIZE=BLOCK_SIZE, # constants
192
+ num_warps=num_warps,
193
+ SPLIT=split
194
+ )
195
+
196
+ if split:
197
+ # If there's no label_smoothing, if target are in the vocab of this partition, losses contains
198
+ # - predicted logit, and 0 otherwise.
199
+ # If there's label_smoothing=0.1, for target in the vocab of this partition, losses contains
200
+ # -0.9 * predicted logit - 0.1 * sum logit / total_classes.
201
+ # For target not in the vocab of this partition, losses contains
202
+ # -0.1 * sum logit / total_classes.
203
+ if n_splits > 1:
204
+ lse = torch.logsumexp(lse, dim=0)
205
+ losses = losses.sum(dim=0)
206
+ if world_size > 1:
207
+ lse_allgather = torch.empty(world_size, n_rows, dtype=lse.dtype, device=lse.device)
208
+ torch.distributed.all_gather_into_tensor(lse_allgather, lse, group=process_group)
209
+ handle_losses = torch.distributed.all_reduce(
210
+ losses, op=torch.distributed.ReduceOp.SUM, group=process_group, async_op=True
211
+ )
212
+ lse = torch.logsumexp(lse_allgather, dim=0)
213
+ handle_losses.wait()
214
+ # After the allreduce, if there's no label_smoothing, the total losses are - predicted_logit,
215
+ # we just have to add the (global) lse.
216
+ # If there's label_smoothing=0.1, the total losses are
217
+ # -0.9 * predicted_logit - 0.1 * sum logit / total_classes.
218
+ # Again, we just have to add the (global) lse.
219
+ losses += lse
220
+ if lse_square_scale != 0.0:
221
+ z_losses = lse_square_scale * lse.square()
222
+ z_losses.masked_fill_(target == ignore_index, 0.0)
223
+ losses += z_losses
224
+ else:
225
+ z_losses = torch.zeros_like(losses)
226
+ losses.masked_fill_(target == ignore_index, 0.0)
227
+
228
+ return losses, z_losses, lse, total_classes, class_start_idx
229
+
230
+
231
+ class CrossEntropyLossFunction(torch.autograd.Function):
232
+
233
+ @staticmethod
234
+ @input_guard
235
+ def forward(
236
+ ctx,
237
+ logits,
238
+ target,
239
+ label_smoothing=0.0,
240
+ logit_scale=1.0,
241
+ lse_square_scale=0.0,
242
+ ignore_index=-100,
243
+ inplace_backward=False,
244
+ process_group=None,
245
+ ):
246
+ losses, z_losses, lse, total_classes, class_start_idx = fused_cross_entropy_forward(
247
+ logits,
248
+ target,
249
+ label_smoothing,
250
+ logit_scale,
251
+ lse_square_scale,
252
+ ignore_index,
253
+ process_group,
254
+ )
255
+ ctx.save_for_backward(logits, lse, target)
256
+ ctx.mark_non_differentiable(z_losses)
257
+ ctx.label_smoothing = label_smoothing
258
+ ctx.logit_scale = logit_scale
259
+ ctx.lse_square_scale = lse_square_scale
260
+ ctx.ignore_index = ignore_index
261
+ ctx.total_classes = total_classes
262
+ ctx.class_start_idx = class_start_idx
263
+ ctx.inplace_backward = inplace_backward
264
+
265
+ return losses, z_losses
266
+
267
+ @staticmethod
268
+ @input_guard
269
+ def backward(ctx, grad_losses, grad_z_losses):
270
+ del grad_z_losses # z_losses are only for logging.
271
+
272
+ logits, lse, target = ctx.saved_tensors
273
+ dlogits = logits if ctx.inplace_backward else torch.empty_like(logits)
274
+ n_rows, n_cols = logits.shape
275
+ BLOCK_SIZE = min(triton.next_power_of_2(n_cols), 4 * 1024)
276
+ num_warps = 4 if BLOCK_SIZE < 2048 else (8 if BLOCK_SIZE < 8192 else 16)
277
+ def grid(META): return (n_rows, triton.cdiv(n_cols, META["BLOCK_SIZE"])) # noqa
278
+ cross_entropy_bwd_kernel[grid](
279
+ dlogits, # data ptrs
280
+ grad_losses,
281
+ logits,
282
+ lse,
283
+ target,
284
+ ctx.label_smoothing,
285
+ ctx.logit_scale,
286
+ ctx.lse_square_scale,
287
+ ctx.ignore_index,
288
+ ctx.total_classes,
289
+ ctx.class_start_idx,
290
+ n_cols, # shapes
291
+ logits.stride(0), # strides
292
+ dlogits.stride(0),
293
+ grad_losses.stride(0),
294
+ BLOCK_SIZE=BLOCK_SIZE, # constants
295
+ num_warps=num_warps,
296
+ )
297
+ return dlogits, None, None, None, None, None, None, None, None
298
+
299
+
300
+ def cross_entropy_loss(
301
+ logits: torch.Tensor,
302
+ target: torch.Tensor,
303
+ label_smoothing: float = 0.0,
304
+ logit_scale: float = 1.0,
305
+ lse_square_scale: float = 0.0,
306
+ ignore_index=-100,
307
+ inplace_backward: bool = False,
308
+ process_group=None,
309
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
310
+ """
311
+ Arguments:
312
+ logits: [batch, vocab_size]
313
+ target: [batch,]
314
+ label_smoothing: float
315
+ logit_scale: float.
316
+ Multiply logits by this scale before calculating the loss.
317
+ lse_square_scale: float.
318
+ If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss.
319
+ This is also referred to as "z-loss".
320
+ ignore_index: int.
321
+ If target == ignore_index, the loss is set to 0.0.
322
+ inplace_backward: bool.
323
+ If True, we do the backward pass in-place by modifying the logits.
324
+ This saves memory.
325
+ process_group:
326
+ if not None, we're doing Tensor Parallel: each process is responsible for
327
+ one part of the vocab. The loss will be aggregated across processes.
328
+ Returns:
329
+ losses: [batch,], float
330
+ z_losses: [batch,], float
331
+ """
332
+ return CrossEntropyLossFunction.apply(
333
+ logits,
334
+ target,
335
+ label_smoothing,
336
+ logit_scale,
337
+ lse_square_scale,
338
+ ignore_index,
339
+ inplace_backward,
340
+ process_group,
341
+ )
342
+
343
+
344
+ class FusedCrossEntropyLoss(nn.Module):
345
+ def __init__(
346
+ self,
347
+ ignore_index: int = -100,
348
+ reduction: str = "mean",
349
+ label_smoothing: float = 0.0,
350
+ logit_scale: float = 1.0,
351
+ lse_square_scale: float = 0.0,
352
+ inplace_backward: bool = False,
353
+ process_group: Any = None,
354
+ return_z_loss: bool = False,
355
+ ):
356
+ """
357
+ Arguments:
358
+ ignore_index: int. If target == ignore_index, the loss is set to 0.0.
359
+ label_smoothing: float
360
+ lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss.
361
+ This is also referred to as "z-loss".
362
+ inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits.
363
+ This saves memory.
364
+ process_group: if not None, we're doing Tensor Parallel: each process is responsible for
365
+ one part of the vocab. The loss will be aggregated across processes.
366
+ return_z_loss: bool. If True, we return the component of the loss contributed by
367
+ the lse_square_scale value. This value is only for logging and does not support
368
+ backprop.
369
+ """
370
+ super().__init__()
371
+ if reduction not in ["mean", "none", "sum"]:
372
+ raise NotImplementedError("Only support reduction = 'mean' or 'none' or 'sum'")
373
+ self.ignore_index = ignore_index
374
+ self.reduction = reduction
375
+ self.label_smoothing = label_smoothing
376
+ self.logit_scale = logit_scale
377
+ self.lse_square_scale = lse_square_scale
378
+ self.inplace_backward = inplace_backward
379
+ self.process_group = process_group
380
+ self.return_z_loss = return_z_loss
381
+
382
+ def forward(self, input, target):
383
+ """
384
+ Arguments:
385
+ input: (batch, vocab_size)
386
+ target: (batch,)
387
+ Returns:
388
+ losses: (batch,) if reduction is 'none', else (1,), dtype float
389
+ z_loss: (batch,) if reduction is 'none', else (1,), dtype float (if self.return_z_loss)
390
+ """
391
+ assert input.is_cuda and target.is_cuda, "Only support CUDA tensors"
392
+ loss, z_loss = cross_entropy_loss(
393
+ input,
394
+ target,
395
+ label_smoothing=self.label_smoothing,
396
+ logit_scale=self.logit_scale,
397
+ lse_square_scale=self.lse_square_scale,
398
+ ignore_index=self.ignore_index,
399
+ inplace_backward=self.inplace_backward,
400
+ process_group=self.process_group,
401
+ )
402
+ if self.reduction == "mean":
403
+ loss = loss.sum() / (target != self.ignore_index).sum()
404
+ elif self.reduction == "sum":
405
+ loss = loss.sum()
406
+ else:
407
+ loss = loss
408
+
409
+ if not self.return_z_loss:
410
+ return loss
411
+
412
+ if self.reduction == "mean":
413
+ z_loss = z_loss.sum() / (target != self.ignore_index).sum()
414
+ elif self.reduction == "sum":
415
+ z_loss = z_loss.sum()
416
+ else:
417
+ z_loss = z_loss
418
+
419
+ return loss, z_loss
modules/fused_linear_cross_entropy.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Code adapted from
4
+ # https://github.com/linkedin/Liger-Kernel/blob/main/src/liger_kernel/ops/fused_linear_cross_entropy.py
5
+
6
+ from functools import partial
7
+ from typing import Optional, Tuple
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ import triton
13
+ import triton.language as tl
14
+ from torch.distributed import DeviceMesh
15
+ from torch.distributed.tensor import Replicate, Shard, distribute_module
16
+ from torch.distributed.tensor.parallel import ParallelStyle
17
+
18
+ from fla.ops.utils import logsumexp_fwd
19
+ from fla.ops.utils.op import exp
20
+ from fla.utils import input_guard, is_amd
21
+
22
+ try:
23
+ from torch.distributed.tensor import DTensor
24
+ except (ImportError, AttributeError):
25
+ DTensor = None
26
+
27
+ # The hard limit of TRITON_MAX_TENSOR_NUMEL is 1048576
28
+ # https://github.com/triton-lang/triton/blob/ba42a5c68fd0505f8c42f4202d53be0f8d9a5fe0/python/triton/language/core.py#L19
29
+ # However, setting limit as 65536 as in LayerNorm tutorial is faster because of less register spilling
30
+ # The optimal maximum block size depends on your hardware, your kernel, and your dtype
31
+ MAX_FUSED_SIZE = 65536 // 2
32
+ STATIC_WARPS = 32 if not is_amd else 16
33
+
34
+
35
+ @triton.jit
36
+ def cross_entropy_kernel(
37
+ logits,
38
+ lse,
39
+ target,
40
+ loss,
41
+ total,
42
+ ignore_index,
43
+ label_smoothing: tl.constexpr,
44
+ logit_scale: tl.constexpr,
45
+ reduction: tl.constexpr,
46
+ V: tl.constexpr,
47
+ BV: tl.constexpr
48
+ ):
49
+ """
50
+ This kernel computes both cross entropy loss and the gradient of the input.
51
+ We only consider hard label + mean reduction for now.
52
+ Please refer to https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html for the math.
53
+
54
+ Args:
55
+ logits:
56
+ Pointer to logits tensor.
57
+ lse:
58
+ Pointer to logsumexp tensor.
59
+ target: Pointer to target tensor.
60
+ loss:
61
+ Pointer to tensor to store the loss.
62
+ V (int):
63
+ The number of columns in the input tensor.
64
+ total (int):
65
+ The number of non-ignored classes.
66
+ ignore_index (int):
67
+ The index to ignore in the target.
68
+ label_smoothing (float):
69
+ The amount of smoothing when computing the loss, where 0.0 means no smoothing.
70
+ reduction (str):
71
+ The string for the reduction to apply
72
+ BV (int):
73
+ The block size for vocab.
74
+ """
75
+
76
+ # https://github.com/triton-lang/triton/issues/1058
77
+ # If B*T*V is too large, i_n * stride will overflow out of int32, so we convert to int64
78
+ i_n = tl.program_id(0).to(tl.int64)
79
+ NV = tl.cdiv(V, BV)
80
+
81
+ # 1. Load target first because if the target is ignore_index, we can return right away
82
+ b_y = tl.load(target + i_n)
83
+
84
+ # 2. locate the start index
85
+ logits += i_n * V
86
+
87
+ if b_y == ignore_index:
88
+ # set all x as 0
89
+ for i in range(0, V, BV):
90
+ o_v = i + tl.arange(0, BV)
91
+ tl.store(logits + o_v, 0.0, mask=o_v < V)
92
+ return
93
+
94
+ # Online softmax: 2 loads + 1 store (compared with 3 loads + 1 store for the safe softmax)
95
+ # Refer to Algorithm 3 in the paper: https://arxiv.org/pdf/1805.02867
96
+
97
+ # 3. [Online softmax] first pass: compute logsumexp
98
+ # we did this in anouter kernel
99
+ b_l = tl.load(logits + b_y) * logit_scale
100
+ b_lse = tl.load(lse + i_n)
101
+
102
+ # 4. Calculate the loss
103
+ # loss = lse - logits_l
104
+ b_loss = b_lse - b_l
105
+
106
+ # Label smoothing is a general case of normal cross entropy
107
+ # See the full derivation at https://github.com/linkedin/Liger-Kernel/pull/198#issue-2503665310
108
+ b_z = 0.0
109
+ eps = label_smoothing / V
110
+
111
+ # We need tl.debug_barrier() as mentioned in
112
+ # https://github.com/triton-lang/triton/blob/ba42a5c68fd0505f8c42f4202d53be0f8d9a5fe0/python/triton/ops/cross_entropy.py#L34
113
+ tl.debug_barrier()
114
+
115
+ # 5. [Online Softmax] Second pass: compute gradients
116
+ # For 'mean' reduction, gradients are normalized by number of non-ignored elements
117
+ # dx_y = (softmax(x_y) - 1) / N
118
+ # dx_i = softmax(x_i) / N, i != y
119
+ # For label smoothing:
120
+ # dx_i = (softmax(x_y) - label_smoothing / V) / N, i != y
121
+ # dx_y = (softmax(x_y) - label_smoothing / V - (1 - label_smoothing)) / N
122
+ # = dx_i - (1 - label_smoothing) / N
123
+ for iv in range(0, NV):
124
+ o_v = iv * BV + tl.arange(0, BV)
125
+ b_logits = tl.load(logits + o_v, mask=o_v < V, other=float('-inf')) * logit_scale
126
+ if label_smoothing > 0:
127
+ # scale X beforehand to avoid overflow
128
+ b_z += tl.sum(tl.where(o_v < V, -eps * b_logits, 0.0))
129
+ b_p = (exp(b_logits - b_lse) - eps) * logit_scale
130
+ if reduction == "mean":
131
+ b_p = b_p / total
132
+ tl.store(logits + o_v, b_p, mask=o_v < V)
133
+
134
+ tl.debug_barrier()
135
+
136
+ # Orginal loss = H(q, p), with label smoothing regularization = H(q', p) and (label_smoothing / V) = eps
137
+ # H(q', p) = (1 - label_smoothing) * H(q, p) + label_smoothing * H(u, p)
138
+ # = (1 - label_smoothing) * H(q, p) + eps * sum(logsoftmax(x_i))
139
+ # By using m (global max of xi) and d (sum of e^(xi-m)), we can simplify as:
140
+ # = (1 - label_smoothing) * H(q, p) + (-sum(x_i * eps) + label_smoothing * (m + logd))
141
+ # Refer to H(q', p) in section 7 of the paper:
142
+ # https://arxiv.org/pdf/1512.00567
143
+ # pytorch:
144
+ # https://github.com/pytorch/pytorch/blob/2981534f54d49fa3a9755c9b0855e7929c2527f0/aten/src/ATen/native/LossNLL.cpp#L516
145
+ # See full derivation at https://github.com/linkedin/Liger-Kernel/pull/198#issuecomment-2333753087
146
+ if label_smoothing > 0:
147
+ b_loss = b_loss * (1 - label_smoothing) + (b_z + label_smoothing * b_lse)
148
+
149
+ # 6. Specially handle the i==y case where `dx_y = (softmax(x_y) - (1 - label_smoothing) / N`
150
+ b_l = tl.load(logits + b_y)
151
+
152
+ # Normalize the loss by the number of non-ignored elements if reduction is "mean"
153
+ if reduction == 'mean':
154
+ b_loss = b_loss / total
155
+ b_l += (label_smoothing - 1) / total * logit_scale
156
+ else:
157
+ b_l += (label_smoothing - 1) * logit_scale
158
+
159
+ tl.store(loss + i_n, b_loss)
160
+ tl.store(logits + b_y, b_l)
161
+
162
+
163
+ @triton.jit
164
+ def elementwise_mul_kernel(
165
+ x,
166
+ g,
167
+ N: tl.constexpr,
168
+ B: tl.constexpr
169
+ ):
170
+ """
171
+ This function multiplies each element of the tensor pointed by x with the value pointed by g.
172
+ The multiplication is performed in-place on the tensor pointed by x.
173
+
174
+ Parameters:
175
+ x:
176
+ Pointer to the input tensor.
177
+ g:
178
+ Pointer to the gradient output value.
179
+ N (int):
180
+ The number of columns in the input tensor.
181
+ B (int):
182
+ The block size for Triton operations.
183
+ """
184
+
185
+ # Get the program ID and convert it to int64 to avoid overflow
186
+ i_x = tl.program_id(0).to(tl.int64)
187
+ o_x = i_x * B + tl.arange(0, B)
188
+
189
+ # Load the gradient output value
190
+ b_g = tl.load(g)
191
+ b_x = tl.load(x + o_x, mask=o_x < N)
192
+ tl.store(x + o_x, b_x * b_g, mask=o_x < N)
193
+
194
+
195
+ def fused_linear_cross_entropy_forward(
196
+ x: torch.Tensor,
197
+ target: torch.LongTensor,
198
+ weight: torch.Tensor,
199
+ bias: torch.Tensor = None,
200
+ ignore_index: int = -100,
201
+ label_smoothing: float = 0.0,
202
+ logit_scale: float = 1.0,
203
+ num_chunks: int = 8,
204
+ reduction: str = "mean",
205
+ use_l2warp: bool = False,
206
+ l2_penalty_factor: float = 1e-4
207
+ ):
208
+ device = x.device
209
+ # inputs have shape: [N, H]
210
+ # materialized activations will have shape: [N, V]
211
+ # the increase in memory = [N, V]
212
+ # reduction can be achieved by partitioning the number of tokens N into smaller chunks.
213
+
214
+ # ideally, we would like to achieve the same memory consumption as [N, H],
215
+ # so the expected chunk size should be:
216
+ # NC = ceil(V / H)
217
+ # C = ceil(N / NC)
218
+ # for ex: N = 4096*4, V = 32000, H = 4096 ==> NC = 8, C = ceil(N / NC) = 2048
219
+ N, H, V = *x.shape, weight.shape[0]
220
+ BV = min(MAX_FUSED_SIZE, triton.next_power_of_2(V))
221
+ # TODO: in real cases, we may need to limit the number of chunks NC to
222
+ # ensure the precisions of accumulated gradients
223
+ NC = min(num_chunks, triton.cdiv(V, H))
224
+ C = triton.next_power_of_2(triton.cdiv(N, NC))
225
+ NC = triton.cdiv(N, C)
226
+
227
+ # [N, H]
228
+ dx = torch.zeros_like(x, device=device)
229
+ # [V, H]
230
+ dw = torch.zeros_like(weight, device=device, dtype=torch.float) if weight is not None else None
231
+ # [V]
232
+ db = torch.zeros_like(bias, device=device, dtype=torch.float) if bias is not None else None
233
+ # [N]
234
+ loss = torch.zeros(N, device=device, dtype=torch.float)
235
+
236
+ total = target.ne(ignore_index).sum().item()
237
+
238
+ for ic in range(NC):
239
+ start, end = ic * C, min((ic + 1) * C, N)
240
+ # [C, N]
241
+ c_x = x[start:end]
242
+ # when doing matmul, use the original precision
243
+ # [C, V]
244
+ c_logits = F.linear(c_x, weight, bias)
245
+ c_target = target[start:end]
246
+ # [C]
247
+ # keep lse in fp32 to maintain precision
248
+ c_lse = logsumexp_fwd(c_logits, scale=logit_scale, dtype=torch.float)
249
+
250
+ # unreduced loss
251
+ c_loss = loss[start:end]
252
+ if use_l2warp:
253
+ c_maxx, c_ids = torch.max(c_logits, -1, keepdim=True)
254
+
255
+ # Here we calculate the gradient of c_logits in place so we can save memory.
256
+ cross_entropy_kernel[(c_logits.shape[0],)](
257
+ logits=c_logits,
258
+ lse=c_lse,
259
+ target=c_target,
260
+ loss=c_loss,
261
+ total=total,
262
+ ignore_index=ignore_index,
263
+ label_smoothing=label_smoothing,
264
+ logit_scale=logit_scale,
265
+ reduction=reduction,
266
+ V=V,
267
+ BV=BV,
268
+ num_warps=STATIC_WARPS
269
+ )
270
+ if use_l2warp:
271
+ # a. Calculate the L2 gradient w.r.t logits (g_logits_l2)
272
+ g_logits_l2 = torch.zeros_like(c_logits)
273
+
274
+ # Normalize factor by B*T, which is the 'total' variable here
275
+ l2_factor = l2_penalty_factor / total if reduction == 'mean' else l2_penalty_factor
276
+ penalty_grad = c_maxx * l2_factor
277
+ g_logits_l2.scatter_(-1, c_ids, penalty_grad)
278
+
279
+ # b. Backpropagate g_logits_l2 to get its effect on dx, dw, db
280
+ # and add it to the main gradients.
281
+ # Total_dx = CE_dx + L2_dx
282
+ # Total_dw = CE_dw + L2_dw
283
+ # Total_db = CE_db + L2_db
284
+ if weight is not None:
285
+ dw.add_(g_logits_l2.t() @ c_x)
286
+ if bias is not None:
287
+ db.add_(g_logits_l2.sum(0))
288
+ # The dx contribution must be added to the final dx calculation
289
+ dx_l2_contribution = torch.mm(g_logits_l2, weight)
290
+ else:
291
+ dx_l2_contribution = 0.0
292
+
293
+ # gradient of logits is computed in-place by the above triton kernel and is of shape: C x V
294
+ # thus dx should be of shape: C x H
295
+ dx[start:end] = torch.mm(c_logits, weight) + dx_l2_contribution
296
+
297
+ # keep dw in fp32 to maintain precision
298
+ if weight is not None:
299
+ dw += c_logits.t() @ c_x
300
+
301
+ if bias is not None:
302
+ torch.add(input=db, other=c_logits.sum(0), out=db)
303
+
304
+ loss = loss.sum()
305
+ if dw is not None:
306
+ dw = dw.to(weight)
307
+ if db is not None:
308
+ db = db.to(bias)
309
+ return loss, dx, dw, db
310
+
311
+
312
+ def fused_linear_cross_entropy_backward(
313
+ do: torch.Tensor,
314
+ dx: torch.Tensor,
315
+ dw: torch.Tensor,
316
+ db: torch.Tensor
317
+ ):
318
+ # If cross entropy is the last layer, do is 1.0. Skip the mul to save time
319
+ if torch.ne(do, torch.tensor(1.0, device=do.device)):
320
+ # We use a Triton kernel instead of a PyTorch operation because modifying inputs in-place
321
+ # for gradient storage and backward multiple times causes anomalies with PyTorch but not with Triton.
322
+ N, H = dx.shape
323
+ B = min(MAX_FUSED_SIZE, triton.next_power_of_2(H))
324
+
325
+ elementwise_mul_kernel[(triton.cdiv(N * H, B),)](
326
+ x=dx,
327
+ g=do,
328
+ N=N*H,
329
+ B=B,
330
+ num_warps=STATIC_WARPS,
331
+ )
332
+
333
+ # handle dw
334
+ if dw is not None:
335
+ V, H = dw.shape
336
+ elementwise_mul_kernel[(triton.cdiv(V * H, B),)](
337
+ x=dw,
338
+ g=do,
339
+ N=V*H,
340
+ B=B,
341
+ num_warps=STATIC_WARPS,
342
+ )
343
+
344
+ if db is not None:
345
+ V = db.shape[0]
346
+ elementwise_mul_kernel[(triton.cdiv(V, B),)](
347
+ x=db,
348
+ g=do,
349
+ N=V,
350
+ B=B,
351
+ num_warps=STATIC_WARPS,
352
+ )
353
+ return dx, dw, db
354
+
355
+
356
+ class FusedLinearCrossEntropyFunction(torch.autograd.Function):
357
+
358
+ @staticmethod
359
+ @input_guard
360
+ def forward(
361
+ ctx,
362
+ x: torch.Tensor,
363
+ target: torch.LongTensor,
364
+ weight: torch.Tensor,
365
+ bias: torch.Tensor = None,
366
+ ignore_index: int = -100,
367
+ label_smoothing: float = 0.0,
368
+ logit_scale: float = 1.0,
369
+ num_chunks: int = 8,
370
+ reduction: str = "mean",
371
+ use_l2warp: bool = False,
372
+ l2_penalty_factor: float = 1e-4,
373
+ ):
374
+ """
375
+ Fusing the last linear layer with cross-entropy loss
376
+ Reference: https://github.com/mgmalek/efficient_cross_entropy
377
+
378
+ Handle the forward and backward pass of the final linear layer via cross-entropy loss by avoiding
379
+ the materialization of the large logits tensor. Since Cross Entropy Loss is the last layer, we can
380
+ compute the gradient at the forward pass. By doing so, we don't have to store the x and target
381
+ for the backward pass.
382
+
383
+ x (torch.Tensor): [batch_size * seq_len, hidden_size]
384
+ target (torch.LongTensor): [batch_size * seq_len]
385
+ where each value is in [0, vocab_size).
386
+ weight (torch.Tensor): [vocab_size, hidden_size]
387
+ where `vocab_size` is the number of classes.
388
+ bias (Optional[torch.Tensor]): [vocab_size]
389
+ where `vocab_size` is the number of classes.
390
+ ignore_index:
391
+ the index to ignore in the target.
392
+ label_smoothing:
393
+ the amount of smoothing when computing the loss, where 0.0 means no smoothing.
394
+ logit_scale: float = 1.0,
395
+ A scaling factor applied to the logits. Default: 1.0
396
+ num_chunks: int
397
+ The number of chunks to split the input tensor into for processing.
398
+ This can help optimize memory usage and computation speed.
399
+ Default: 8
400
+ reduction:
401
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
402
+ 'mean': the weighted mean of the output is taken,
403
+ 'sum': the output will be summed.
404
+ Default: 'mean'.
405
+ use_l2warp: bool = False,
406
+ Whether to use L2 regularization on the logits to prevent overconfidence.
407
+ Default: False
408
+ l2_penalty_factor: float = 1e-4,
409
+ """
410
+ loss, dx, dw, db = fused_linear_cross_entropy_forward(
411
+ x,
412
+ target,
413
+ weight,
414
+ bias,
415
+ ignore_index,
416
+ label_smoothing,
417
+ logit_scale,
418
+ num_chunks,
419
+ reduction,
420
+ use_l2warp,
421
+ l2_penalty_factor
422
+ )
423
+ # downcast to dtype and store for backward
424
+ ctx.save_for_backward(
425
+ dx.detach(),
426
+ dw.detach() if weight is not None else None,
427
+ db.detach() if bias is not None else None,
428
+ )
429
+ return loss
430
+
431
+ @staticmethod
432
+ @input_guard
433
+ def backward(ctx, do):
434
+ dx, dw, db = ctx.saved_tensors
435
+ dx, dw, db = fused_linear_cross_entropy_backward(do, dx, dw, db)
436
+ return dx, None, dw, db, None, None, None, None, None, None, None
437
+
438
+
439
+ def fused_linear_cross_entropy_loss(
440
+ x: torch.Tensor,
441
+ target: torch.LongTensor,
442
+ weight: torch.Tensor,
443
+ bias: torch.Tensor = None,
444
+ ignore_index: int = -100,
445
+ label_smoothing: float = 0.0,
446
+ logit_scale: float = 1.0,
447
+ num_chunks: int = 8,
448
+ reduction: str = "mean",
449
+ use_l2warp: bool = False,
450
+ l2_penalty_factor: float = 1e-4,
451
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
452
+ """
453
+ Args:
454
+ x (torch.Tensor): [batch_size * seq_len, hidden_size]
455
+ target (torch.LongTensor): [batch_size * seq_len]
456
+ where each value is in [0, vocab_size).
457
+ weight (torch.Tensor): [vocab_size, hidden_size]
458
+ where `vocab_size` is the number of classes.
459
+ bias (Optional[torch.Tensor]): [vocab_size]
460
+ where `vocab_size` is the number of classes.
461
+ ignore_index: int.
462
+ If target == ignore_index, the loss is set to 0.0.
463
+ label_smoothing: float
464
+ logit_scale: float
465
+ A scaling factor applied to the logits. Default: 1.0
466
+ num_chunks: int
467
+ The number of chunks to split the input tensor into for processing.
468
+ This can help optimize memory usage and computation speed.
469
+ Default: 8
470
+ reduction:
471
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
472
+ 'mean': the weighted mean of the output is taken,
473
+ 'sum': the output will be summed.
474
+ Default: 'mean'.
475
+ Returns:
476
+ losses: [batch,], float
477
+ """
478
+ return FusedLinearCrossEntropyFunction.apply(
479
+ x,
480
+ target,
481
+ weight,
482
+ bias,
483
+ ignore_index,
484
+ label_smoothing,
485
+ logit_scale,
486
+ num_chunks,
487
+ reduction,
488
+ use_l2warp,
489
+ l2_penalty_factor
490
+ )
491
+
492
+
493
+ class FusedLinearCrossEntropyLoss(nn.Module):
494
+
495
+ def __init__(
496
+ self,
497
+ ignore_index: int = -100,
498
+ label_smoothing: float = 0.0,
499
+ logit_scale: float = 1.0,
500
+ num_chunks: int = 8,
501
+ reduction: str = "mean",
502
+ use_l2warp: bool = False,
503
+ l2_penalty_factor: float = 1e-4,
504
+ ):
505
+ """
506
+ Args:
507
+ ignore_index: int.
508
+ If target == ignore_index, the loss is set to 0.0.
509
+ label_smoothing: float
510
+ logit_scale: float
511
+ A scaling factor applied to the logits. Default: 1.0
512
+ num_chunks: int
513
+ The number of chunks to split the input tensor into for processing.
514
+ This can help optimize memory usage and computation speed.
515
+ Default: 8
516
+ reduction:
517
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
518
+ 'mean': the weighted mean of the output is taken,
519
+ 'sum': the output will be summed.
520
+ Default: 'mean'.
521
+ """
522
+ super().__init__()
523
+
524
+ assert reduction in ["mean", "sum"], f"reduction: {reduction} is not supported"
525
+
526
+ self.ignore_index = ignore_index
527
+ self.label_smoothing = label_smoothing
528
+ self.logit_scale = logit_scale
529
+ self.num_chunks = num_chunks
530
+ self.reduction = reduction
531
+ self.use_l2warp = use_l2warp
532
+ self.l2_penalty_factor = l2_penalty_factor
533
+
534
+ @torch.compiler.disable
535
+ def forward(
536
+ self,
537
+ x: torch.Tensor,
538
+ target: torch.LongTensor,
539
+ weight: torch.Tensor,
540
+ bias: Optional[torch.Tensor] = None
541
+ ):
542
+ """
543
+ Args:
544
+ x (torch.Tensor): [batch_size, seq_len, hidden_size]
545
+ target (torch.LongTensor): [batch_size, seq_len]
546
+ where each value is in [0, V).
547
+ weight (torch.Tensor): [vocab_size, hidden_size]
548
+ where `vocab_size` is the number of classes.
549
+ bias (Optional[torch.Tensor]): [vocab_size]
550
+ where `vocab_size` is the number of classes.
551
+ Returns:
552
+ loss
553
+ """
554
+ loss = fused_linear_cross_entropy_loss(
555
+ x.view(-1, x.shape[-1]),
556
+ target.view(-1),
557
+ weight=weight,
558
+ bias=bias,
559
+ ignore_index=self.ignore_index,
560
+ label_smoothing=self.label_smoothing,
561
+ logit_scale=self.logit_scale,
562
+ num_chunks=self.num_chunks,
563
+ reduction=self.reduction,
564
+ use_l2warp=self.use_l2warp,
565
+ l2_penalty_factor=self.l2_penalty_factor
566
+ )
567
+ return loss
568
+
569
+
570
+ class LinearLossParallel(ParallelStyle):
571
+ def __init__(
572
+ self,
573
+ *,
574
+ sequence_dim: int = 1,
575
+ use_local_output: bool = False,
576
+ ):
577
+ super().__init__()
578
+
579
+ self.sequence_sharding = (Shard(sequence_dim),)
580
+ self.use_local_output = use_local_output
581
+
582
+ @staticmethod
583
+ def _prepare_input_fn(sequence_sharding, mod, inputs, device_mesh):
584
+ x, target, weight, bias = inputs
585
+
586
+ if not isinstance(x, DTensor):
587
+ # assume the input passed in already sharded on the sequence dim and create the DTensor
588
+ x = DTensor.from_local(x, device_mesh, sequence_sharding)
589
+ if x.placements != sequence_sharding:
590
+ x = x.redistribute(placements=sequence_sharding, async_op=True)
591
+ if not isinstance(target, DTensor):
592
+ target = DTensor.from_local(target, device_mesh, [Replicate()])
593
+ if target.placements != sequence_sharding:
594
+ target = target.redistribute(placements=sequence_sharding, async_op=True)
595
+
596
+ if not isinstance(weight, DTensor):
597
+ weight = DTensor.from_local(weight, device_mesh, [Replicate()])
598
+ if weight.placements != [Replicate()]:
599
+ # we replicate the weight/bias in FLCE
600
+ weight = weight.redistribute(placements=[Replicate()], async_op=True)
601
+
602
+ if bias is not None and not isinstance(bias, DTensor):
603
+ bias = DTensor.from_local(bias, device_mesh, [Replicate()])
604
+ if bias is not None and bias.placements != [Replicate()]:
605
+ bias = bias.redistribute(placements=[Replicate()], async_op=True)
606
+
607
+ return x.to_local(), target.to_local(), weight.to_local(), bias.to_local() if bias is not None else bias
608
+
609
+ @staticmethod
610
+ def _prepare_output_fn(use_local_output, mod, outputs, device_mesh):
611
+ return outputs.to_local() if use_local_output else outputs
612
+
613
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
614
+ return distribute_module(
615
+ module,
616
+ device_mesh,
617
+ partition_fn=None,
618
+ input_fn=partial(self._prepare_input_fn, self.sequence_sharding),
619
+ output_fn=partial(self._prepare_output_fn, self.use_local_output)
620
+ )
modules/fused_norm_gate.py ADDED
@@ -0,0 +1,1257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from __future__ import annotations
5
+
6
+ import math
7
+ from typing import Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ import triton
13
+ import triton.language as tl
14
+
15
+ from fla.utils import autotune_cache_kwargs, get_multiprocessor_count, input_guard
16
+
17
+
18
+ @triton.heuristics({
19
+ 'STORE_RESIDUAL_OUT': lambda args: args['residual_out'] is not None,
20
+ 'HAS_RESIDUAL': lambda args: args['residual'] is not None,
21
+ 'HAS_WEIGHT': lambda args: args['w'] is not None,
22
+ 'HAS_BIAS': lambda args: args['b'] is not None,
23
+ })
24
+ @triton.autotune(
25
+ configs=[
26
+ triton.Config({'BT': BT}, num_warps=num_warps)
27
+ for BT in [16, 32, 64]
28
+ for num_warps in [4, 8, 16]
29
+ ],
30
+ key=['D', 'NB', 'IS_RMS_NORM', 'STORE_RESIDUAL_OUT', 'HAS_RESIDUAL', 'HAS_WEIGHT'],
31
+ **autotune_cache_kwargs
32
+ )
33
+ @triton.jit
34
+ def layer_norm_gated_fwd_kernel(
35
+ x, # pointer to the input
36
+ g, # pointer to the gate
37
+ y, # pointer to the output
38
+ w, # pointer to the weights
39
+ b, # pointer to the biases
40
+ residual, # pointer to the residual
41
+ residual_out, # pointer to the residual
42
+ mean, # pointer to the mean
43
+ rstd, # pointer to the 1/std
44
+ eps, # epsilon to avoid division by zero
45
+ T, # number of rows in x
46
+ D: tl.constexpr, # number of columns in x
47
+ BT: tl.constexpr,
48
+ BD: tl.constexpr,
49
+ NB: tl.constexpr,
50
+ ACTIVATION: tl.constexpr,
51
+ IS_RMS_NORM: tl.constexpr,
52
+ STORE_RESIDUAL_OUT: tl.constexpr,
53
+ HAS_RESIDUAL: tl.constexpr,
54
+ HAS_WEIGHT: tl.constexpr,
55
+ HAS_BIAS: tl.constexpr
56
+ ):
57
+ i_t = tl.program_id(0)
58
+
59
+ o_d = tl.arange(0, BD)
60
+ m_d = o_d < D
61
+
62
+ p_x = tl.make_block_ptr(x, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
63
+ b_x = tl.load(p_x, boundary_check=(0, 1)).to(tl.float32)
64
+ if HAS_RESIDUAL:
65
+ p_res = tl.make_block_ptr(residual, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
66
+ b_x += tl.load(p_res, boundary_check=(0, 1)).to(tl.float32)
67
+ if STORE_RESIDUAL_OUT:
68
+ p_res_out = tl.make_block_ptr(residual_out, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
69
+ tl.store(p_res_out, b_x.to(p_res_out.dtype.element_ty), boundary_check=(0, 1))
70
+ if not IS_RMS_NORM:
71
+ b_mean = tl.sum(b_x, axis=1) / D
72
+ p_mean = tl.make_block_ptr(mean, (T,), (1,), (i_t * BT,), (BT,), (0,))
73
+ tl.store(p_mean, b_mean.to(p_mean.dtype.element_ty), boundary_check=(0,))
74
+ b_xbar = tl.where(m_d[None, :], b_x - b_mean[:, None], 0.0)
75
+ b_var = tl.sum(b_xbar * b_xbar, axis=1) / D
76
+ else:
77
+ b_xbar = tl.where(m_d[None, :], b_x, 0.0)
78
+ b_var = tl.sum(b_xbar * b_xbar, axis=1) / D
79
+ b_rstd = 1 / tl.sqrt(b_var + eps)
80
+
81
+ p_rstd = tl.make_block_ptr(rstd, (T,), (1,), (i_t * BT,), (BT,), (0,))
82
+ tl.store(p_rstd, b_rstd.to(p_rstd.dtype.element_ty), boundary_check=(0,))
83
+
84
+ if HAS_WEIGHT:
85
+ b_w = tl.load(w + o_d, mask=m_d).to(tl.float32)
86
+ if HAS_BIAS:
87
+ b_b = tl.load(b + o_d, mask=m_d).to(tl.float32)
88
+ b_x_hat = (b_x - b_mean[:, None]) * b_rstd[:, None] if not IS_RMS_NORM else b_x * b_rstd[:, None]
89
+ b_y = b_x_hat * b_w[None, :] if HAS_WEIGHT else b_x_hat
90
+ if HAS_BIAS:
91
+ b_y = b_y + b_b[None, :]
92
+
93
+ # swish/sigmoid output gate
94
+ p_g = tl.make_block_ptr(g, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
95
+ b_g = tl.load(p_g, boundary_check=(0, 1)).to(tl.float32)
96
+ if ACTIVATION == 'swish':
97
+ b_y = b_y * b_g * tl.sigmoid(b_g)
98
+ elif ACTIVATION == 'silu':
99
+ b_y = b_y * b_g * tl.sigmoid(b_g)
100
+ elif ACTIVATION == 'sigmoid':
101
+ b_y = b_y * tl.sigmoid(b_g)
102
+
103
+ # Write output
104
+ p_y = tl.make_block_ptr(y, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
105
+ tl.store(p_y, b_y.to(p_y.dtype.element_ty), boundary_check=(0, 1))
106
+
107
+
108
+ @triton.heuristics({
109
+ 'STORE_RESIDUAL_OUT': lambda args: args['residual_out'] is not None,
110
+ 'HAS_RESIDUAL': lambda args: args['residual'] is not None,
111
+ 'HAS_WEIGHT': lambda args: args['w'] is not None,
112
+ 'HAS_BIAS': lambda args: args['b'] is not None,
113
+ })
114
+ @triton.autotune(
115
+ configs=[
116
+ triton.Config({}, num_warps=num_warps)
117
+ for num_warps in [2, 4, 8, 16]
118
+ ],
119
+ key=['D', 'IS_RMS_NORM', 'STORE_RESIDUAL_OUT', 'HAS_RESIDUAL', 'HAS_WEIGHT'],
120
+ **autotune_cache_kwargs
121
+ )
122
+ @triton.jit
123
+ def layer_norm_gated_fwd_kernel1(
124
+ x, # pointer to the input
125
+ g, # pointer to the gate
126
+ y, # pointer to the output
127
+ w, # pointer to the weights
128
+ b, # pointer to the biases
129
+ residual, # pointer to the residual
130
+ residual_out, # pointer to the residual
131
+ mean, # pointer to the mean
132
+ rstd, # pointer to the 1/std
133
+ eps, # epsilon to avoid division by zero
134
+ D: tl.constexpr, # number of columns in x
135
+ BD: tl.constexpr,
136
+ ACTIVATION: tl.constexpr,
137
+ IS_RMS_NORM: tl.constexpr,
138
+ STORE_RESIDUAL_OUT: tl.constexpr,
139
+ HAS_RESIDUAL: tl.constexpr,
140
+ HAS_WEIGHT: tl.constexpr,
141
+ HAS_BIAS: tl.constexpr
142
+ ):
143
+ i_t = tl.program_id(0)
144
+ x += i_t * D
145
+ y += i_t * D
146
+ g += i_t * D
147
+ if HAS_RESIDUAL:
148
+ residual += i_t * D
149
+ if STORE_RESIDUAL_OUT:
150
+ residual_out += i_t * D
151
+
152
+ o_d = tl.arange(0, BD)
153
+ m_d = o_d < D
154
+ b_x = tl.load(x + o_d, mask=m_d, other=0.0).to(tl.float32)
155
+ if HAS_RESIDUAL:
156
+ b_x += tl.load(residual + o_d, mask=m_d, other=0.0).to(tl.float32)
157
+ if STORE_RESIDUAL_OUT:
158
+ tl.store(residual_out + o_d, b_x, mask=m_d)
159
+ if not IS_RMS_NORM:
160
+ b_mean = tl.sum(b_x, axis=0) / D
161
+ tl.store(mean + i_t, b_mean)
162
+ b_xbar = tl.where(m_d, b_x - b_mean, 0.0)
163
+ b_var = tl.sum(b_xbar * b_xbar, axis=0) / D
164
+ else:
165
+ b_xbar = tl.where(m_d, b_x, 0.0)
166
+ b_var = tl.sum(b_xbar * b_xbar, axis=0) / D
167
+ b_rstd = 1 / tl.sqrt(b_var + eps)
168
+ tl.store(rstd + i_t, b_rstd)
169
+
170
+ if HAS_WEIGHT:
171
+ b_w = tl.load(w + o_d, mask=m_d).to(tl.float32)
172
+ if HAS_BIAS:
173
+ b_b = tl.load(b + o_d, mask=m_d).to(tl.float32)
174
+ b_x_hat = (b_x - b_mean) * b_rstd if not IS_RMS_NORM else b_x * b_rstd
175
+ b_y = b_x_hat * b_w if HAS_WEIGHT else b_x_hat
176
+ if HAS_BIAS:
177
+ b_y = b_y + b_b
178
+
179
+ # swish/sigmoid output gate
180
+ b_g = tl.load(g + o_d, mask=m_d, other=0.0).to(tl.float32)
181
+ if ACTIVATION == 'swish':
182
+ b_y = b_y * b_g * tl.sigmoid(b_g)
183
+ elif ACTIVATION == 'silu':
184
+ b_y = b_y * b_g * tl.sigmoid(b_g)
185
+ elif ACTIVATION == 'sigmoid':
186
+ b_y = b_y * tl.sigmoid(b_g)
187
+
188
+ # Write output
189
+ tl.store(y + o_d, b_y, mask=m_d)
190
+
191
+
192
+ @triton.heuristics({
193
+ 'HAS_DRESIDUAL': lambda args: args['dresidual'] is not None,
194
+ 'HAS_WEIGHT': lambda args: args['w'] is not None,
195
+ 'HAS_BIAS': lambda args: args['b'] is not None,
196
+ 'RECOMPUTE_OUTPUT': lambda args: args['y'] is not None
197
+ })
198
+ @triton.autotune(
199
+ configs=[
200
+ triton.Config({'BT': BT}, num_warps=num_warps)
201
+ for BT in [16, 32, 64]
202
+ for num_warps in [4, 8, 16]
203
+ ],
204
+ key=['D', 'NB', 'IS_RMS_NORM', 'HAS_DRESIDUAL', 'HAS_WEIGHT'],
205
+ **autotune_cache_kwargs
206
+ )
207
+ @triton.jit
208
+ def layer_norm_gated_bwd_kernel(
209
+ x, # pointer to the input
210
+ g, # pointer to the gate
211
+ w, # pointer to the weights
212
+ b, # pointer to the biases
213
+ y, # pointer to the output to be recomputed
214
+ dy, # pointer to the output gradient
215
+ dx, # pointer to the input gradient
216
+ dg, # pointer to the gate gradient
217
+ dw, # pointer to the partial sum of weights gradient
218
+ db, # pointer to the partial sum of biases gradient
219
+ dresidual,
220
+ dresidual_in,
221
+ mean,
222
+ rstd,
223
+ T,
224
+ BS,
225
+ D: tl.constexpr,
226
+ BT: tl.constexpr,
227
+ BD: tl.constexpr,
228
+ NB: tl.constexpr,
229
+ ACTIVATION: tl.constexpr,
230
+ IS_RMS_NORM: tl.constexpr,
231
+ STORE_DRESIDUAL: tl.constexpr,
232
+ HAS_DRESIDUAL: tl.constexpr,
233
+ HAS_WEIGHT: tl.constexpr,
234
+ HAS_BIAS: tl.constexpr,
235
+ RECOMPUTE_OUTPUT: tl.constexpr,
236
+ ):
237
+ i_s = tl.program_id(0)
238
+ o_d = tl.arange(0, BD)
239
+ m_d = o_d < D
240
+ if HAS_WEIGHT:
241
+ b_w = tl.load(w + o_d, mask=m_d).to(tl.float32)
242
+ b_dw = tl.zeros((BT, BD), dtype=tl.float32)
243
+ if HAS_BIAS:
244
+ b_b = tl.load(b + o_d, mask=m_d, other=0.0).to(tl.float32)
245
+ b_db = tl.zeros((BT, BD), dtype=tl.float32)
246
+
247
+ T = min(i_s * BS + BS, T)
248
+ for i_t in range(i_s * BS, T, BT):
249
+ p_x = tl.make_block_ptr(x, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
250
+ p_g = tl.make_block_ptr(g, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
251
+ p_dy = tl.make_block_ptr(dy, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
252
+ p_dx = tl.make_block_ptr(dx, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
253
+ p_dg = tl.make_block_ptr(dg, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
254
+ # [BT, BD]
255
+ b_x = tl.load(p_x, boundary_check=(0, 1)).to(tl.float32)
256
+ b_g = tl.load(p_g, boundary_check=(0, 1)).to(tl.float32)
257
+ b_dy = tl.load(p_dy, boundary_check=(0, 1)).to(tl.float32)
258
+
259
+ if not IS_RMS_NORM:
260
+ p_mean = tl.make_block_ptr(mean, (T,), (1,), (i_t,), (BT,), (0,))
261
+ b_mean = tl.load(p_mean, boundary_check=(0,))
262
+ p_rstd = tl.make_block_ptr(rstd, (T,), (1,), (i_t,), (BT,), (0,))
263
+ b_rstd = tl.load(p_rstd, boundary_check=(0,))
264
+ # Compute dx
265
+ b_xhat = (b_x - b_mean[:, None]) * b_rstd[:, None] if not IS_RMS_NORM else b_x * b_rstd[:, None]
266
+ b_xhat = tl.where(m_d[None, :], b_xhat, 0.0)
267
+
268
+ b_y = b_xhat * b_w[None, :] if HAS_WEIGHT else b_xhat
269
+ if HAS_BIAS:
270
+ b_y = b_y + b_b[None, :]
271
+ if RECOMPUTE_OUTPUT:
272
+ p_y = tl.make_block_ptr(y, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
273
+ tl.store(p_y, b_y.to(p_y.dtype.element_ty), boundary_check=(0, 1))
274
+
275
+ b_sigmoid_g = tl.sigmoid(b_g)
276
+ if ACTIVATION == 'swish':
277
+ b_dg = b_dy * b_y * (b_sigmoid_g + b_g * b_sigmoid_g * (1 - b_sigmoid_g))
278
+ b_dy = b_dy * b_g * b_sigmoid_g
279
+ elif ACTIVATION == 'silu':
280
+ b_dg = b_dy * b_y * (b_sigmoid_g + b_g * b_sigmoid_g * (1 - b_sigmoid_g))
281
+ b_dy = b_dy * b_g * b_sigmoid_g
282
+ elif ACTIVATION == 'sigmoid':
283
+ b_dg = b_dy * b_y * b_sigmoid_g * (1 - b_sigmoid_g)
284
+ b_dy = b_dy * b_sigmoid_g
285
+ b_wdy = b_dy
286
+
287
+ if HAS_WEIGHT or HAS_BIAS:
288
+ m_t = (i_t + tl.arange(0, BT)) < T
289
+ if HAS_WEIGHT:
290
+ b_wdy = b_dy * b_w
291
+ b_dw += tl.where(m_t[:, None], b_dy * b_xhat, 0.0)
292
+ if HAS_BIAS:
293
+ b_db += tl.where(m_t[:, None], b_dy, 0.0)
294
+ if not IS_RMS_NORM:
295
+ b_c1 = tl.sum(b_xhat * b_wdy, axis=1) / D
296
+ b_c2 = tl.sum(b_wdy, axis=1) / D
297
+ b_dx = (b_wdy - (b_xhat * b_c1[:, None] + b_c2[:, None])) * b_rstd[:, None]
298
+ else:
299
+ b_c1 = tl.sum(b_xhat * b_wdy, axis=1) / D
300
+ b_dx = (b_wdy - b_xhat * b_c1[:, None]) * b_rstd[:, None]
301
+ if HAS_DRESIDUAL:
302
+ p_dres = tl.make_block_ptr(dresidual, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
303
+ b_dres = tl.load(p_dres, boundary_check=(0, 1)).to(tl.float32)
304
+ b_dx += b_dres
305
+ # Write dx
306
+ if STORE_DRESIDUAL:
307
+ p_dres_in = tl.make_block_ptr(dresidual_in, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
308
+ tl.store(p_dres_in, b_dx.to(p_dres_in.dtype.element_ty), boundary_check=(0, 1))
309
+
310
+ tl.store(p_dx, b_dx.to(p_dx.dtype.element_ty), boundary_check=(0, 1))
311
+ tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0, 1))
312
+
313
+ if HAS_WEIGHT:
314
+ tl.store(dw + i_s * D + o_d, tl.sum(b_dw, axis=0), mask=m_d)
315
+ if HAS_BIAS:
316
+ tl.store(db + i_s * D + o_d, tl.sum(b_db, axis=0), mask=m_d)
317
+
318
+
319
+ @triton.heuristics({
320
+ 'HAS_DRESIDUAL': lambda args: args['dresidual'] is not None,
321
+ 'HAS_WEIGHT': lambda args: args['w'] is not None,
322
+ 'HAS_BIAS': lambda args: args['b'] is not None,
323
+ 'RECOMPUTE_OUTPUT': lambda args: args['y'] is not None
324
+ })
325
+ @triton.autotune(
326
+ configs=[
327
+ triton.Config({}, num_warps=num_warps)
328
+ for num_warps in [2, 4, 8, 16]
329
+ ],
330
+ key=['D', 'IS_RMS_NORM', 'STORE_DRESIDUAL', 'HAS_DRESIDUAL', 'HAS_WEIGHT'],
331
+ **autotune_cache_kwargs
332
+ )
333
+ @triton.jit
334
+ def layer_norm_gated_bwd_kernel1(
335
+ x, # pointer to the input
336
+ g, # pointer to the gate
337
+ w, # pointer to the weights
338
+ b, # pointer to the biases
339
+ y, # pointer to the output to be recomputed
340
+ dy, # pointer to the output gradient
341
+ dx, # pointer to the input gradient
342
+ dg, # pointer to the gate gradient
343
+ dw, # pointer to the partial sum of weights gradient
344
+ db, # pointer to the partial sum of biases gradient
345
+ dresidual,
346
+ dresidual_in,
347
+ mean,
348
+ rstd,
349
+ T,
350
+ BS,
351
+ D: tl.constexpr,
352
+ BD: tl.constexpr,
353
+ ACTIVATION: tl.constexpr,
354
+ IS_RMS_NORM: tl.constexpr,
355
+ STORE_DRESIDUAL: tl.constexpr,
356
+ HAS_DRESIDUAL: tl.constexpr,
357
+ HAS_WEIGHT: tl.constexpr,
358
+ HAS_BIAS: tl.constexpr,
359
+ RECOMPUTE_OUTPUT: tl.constexpr,
360
+ ):
361
+ i_s = tl.program_id(0)
362
+ o_d = tl.arange(0, BD)
363
+ mask = o_d < D
364
+ x += i_s * BS * D
365
+ g += i_s * BS * D
366
+ if HAS_DRESIDUAL:
367
+ dresidual += i_s * BS * D
368
+ if STORE_DRESIDUAL:
369
+ dresidual_in += i_s * BS * D
370
+ dy += i_s * BS * D
371
+ dx += i_s * BS * D
372
+ dg += i_s * BS * D
373
+ if RECOMPUTE_OUTPUT:
374
+ y += i_s * BS * D
375
+ if HAS_WEIGHT:
376
+ b_w = tl.load(w + o_d, mask=mask).to(tl.float32)
377
+ b_dw = tl.zeros((BD,), dtype=tl.float32)
378
+ if HAS_BIAS:
379
+ b_b = tl.load(b + o_d, mask=mask, other=0.0).to(tl.float32)
380
+ b_db = tl.zeros((BD,), dtype=tl.float32)
381
+
382
+ for i_t in range(i_s * BS, min(i_s * BS + BS, T)):
383
+ # Load data to SRAM
384
+ b_x = tl.load(x + o_d, mask=mask, other=0).to(tl.float32)
385
+ b_g = tl.load(g + o_d, mask=mask, other=0).to(tl.float32)
386
+ b_dy = tl.load(dy + o_d, mask=mask, other=0).to(tl.float32)
387
+
388
+ if not IS_RMS_NORM:
389
+ b_mean = tl.load(mean + i_t)
390
+ b_rstd = tl.load(rstd + i_t)
391
+ # Compute dx
392
+ b_xhat = (b_x - b_mean) * b_rstd if not IS_RMS_NORM else b_x * b_rstd
393
+ b_xhat = tl.where(mask, b_xhat, 0.0)
394
+
395
+ b_y = b_xhat * b_w if HAS_WEIGHT else b_xhat
396
+ if HAS_BIAS:
397
+ b_y = b_y + b_b
398
+ if RECOMPUTE_OUTPUT:
399
+ tl.store(y + o_d, b_y, mask=mask)
400
+
401
+ b_sigmoid_g = tl.sigmoid(b_g)
402
+ if ACTIVATION == 'swish':
403
+ b_dg = b_dy * b_y * (b_sigmoid_g + b_g * b_sigmoid_g * (1 - b_sigmoid_g))
404
+ b_dy = b_dy * b_g * b_sigmoid_g
405
+ elif ACTIVATION == 'silu':
406
+ b_dg = b_dy * b_y * (b_sigmoid_g + b_g * b_sigmoid_g * (1 - b_sigmoid_g))
407
+ b_dy = b_dy * b_g * b_sigmoid_g
408
+ elif ACTIVATION == 'sigmoid':
409
+ b_dg = b_dy * b_y * b_sigmoid_g * (1 - b_sigmoid_g)
410
+ b_dy = b_dy * b_sigmoid_g
411
+ b_wdy = b_dy
412
+ if HAS_WEIGHT:
413
+ b_wdy = b_dy * b_w
414
+ b_dw += b_dy * b_xhat
415
+ if HAS_BIAS:
416
+ b_db += b_dy
417
+ if not IS_RMS_NORM:
418
+ b_c1 = tl.sum(b_xhat * b_wdy, axis=0) / D
419
+ b_c2 = tl.sum(b_wdy, axis=0) / D
420
+ b_dx = (b_wdy - (b_xhat * b_c1 + b_c2)) * b_rstd
421
+ else:
422
+ b_c1 = tl.sum(b_xhat * b_wdy, axis=0) / D
423
+ b_dx = (b_wdy - b_xhat * b_c1) * b_rstd
424
+ if HAS_DRESIDUAL:
425
+ b_dres = tl.load(dresidual + o_d, mask=mask, other=0).to(tl.float32)
426
+ b_dx += b_dres
427
+ # Write dx
428
+ if STORE_DRESIDUAL:
429
+ tl.store(dresidual_in + o_d, b_dx, mask=mask)
430
+ tl.store(dx + o_d, b_dx, mask=mask)
431
+ tl.store(dg + o_d, b_dg, mask=mask)
432
+
433
+ x += D
434
+ g += D
435
+ if HAS_DRESIDUAL:
436
+ dresidual += D
437
+ if STORE_DRESIDUAL:
438
+ dresidual_in += D
439
+ if RECOMPUTE_OUTPUT:
440
+ y += D
441
+ dy += D
442
+ dx += D
443
+ dg += D
444
+ if HAS_WEIGHT:
445
+ tl.store(dw + i_s * D + o_d, b_dw, mask=mask)
446
+ if HAS_BIAS:
447
+ tl.store(db + i_s * D + o_d, b_db, mask=mask)
448
+
449
+
450
+ def layer_norm_gated_fwd(
451
+ x: torch.Tensor,
452
+ g: torch.Tensor,
453
+ weight: torch.Tensor,
454
+ bias: torch.Tensor,
455
+ activation: str = 'swish',
456
+ eps: float = 1e-5,
457
+ residual: torch.Tensor = None,
458
+ out_dtype: torch.dtype = None,
459
+ residual_dtype: torch.dtype = None,
460
+ is_rms_norm: bool = False
461
+ ):
462
+ if residual is not None:
463
+ residual_dtype = residual.dtype
464
+ T, D = x.shape
465
+ if residual is not None:
466
+ assert residual.shape == (T, D)
467
+ if weight is not None:
468
+ assert weight.shape == (D,)
469
+ if bias is not None:
470
+ assert bias.shape == (D,)
471
+ # allocate output
472
+ y = torch.empty_like(x, dtype=x.dtype if out_dtype is None else out_dtype)
473
+ if residual is not None or (residual_dtype is not None and residual_dtype != x.dtype):
474
+ residual_out = torch.empty(T, D, device=x.device, dtype=residual_dtype)
475
+ else:
476
+ residual_out = None
477
+ mean = torch.empty((T,), dtype=torch.float, device=x.device) if not is_rms_norm else None
478
+ rstd = torch.empty((T,), dtype=torch.float, device=x.device)
479
+ # Less than 64KB per feature: enqueue fused kernel
480
+ MAX_FUSED_SIZE = 65536 // x.element_size()
481
+ BD = min(MAX_FUSED_SIZE, triton.next_power_of_2(D))
482
+ if D > BD:
483
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
484
+ # heuristics for number of warps
485
+
486
+ if D <= 512:
487
+ NB = triton.cdiv(T, 2048)
488
+ def grid(meta): return (triton.cdiv(T, meta['BT']),)
489
+ layer_norm_gated_fwd_kernel[grid](
490
+ x=x,
491
+ g=g,
492
+ y=y,
493
+ w=weight,
494
+ b=bias,
495
+ residual=residual,
496
+ residual_out=residual_out,
497
+ mean=mean,
498
+ rstd=rstd,
499
+ eps=eps,
500
+ T=T,
501
+ D=D,
502
+ BD=BD,
503
+ NB=NB,
504
+ ACTIVATION=activation,
505
+ IS_RMS_NORM=is_rms_norm,
506
+ )
507
+ else:
508
+ layer_norm_gated_fwd_kernel1[(T,)](
509
+ x=x,
510
+ g=g,
511
+ y=y,
512
+ w=weight,
513
+ b=bias,
514
+ residual=residual,
515
+ residual_out=residual_out,
516
+ mean=mean,
517
+ rstd=rstd,
518
+ eps=eps,
519
+ D=D,
520
+ BD=BD,
521
+ ACTIVATION=activation,
522
+ IS_RMS_NORM=is_rms_norm,
523
+ )
524
+ # residual_out is None if residual is None and residual_dtype == input_dtype
525
+ return y, mean, rstd, residual_out if residual_out is not None else x
526
+
527
+
528
+ def layer_norm_gated_bwd(
529
+ dy: torch.Tensor,
530
+ x: torch.Tensor,
531
+ g: torch.Tensor,
532
+ weight: torch.Tensor,
533
+ bias: torch.Tensor,
534
+ activation: str = 'swish',
535
+ eps: float = 1e-5,
536
+ mean: torch.Tensor = None,
537
+ rstd: torch.Tensor = None,
538
+ dresidual: torch.Tensor = None,
539
+ has_residual: bool = False,
540
+ is_rms_norm: bool = False,
541
+ x_dtype: torch.dtype = None,
542
+ recompute_output: bool = False,
543
+ ):
544
+ T, D = x.shape
545
+ assert dy.shape == (T, D)
546
+ if dresidual is not None:
547
+ assert dresidual.shape == (T, D)
548
+ if weight is not None:
549
+ assert weight.shape == (D,)
550
+ if bias is not None:
551
+ assert bias.shape == (D,)
552
+ # allocate output
553
+ dx = torch.empty_like(x) if x_dtype is None else torch.empty(T, D, dtype=x_dtype, device=x.device)
554
+ dg = torch.empty_like(g) if x_dtype is None else torch.empty(T, D, dtype=x_dtype, device=x.device)
555
+ dresidual_in = torch.empty_like(x) if has_residual and dx.dtype != x.dtype else None
556
+ y = torch.empty(T, D, dtype=dy.dtype, device=dy.device) if recompute_output else None
557
+
558
+ # Less than 64KB per feature: enqueue fused kernel
559
+ MAX_FUSED_SIZE = 65536 // x.element_size()
560
+ BD = min(MAX_FUSED_SIZE, triton.next_power_of_2(D))
561
+ if D > BD:
562
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
563
+ NS = get_multiprocessor_count(x.device.index)
564
+ BS = math.ceil(T / NS)
565
+
566
+ dw = torch.empty((NS, D), dtype=torch.float, device=weight.device) if weight is not None else None
567
+ db = torch.empty((NS, D), dtype=torch.float, device=bias.device) if bias is not None else None
568
+ grid = (NS,)
569
+
570
+ if D <= 512:
571
+ NB = triton.cdiv(T, 2048)
572
+ layer_norm_gated_bwd_kernel[grid](
573
+ x=x,
574
+ g=g,
575
+ w=weight,
576
+ b=bias,
577
+ y=y,
578
+ dy=dy,
579
+ dx=dx,
580
+ dg=dg,
581
+ dw=dw,
582
+ db=db,
583
+ dresidual=dresidual,
584
+ dresidual_in=dresidual_in,
585
+ mean=mean,
586
+ rstd=rstd,
587
+ T=T,
588
+ D=D,
589
+ BS=BS,
590
+ BD=BD,
591
+ NB=NB,
592
+ ACTIVATION=activation,
593
+ IS_RMS_NORM=is_rms_norm,
594
+ STORE_DRESIDUAL=dresidual_in is not None,
595
+ )
596
+ else:
597
+ layer_norm_gated_bwd_kernel1[grid](
598
+ x=x,
599
+ g=g,
600
+ w=weight,
601
+ b=bias,
602
+ y=y,
603
+ dy=dy,
604
+ dx=dx,
605
+ dg=dg,
606
+ dw=dw,
607
+ db=db,
608
+ dresidual=dresidual,
609
+ dresidual_in=dresidual_in,
610
+ mean=mean,
611
+ rstd=rstd,
612
+ T=T,
613
+ D=D,
614
+ BS=BS,
615
+ BD=BD,
616
+ ACTIVATION=activation,
617
+ IS_RMS_NORM=is_rms_norm,
618
+ STORE_DRESIDUAL=dresidual_in is not None,
619
+ )
620
+ dw = dw.sum(0).to(weight.dtype) if weight is not None else None
621
+ db = db.sum(0).to(bias.dtype) if bias is not None else None
622
+ # Don't need to compute dresidual_in separately in this case
623
+ if has_residual and dx.dtype == x.dtype:
624
+ dresidual_in = dx
625
+ return (dx, dg, dw, db, dresidual_in) if not recompute_output else (dx, dg, dw, db, dresidual_in, y)
626
+
627
+
628
+ class LayerNormGatedFunction(torch.autograd.Function):
629
+
630
+ @staticmethod
631
+ @input_guard
632
+ def forward(
633
+ ctx,
634
+ x: torch.Tensor,
635
+ g: torch.Tensor,
636
+ weight: torch.Tensor,
637
+ bias: torch.Tensor,
638
+ activation: str,
639
+ residual: Optional[torch.Tensor] = None,
640
+ eps: float = 1e-6,
641
+ prenorm: bool = False,
642
+ residual_in_fp32: bool = False,
643
+ is_rms_norm: bool = False,
644
+ ):
645
+ x_shape_og = x.shape
646
+ g_shape_og = g.shape
647
+ # reshape input data into 2D tensor
648
+ x = x.reshape(-1, x.shape[-1])
649
+ g = g.reshape(-1, g.shape[-1])
650
+ if residual is not None:
651
+ assert residual.shape == x_shape_og
652
+ residual = residual.reshape(-1, residual.shape[-1])
653
+ residual_dtype = (
654
+ residual.dtype
655
+ if residual is not None
656
+ else (torch.float if residual_in_fp32 else None)
657
+ )
658
+ y, mean, rstd, residual_out = layer_norm_gated_fwd(
659
+ x=x,
660
+ g=g,
661
+ weight=weight,
662
+ bias=bias,
663
+ activation=activation,
664
+ eps=eps,
665
+ residual=residual,
666
+ residual_dtype=residual_dtype,
667
+ is_rms_norm=is_rms_norm
668
+ )
669
+ ctx.save_for_backward(residual_out, g, weight, bias, mean, rstd)
670
+ ctx.x_shape_og = x_shape_og
671
+ ctx.g_shape_og = g_shape_og
672
+ ctx.activation = activation
673
+ ctx.eps = eps
674
+ ctx.is_rms_norm = is_rms_norm
675
+ ctx.has_residual = residual is not None
676
+ ctx.prenorm = prenorm
677
+ ctx.x_dtype = x.dtype
678
+ y = y.reshape(x_shape_og)
679
+ return y if not prenorm else (y, residual_out.reshape(x_shape_og))
680
+
681
+ @staticmethod
682
+ @input_guard
683
+ def backward(ctx, dy, *args):
684
+ x, g, weight, bias, mean, rstd = ctx.saved_tensors
685
+ dy = dy.reshape(-1, dy.shape[-1])
686
+ assert dy.shape == x.shape
687
+ if ctx.prenorm:
688
+ dresidual = args[0]
689
+ dresidual = dresidual.reshape(-1, dresidual.shape[-1])
690
+ assert dresidual.shape == x.shape
691
+ else:
692
+ dresidual = None
693
+ dx, dg, dw, db, dres_in = layer_norm_gated_bwd(
694
+ dy=dy,
695
+ x=x,
696
+ g=g,
697
+ weight=weight,
698
+ bias=bias,
699
+ activation=ctx.activation,
700
+ eps=ctx.eps,
701
+ mean=mean,
702
+ rstd=rstd,
703
+ dresidual=dresidual,
704
+ has_residual=ctx.has_residual,
705
+ is_rms_norm=ctx.is_rms_norm,
706
+ x_dtype=ctx.x_dtype,
707
+ )
708
+ return (
709
+ dx.reshape(ctx.x_shape_og),
710
+ dg.reshape(ctx.g_shape_og),
711
+ dw,
712
+ db,
713
+ None,
714
+ dres_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
715
+ None,
716
+ None,
717
+ None,
718
+ None,
719
+ )
720
+
721
+
722
+ class LayerNormGatedLinearFunction(torch.autograd.Function):
723
+
724
+ @staticmethod
725
+ @input_guard
726
+ def forward(
727
+ ctx,
728
+ x: torch.Tensor,
729
+ g: torch.Tensor,
730
+ norm_weight: torch.Tensor,
731
+ norm_bias: torch.Tensor,
732
+ linear_weight: torch.Tensor,
733
+ linear_bias: torch.Tensor,
734
+ residual: Optional[torch.Tensor] = None,
735
+ eps: float = 1e-6,
736
+ prenorm: bool = False,
737
+ residual_in_fp32: bool = False,
738
+ is_rms_norm: bool = False,
739
+ ):
740
+ x_shape_og = x.shape
741
+ g_shape_og = g.shape
742
+ # reshape input data into 2D tensor
743
+ x = x.reshape(-1, x.shape[-1])
744
+ g = g.reshape(-1, g.shape[-1])
745
+ if residual is not None:
746
+ assert residual.shape == x_shape_og
747
+ residual = residual.reshape(-1, residual.shape[-1])
748
+ residual_dtype = (
749
+ residual.dtype
750
+ if residual is not None
751
+ else (torch.float if residual_in_fp32 else None)
752
+ )
753
+ y, mean, rstd, residual_out = layer_norm_gated_fwd(
754
+ x=x,
755
+ g=g,
756
+ weight=norm_weight,
757
+ bias=norm_bias,
758
+ eps=eps,
759
+ residual=residual,
760
+ residual_dtype=residual_dtype,
761
+ is_rms_norm=is_rms_norm
762
+ )
763
+ y = y.reshape(x_shape_og)
764
+ dtype = torch.get_autocast_gpu_dtype() if torch.is_autocast_enabled() else y.dtype
765
+ linear_weight = linear_weight.to(dtype)
766
+ linear_bias = linear_bias.to(dtype) if linear_bias is not None else None
767
+ out = F.linear(y.to(linear_weight.dtype), linear_weight, linear_bias)
768
+ # We don't store y, will be recomputed in the backward pass to save memory
769
+ ctx.save_for_backward(residual_out, g, norm_weight, norm_bias, linear_weight, mean, rstd)
770
+ ctx.x_shape_og = x_shape_og
771
+ ctx.g_shape_og = g_shape_og
772
+ ctx.eps = eps
773
+ ctx.is_rms_norm = is_rms_norm
774
+ ctx.has_residual = residual is not None
775
+ ctx.prenorm = prenorm
776
+ ctx.x_dtype = x.dtype
777
+ ctx.linear_bias_is_none = linear_bias is None
778
+ return out if not prenorm else (out, residual_out.reshape(x_shape_og))
779
+
780
+ @staticmethod
781
+ @input_guard
782
+ def backward(ctx, dout, *args):
783
+ x, g, norm_weight, norm_bias, linear_weight, mean, rstd = ctx.saved_tensors
784
+ dout = dout.reshape(-1, dout.shape[-1])
785
+ dy = F.linear(dout, linear_weight.t())
786
+ dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0)
787
+ assert dy.shape == x.shape
788
+ if ctx.prenorm:
789
+ dresidual = args[0]
790
+ dresidual = dresidual.reshape(-1, dresidual.shape[-1])
791
+ assert dresidual.shape == x.shape
792
+ else:
793
+ dresidual = None
794
+ dx, dg, dnorm_weight, dnorm_bias, dres_in, y = layer_norm_gated_bwd(
795
+ dy=dy,
796
+ x=x,
797
+ g=g,
798
+ weight=norm_weight,
799
+ bias=norm_bias,
800
+ eps=ctx.eps,
801
+ mean=mean,
802
+ rstd=rstd,
803
+ dresidual=dresidual,
804
+ has_residual=ctx.has_residual,
805
+ is_rms_norm=ctx.is_rms_norm,
806
+ x_dtype=ctx.x_dtype,
807
+ recompute_output=True,
808
+ )
809
+ dlinear_weight = torch.einsum("bo,bi->oi", dout, y)
810
+ return (
811
+ dx.reshape(ctx.x_shape_og),
812
+ dg.reshape(ctx.g_shape_og),
813
+ dnorm_weight,
814
+ dnorm_bias,
815
+ dlinear_weight,
816
+ dlinear_bias,
817
+ dres_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
818
+ None,
819
+ None,
820
+ None,
821
+ None,
822
+ )
823
+
824
+
825
+ def layer_norm_gated(
826
+ x: torch.Tensor,
827
+ g: torch.Tensor,
828
+ weight: torch.Tensor,
829
+ bias: torch.Tensor,
830
+ activation: str = 'swish',
831
+ residual: Optional[torch.Tensor] = None,
832
+ prenorm: bool = False,
833
+ residual_in_fp32: bool = False,
834
+ eps: float = 1e-6
835
+ ):
836
+ return LayerNormGatedFunction.apply(
837
+ x,
838
+ g,
839
+ weight,
840
+ bias,
841
+ activation,
842
+ residual,
843
+ eps,
844
+ prenorm,
845
+ residual_in_fp32,
846
+ False
847
+ )
848
+
849
+
850
+ def rms_norm_gated(
851
+ x: torch.Tensor,
852
+ g: torch.Tensor,
853
+ weight: torch.Tensor,
854
+ bias: torch.Tensor,
855
+ activation: str = 'swish',
856
+ residual: Optional[torch.Tensor] = None,
857
+ prenorm: bool = False,
858
+ residual_in_fp32: bool = False,
859
+ eps: float = 1e-6
860
+ ):
861
+ return LayerNormGatedFunction.apply(
862
+ x,
863
+ g,
864
+ weight,
865
+ bias,
866
+ activation,
867
+ residual,
868
+ eps,
869
+ prenorm,
870
+ residual_in_fp32,
871
+ True
872
+ )
873
+
874
+
875
+ def layer_norm_swish_gate_linear(
876
+ x: torch.Tensor,
877
+ g: torch.Tensor,
878
+ norm_weight: torch.Tensor,
879
+ norm_bias: torch.Tensor,
880
+ linear_weight: torch.Tensor,
881
+ linear_bias: torch.Tensor,
882
+ residual: Optional[torch.Tensor] = None,
883
+ prenorm: bool = False,
884
+ residual_in_fp32: bool = False,
885
+ eps: float = 1e-6
886
+ ):
887
+ return LayerNormGatedLinearFunction.apply(
888
+ x,
889
+ g,
890
+ norm_weight,
891
+ norm_bias,
892
+ linear_weight,
893
+ linear_bias,
894
+ residual,
895
+ eps,
896
+ prenorm,
897
+ residual_in_fp32,
898
+ False
899
+ )
900
+
901
+
902
+ def rms_norm_swish_gate_linear(
903
+ x,
904
+ g: torch.Tensor,
905
+ norm_weight: torch.Tensor,
906
+ norm_bias: torch.Tensor,
907
+ linear_weight: torch.Tensor,
908
+ linear_bias: torch.Tensor,
909
+ residual: Optional[torch.Tensor] = None,
910
+ prenorm: bool = False,
911
+ residual_in_fp32: bool = False,
912
+ eps: float = 1e-6
913
+ ):
914
+ return LayerNormGatedLinearFunction.apply(
915
+ x,
916
+ g,
917
+ norm_weight,
918
+ norm_bias,
919
+ linear_weight,
920
+ linear_bias,
921
+ residual,
922
+ eps,
923
+ prenorm,
924
+ residual_in_fp32,
925
+ True
926
+ )
927
+
928
+
929
+ class FusedLayerNormGated(nn.Module):
930
+
931
+ def __init__(
932
+ self,
933
+ hidden_size: int,
934
+ elementwise_affine: bool = True,
935
+ bias: bool = False,
936
+ activation: str = 'swish',
937
+ eps: float = 1e-5,
938
+ device: Optional[torch.device] = None,
939
+ dtype: Optional[torch.dtype] = None,
940
+ ) -> FusedLayerNormGated:
941
+ factory_kwargs = {"device": device, "dtype": dtype}
942
+ super().__init__()
943
+
944
+ self.hidden_size = hidden_size
945
+ self.elementwise_affine = elementwise_affine
946
+ self.eps = eps
947
+ self.activation = activation
948
+
949
+ if self.activation not in ['swish', 'silu', 'sigmoid']:
950
+ raise ValueError(f"Unsupported activation: {self.activation}")
951
+
952
+ self.register_parameter("weight", None)
953
+ self.register_parameter("bias", None)
954
+ if elementwise_affine:
955
+ self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
956
+ if bias:
957
+ self.bias = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
958
+
959
+ self.reset_parameters()
960
+
961
+ def reset_parameters(self):
962
+ if self.elementwise_affine:
963
+ nn.init.ones_(self.weight)
964
+ if self.bias is not None:
965
+ nn.init.zeros_(self.bias)
966
+
967
+ def __repr__(self) -> str:
968
+ s = f"{self.__class__.__name__}({self.hidden_size}"
969
+ if not self.elementwise_affine:
970
+ s += f", elementwise_affine={self.elementwise_affine}"
971
+ s += f", eps={self.eps}"
972
+ s += f", activation={self.activation}"
973
+ s += ")"
974
+ return s
975
+
976
+ def forward(
977
+ self,
978
+ x: torch.Tensor,
979
+ g: torch.Tensor,
980
+ residual: Optional[torch.Tensor] = None,
981
+ prenorm: bool = False,
982
+ residual_in_fp32: bool = False
983
+ ) -> torch.Tensor:
984
+ return layer_norm_gated(
985
+ x,
986
+ g,
987
+ self.weight,
988
+ self.bias,
989
+ self.activation,
990
+ residual=residual,
991
+ eps=self.eps,
992
+ prenorm=prenorm,
993
+ residual_in_fp32=residual_in_fp32
994
+ )
995
+
996
+
997
+ class FusedRMSNormGated(nn.Module):
998
+
999
+ def __init__(
1000
+ self,
1001
+ hidden_size: int,
1002
+ elementwise_affine: bool = True,
1003
+ eps: float = 1e-5,
1004
+ activation: str = 'swish',
1005
+ device: Optional[torch.device] = None,
1006
+ dtype: Optional[torch.dtype] = None,
1007
+ ) -> FusedRMSNormGated:
1008
+ factory_kwargs = {"device": device, "dtype": dtype}
1009
+ super().__init__()
1010
+
1011
+ self.hidden_size = hidden_size
1012
+ self.elementwise_affine = elementwise_affine
1013
+ self.eps = eps
1014
+ self.activation = activation
1015
+
1016
+ if self.activation not in ['swish', 'silu', 'sigmoid']:
1017
+ raise ValueError(f"Unsupported activation: {self.activation}")
1018
+
1019
+ if elementwise_affine:
1020
+ self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
1021
+ else:
1022
+ self.register_parameter("weight", None)
1023
+ self.register_parameter("bias", None)
1024
+
1025
+ self.reset_parameters()
1026
+
1027
+ def reset_parameters(self):
1028
+ if self.elementwise_affine:
1029
+ nn.init.ones_(self.weight)
1030
+
1031
+ def __repr__(self) -> str:
1032
+ s = f"{self.__class__.__name__}({self.hidden_size}"
1033
+ if not self.elementwise_affine:
1034
+ s += f", elementwise_affine={self.elementwise_affine}"
1035
+ s += f", eps={self.eps}"
1036
+ s += f", activation={self.activation}"
1037
+ s += ")"
1038
+ return s
1039
+
1040
+ def forward(
1041
+ self,
1042
+ x: torch.Tensor,
1043
+ g: torch.Tensor,
1044
+ residual: Optional[torch.Tensor] = None,
1045
+ prenorm: bool = False,
1046
+ residual_in_fp32: bool = False
1047
+ ) -> torch.Tensor:
1048
+ return rms_norm_gated(
1049
+ x,
1050
+ g,
1051
+ self.weight,
1052
+ self.bias,
1053
+ self.activation,
1054
+ residual=residual,
1055
+ eps=self.eps,
1056
+ prenorm=prenorm,
1057
+ residual_in_fp32=residual_in_fp32
1058
+ )
1059
+
1060
+
1061
+ class FusedLayerNormSwishGate(FusedLayerNormGated):
1062
+
1063
+ def __init__(
1064
+ self,
1065
+ hidden_size: int,
1066
+ elementwise_affine: bool = True,
1067
+ bias: bool = False,
1068
+ eps: float = 1e-5,
1069
+ device: Optional[torch.device] = None,
1070
+ dtype: Optional[torch.dtype] = None,
1071
+ ) -> FusedLayerNormSwishGate:
1072
+ super().__init__(
1073
+ hidden_size=hidden_size,
1074
+ elementwise_affine=elementwise_affine,
1075
+ bias=bias,
1076
+ eps=eps,
1077
+ device=device,
1078
+ dtype=dtype
1079
+ )
1080
+
1081
+
1082
+ class FusedRMSNormSwishGate(FusedRMSNormGated):
1083
+
1084
+ def __init__(
1085
+ self,
1086
+ hidden_size: int,
1087
+ elementwise_affine: bool = True,
1088
+ eps: float = 1e-5,
1089
+ device: Optional[torch.device] = None,
1090
+ dtype: Optional[torch.dtype] = None,
1091
+ ) -> FusedRMSNormSwishGate:
1092
+ super().__init__(
1093
+ hidden_size=hidden_size,
1094
+ elementwise_affine=elementwise_affine,
1095
+ eps=eps,
1096
+ device=device,
1097
+ dtype=dtype
1098
+ )
1099
+
1100
+
1101
+ class FusedLayerNormGatedLinear(nn.Module):
1102
+
1103
+ def __init__(
1104
+ self,
1105
+ hidden_size: int,
1106
+ elementwise_affine: bool = True,
1107
+ eps: float = 1e-5,
1108
+ device: Optional[torch.device] = None,
1109
+ dtype: Optional[torch.dtype] = None,
1110
+ ) -> FusedLayerNormGatedLinear:
1111
+ factory_kwargs = {"device": device, "dtype": dtype}
1112
+ super().__init__()
1113
+
1114
+ self.hidden_size = hidden_size
1115
+ self.elementwise_affine = elementwise_affine
1116
+ self.eps = eps
1117
+
1118
+ if elementwise_affine:
1119
+ self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
1120
+ else:
1121
+ self.register_parameter("weight", None)
1122
+ self.register_parameter("bias", None)
1123
+
1124
+ self.reset_parameters()
1125
+
1126
+ def reset_parameters(self):
1127
+ if self.elementwise_affine:
1128
+ nn.init.ones_(self.weight)
1129
+
1130
+ def __repr__(self) -> str:
1131
+ s = f"{self.__class__.__name__}({self.hidden_size}"
1132
+ if not self.elementwise_affine:
1133
+ s += f", elementwise_affine={self.elementwise_affine}"
1134
+ s += f", eps={self.eps}"
1135
+ s += ")"
1136
+ return s
1137
+
1138
+ def forward(
1139
+ self,
1140
+ x: torch.Tensor,
1141
+ g: torch.Tensor,
1142
+ weight: Optional[torch.Tensor] = None,
1143
+ bias: Optional[torch.Tensor] = None,
1144
+ residual: Optional[torch.Tensor] = None,
1145
+ prenorm: bool = False,
1146
+ residual_in_fp32: bool = False
1147
+ ) -> torch.Tensor:
1148
+ return layer_norm_swish_gate_linear(
1149
+ x,
1150
+ g,
1151
+ self.weight,
1152
+ self.bias,
1153
+ weight,
1154
+ bias,
1155
+ residual=residual,
1156
+ eps=self.eps,
1157
+ prenorm=prenorm,
1158
+ residual_in_fp32=residual_in_fp32
1159
+ )
1160
+
1161
+
1162
+ class FusedLayerNormSwishGateLinear(FusedLayerNormGatedLinear):
1163
+
1164
+ def __init__(
1165
+ self,
1166
+ hidden_size: int,
1167
+ elementwise_affine: bool = True,
1168
+ eps: float = 1e-5,
1169
+ device: Optional[torch.device] = None,
1170
+ dtype: Optional[torch.dtype] = None,
1171
+ ) -> FusedLayerNormSwishGateLinear:
1172
+ super().__init__(
1173
+ hidden_size=hidden_size,
1174
+ elementwise_affine=elementwise_affine,
1175
+ eps=eps,
1176
+ device=device,
1177
+ dtype=dtype
1178
+ )
1179
+
1180
+
1181
+ class FusedRMSNormGatedLinear(nn.Module):
1182
+
1183
+ def __init__(
1184
+ self,
1185
+ hidden_size,
1186
+ elementwise_affine: bool = True,
1187
+ eps: float = 1e-5,
1188
+ device: Optional[torch.device] = None,
1189
+ dtype: Optional[torch.dtype] = None,
1190
+ ) -> FusedRMSNormGatedLinear:
1191
+ factory_kwargs = {"device": device, "dtype": dtype}
1192
+ super().__init__()
1193
+
1194
+ self.hidden_size = hidden_size
1195
+ self.elementwise_affine = elementwise_affine
1196
+ self.eps = eps
1197
+
1198
+ self.register_parameter("weight", None)
1199
+ self.register_parameter("bias", None)
1200
+ if elementwise_affine:
1201
+ self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
1202
+
1203
+ self.reset_parameters()
1204
+
1205
+ def reset_parameters(self):
1206
+ if self.elementwise_affine:
1207
+ nn.init.ones_(self.weight)
1208
+
1209
+ def __repr__(self) -> str:
1210
+ s = f"{self.__class__.__name__}({self.hidden_size}"
1211
+ if not self.elementwise_affine:
1212
+ s += f", elementwise_affine={self.elementwise_affine}"
1213
+ s += f", eps={self.eps}"
1214
+ s += ")"
1215
+ return s
1216
+
1217
+ def forward(
1218
+ self,
1219
+ x: torch.Tensor,
1220
+ g: torch.Tensor,
1221
+ weight: Optional[torch.Tensor] = None,
1222
+ bias: Optional[torch.Tensor] = None,
1223
+ residual: Optional[torch.Tensor] = None,
1224
+ prenorm: bool = False,
1225
+ residual_in_fp32: bool = False
1226
+ ) -> torch.Tensor:
1227
+ return rms_norm_swish_gate_linear(
1228
+ x,
1229
+ g,
1230
+ self.weight,
1231
+ self.bias,
1232
+ weight,
1233
+ bias,
1234
+ residual=residual,
1235
+ eps=self.eps,
1236
+ prenorm=prenorm,
1237
+ residual_in_fp32=residual_in_fp32
1238
+ )
1239
+
1240
+
1241
+ class FusedRMSNormSwishGateLinear(FusedRMSNormGatedLinear):
1242
+
1243
+ def __init__(
1244
+ self,
1245
+ hidden_size: int,
1246
+ elementwise_affine: bool = True,
1247
+ eps: float = 1e-5,
1248
+ device: Optional[torch.device] = None,
1249
+ dtype: Optional[torch.dtype] = None,
1250
+ ) -> FusedRMSNormSwishGateLinear:
1251
+ super().__init__(
1252
+ hidden_size=hidden_size,
1253
+ elementwise_affine=elementwise_affine,
1254
+ eps=eps,
1255
+ device=device,
1256
+ dtype=dtype
1257
+ )
modules/grpo.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # modified from https://github.com/mdy666/mdy_triton/blob/e0a856347bd988e05e0152332bba35f1d33c5b1f/others/grpo/grpo_loss.ipynb
3
+ # XHS ID: blueeeee
4
+
5
+ # https://github.com/huggingface/trl/blob/main/trl/trainer/grpo_trainer.py
6
+ """
7
+ # Get the per-token log probabilities for the completions for the model and the reference model
8
+ def _get_per_token_logps(self, model, input_ids, attention_mask, logits_to_keep):
9
+ # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded
10
+ logits = model(input_ids=input_ids, attention_mask=attention_mask, logits_to_keep=logits_to_keep + 1).logits
11
+ logits = logits[:, :-1, :] # (B, L-1, V), exclude the last logit: it corresponds to the next token pred
12
+
13
+ input_ids = input_ids[:, -logits_to_keep:]
14
+ # For transformers<=4.48, logits_to_keep argument isn't supported, so here we drop logits ourselves.
15
+ # See https://github.com/huggingface/trl/issues/2770
16
+ logits = logits[:, -logits_to_keep:]
17
+ return selective_log_softmax(logits, input_ids) # compute logprobs for the input tokens
18
+
19
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
20
+ if return_outputs:
21
+ raise ValueError("The GRPOTrainer does not support returning outputs")
22
+ # Compute the per-token log probabilities for the model
23
+
24
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
25
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
26
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
27
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
28
+ logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
29
+
30
+ per_token_logps = self._get_per_token_logps(model, input_ids, attention_mask, logits_to_keep)
31
+
32
+ # Compute the KL divergence between the model and the reference model
33
+ ref_per_token_logps = inputs["ref_per_token_logps"]
34
+ per_token_kl = torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
35
+
36
+ # x - x.detach() allows for preserving gradients from x
37
+ advantages = inputs["advantages"]
38
+ per_token_loss = torch.exp(per_token_logps - per_token_logps.detach()) * advantages.unsqueeze(1)
39
+ per_token_loss = -(per_token_loss - self.beta * per_token_kl)
40
+ loss = ((per_token_loss * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)).mean()
41
+
42
+ # Log the metrics
43
+ completion_length = self.accelerator.gather_for_metrics(completion_mask.sum(1)).float().mean().item()
44
+ self._metrics["completion_length"].append(completion_length)
45
+
46
+ mean_kl = ((per_token_kl * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)).mean()
47
+ self._metrics["kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item())
48
+
49
+ return loss
50
+ """
51
+
52
+
53
+ import torch
54
+ import triton
55
+ import triton.language as tl
56
+
57
+ from fla.ops.utils.op import exp, log
58
+ from fla.utils import autotune_cache_kwargs, input_guard, is_amd
59
+
60
+ NUM_WARPS_AUTOTUNE = [4, 8, 16] if is_amd else [4, 8, 16, 32]
61
+
62
+
63
+ @triton.autotune(
64
+ configs=[
65
+ triton.Config({'BLOCK_SIZE': BLOCK_SIZE}, num_warps=NUM_WARPS, num_stages=NUM_STAGES)
66
+ for BLOCK_SIZE in [1024, 2048, 4096, 8192]
67
+ for NUM_WARPS in NUM_WARPS_AUTOTUNE
68
+ for NUM_STAGES in [1, 2, 4]
69
+ ],
70
+ key=['B', 'N'],
71
+ **autotune_cache_kwargs
72
+ )
73
+ @triton.jit
74
+ def grpo_fwd_kernel(
75
+ logits_ptr,
76
+ ref_logp_ptr,
77
+ input_ids_ptr,
78
+ advantages_ptr,
79
+ completion_mask_ptr,
80
+ loss_ptr,
81
+ lse_ptr,
82
+ beta,
83
+ save_kl: tl.constexpr,
84
+ B,
85
+ M,
86
+ N,
87
+ L,
88
+ start_idx,
89
+ BLOCK_SIZE: tl.constexpr
90
+ ):
91
+ row_idx = tl.program_id(0)
92
+
93
+ off_b = row_idx // L
94
+ N = tl.cast(N, tl.int64)
95
+
96
+ loss_ptr += row_idx
97
+
98
+ completion_mask_ptr += row_idx
99
+ not_skip = tl.load(completion_mask_ptr).to(tl.int1)
100
+ if not_skip == 1:
101
+ ref_logp_ptr += row_idx
102
+ lse_ptr += row_idx
103
+ advantages_ptr += off_b
104
+ logits_ptr += N * (row_idx + off_b)
105
+ input_ids_ptr += row_idx + (off_b+1) * start_idx
106
+ base_cols = tl.arange(0, BLOCK_SIZE)
107
+
108
+ m_i = -float("inf")
109
+ l_i = 0.0
110
+ for start_n in tl.range(0, N, BLOCK_SIZE):
111
+ cols = start_n + base_cols
112
+ mask = cols < N
113
+ logits = tl.load(logits_ptr+cols, mask=mask, other=-float('inf')).to(tl.float32)
114
+ m_ij = tl.max(logits)
115
+ new_m_i = tl.maximum(m_i, m_ij)
116
+ l_i = l_i * exp(m_i - new_m_i) + tl.sum(exp(logits - new_m_i))
117
+ m_i = new_m_i
118
+ lse = log(l_i) + m_i
119
+
120
+ idx = tl.load(input_ids_ptr)
121
+ x = tl.load(logits_ptr+idx).to(tl.float32)
122
+ advantage = tl.load(advantages_ptr).to(tl.float32)
123
+ ref_logp = tl.load(ref_logp_ptr)
124
+ logp = x - lse
125
+ diff = ref_logp - logp
126
+ kl = exp(diff) - diff - 1
127
+ loss = kl * beta - advantage
128
+
129
+ tl.store(loss_ptr, loss.to(loss_ptr.dtype.element_ty))
130
+ tl.store(lse_ptr, lse.to(lse_ptr.dtype.element_ty))
131
+ if save_kl:
132
+ tl.store(loss_ptr+M, kl.to(loss_ptr.dtype.element_ty))
133
+ else:
134
+ # store 0
135
+ tl.store(loss_ptr, 0.0)
136
+ if save_kl:
137
+ tl.store(loss_ptr+M, 0.0)
138
+
139
+
140
+ @triton.autotune(
141
+ configs=[
142
+ triton.Config({}, num_warps=NUM_WARPS, num_stages=NUM_STAGES)
143
+ for NUM_WARPS in [32]
144
+ for NUM_STAGES in [4]
145
+ ],
146
+ key=['B', 'N'],
147
+ **autotune_cache_kwargs
148
+ )
149
+ @triton.jit
150
+ def grpo_bwd_kernel(
151
+ dloss_ptr,
152
+ dlogits_ptr,
153
+ logits_ptr,
154
+ ref_logp_ptr,
155
+ input_ids_ptr,
156
+ advantages_ptr,
157
+ completion_mask_ptr,
158
+ lse_ptr,
159
+ beta,
160
+ B,
161
+ N,
162
+ L,
163
+ start_idx,
164
+ BLOCK_SIZE: tl.constexpr
165
+ ):
166
+
167
+ row_idx = tl.program_id(0) # B*L
168
+ off_b = row_idx // L
169
+
170
+ N = tl.cast(N, tl.int64)
171
+
172
+ dlogits_ptr += N * (row_idx + off_b)
173
+ base_cols = tl.arange(0, BLOCK_SIZE)
174
+ completion_mask_ptr += row_idx
175
+ not_skip = tl.load(completion_mask_ptr).to(tl.int1)
176
+
177
+ if not_skip == 1:
178
+ lse_ptr += row_idx
179
+ dloss_ptr += row_idx
180
+ advantages_ptr += off_b
181
+ ref_logp_ptr += row_idx
182
+ logits_ptr += N * (row_idx + off_b)
183
+ input_ids_ptr += row_idx + (off_b+1) * start_idx
184
+ dloss = tl.load(dloss_ptr).to(tl.float32)
185
+ lse = tl.load(lse_ptr).to(tl.float32)
186
+ idx = tl.load(input_ids_ptr)
187
+ x = tl.load(logits_ptr+idx).to(tl.float32)
188
+ advantage = tl.load(advantages_ptr).to(tl.float32)
189
+ ref_logp = tl.load(ref_logp_ptr)
190
+ # Need for in-place grad.
191
+ tl.debug_barrier()
192
+ logp = x - lse
193
+
194
+ dlogp = (beta * (-1.0 * exp(ref_logp - logp) + 1)
195
+ - advantage) * dloss
196
+
197
+ for start_n in tl.range(0, N, BLOCK_SIZE):
198
+ cols = start_n + base_cols
199
+ mask = cols < N
200
+ logits = tl.load(logits_ptr+cols, mask=mask, other=-float('inf')).to(tl.float32)
201
+ probs = exp(logits - lse)
202
+ dlogits = tl.where(cols == idx, 1-probs, -probs) * dlogp
203
+
204
+ tl.store(dlogits_ptr+cols, dlogits.to(dlogits_ptr.dtype.element_ty), mask=mask)
205
+ else:
206
+ dlogits = tl.zeros((BLOCK_SIZE,), dtype=tl.float32)
207
+ for start_n in tl.range(0, N, BLOCK_SIZE):
208
+ cols = start_n + base_cols
209
+ mask = cols < N
210
+
211
+ tl.store(dlogits_ptr+cols, dlogits.to(dlogits_ptr.dtype.element_ty), mask=mask)
212
+
213
+
214
+ class GrpoLoss(torch.autograd.Function):
215
+
216
+ @input_guard
217
+ @staticmethod
218
+ def forward(ctx, logits, ref_logp, input_ids, advantages, beta, completion_mask, save_kl, inplace=True):
219
+ ctx.input_shape = logits.shape
220
+ B, L_ADD_1, N = ctx.input_shape
221
+ L = L_ADD_1 - 1
222
+ M = B * L
223
+ input_ids_start_index = input_ids.size(1) - L
224
+
225
+ if not save_kl:
226
+ loss = torch.empty(B, L, device=logits.device, dtype=torch.float32)
227
+ else:
228
+ loss = torch.empty(B*2, L, device=logits.device, dtype=torch.float32)
229
+
230
+ lse = torch.empty(B, L, device=logits.device, dtype=torch.float32)
231
+
232
+ if completion_mask is None:
233
+ completion_mask = torch.ones(B, L, device=logits.device, dtype=torch.int32)
234
+ else:
235
+ loss[:B].masked_fill_(completion_mask.logical_not(), 0.0)
236
+
237
+ grpo_fwd_kernel[(M,)](
238
+ logits_ptr=logits,
239
+ ref_logp_ptr=ref_logp,
240
+ input_ids_ptr=input_ids,
241
+ advantages_ptr=advantages,
242
+ completion_mask_ptr=completion_mask,
243
+ loss_ptr=loss,
244
+ lse_ptr=lse,
245
+ beta=beta,
246
+ save_kl=save_kl,
247
+ B=B, M=M, N=N, L=L,
248
+ start_idx=input_ids_start_index,
249
+ )
250
+ ctx.beta = beta
251
+ ctx.save_for_backward(lse, logits, input_ids, advantages, completion_mask)
252
+ ctx.ref_logp = ref_logp
253
+ ctx.inplace = inplace
254
+ return loss
255
+
256
+ @input_guard
257
+ @staticmethod
258
+ def backward(ctx, dloss):
259
+ # The grad of logits comes from two parts, the reward part and the kl part
260
+ lse, logits, input_ids, advantages, completion_mask = ctx.saved_tensors
261
+ inplace = ctx.inplace
262
+ B, L_ADD_1, N = ctx.input_shape
263
+ L = L_ADD_1 - 1
264
+ M = B * L
265
+
266
+ input_ids_start_index = input_ids.size(1) - L
267
+
268
+ # B, L_ADD_1, N
269
+ dlogits = logits if inplace else torch.empty_like(logits)
270
+ BN = min(65536, triton.next_power_of_2(N))
271
+
272
+ grpo_bwd_kernel[(M,)](
273
+ dloss_ptr=dloss,
274
+ dlogits_ptr=dlogits,
275
+ logits_ptr=logits,
276
+ ref_logp_ptr=ctx.ref_logp,
277
+ input_ids_ptr=input_ids,
278
+ advantages_ptr=advantages,
279
+ completion_mask_ptr=completion_mask,
280
+ lse_ptr=lse,
281
+ beta=ctx.beta,
282
+ B=B, N=N, L=L,
283
+ BLOCK_SIZE=BN,
284
+ start_idx=input_ids_start_index,
285
+ )
286
+ # The last token in the completion is not used in the loss computation
287
+ # and therefore its gradient should be set to 0
288
+ dlogits[:, -1, :].fill_(0.0)
289
+ return dlogits.view(*ctx.input_shape), None, None, None, None, None, None, None
290
+
291
+
292
+ def fused_grpo_loss(logits, ref_logp, input_ids, advantages,
293
+ beta=0.1, completion_mask=None, save_kl=False, inplace=False) -> torch.Tensor:
294
+ '''
295
+ compute grpo loss, save memory(no addition usage) and fast speed(6X for A800)
296
+
297
+ Args:
298
+ logtits: Tensor, [B, L+1, vocab_size], the origin output of model, it's not logits[:, :-1]
299
+ ref_logp: Tensor, [B, L], the origin output of model, it's not ref_logits[:, :-1]
300
+ input_ids: Tensor, [B, K+L], it's prompt_completion_id, it contains the prompt ids and output ids
301
+ advantages: Tensor, [B], the advantages of each prompt
302
+ beta: float, the weight of kl loss
303
+ completion_mask: Tensor, loss mask
304
+ save_kl: bool, if true will save kl
305
+
306
+ Retutn:
307
+ loss: Tensor, [B, L], the loss of grpo, it contains the advantage part and kl part
308
+
309
+ NOTE: logits(ref_logits) is computed by these steps
310
+ logits_to_keep = completion_ids.size(1)
311
+
312
+ def get_per_token_logits(model, input_ids, attention_mask, logits_to_keep):
313
+ # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded
314
+ logits = model(
315
+ input_ids=input_ids, attention_mask=attention_mask, logits_to_keep=logits_to_keep + 1
316
+ ).logits
317
+ return logits
318
+
319
+ logits = get_per_token_logits(model, prompt_completion_ids, attention_mask, logits_to_keep)
320
+ '''
321
+ out = GrpoLoss.apply(logits, ref_logp, input_ids, advantages, beta, completion_mask, save_kl, inplace)
322
+ if not save_kl:
323
+ return out
324
+ else:
325
+ return out.chunk(2, axis=0)
326
+
327
+
328
+ def grpo_loss_torch(logits, ref_logp, input_ids, advantages, beta=0.1, completion_mask=None, save_kl=False):
329
+ def get_log_probs(logits, input_ids):
330
+ per_token_logps = []
331
+ for logits_row, input_ids_row in zip(logits, input_ids[:, -logits.size(1):]):
332
+ log_probs = logits_row.log_softmax(dim=-1)
333
+ token_log_prob = torch.gather(log_probs, dim=1, index=input_ids_row.unsqueeze(1)).squeeze(1)
334
+ per_token_logps.append(token_log_prob)
335
+ return torch.stack(per_token_logps)
336
+
337
+ logits = logits[:, :-1]
338
+ per_token_logps = get_log_probs(logits, input_ids)
339
+ ref_per_token_logps = ref_logp
340
+ per_token_kl = torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
341
+
342
+ per_token_loss = torch.exp(per_token_logps - per_token_logps.detach()) * advantages.unsqueeze(1)
343
+ per_token_loss = -(per_token_loss - beta * per_token_kl)
344
+ if completion_mask is not None:
345
+ per_token_loss *= completion_mask
346
+ if save_kl:
347
+ per_token_kl *= completion_mask
348
+ return per_token_loss if not save_kl else (per_token_loss, per_token_kl)
349
+
350
+
351
+ @torch.compile(fullgraph=True)
352
+ def grpo_loss_with_old_logps(
353
+ logps: torch.Tensor,
354
+ ref_logps: torch.Tensor,
355
+ old_logps: torch.Tensor,
356
+ pad_mask: torch.Tensor,
357
+ logits_to_keep: int,
358
+ rewards: torch.Tensor,
359
+ beta: float = 0.2,
360
+ epsilon: float = 0.2
361
+ ):
362
+ """
363
+ Compute the GRPO (Group Relative Policy Optimization) loss.
364
+
365
+ Args:
366
+ logps (torch.Tensor): [Batch, Token_length] Log probabilities of the current policy.
367
+ ref_logps (torch.Tensor):[Batch, Token_length] Log probabilities of the reference policy.
368
+ old_logps (torch.Tensor): [Batch, Token_length] Log probabilities of the old policy.
369
+ completion_ids (torch.Tensor): [Batch, Token_length] Completion token IDs (bool).
370
+ pad_token_id: Pad token ID.
371
+ logits_to_keep (int): Number of logits to keep for masking.
372
+ rewards (torch.Tensor): [Batch] Rewards for each generation.
373
+ beta (float) = 0.2: A hyperparameter for weighting the KL divergence term.
374
+ epsilon (float) = 0.2: An float hyperparameter for clipping the importance weights.
375
+
376
+ Returns:
377
+ torch.Tensor: The computed GRPO loss.
378
+ """
379
+ B = logps.shape[0]
380
+ assert B > 1, "Batch * Num generations should be greater than 1"
381
+
382
+ rewards_shaped = rewards.view(-1, B) # B,num_generations
383
+ advantages = (rewards_shaped - rewards_shaped.mean(dim=1, keepdim=True)) / \
384
+ (rewards_shaped.std(dim=1, keepdim=True) + 1e-8)
385
+ advantages = advantages.view(-1) # B*num_generations
386
+ # Calculate the per - token KL divergence
387
+ per_token_kl = torch.exp(ref_logps - logps) - (ref_logps - logps) - 1
388
+
389
+ # Calculate the ratio of probabilities (importance weights)
390
+ # Importance weights are calculated as exp(log_pi_theta - log_pi_theta_old)
391
+ importance_weights = torch.exp(logps - old_logps)
392
+
393
+ # Clip the importance weights to the range [1 - epsilon, 1 + epsilon]
394
+ importance_weights_clipped = torch.clamp(importance_weights, 1 - epsilon, 1 + epsilon)
395
+
396
+ # Create a completion mask. It checks which positions are valid based on logits_to_keep
397
+ completion_mask = torch.arange(logits_to_keep, device=logps.device)[None, :] >= 0
398
+
399
+ # Combine the completion mask and padding mask
400
+ completion_mask = completion_mask & pad_mask # Ensure matching shape
401
+
402
+ # Add an extra dimension to advantages to match the shape for element - wise multiplication
403
+ advantages = advantages.unsqueeze(1)
404
+
405
+ # Calculate the per - token loss. It takes the minimum of the unclipped and clipped importance weights
406
+ # and subtracts the KL divergence term weighted by beta, then multiplies by the completion mask
407
+ token_loss = -(torch.min(advantages * importance_weights, advantages *
408
+ importance_weights_clipped) - beta * per_token_kl) * completion_mask
409
+
410
+ # Calculate the final loss by summing the token losses and normalizing by the number of valid tokens
411
+ loss = -token_loss.sum() / completion_mask.sum()
412
+
413
+ return loss
modules/l2norm.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Optional
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ from ..utils import autotune_cache_kwargs, input_guard, is_amd
12
+
13
+ BT_LIST = [8, 16, 32, 64, 128]
14
+ NUM_WARPS_AUTOTUNE = [1, 2, 4, 8, 16] if is_amd else [1, 2, 4, 8, 16, 32]
15
+
16
+
17
+ @triton.autotune(
18
+ configs=[
19
+ triton.Config({}, num_warps=num_warps)
20
+ for num_warps in NUM_WARPS_AUTOTUNE
21
+ ],
22
+ key=['D'],
23
+ **autotune_cache_kwargs
24
+ )
25
+ @triton.jit
26
+ def l2norm_fwd_kernel1(
27
+ x,
28
+ y,
29
+ rstd,
30
+ eps,
31
+ D,
32
+ BD: tl.constexpr,
33
+ ):
34
+ i_t = tl.program_id(0)
35
+ x += i_t * D
36
+ y += i_t * D
37
+ # Compute mean and variance
38
+ cols = tl.arange(0, BD)
39
+ mask = cols < D
40
+
41
+ b_x = tl.load(x + cols, mask=mask, other=0.0).to(tl.float32)
42
+ b_rstd = 1 / tl.sqrt(tl.sum(b_x * b_x) + eps)
43
+ b_y = b_x * b_rstd
44
+ tl.store(y + cols, b_y, mask=mask)
45
+ tl.store(rstd + i_t, b_rstd)
46
+
47
+
48
+ @triton.autotune(
49
+ configs=[
50
+ triton.Config({}, num_warps=num_warps)
51
+ for num_warps in NUM_WARPS_AUTOTUNE
52
+ ],
53
+ key=['D'],
54
+ **autotune_cache_kwargs
55
+ )
56
+ @triton.jit
57
+ def l2norm_bwd_kernel1(
58
+ y,
59
+ rstd,
60
+ dy,
61
+ dx,
62
+ eps,
63
+ D,
64
+ BD: tl.constexpr,
65
+ ):
66
+ i_t = tl.program_id(0)
67
+ y += i_t * D
68
+ dx += i_t * D
69
+ dy += i_t * D
70
+
71
+ cols = tl.arange(0, BD)
72
+ mask = cols < D
73
+ b_y = tl.load(y + cols, mask=mask, other=0.0).to(tl.float32)
74
+ b_rstd = tl.load(rstd + i_t).to(tl.float32)
75
+ b_dy = tl.load(dy + cols, mask=mask, other=0.0).to(tl.float32)
76
+ b_dx = b_dy * b_rstd - tl.sum(b_dy * b_y) * b_y * b_rstd
77
+ tl.store(dx + cols, b_dx, mask=mask)
78
+
79
+
80
+ @triton.autotune(
81
+ configs=[
82
+ triton.Config({'BT': BT}, num_warps=num_warps)
83
+ for num_warps in [1, 2, 4, 8, 16]
84
+ for BT in BT_LIST
85
+ ],
86
+ key=['D', 'NB'],
87
+ **autotune_cache_kwargs
88
+ )
89
+ @triton.jit
90
+ def l2norm_fwd_kernel(
91
+ x,
92
+ y,
93
+ rstd,
94
+ eps,
95
+ T: tl.constexpr,
96
+ D: tl.constexpr,
97
+ BD: tl.constexpr,
98
+ NB: tl.constexpr,
99
+ BT: tl.constexpr,
100
+ ):
101
+ i_t = tl.program_id(0)
102
+ p_x = tl.make_block_ptr(x, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
103
+ p_y = tl.make_block_ptr(y, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
104
+ p_rstd = tl.make_block_ptr(rstd, (T,), (1,), (i_t * BT,), (BT,), (0,))
105
+
106
+ b_x = tl.load(p_x, boundary_check=(0, 1)).to(tl.float32)
107
+ b_rstd = 1 / tl.sqrt(tl.sum(b_x * b_x, 1) + eps)
108
+ b_y = b_x * b_rstd[:, None]
109
+
110
+ tl.store(p_y, b_y.to(p_y.dtype.element_ty), boundary_check=(0, 1))
111
+ tl.store(p_rstd, b_rstd.to(p_rstd.dtype.element_ty), boundary_check=(0,))
112
+
113
+
114
+ @triton.autotune(
115
+ configs=[
116
+ triton.Config({'BT': BT}, num_warps=num_warps)
117
+ for num_warps in [1, 2, 4, 8, 16]
118
+ for BT in BT_LIST
119
+ ],
120
+ key=['D', 'NB'],
121
+ **autotune_cache_kwargs
122
+ )
123
+ @triton.jit
124
+ def l2norm_bwd_kernel(
125
+ y,
126
+ rstd,
127
+ dy,
128
+ dx,
129
+ eps,
130
+ T: tl.constexpr,
131
+ D: tl.constexpr,
132
+ BD: tl.constexpr,
133
+ NB: tl.constexpr,
134
+ BT: tl.constexpr,
135
+ ):
136
+ i_t = tl.program_id(0)
137
+ p_y = tl.make_block_ptr(y, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
138
+ p_rstd = tl.make_block_ptr(rstd, (T,), (1,), (i_t * BT,), (BT,), (0,))
139
+ p_dy = tl.make_block_ptr(dy, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
140
+ p_dx = tl.make_block_ptr(dx, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
141
+
142
+ b_y = tl.load(p_y, boundary_check=(0, 1)).to(tl.float32)
143
+ b_rstd = tl.load(p_rstd, boundary_check=(0,)).to(tl.float32)
144
+ b_dy = tl.load(p_dy, boundary_check=(0, 1)).to(tl.float32)
145
+ b_dx = b_dy * b_rstd[:, None] - tl.sum(b_dy * b_y, 1)[:, None] * b_y * b_rstd[:, None]
146
+ tl.store(p_dx, b_dx.to(p_dx.dtype.element_ty), boundary_check=(0, 1))
147
+
148
+
149
+ def l2norm_fwd(
150
+ x: torch.Tensor,
151
+ eps: float = 1e-6,
152
+ output_dtype: Optional[torch.dtype] = None
153
+ ):
154
+ x_shape_og = x.shape
155
+ x = x.view(-1, x.shape[-1])
156
+ # allocate output
157
+ if output_dtype is None:
158
+ y = torch.empty_like(x)
159
+ else:
160
+ y = torch.empty_like(x, dtype=output_dtype)
161
+ assert y.stride(-1) == 1
162
+ T, D = x.shape[0], x.shape[-1]
163
+ # Less than 64KB per feature: enqueue fused kernel
164
+ MAX_FUSED_SIZE = 65536 // x.element_size()
165
+ BD = min(MAX_FUSED_SIZE, triton.next_power_of_2(D))
166
+ if D > BD:
167
+ raise RuntimeError("This layer doesn't support feature dim >= 64KB.")
168
+
169
+ rstd = torch.empty((T,), dtype=torch.float32, device=x.device)
170
+ if D <= 512:
171
+ NB = triton.cdiv(T, 2048)
172
+ def grid(meta): return (triton.cdiv(T, meta['BT']), )
173
+ l2norm_fwd_kernel[grid](
174
+ x=x,
175
+ y=y,
176
+ rstd=rstd,
177
+ eps=eps,
178
+ T=T,
179
+ D=D,
180
+ BD=BD,
181
+ NB=NB,
182
+ )
183
+ else:
184
+ l2norm_fwd_kernel1[(T,)](
185
+ x=x,
186
+ y=y,
187
+ rstd=rstd,
188
+ eps=eps,
189
+ D=D,
190
+ BD=BD,
191
+ )
192
+ return y.view(x_shape_og), rstd.view(x_shape_og[:-1])
193
+
194
+
195
+ def l2norm_bwd(
196
+ y: torch.Tensor,
197
+ rstd: torch.Tensor,
198
+ dy: torch.Tensor,
199
+ eps: float = 1e-6
200
+ ):
201
+ y_shape_og = y.shape
202
+ y = y.view(-1, dy.shape[-1])
203
+ dy = dy.view(-1, dy.shape[-1])
204
+ assert dy.shape == y.shape
205
+ # allocate output
206
+ dx = torch.empty_like(y)
207
+ T, D = y.shape[0], y.shape[-1]
208
+ # Less than 64KB per feature: enqueue fused kernel
209
+ MAX_FUSED_SIZE = 65536 // y.element_size()
210
+ BD = min(MAX_FUSED_SIZE, triton.next_power_of_2(D))
211
+ if D > BD:
212
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
213
+
214
+ if D <= 512:
215
+ NB = triton.cdiv(T, 2048)
216
+ def grid(meta): return (triton.cdiv(T, meta['BT']), )
217
+ l2norm_bwd_kernel[grid](
218
+ y=y,
219
+ rstd=rstd,
220
+ dy=dy,
221
+ dx=dx,
222
+ eps=eps,
223
+ T=T,
224
+ D=D,
225
+ BD=BD,
226
+ NB=NB,
227
+ )
228
+ else:
229
+ l2norm_bwd_kernel1[(T,)](
230
+ y=y,
231
+ rstd=rstd,
232
+ dy=dy,
233
+ dx=dx,
234
+ eps=eps,
235
+ D=D,
236
+ BD=BD,
237
+ )
238
+
239
+ return dx.view(y_shape_og)
240
+
241
+
242
+ class L2NormFunction(torch.autograd.Function):
243
+
244
+ @staticmethod
245
+ @input_guard
246
+ def forward(
247
+ ctx,
248
+ x,
249
+ eps=1e-6,
250
+ output_dtype=None
251
+ ):
252
+ y, rstd = l2norm_fwd(x, eps, output_dtype)
253
+ ctx.eps = eps
254
+ ctx.x_dtype = x.dtype
255
+ ctx.save_for_backward(y, rstd)
256
+ return y
257
+
258
+ @staticmethod
259
+ @input_guard
260
+ def backward(ctx, dy):
261
+ y, rstd = ctx.saved_tensors
262
+ dx = l2norm_bwd(y, rstd, dy, ctx.eps)
263
+ return dx, None, None
264
+
265
+
266
+ def l2norm(
267
+ x: torch.Tensor,
268
+ eps: float = 1e-6,
269
+ output_dtype: Optional[torch.dtype] = None
270
+ ) -> torch.Tensor:
271
+ return L2NormFunction.apply(x, eps, output_dtype)
272
+
273
+
274
+ l2_norm = l2norm
275
+
276
+
277
+ class L2Norm(nn.Module):
278
+
279
+ def __init__(
280
+ self,
281
+ eps: float = 1e-6,
282
+ output_dtype: Optional[torch.dtype] = None
283
+ ):
284
+ super().__init__()
285
+ self.eps = eps
286
+ self.output_dtype = output_dtype
287
+
288
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
289
+ return l2norm(x, self.eps, self.output_dtype)
modules/l2warp.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import torch
4
+
5
+
6
+ class L2Wrap(torch.autograd.Function):
7
+ r"""
8
+ This class of penalty prevents the model from becoming overconfident,
9
+ thereby mitigating precision loss in BF16.
10
+
11
+ This version is memory-optimized by not storing the full logits tensor.
12
+ """
13
+ @staticmethod
14
+ def forward(ctx, loss, logits, l2_penalty_factor=1e-4):
15
+ """
16
+ Forward pass for L2 penalty.
17
+ Args:
18
+ loss (torch.Tensor): The loss tensor.
19
+ logits (torch.Tensor): Shape[B, T, V] The logits tensor.
20
+ l2_penalty_factor (float): The factor for L2 penalty.
21
+ """
22
+ maxx, ids = torch.max(logits, dim=-1, keepdim=True)
23
+ ctx.logits_shape = logits.shape
24
+ factor = l2_penalty_factor / (logits.shape[0] * logits.shape[1])
25
+ maxx = maxx * factor
26
+ ctx.save_for_backward(maxx, ids)
27
+ return loss
28
+
29
+ @staticmethod
30
+ def backward(ctx, grad_output):
31
+ maxx, ids = ctx.saved_tensors
32
+ glogits = torch.zeros(ctx.logits_shape, device=grad_output.device,
33
+ dtype=grad_output.dtype)
34
+ glogits.scatter_(-1, ids, maxx)
35
+ return grad_output, glogits, None
36
+
37
+
38
+ l2_warp = L2Wrap.apply
modules/layernorm_gated.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, Tri Dao.
2
+ # Based on the Triton LayerNorm tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
3
+ # For the backward pass, we keep weight_grad and bias_grad in registers and accumulate.
4
+ # This backward pass is faster for dimensions up to 8k, but after that it's much slower due to register spilling.
5
+ # The models we train have hidden dim up to 8k anyway (e.g. Llama 70B), so this is fine.
6
+
7
+ import math
8
+ from typing import Optional
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import triton
14
+ import triton.language as tl
15
+ from einops import rearrange
16
+
17
+ from fla.utils import get_multiprocessor_count, input_guard
18
+
19
+
20
+ def rms_norm_ref(x, weight, bias, z=None, eps=1e-6, group_size=None, norm_before_gate=True, upcast=True):
21
+ dtype = x.dtype
22
+ weight = weight.float()
23
+ bias = bias.float() if bias is not None else None
24
+ if upcast:
25
+ x = x.float()
26
+ z = z.float() if z is not None else z
27
+ if z is not None and not norm_before_gate:
28
+ x = x * F.silu(z)
29
+ if group_size is None:
30
+ rstd = 1 / torch.sqrt((x.square()).mean(dim=-1, keepdim=True) + eps)
31
+ out = (x * rstd * weight) + bias if bias is not None else (x * rstd * weight)
32
+ else:
33
+ x_group = rearrange(x, "... (g d) -> ... g d", d=group_size)
34
+ rstd = 1 / torch.sqrt((x_group.square()).mean(dim=-1, keepdim=True) + eps)
35
+ out = rearrange(x_group * rstd, "... g d -> ... (g d)") * weight
36
+ if bias is not None:
37
+ out = out + bias
38
+ if z is not None and norm_before_gate:
39
+ out *= F.silu(z)
40
+ return out.to(dtype)
41
+
42
+
43
+ @triton.heuristics({
44
+ "HAS_BIAS": lambda args: args["B"] is not None,
45
+ "HAS_Z": lambda args: args["Z"] is not None,
46
+ })
47
+ @triton.jit
48
+ def layer_norm_fwd_kernel(
49
+ X, # pointer to the input
50
+ Y, # pointer to the output
51
+ W, # pointer to the weights
52
+ B, # pointer to the biases
53
+ Z, # pointer to the other branch
54
+ Mean, # pointer to the mean
55
+ Rstd, # pointer to the 1/std
56
+ stride_x_row, # how much to increase the pointer when moving by 1 row
57
+ stride_y_row,
58
+ stride_z_row,
59
+ M, # number of rows in X
60
+ N, # number of columns in X
61
+ eps, # epsilon to avoid division by zero
62
+ BLOCK_N: tl.constexpr,
63
+ HAS_BIAS: tl.constexpr,
64
+ HAS_Z: tl.constexpr,
65
+ NORM_BEFORE_GATE: tl.constexpr,
66
+ IS_RMS_NORM: tl.constexpr,
67
+ ):
68
+ # Map the program id to the row of X and Y it should compute.
69
+ row = tl.program_id(0)
70
+ group = tl.program_id(1)
71
+ X += row * stride_x_row + group * N
72
+ Y += row * stride_y_row + group * N
73
+ if HAS_Z:
74
+ Z += row * stride_z_row + group * N
75
+ if not IS_RMS_NORM:
76
+ Mean += group * M
77
+ Rstd += group * M
78
+ W += group * N
79
+ if HAS_BIAS:
80
+ B += group * N
81
+ # Compute mean and variance
82
+ cols = tl.arange(0, BLOCK_N)
83
+ x = tl.load(X + cols, mask=cols < N, other=0.).to(tl.float32)
84
+ if HAS_Z and not NORM_BEFORE_GATE:
85
+ z = tl.load(Z + cols, mask=cols < N).to(tl.float32)
86
+ x *= z * tl.sigmoid(z)
87
+ if not IS_RMS_NORM:
88
+ mean = tl.sum(x, axis=0) / N
89
+ tl.store(Mean + row, mean)
90
+ xbar = tl.where(cols < N, x - mean, 0.)
91
+ var = tl.sum(xbar * xbar, axis=0) / N
92
+ else:
93
+ xbar = tl.where(cols < N, x, 0.)
94
+ var = tl.sum(xbar * xbar, axis=0) / N
95
+ rstd = 1 / tl.sqrt(var + eps)
96
+ tl.store(Rstd + row, rstd)
97
+ # Normalize and apply linear transformation
98
+ mask = cols < N
99
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
100
+ if HAS_BIAS:
101
+ b = tl.load(B + cols, mask=mask).to(tl.float32)
102
+ x_hat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
103
+ y = x_hat * w + b if HAS_BIAS else x_hat * w
104
+ if HAS_Z and NORM_BEFORE_GATE:
105
+ z = tl.load(Z + cols, mask=mask).to(tl.float32)
106
+ y *= z * tl.sigmoid(z)
107
+ # Write output
108
+ tl.store(Y + cols, y, mask=mask)
109
+
110
+
111
+ def layer_norm_fwd(
112
+ x: torch.Tensor,
113
+ weight: torch.Tensor,
114
+ bias: torch.Tensor,
115
+ eps: float,
116
+ z: torch.Tensor = None,
117
+ out: torch.Tensor = None,
118
+ group_size: int = None,
119
+ norm_before_gate: bool = True,
120
+ is_rms_norm: bool = False,
121
+ ):
122
+ M, N = x.shape
123
+ if group_size is None:
124
+ group_size = N
125
+ assert N % group_size == 0
126
+ ngroups = N // group_size
127
+ assert x.stride(-1) == 1
128
+ if z is not None:
129
+ assert z.stride(-1) == 1
130
+ assert z.shape == (M, N)
131
+ assert weight.shape == (N,)
132
+ assert weight.stride(-1) == 1
133
+ if bias is not None:
134
+ assert bias.stride(-1) == 1
135
+ assert bias.shape == (N,)
136
+ # allocate output
137
+ if out is not None:
138
+ assert out.shape == x.shape
139
+ else:
140
+ out = torch.empty_like(x)
141
+ assert out.stride(-1) == 1
142
+ mean = torch.empty((ngroups * M, ), dtype=torch.float32, device=x.device) if not is_rms_norm else None
143
+ rstd = torch.empty((ngroups * M, ), dtype=torch.float32, device=x.device)
144
+ # Less than 64KB per feature: enqueue fused kernel
145
+ MAX_FUSED_SIZE = 65536 // x.element_size()
146
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(group_size))
147
+ if group_size > BLOCK_N:
148
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
149
+ # heuristics for number of warps
150
+ num_warps = min(max(BLOCK_N // 256, 1), 8)
151
+ grid = (M, ngroups)
152
+ layer_norm_fwd_kernel[grid](
153
+ x,
154
+ out,
155
+ weight,
156
+ bias,
157
+ z,
158
+ mean,
159
+ rstd,
160
+ x.stride(0),
161
+ out.stride(0),
162
+ z.stride(0) if z is not None else 0,
163
+ M,
164
+ group_size,
165
+ eps,
166
+ BLOCK_N=BLOCK_N,
167
+ NORM_BEFORE_GATE=norm_before_gate,
168
+ IS_RMS_NORM=is_rms_norm,
169
+ num_warps=num_warps
170
+ )
171
+ return out, mean, rstd
172
+
173
+
174
+ @triton.heuristics({
175
+ "HAS_BIAS": lambda args: args["B"] is not None,
176
+ "HAS_Z": lambda args: args["Z"] is not None,
177
+ "RECOMPUTE_OUTPUT": lambda args: args["Y"] is not None,
178
+ })
179
+ @triton.jit
180
+ def layer_norm_bwd_kernel(
181
+ X, # pointer to the input
182
+ W, # pointer to the weights
183
+ B, # pointer to the biases
184
+ Z, # pointer to the other branch
185
+ Y, # pointer to the output to be recomputed
186
+ DY, # pointer to the output gradient
187
+ DX, # pointer to the input gradient
188
+ DW, # pointer to the partial sum of weights gradient
189
+ DB, # pointer to the partial sum of biases gradient
190
+ DZ, # pointer to the other branch
191
+ Mean, # pointer to the mean
192
+ Rstd, # pointer to the 1/std
193
+ stride_x_row, # how much to increase the pointer when moving by 1 row
194
+ stride_z_row,
195
+ stride_y_row,
196
+ stride_dy_row,
197
+ stride_dx_row,
198
+ stride_dz_row,
199
+ stride_dw_row,
200
+ stride_db_row,
201
+ M, # number of rows in X
202
+ N, # number of columns in X
203
+ eps, # epsilon to avoid division by zero
204
+ rows_per_program,
205
+ NORM_BEFORE_GATE: tl.constexpr,
206
+ IS_RMS_NORM: tl.constexpr,
207
+ HAS_BIAS: tl.constexpr,
208
+ HAS_Z: tl.constexpr,
209
+ RECOMPUTE_OUTPUT: tl.constexpr,
210
+ BLOCK_N: tl.constexpr,
211
+ ):
212
+ # Map the program id to the elements of X, DX, and DY it should compute.
213
+ row_block_id = tl.program_id(0)
214
+ group = tl.program_id(1)
215
+ row_start = row_block_id * rows_per_program
216
+ cols = tl.arange(0, BLOCK_N)
217
+ mask = cols < N
218
+ X += row_start * stride_x_row + group * N
219
+ if HAS_Z:
220
+ Z += row_start * stride_z_row + group * N
221
+ DZ += row_start * stride_dz_row + group * N
222
+ DY += row_start * stride_dy_row + group * N
223
+ DX += row_start * stride_dx_row + group * N
224
+ if RECOMPUTE_OUTPUT:
225
+ Y += row_start * stride_y_row + group * N
226
+ if not IS_RMS_NORM:
227
+ Mean += group * M
228
+ Rstd += group * M
229
+ W += group * N
230
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
231
+ if (RECOMPUTE_OUTPUT or HAS_Z) and HAS_BIAS:
232
+ B += group * N
233
+ b = tl.load(B + cols, mask=mask, other=0.).to(tl.float32)
234
+ dw = tl.zeros((BLOCK_N,), dtype=tl.float32)
235
+ if HAS_BIAS:
236
+ db = tl.zeros((BLOCK_N,), dtype=tl.float32)
237
+ row_end = min((row_block_id + 1) * rows_per_program, M)
238
+ for row in range(row_start, row_end):
239
+ # Load data to SRAM
240
+ x = tl.load(X + cols, mask=mask, other=0).to(tl.float32)
241
+ dy = tl.load(DY + cols, mask=mask, other=0).to(tl.float32)
242
+ if not IS_RMS_NORM:
243
+ mean = tl.load(Mean + row)
244
+ if HAS_Z and not NORM_BEFORE_GATE:
245
+ z = tl.load(Z + cols, mask=mask, other=0.).to(tl.float32)
246
+ x_og = x
247
+ x = x_og * z * tl.sigmoid(z)
248
+ rstd = tl.load(Rstd + row)
249
+ # Compute dx
250
+ xhat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
251
+ xhat = tl.where(mask, xhat, 0.)
252
+ if HAS_Z and NORM_BEFORE_GATE:
253
+ z = tl.load(Z + cols, mask=mask, other=0.).to(tl.float32)
254
+ z_sigmoid = tl.sigmoid(z)
255
+ y = xhat * w + b if HAS_BIAS else xhat * w
256
+ if RECOMPUTE_OUTPUT:
257
+ tl.store(Y + cols, y * z * z_sigmoid, mask=mask)
258
+ dz = dy * y * z_sigmoid * (1 + z * (1 - z_sigmoid))
259
+ tl.store(DZ + cols, dz, mask=mask)
260
+ dy *= z * z_sigmoid
261
+ else:
262
+ if RECOMPUTE_OUTPUT:
263
+ y = xhat * w + b if HAS_BIAS else xhat * w
264
+ tl.store(Y + cols, y, mask=mask)
265
+ wdy = w * dy
266
+ c1 = tl.sum(xhat * wdy, axis=0) / N
267
+ if not IS_RMS_NORM:
268
+ c2 = tl.sum(wdy, axis=0) / N
269
+ dx = (wdy - (xhat * c1 + c2)) * rstd
270
+ else:
271
+ dx = (wdy - xhat * c1) * rstd
272
+ dw += dy * xhat
273
+ if HAS_BIAS:
274
+ db += dy
275
+ if HAS_Z and not NORM_BEFORE_GATE:
276
+ z_sigmoid = tl.sigmoid(z)
277
+ dz = dx * x_og * z_sigmoid * (1 + z * (1 - z_sigmoid))
278
+ tl.store(DZ + cols, dz, mask=mask)
279
+ dx *= z * z_sigmoid
280
+ # Write dx
281
+ tl.store(DX + cols, dx, mask=mask)
282
+
283
+ X += stride_x_row
284
+ if HAS_Z:
285
+ Z += stride_z_row
286
+ DZ += stride_dz_row
287
+ if RECOMPUTE_OUTPUT:
288
+ Y += stride_y_row
289
+ DY += stride_dy_row
290
+ DX += stride_dx_row
291
+ tl.store(DW + row_block_id * stride_dw_row + group * N + cols, dw, mask=mask)
292
+ if HAS_BIAS:
293
+ tl.store(DB + row_block_id * stride_db_row + group * N + cols, db, mask=mask)
294
+
295
+
296
+ def layer_norm_bwd(
297
+ dy: torch.Tensor,
298
+ x: torch.Tensor,
299
+ weight: torch.Tensor,
300
+ bias: torch.Tensor,
301
+ eps: float,
302
+ mean: torch.Tensor,
303
+ rstd: torch.Tensor,
304
+ z: torch.Tensor = None,
305
+ group_size: int = None,
306
+ norm_before_gate: bool = True,
307
+ is_rms_norm: bool = False,
308
+ recompute_output: bool = False,
309
+ dz: torch.Tensor = None,
310
+ out: torch.Tensor = None,
311
+ ):
312
+ M, N = x.shape
313
+ if group_size is None:
314
+ group_size = N
315
+ assert N % group_size == 0
316
+ ngroups = N // group_size
317
+ assert x.stride(-1) == 1
318
+ assert dy.stride(-1) == 1
319
+ assert dy.shape == (M, N)
320
+ if z is not None:
321
+ assert z.stride(-1) == 1
322
+ assert z.shape == (M, N)
323
+ assert weight.shape == (N,)
324
+ assert weight.stride(-1) == 1
325
+ if bias is not None:
326
+ assert bias.stride(-1) == 1
327
+ assert bias.shape == (N,)
328
+ # allocate output
329
+ dx = torch.empty_like(x)
330
+ if dz is not None:
331
+ assert z is not None
332
+ assert dz.shape == z.shape
333
+ assert dz.stride(-1) == 1
334
+ else:
335
+ dz = torch.empty_like(z) if z is not None else None
336
+ if recompute_output:
337
+ if out is None:
338
+ out = torch.empty_like(x)
339
+ assert out.shape == x.shape
340
+
341
+ # Less than 64KB per feature: enqueue fused kernel
342
+ MAX_FUSED_SIZE = 65536 // x.element_size()
343
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(group_size))
344
+ if group_size > BLOCK_N:
345
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
346
+ # heuristics for number of warps
347
+ num_warps = min(max(BLOCK_N // 256, 1), 8)
348
+ sm_count = get_multiprocessor_count(x.device.index)
349
+ # If group size is small (e.g., 64), we're only using 1 warp. So having just 108 programs
350
+ # would limit the occupancy.
351
+ nrow_groups = math.ceil(sm_count * math.ceil(4 / num_warps) / ngroups)
352
+ _dw = torch.empty((nrow_groups, N), dtype=torch.float32, device=weight.device)
353
+ _db = torch.empty((nrow_groups, N), dtype=torch.float32, device=bias.device) if bias is not None else None
354
+ rows_per_program = math.ceil(M / nrow_groups)
355
+ grid = (nrow_groups, ngroups)
356
+ layer_norm_bwd_kernel[grid](
357
+ x,
358
+ weight,
359
+ bias,
360
+ z,
361
+ out if recompute_output else None,
362
+ dy,
363
+ dx,
364
+ _dw,
365
+ _db,
366
+ dz,
367
+ mean,
368
+ rstd,
369
+ x.stride(0),
370
+ z.stride(0) if z is not None else 0,
371
+ 0 if not recompute_output else out.stride(0),
372
+ dy.stride(0),
373
+ dx.stride(0),
374
+ dz.stride(0) if dz is not None else 0,
375
+ _dw.stride(0),
376
+ _db.stride(0) if _db is not None else 0,
377
+ M, group_size, eps,
378
+ rows_per_program,
379
+ BLOCK_N=BLOCK_N,
380
+ NORM_BEFORE_GATE=norm_before_gate,
381
+ IS_RMS_NORM=is_rms_norm,
382
+ num_warps=num_warps
383
+ )
384
+ dw = _dw.sum(0).to(weight.dtype)
385
+ db = _db.sum(0).to(bias.dtype) if bias is not None else None
386
+ return (dx, dw, db, dz) if not recompute_output else (dx, dw, db, dz, out)
387
+
388
+
389
+ class LayerNormFn(torch.autograd.Function):
390
+
391
+ @input_guard
392
+ @staticmethod
393
+ def forward(ctx, x, weight, bias, z=None, eps=1e-6, group_size=None, norm_before_gate=True,
394
+ is_rms_norm=False):
395
+ """If z is not None, we do norm(x) * silu(z) if norm_before_gate, else norm(x * silu(z))
396
+ """
397
+
398
+ x_shape_og = x.shape
399
+ # reshape input data into 2D tensor
400
+ x = x.reshape(-1, x.shape[-1])
401
+ if x.stride(-1) != 1:
402
+ x = x.contiguous()
403
+ if z is not None:
404
+ assert z.shape == x_shape_og
405
+ z = z.reshape(-1, z.shape[-1])
406
+ if z.stride(-1) != 1:
407
+ z = z.contiguous()
408
+ weight = weight.contiguous()
409
+ if bias is not None:
410
+ bias = bias.contiguous()
411
+ y, mean, rstd = layer_norm_fwd(
412
+ x,
413
+ weight,
414
+ bias,
415
+ eps,
416
+ z=z,
417
+ group_size=group_size,
418
+ norm_before_gate=norm_before_gate,
419
+ is_rms_norm=is_rms_norm,
420
+ )
421
+ ctx.save_for_backward(x, weight, bias, mean, rstd, z)
422
+ ctx.x_shape_og = x_shape_og
423
+ ctx.eps = eps
424
+ ctx.group_size = group_size
425
+ ctx.norm_before_gate = norm_before_gate
426
+ ctx.is_rms_norm = is_rms_norm
427
+ return y.reshape(x_shape_og)
428
+
429
+ @input_guard
430
+ @staticmethod
431
+ def backward(ctx, dy):
432
+ x, weight, bias, mean, rstd, z = ctx.saved_tensors
433
+ dy = dy.reshape(-1, dy.shape[-1])
434
+ if dy.stride(-1) != 1:
435
+ dy = dy.contiguous()
436
+ assert dy.shape == x.shape
437
+ dx, dw, db, dz = layer_norm_bwd(
438
+ dy,
439
+ x,
440
+ weight,
441
+ bias,
442
+ ctx.eps,
443
+ mean,
444
+ rstd,
445
+ z,
446
+ ctx.group_size,
447
+ ctx.norm_before_gate,
448
+ ctx.is_rms_norm
449
+ )
450
+ dx = dx.reshape(ctx.x_shape_og)
451
+ dz = dz.reshape(ctx.x_shape_og) if dz is not None else None
452
+ return dx, dw, db, dz, None, None, None, None
453
+
454
+
455
+ def layernorm_fn(x, weight, bias, z=None, eps=1e-6, group_size=None, norm_before_gate=True, is_rms_norm=False):
456
+ return LayerNormFn.apply(x, weight, bias, z, eps, group_size, norm_before_gate, is_rms_norm)
457
+
458
+
459
+ def rmsnorm_fn(x, weight, bias, z=None, eps=1e-6, group_size=None, norm_before_gate=True):
460
+ return LayerNormFn.apply(x, weight, bias, z, eps, group_size, norm_before_gate, True)
461
+
462
+
463
+ class LayerNormGated(nn.Module):
464
+
465
+ def __init__(
466
+ self,
467
+ hidden_size,
468
+ eps: float = 1e-5,
469
+ group_size: Optional[int] = None,
470
+ norm_before_gate: bool = True,
471
+ device: Optional[torch.device] = None,
472
+ dtype: Optional[torch.dtype] = None,
473
+ ):
474
+ """If group_size is not None, we do GroupNorm with each group having group_size elements.
475
+ group_size=None is equivalent to group_size=hidden_size (i.e. there's only 1 group).
476
+ """
477
+
478
+ factory_kwargs = {"device": device, "dtype": dtype}
479
+ super().__init__()
480
+ self.eps = eps
481
+ self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
482
+ self.bias = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
483
+ self.group_size = group_size
484
+ self.norm_before_gate = norm_before_gate
485
+ self.reset_parameters()
486
+
487
+ def reset_parameters(self):
488
+ torch.nn.init.ones_(self.weight)
489
+ torch.nn.init.zeros_(self.bias)
490
+
491
+ def forward(self, x, z=None):
492
+ """If z is not None, we do norm(x) * silu(z) if norm_before_gate, else norm(x * silu(z))
493
+ """
494
+ return layernorm_fn(x, self.weight, self.bias, z=z, group_size=self.group_size, eps=self.eps,
495
+ norm_before_gate=self.norm_before_gate)
496
+
497
+
498
+ class RMSNormGated(nn.Module):
499
+
500
+ def __init__(
501
+ self,
502
+ hidden_size,
503
+ eps: float = 1e-5,
504
+ group_size: Optional[int] = None,
505
+ norm_before_gate: bool = False,
506
+ device: Optional[torch.device] = None,
507
+ dtype: Optional[torch.dtype] = None,
508
+ ):
509
+ """If group_size is not None, we do GroupNorm with each group having group_size elements.
510
+ group_size=None is equivalent to group_size=hidden_size (i.e. there's only 1 group).
511
+ """
512
+ factory_kwargs = {"device": device, "dtype": dtype}
513
+ super().__init__()
514
+ self.eps = eps
515
+ self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
516
+ self.register_parameter("bias", None)
517
+ self.group_size = group_size
518
+ self.norm_before_gate = norm_before_gate
519
+ self.reset_parameters()
520
+
521
+ def reset_parameters(self):
522
+ torch.nn.init.ones_(self.weight)
523
+
524
+ def forward(self, x, z=None):
525
+ """If z is not None, we do norm(x) * silu(z) if norm_before_gate, else norm(x * silu(z))
526
+ """
527
+ return rmsnorm_fn(x, self.weight, self.bias, z=z, eps=self.eps, group_size=self.group_size,
528
+ norm_before_gate=self.norm_before_gate)
modules/mlp.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from __future__ import annotations
5
+
6
+ from functools import partial
7
+ from typing import TYPE_CHECKING, Any, Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from torch.distributed import DeviceMesh
12
+ from torch.distributed.tensor import Placement, Replicate, Shard, distribute_module
13
+ from torch.distributed.tensor.parallel import ParallelStyle
14
+
15
+ from fla.modules.activations import swiglu, swiglu_linear
16
+
17
+ try:
18
+ from torch.distributed.tensor import DTensor
19
+ except (ImportError, AttributeError):
20
+ DTensor = None
21
+
22
+ if TYPE_CHECKING:
23
+ from transformers.processing_utils import Unpack
24
+
25
+
26
+ class GatedMLP(nn.Module):
27
+
28
+ def __init__(
29
+ self,
30
+ hidden_size: int,
31
+ hidden_ratio: Optional[int] = None,
32
+ intermediate_size: Optional[int] = None,
33
+ hidden_act: str = 'swish',
34
+ fuse_swiglu: bool = True
35
+ ) -> GatedMLP:
36
+ super().__init__()
37
+
38
+ self.hidden_size = hidden_size
39
+ # the final number of params is `hidden_ratio * hidden_size^2`
40
+ # `intermediate_size` is chosen to be a multiple of 256 closest to `2/3 * hidden_size * hidden_ratio`
41
+ if hidden_ratio is None:
42
+ hidden_ratio = 4
43
+ if intermediate_size is None:
44
+ intermediate_size = int(hidden_size * hidden_ratio * 2 / 3)
45
+ intermediate_size = 256 * ((intermediate_size + 256 - 1) // 256)
46
+ self.hidden_ratio = hidden_ratio
47
+ self.intermediate_size = intermediate_size
48
+ self.hidden_act = hidden_act
49
+ self.fuse_swiglu = fuse_swiglu
50
+
51
+ if hidden_act != 'swish':
52
+ raise ValueError(f'Unsupported hidden_act: {hidden_act}')
53
+
54
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
55
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
56
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
57
+ if self.fuse_swiglu:
58
+ self.swiglu_linear = SwiGLULinear()
59
+
60
+ def forward(
61
+ self,
62
+ x: torch.Tensor,
63
+ **kwargs: Unpack[Any]
64
+ ) -> torch.Tensor:
65
+ gate, y = self.gate_proj(x), self.up_proj(x)
66
+ if self.fuse_swiglu:
67
+ return self.swiglu_linear(gate, y, self.down_proj.weight, self.down_proj.bias)
68
+ else:
69
+ return self.down_proj(swiglu(gate, y))
70
+
71
+
72
+ class SwiGLULinear(nn.Module):
73
+
74
+ def forward(self, x, y, weight, bias):
75
+ return swiglu_linear(x, y, weight, bias)
76
+
77
+
78
+ class SwiGLULinearParallel(ParallelStyle):
79
+ def __init__(
80
+ self,
81
+ *,
82
+ input_layouts: Optional[Placement] = None,
83
+ output_layouts: Optional[Placement] = None,
84
+ use_local_output: bool = True,
85
+ ):
86
+ super().__init__()
87
+ self.input_layouts = (input_layouts or Shard(-1),)
88
+ self.output_layouts = (output_layouts or Replicate(),)
89
+ self.desired_input_layouts = (Shard(-1),)
90
+ self.use_local_output = use_local_output
91
+
92
+ @staticmethod
93
+ def _prepare_input_fn(
94
+ input_layouts, desired_input_layouts, mod, inputs, device_mesh
95
+ ):
96
+ x, y, weight, bias = inputs
97
+ if not isinstance(x, DTensor):
98
+ x = DTensor.from_local(x, device_mesh, input_layouts, run_check=False)
99
+ if x.placements != desired_input_layouts:
100
+ x = x.redistribute(placements=desired_input_layouts, async_op=True)
101
+
102
+ if not isinstance(y, DTensor):
103
+ y = DTensor.from_local(y, device_mesh, input_layouts, run_check=False)
104
+ if y.placements != desired_input_layouts:
105
+ y = y.redistribute(placements=desired_input_layouts, async_op=True)
106
+
107
+ if not isinstance(weight, DTensor):
108
+ weight = DTensor.from_local(weight, device_mesh, (Shard(1),))
109
+
110
+ if bias is not None and not isinstance(bias, DTensor):
111
+ bias = DTensor.from_local(bias, device_mesh, (Replicate(),))
112
+
113
+ return x, y, weight, bias
114
+
115
+ @staticmethod
116
+ def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
117
+ # Rowwise sharding produces partial output, depending on output layouts:
118
+ # 1. to replicate -> allreduce
119
+ # 2. to shard -> reduce_scatter
120
+ if outputs.placements != output_layouts:
121
+ outputs = outputs.redistribute(placements=output_layouts, async_op=True)
122
+ # back to local tensor if use_local_output is True
123
+ return outputs.to_local() if use_local_output else outputs
124
+
125
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
126
+ return distribute_module(
127
+ module,
128
+ device_mesh,
129
+ partition_fn=None,
130
+ input_fn=partial(self._prepare_input_fn, self.input_layouts, self.desired_input_layouts),
131
+ output_fn=partial(self._prepare_output_fn, self.output_layouts, self.use_local_output)
132
+ )
modules/rotary.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 autotune_cache_kwargs, 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
+ **autotune_cache_kwargs
43
+ )
44
+ @triton.jit(do_not_specialize=['T'])
45
+ def rotary_embedding_kernel(
46
+ x,
47
+ cos,
48
+ sin,
49
+ y,
50
+ cu_seqlens,
51
+ chunk_indices,
52
+ seq_offsets,
53
+ T,
54
+ B: tl.constexpr,
55
+ H: tl.constexpr,
56
+ D: tl.constexpr,
57
+ R: tl.constexpr,
58
+ TR: tl.constexpr,
59
+ BT: tl.constexpr,
60
+ BD: tl.constexpr,
61
+ IS_SEQLEN_OFFSETS_TENSOR: tl.constexpr,
62
+ IS_VARLEN: tl.constexpr,
63
+ INTERLEAVED: tl.constexpr,
64
+ CONJUGATE: tl.constexpr
65
+ ):
66
+ i_t, i_b, i_h = tl.program_id(0), tl.program_id(1), tl.program_id(2)
67
+
68
+ if IS_VARLEN:
69
+ 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)
70
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
71
+ T = eos - bos
72
+ x = x + bos * H*D + i_h * D
73
+ y = y + bos * H*D + i_h * D
74
+ else:
75
+ i_n = i_b
76
+ x = x + i_n * T*H*D + i_h * D
77
+ y = y + i_n * T*H*D + i_h * D
78
+
79
+ if i_t * BT >= T:
80
+ return
81
+
82
+ o_t = i_t * BT + tl.arange(0, BT)
83
+ if not IS_SEQLEN_OFFSETS_TENSOR:
84
+ o_cs = o_t + seq_offsets
85
+ else:
86
+ o_cs = o_t + tl.load(seq_offsets + i_n)
87
+ m_t = (o_t >= 0) & (o_t < T) & (o_cs >= 0) & (o_cs < TR)
88
+
89
+ if not INTERLEAVED:
90
+ # Load the 1st and 2nd halves of x, do calculation, then store to 1st and 2nd halves of out
91
+ o_r = tl.arange(0, BD // 2)
92
+ p_x = x + o_t[:, None] * H*D + o_r[None, :]
93
+ p_cos = cos + (o_cs[:, None] * R + o_r[None, :])
94
+ p_sin = sin + (o_cs[:, None] * R + o_r[None, :])
95
+ mask = m_t[:, None] & (o_r < R)[None, :]
96
+
97
+ b_cos = tl.load(p_cos, mask=mask, other=1.0).to(tl.float32)
98
+ b_sin = tl.load(p_sin, mask=mask, other=0.0).to(tl.float32)
99
+ b_x0 = tl.load(p_x, mask=mask, other=0.0).to(tl.float32)
100
+ b_x1 = tl.load(p_x + R, mask=mask, other=0.0).to(tl.float32)
101
+ if CONJUGATE:
102
+ b_sin = -b_sin
103
+ b_o0 = b_x0 * b_cos - b_x1 * b_sin
104
+ b_o1 = b_x0 * b_sin + b_x1 * b_cos
105
+ # write back result
106
+ p_y = y + (o_t[:, None] * H*D + o_r[None, :])
107
+ tl.store(p_y, b_o0, mask=mask)
108
+ tl.store(p_y + R, b_o1, mask=mask)
109
+ else:
110
+ # We don't want to load x[0, 2, 4, ...] and x[1, 3, 5, ...] separately since both are slow.
111
+ # Instead, we load x0 = x[0, 1, 2, 3, ...] and x1 = x[1, 0, 3, 2, ...].
112
+ # Loading x0 will be fast but x1 will be slow.
113
+ # Then we load cos = cos[0, 0, 1, 1, ...] and sin = sin[0, 0, 1, 1, ...].
114
+ # Then we do the calculation and use tl.where to pick put the right outputs for the even
115
+ # and for the odd indices.
116
+ o_d = tl.arange(0, BD)
117
+ o_d_swap = o_d + ((o_d + 1) % 2) * 2 - 1 # 1, 0, 3, 2, 5, 4, ...
118
+ o_d_repeat = tl.arange(0, BD) // 2
119
+ p_x0 = x + o_t[:, None] * H*D + o_d[None, :]
120
+ p_x1 = x + o_t[:, None] * H*D + o_d_swap[None, :]
121
+ p_cos = cos + (o_cs[:, None] * R + o_d_repeat[None, :])
122
+ p_sin = sin + (o_cs[:, None] * R + o_d_repeat[None, :])
123
+ mask = m_t[:, None] & (o_d_repeat < R)[None, :]
124
+
125
+ b_cos = tl.load(p_cos, mask=mask, other=1.0).to(tl.float32)
126
+ b_sin = tl.load(p_sin, mask=mask, other=0.0).to(tl.float32)
127
+ b_x0 = tl.load(p_x0, mask=mask, other=0.0).to(tl.float32)
128
+ b_x1 = tl.load(p_x1, mask=mask, other=0.0).to(tl.float32)
129
+ if CONJUGATE:
130
+ b_sin = -b_sin
131
+ b_o0 = b_x0 * b_cos
132
+ b_o1 = b_x1 * b_sin
133
+ b_y = tl.where(o_d[None, :] % 2 == 0, b_o0 - b_o1, b_o0 + b_o1)
134
+ p_y = y + (o_t[:, None] * H*D + o_d[None, :])
135
+ tl.store(p_y, b_y, mask=mask)
136
+
137
+
138
+ def rotary_embedding_fwdbwd(
139
+ x: torch.Tensor,
140
+ cos: torch.Tensor,
141
+ sin: torch.Tensor,
142
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
143
+ cu_seqlens: Optional[torch.Tensor] = None,
144
+ interleaved: bool = False,
145
+ inplace: bool = False,
146
+ conjugate: bool = False
147
+ ) -> torch.Tensor:
148
+ """
149
+ Args:
150
+ x: [B, T, H, D].
151
+ cos: [TR, R / 2]
152
+ sin: [TR, R / 2]
153
+ seqlen_offsets: integer or integer tensor of size [N]
154
+ cu_seqlens: [N + 1,] or None
155
+
156
+ Returns:
157
+ y: [B, T, H, D]
158
+ """
159
+ is_varlen = cu_seqlens is not None
160
+
161
+ B, T, H, D = x.shape
162
+ N = B if not is_varlen else cu_seqlens.shape[0] - 1
163
+ TR, R = cos.shape
164
+ R2 = R * 2
165
+
166
+ assert D <= 256, "Only support D <= 256"
167
+ assert TR >= T, f"TR must be >= T, got {TR} and {T}"
168
+
169
+ assert cos.dtype == sin.dtype, f"cos and sin must have the same dtype, got {cos.dtype} and {sin.dtype}"
170
+ assert x.dtype == cos.dtype, f"Input and cos/sin must have the same dtype, got {x.dtype} and {cos.dtype}"
171
+
172
+ if isinstance(seqlen_offsets, torch.Tensor):
173
+ assert seqlen_offsets.shape == (N,)
174
+ assert seqlen_offsets.dtype in [torch.int32, torch.int64]
175
+ else:
176
+ assert seqlen_offsets + T <= TR
177
+
178
+ y = torch.empty_like(x) if not inplace else x
179
+ if R2 < D and not inplace:
180
+ y[..., R2:].copy_(x[..., R2:])
181
+
182
+ BD = triton.next_power_of_2(R2)
183
+ BT = min(128, triton.next_power_of_2(triton.cdiv(T, get_multiprocessor_count(x.device.index))))
184
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if is_varlen else None
185
+ NT = len(chunk_indices) if is_varlen else triton.cdiv(T, BT)
186
+
187
+ grid = (NT, B, H)
188
+ rotary_embedding_kernel[grid](
189
+ x,
190
+ cos,
191
+ sin,
192
+ y,
193
+ cu_seqlens,
194
+ chunk_indices,
195
+ seqlen_offsets,
196
+ B=B,
197
+ T=T,
198
+ H=H,
199
+ D=D,
200
+ R=R,
201
+ TR=TR,
202
+ BT=BT,
203
+ BD=BD,
204
+ IS_SEQLEN_OFFSETS_TENSOR=isinstance(seqlen_offsets, torch.Tensor),
205
+ IS_VARLEN=is_varlen,
206
+ INTERLEAVED=interleaved,
207
+ CONJUGATE=conjugate
208
+ )
209
+ return y
210
+
211
+
212
+ class RotaryEmbeddingFunction(torch.autograd.Function):
213
+
214
+ @staticmethod
215
+ @input_guard
216
+ def forward(
217
+ ctx,
218
+ x,
219
+ cos,
220
+ sin,
221
+ interleaved=False,
222
+ inplace=False,
223
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
224
+ cu_seqlens: Optional[torch.Tensor] = None,
225
+ ):
226
+ y = rotary_embedding_fwdbwd(
227
+ x,
228
+ cos,
229
+ sin,
230
+ seqlen_offsets=seqlen_offsets,
231
+ cu_seqlens=cu_seqlens,
232
+ interleaved=interleaved,
233
+ inplace=inplace,
234
+ )
235
+ if isinstance(seqlen_offsets, int):
236
+ # Can't save int with save_for_backward
237
+ ctx.save_for_backward(cos, sin, cu_seqlens)
238
+ ctx.seqlen_offsets = seqlen_offsets
239
+ else:
240
+ ctx.save_for_backward(cos, sin, cu_seqlens, seqlen_offsets)
241
+ ctx.seqlen_offsets = None
242
+ ctx.interleaved = interleaved
243
+ ctx.inplace = inplace
244
+ return y if not inplace else x
245
+
246
+ @staticmethod
247
+ @input_guard
248
+ def backward(ctx, do):
249
+ seqlen_offsets = ctx.seqlen_offsets
250
+ if seqlen_offsets is None:
251
+ cos, sin, cu_seqlens, seqlen_offsets = ctx.saved_tensors
252
+ else:
253
+ cos, sin, cu_seqlens = ctx.saved_tensors
254
+ # TD [2023-09-02]: For some reason Triton (2.0.0.post1) errors with
255
+ # "[CUDA]: invalid device context", and cloning makes it work. Idk why. Triton 2.1.0 works.
256
+ if not ctx.interleaved and not ctx.inplace:
257
+ do = do.clone()
258
+ dx = rotary_embedding_fwdbwd(
259
+ do,
260
+ cos,
261
+ sin,
262
+ seqlen_offsets=seqlen_offsets,
263
+ cu_seqlens=cu_seqlens,
264
+ interleaved=ctx.interleaved,
265
+ inplace=ctx.inplace,
266
+ conjugate=True,
267
+ )
268
+ return dx, None, None, None, None, None, None, None
269
+
270
+
271
+ def rotary_embedding(
272
+ x,
273
+ cos,
274
+ sin,
275
+ interleaved=False,
276
+ inplace=False,
277
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
278
+ cu_seqlens: Optional[torch.Tensor] = None
279
+ ):
280
+ """
281
+ Args:
282
+ x: [B, T, H, D]
283
+ cos, sin: [TR, R//2]
284
+ interleaved:
285
+ If True, rotate pairs of even and odd dimensions (GPT-J style) instead of 1st half and 2nd half (GPT-NeoX style).
286
+ inplace:
287
+ If True, apply rotary embedding in-place.
288
+ seqlen_offsets: [N,] or int.
289
+ Each sequence in x is shifted by this amount.
290
+ Most commonly used in inference when we have KV cache.
291
+ cu_seqlens: [N + 1,] or None
292
+
293
+ Returns:
294
+ out: [B, T, H, D]
295
+ """
296
+ return RotaryEmbeddingFunction.apply(
297
+ x,
298
+ cos,
299
+ sin,
300
+ interleaved,
301
+ inplace,
302
+ seqlen_offsets,
303
+ cu_seqlens
304
+ )
305
+
306
+
307
+ class RotaryEmbedding(nn.Module):
308
+ """
309
+ The rotary position embeddings from RoFormer_ (Su et. al).
310
+ A crucial insight from the method is that the query and keys are
311
+ transformed by rotation matrices which depend on the relative positions.
312
+
313
+ Other implementations are available in the Rotary Transformer repo_ and in
314
+ GPT-NeoX_, GPT-NeoX was an inspiration
315
+
316
+ .. _RoFormer: https://arxiv.org/abs/2104.09864
317
+ .. _repo: https://github.com/ZhuiyiTechnology/roformer
318
+ .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox
319
+
320
+ If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554).
321
+ A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96
322
+ Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py
323
+ """
324
+
325
+ def __init__(
326
+ self,
327
+ dim: int,
328
+ base: float = 10000.0,
329
+ scale_base: Optional[float] = None,
330
+ interleaved: bool = False,
331
+ pos_idx_in_fp32: bool = True,
332
+ device: Optional[torch.device] = None,
333
+ ):
334
+ """
335
+ interleaved:
336
+ If True, rotate pairs of even and odd dimensions (GPT-J style) instead of 1st half and 2nd half (GPT-NeoX style).
337
+ pos_idx_in_fp32:
338
+ If True, the position indices [0.0, ..., seqlen - 1] are in fp32, otherwise they might be in lower precision.
339
+ This option was added because previously (before 2023-07-02), when we construct
340
+ the position indices, we use the dtype of self.inv_freq.
341
+ In most cases this would be fp32, but if the model is trained in pure bf16 (not mixed precision), then
342
+ self.inv_freq would be bf16, and the position indices are also in bf16.
343
+ Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the
344
+ embeddings for some positions will coincide.
345
+ To maintain compatibility with models previously trained in pure bf16, we add this option.
346
+ """
347
+ super().__init__()
348
+
349
+ self.dim = dim
350
+ self.base = float(base)
351
+ self.scale_base = scale_base
352
+ self.interleaved = interleaved
353
+ self.pos_idx_in_fp32 = pos_idx_in_fp32
354
+ self.device = device
355
+
356
+ # Generate and save the inverse frequency buffer (non trainable)
357
+ self.register_buffer("inv_freq", torch.empty(-(dim // -2), dtype=torch.float32, device=device), persistent=False)
358
+
359
+ scale = None
360
+ if scale_base is not None:
361
+ scale = torch.empty(-(dim // -2), dtype=torch.float32, device=device)
362
+ self.register_buffer("scale", scale, persistent=False)
363
+
364
+ self._seq_len_cached = 0
365
+ self._cos_cached = None
366
+ self._sin_cached = None
367
+ self._cos_k_cached = None
368
+ self._sin_k_cached = None
369
+
370
+ self.reset_parameters()
371
+
372
+ def reset_parameters(self):
373
+ with torch.no_grad():
374
+ self.inv_freq.copy_(self._compute_inv_freq(device=self.inv_freq.device))
375
+ if self.scale_base is not None:
376
+ self.scale.copy_(self._compute_scale(device=self.scale.device))
377
+
378
+ def __repr__(self):
379
+ s = f"{self.__class__.__name__}("
380
+ s += f"dim={self.dim}, "
381
+ s += f"base={self.base}, "
382
+ s += f"interleaved={self.interleaved}, "
383
+ if self.scale_base is not None:
384
+ s += f"scale_base={self.scale_base}, "
385
+ s += f"pos_idx_in_fp32={self.pos_idx_in_fp32})"
386
+ return s
387
+
388
+ def _compute_inv_freq(self, device=None):
389
+ return 1.0 / (
390
+ self.base
391
+ ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim)
392
+ )
393
+
394
+ def _compute_scale(self, device=None):
395
+ return (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) + 0.4 * self.dim) / (1.4 * self.dim)
396
+
397
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
398
+ # Reset the tables if the sequence length has changed,
399
+ # if we're on a new device (possibly due to tracing for instance),
400
+ # or if we're switching from inference mode to training
401
+ if (
402
+ seqlen > self._seq_len_cached
403
+ or self._cos_cached is None
404
+ or self._cos_cached.device != device
405
+ or self._cos_cached.dtype != dtype
406
+ or (self.training and self._cos_cached.is_inference())
407
+ ):
408
+ self._seq_len_cached = seqlen
409
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
410
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
411
+ # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
412
+ if self.pos_idx_in_fp32:
413
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
414
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
415
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
416
+ # cos & sin output to change significantly.
417
+ # We want to recompute self.inv_freq if it was not loaded in fp32
418
+ if self.inv_freq.dtype != torch.float32:
419
+ inv_freq = self._compute_inv_freq(device=device)
420
+ else:
421
+ inv_freq = self.inv_freq
422
+ else:
423
+ t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
424
+ inv_freq = self.inv_freq
425
+ # Don't do einsum, it converts fp32 to fp16 under AMP
426
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
427
+ freqs = torch.outer(t, inv_freq)
428
+ if self.scale is None:
429
+ self._cos_cached = torch.cos(freqs).to(dtype)
430
+ self._sin_cached = torch.sin(freqs).to(dtype)
431
+ else:
432
+ power = (
433
+ torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device)
434
+ - seqlen // 2
435
+ ) / self.scale_base
436
+ scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
437
+ # We want the multiplication by scale to happen in fp32
438
+ self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
439
+ self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
440
+ self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
441
+ self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
442
+
443
+ def forward(
444
+ self,
445
+ q: torch.Tensor,
446
+ k: torch.Tensor,
447
+ seqlen_offset: Union[int, torch.Tensor] = 0,
448
+ cu_seqlens: Optional[torch.Tensor] = None,
449
+ max_seqlen: Optional[int] = None,
450
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
451
+ """
452
+ q: [B, T, H, D]
453
+ k: [B, T, H, D]
454
+ seqlen_offset:
455
+ [N] or int.
456
+ Each sequence in x is shifted by this amount.
457
+ Most commonly used in inference when we have KV cache.
458
+ cu_seqlens: [N + 1] or None
459
+ max_seqlen: int
460
+ """
461
+ if max_seqlen is not None:
462
+ self._update_cos_sin_cache(max_seqlen, device=q.device, dtype=q.dtype)
463
+ elif isinstance(seqlen_offset, int):
464
+ self._update_cos_sin_cache(q.shape[1] + seqlen_offset, device=q.device, dtype=q.dtype)
465
+ if self.scale is None:
466
+ q = rotary_embedding(
467
+ q,
468
+ self._cos_cached,
469
+ self._sin_cached,
470
+ interleaved=self.interleaved,
471
+ seqlen_offsets=seqlen_offset,
472
+ cu_seqlens=cu_seqlens,
473
+ )
474
+ k = rotary_embedding(
475
+ k,
476
+ self._cos_cached,
477
+ self._sin_cached,
478
+ interleaved=self.interleaved,
479
+ seqlen_offsets=seqlen_offset,
480
+ cu_seqlens=cu_seqlens,
481
+ )
482
+
483
+ else:
484
+ q = rotary_embedding(
485
+ q,
486
+ self._cos_cached,
487
+ self._sin_cached,
488
+ interleaved=self.interleaved,
489
+ seqlen_offsets=seqlen_offset,
490
+ cu_seqlens=cu_seqlens,
491
+ )
492
+ k = rotary_embedding(
493
+ k,
494
+ self._cos_k_cached,
495
+ self._sin_k_cached,
496
+ interleaved=self.interleaved,
497
+ seqlen_offsets=seqlen_offset,
498
+ cu_seqlens=cu_seqlens,
499
+ )
500
+
501
+ return q, k
modules/token_shift.py ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from typing import Optional
4
+
5
+ import torch
6
+ import triton
7
+ import triton.language as tl
8
+
9
+ from fla.ops.utils import prepare_chunk_indices
10
+ from fla.utils import autotune_cache_kwargs, get_multiprocessor_count, input_guard, is_amd, tensor_cache
11
+
12
+ NUM_WARPS_AUTOTUNE = [2, 4, 8, 16] if is_amd else [2, 4, 8, 16, 32]
13
+
14
+
15
+ def token_shift_ref(
16
+ x: torch.Tensor,
17
+ cu_seqlens: Optional[torch.Tensor] = None
18
+ ) -> torch.Tensor:
19
+ if cu_seqlens is not None:
20
+ # Variable length mode with cu_seqlens
21
+ assert x.dim() == 3, "Input must be [B, T, D]"
22
+ B, T, D = x.shape
23
+ assert B == 1, "Batch size must be 1 when using cu_seqlens"
24
+
25
+ result = torch.zeros_like(x)
26
+ N = cu_seqlens.shape[0] - 1
27
+
28
+ for i in range(N):
29
+ start = cu_seqlens[i].item()
30
+ end = cu_seqlens[i+1].item()
31
+ seq_len = end - start
32
+
33
+ if seq_len <= 1:
34
+ # For sequences of length 1 or 0, delta is simply -x
35
+ result[0, start:end] = -x[0, start:end]
36
+ else:
37
+ # For longer sequences, handle padding manually
38
+ shifted = torch.zeros_like(x[0, start:end])
39
+ shifted[1:] = x[0, start:end-1]
40
+ delta = shifted - x[0, start:end]
41
+ result[0, start:end] = delta
42
+
43
+ return result
44
+ else:
45
+ time_shift = torch.nn.ZeroPad2d((0, 0, 1, -1))
46
+ shifted = time_shift(x)
47
+ delta = shifted - x
48
+ return delta
49
+
50
+
51
+ @triton.heuristics({
52
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
53
+ 'USE_INITIAL_STATE': lambda args: args['cache'] is not None,
54
+ })
55
+ @triton.autotune(
56
+ configs=[
57
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
58
+ for num_warps in NUM_WARPS_AUTOTUNE
59
+ for num_stages in [1, 2, 3]
60
+ ],
61
+ key=['BD'],
62
+ **autotune_cache_kwargs
63
+ )
64
+ @triton.jit
65
+ def token_shift_fwd_kernel_short(
66
+ x,
67
+ y,
68
+ cu_seqlens,
69
+ cache,
70
+ cache_out,
71
+ T,
72
+ D: tl.constexpr,
73
+ BD: tl.constexpr,
74
+ IS_VARLEN: tl.constexpr,
75
+ USE_INITIAL_STATE: tl.constexpr,
76
+ STORE_FINAL_STATE: tl.constexpr,
77
+ IS_DECODE: tl.constexpr,
78
+ ):
79
+ i_b, i_t = tl.program_id(0), tl.program_id(1)
80
+
81
+ if IS_VARLEN:
82
+ i_n = i_b
83
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
84
+ g_t = i_t + bos
85
+
86
+ if g_t >= eos:
87
+ return
88
+
89
+ is_first_pos = (i_t == 0)
90
+ is_last_pos = (g_t == eos - 1)
91
+ else:
92
+ g_t = i_t
93
+ is_first_pos = (g_t == 0)
94
+ is_last_pos = (g_t == T - 1)
95
+
96
+ o_d = tl.arange(0, BD)
97
+ m_d = o_d < D
98
+
99
+ if IS_VARLEN:
100
+ base_offset = g_t * D + o_d
101
+ else:
102
+ base_offset = i_b * T*D + g_t * D + o_d
103
+
104
+ b_x = tl.load(x + base_offset, mask=m_d)
105
+ if IS_VARLEN:
106
+ cache_offset = i_n * D + o_d # i_n is seq index
107
+ else:
108
+ cache_offset = i_b * D + o_d # i_b is batch index
109
+
110
+ if IS_DECODE and USE_INITIAL_STATE:
111
+ b_cache = tl.load(cache + cache_offset, mask=m_d)
112
+ delta = b_cache - b_x
113
+ tl.store(y + base_offset, delta, mask=m_d)
114
+ if STORE_FINAL_STATE:
115
+ tl.store(cache_out + cache_offset, b_x, mask=m_d)
116
+ return
117
+
118
+ if is_first_pos:
119
+ # First position in sequence: delta = -hidden_states
120
+ if USE_INITIAL_STATE:
121
+ # cache shape: [N, D]
122
+ b_cache = tl.load(cache + cache_offset, mask=m_d)
123
+ delta = b_cache - b_x
124
+ tl.store(y + base_offset, delta, mask=m_d)
125
+ else:
126
+ tl.store(y + base_offset, -b_x, mask=m_d)
127
+ return
128
+
129
+ # Other positions: delta = prev - curr
130
+ if IS_VARLEN:
131
+ prev_offset = (g_t-1) * D + o_d
132
+ else:
133
+ prev_offset = i_b * T*D + (g_t-1) * D + o_d
134
+
135
+ prev_values = tl.load(x + prev_offset, mask=m_d)
136
+ delta = prev_values - b_x
137
+ tl.store(y + base_offset, delta, mask=m_d)
138
+ if STORE_FINAL_STATE:
139
+ if is_last_pos:
140
+ tl.store(cache_out + cache_offset, b_x, mask=m_d)
141
+
142
+
143
+ @triton.heuristics({
144
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
145
+ 'USE_INITIAL_STATE': lambda args: args['cache'] is not None,
146
+ })
147
+ @triton.autotune(
148
+ configs=[
149
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
150
+ for num_warps in NUM_WARPS_AUTOTUNE
151
+ for num_stages in [1, 2, 3]
152
+ ],
153
+ key=['BD', 'NB'],
154
+ **autotune_cache_kwargs
155
+ )
156
+ @triton.jit
157
+ def token_shift_fwd_kernel_long(
158
+ x,
159
+ y,
160
+ cu_seqlens,
161
+ chunk_indices,
162
+ cache,
163
+ cache_out,
164
+ T,
165
+ D: tl.constexpr,
166
+ BD: tl.constexpr,
167
+ BT: tl.constexpr,
168
+ NB: tl.constexpr,
169
+ IS_VARLEN: tl.constexpr,
170
+ USE_INITIAL_STATE: tl.constexpr,
171
+ STORE_FINAL_STATE: tl.constexpr,
172
+ ):
173
+ i_d, i_t, i_b = tl.program_id(0), tl.program_id(1), tl.program_id(2)
174
+
175
+ if IS_VARLEN:
176
+ i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), \
177
+ tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
178
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
179
+ t_start = i_t * BT
180
+ t_end = tl.minimum(t_start + BT, eos - bos)
181
+ else:
182
+ i_n = i_b
183
+ bos, eos = i_b * T, (i_b + 1) * T
184
+ t_start = i_t * BT
185
+ t_end = tl.minimum(t_start + BT, T)
186
+
187
+ o_d = i_d * BD + tl.arange(0, BD)
188
+ m_d = o_d < D
189
+
190
+ for t in range(t_start, t_end):
191
+ global_t = bos + t
192
+ offset = global_t * D + o_d
193
+ b_x = tl.load(x + offset, mask=m_d)
194
+ is_first = (global_t == bos)
195
+ if is_first:
196
+ if USE_INITIAL_STATE:
197
+ # cache shape: [N, D]
198
+ cache_off = i_n * D + o_d if IS_VARLEN else i_b * D + o_d
199
+ b_cache = tl.load(cache + cache_off, mask=m_d)
200
+ delta = b_cache - b_x
201
+ else:
202
+ delta = -b_x
203
+ else:
204
+ prev_off = offset - D
205
+ b_prev = tl.load(x + prev_off, mask=m_d)
206
+ delta = b_prev - b_x
207
+
208
+ tl.store(y + offset, delta, mask=m_d)
209
+
210
+ if STORE_FINAL_STATE:
211
+ if global_t == eos - 1:
212
+ cache_out_off = i_n * D + o_d if IS_VARLEN else i_b * D + o_d
213
+ tl.store(cache_out + cache_out_off, b_x, mask=m_d)
214
+
215
+
216
+ @triton.heuristics({
217
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
218
+ 'USE_INITIAL_STATE': lambda args: args['grad_cache_out'] is not None,
219
+ 'HAS_DCACHE': lambda args: args['grad_cache_in'] is not None
220
+ })
221
+ @triton.autotune(
222
+ configs=[
223
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
224
+ for num_warps in NUM_WARPS_AUTOTUNE
225
+ for num_stages in [1, 2, 3]
226
+ ],
227
+ key=['BD'],
228
+ **autotune_cache_kwargs
229
+ )
230
+ @triton.jit
231
+ def token_shift_bwd_kernel_short(
232
+ dx,
233
+ dy,
234
+ cu_seqlens,
235
+ grad_cache_in,
236
+ grad_cache_out,
237
+ T,
238
+ D: tl.constexpr,
239
+ BD: tl.constexpr,
240
+ IS_VARLEN: tl.constexpr,
241
+ USE_INITIAL_STATE: tl.constexpr,
242
+ HAS_DCACHE: tl.constexpr,
243
+ ):
244
+ i_b, i_t = tl.program_id(0), tl.program_id(1)
245
+
246
+ if IS_VARLEN:
247
+ i_n = i_b
248
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
249
+ g_t = i_t + bos
250
+ if g_t >= eos:
251
+ return
252
+ is_first_pos = (g_t == bos)
253
+ is_last_pos = (g_t == eos - 1)
254
+ else:
255
+ g_t = i_t
256
+ is_first_pos = (g_t == 0)
257
+ is_last_pos = (g_t == T - 1)
258
+
259
+ o_d = tl.arange(0, BD)
260
+ m_d = o_d < D
261
+
262
+ if IS_VARLEN:
263
+ base_offset = g_t * D + o_d
264
+ # This should not be used for varlen
265
+ cache_off = i_n * D + o_d
266
+ else:
267
+ base_offset = i_b * T * D + g_t * D + o_d
268
+ cache_off = i_b * D + o_d
269
+
270
+ b_dy = tl.load(dy + base_offset, mask=m_d)
271
+
272
+ if is_last_pos:
273
+ # grad = -grad_delta[t] + grad_cache_in(from next rank)
274
+ if HAS_DCACHE:
275
+ b_dy_cache = tl.load(grad_cache_in + cache_off, mask=m_d)
276
+ b_dx = -b_dy + b_dy_cache
277
+ else:
278
+ b_dx = -b_dy
279
+ else:
280
+ # grad = -grad_delta[t] + grad_delta[t+1]
281
+ if IS_VARLEN:
282
+ next_offset = (g_t + 1) * D + o_d
283
+ else:
284
+ next_offset = i_b * T * D + (g_t + 1) * D + o_d
285
+ b_dx = -b_dy + tl.load(dy + next_offset, mask=m_d)
286
+
287
+ tl.store(dx + base_offset, b_dx, mask=m_d)
288
+
289
+ if USE_INITIAL_STATE:
290
+ if is_first_pos:
291
+ tl.store(grad_cache_out + cache_off, b_dy, mask=m_d)
292
+
293
+
294
+ @triton.heuristics({
295
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
296
+ 'USE_INITIAL_STATE': lambda args: args['grad_cache_out'] is not None,
297
+ 'HAS_DCACHE': lambda args: args['grad_cache_in'] is not None
298
+ })
299
+ @triton.autotune(
300
+ configs=[
301
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
302
+ for num_warps in NUM_WARPS_AUTOTUNE
303
+ for num_stages in [1, 2, 3]
304
+ ],
305
+ key=['BD', 'NB'],
306
+ **autotune_cache_kwargs
307
+ )
308
+ @triton.jit
309
+ def token_shift_bwd_kernel_long(
310
+ dx,
311
+ dy,
312
+ cu_seqlens,
313
+ chunk_indices,
314
+ grad_cache_in,
315
+ grad_cache_out,
316
+ T,
317
+ D: tl.constexpr,
318
+ BD: tl.constexpr,
319
+ BT: tl.constexpr,
320
+ NB: tl.constexpr,
321
+ IS_VARLEN: tl.constexpr,
322
+ USE_INITIAL_STATE: tl.constexpr,
323
+ HAS_DCACHE: tl.constexpr,
324
+ ):
325
+ i_d, i_t_blk, i_b = tl.program_id(0), tl.program_id(1), tl.program_id(2)
326
+
327
+ if IS_VARLEN:
328
+ i_n, i_t_blk = tl.load(chunk_indices + i_t_blk * 2).to(tl.int32), \
329
+ tl.load(chunk_indices + i_t_blk * 2 + 1).to(tl.int32)
330
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
331
+ t_start = i_t_blk * BT
332
+ t_end = tl.minimum(t_start + BT, eos - bos)
333
+ else:
334
+ bos, eos = i_b * T, (i_b + 1) * T
335
+ t_start = i_t_blk * BT
336
+ t_end = tl.minimum(t_start + BT, T)
337
+
338
+ o_d = i_d * BD + tl.arange(0, BD)
339
+ m_d = o_d < D
340
+ cache_off = i_n * D + o_d if IS_VARLEN else i_b * D + o_d
341
+
342
+ for t in range(t_start, t_end):
343
+ global_t = bos + t
344
+ offset = global_t * D + o_d
345
+ b_dy = tl.load(dy + offset, mask=m_d)
346
+
347
+ if global_t == eos - 1:
348
+ if HAS_DCACHE:
349
+ b_dy_cache = tl.load(grad_cache_in + cache_off, mask=m_d)
350
+ b_dx = -b_dy + b_dy_cache
351
+ else:
352
+ b_dx = -b_dy
353
+ else:
354
+ next_off = offset + D
355
+ b_dx = -b_dy + tl.load(dy + next_off, mask=m_d)
356
+
357
+ tl.store(dx + offset, b_dx, mask=m_d)
358
+
359
+ if USE_INITIAL_STATE:
360
+ if global_t == bos:
361
+ tl.store(grad_cache_out + cache_off, b_dy, mask=m_d)
362
+
363
+
364
+ @tensor_cache
365
+ def prepare_maxlens(cu_seqlens: torch.LongTensor) -> int:
366
+ return torch.max(cu_seqlens[1:] - cu_seqlens[:-1]).item()
367
+
368
+
369
+ def token_shift_fwd(
370
+ x: torch.Tensor,
371
+ cu_seqlens: Optional[torch.Tensor] = None,
372
+ cache: Optional[torch.Tensor] = None,
373
+ output_cache: bool = False
374
+ ) -> torch.Tensor:
375
+ B, T, D = x.shape
376
+ y = torch.empty_like(x)
377
+ use_short_kernel = T <= 4096
378
+
379
+ if cu_seqlens is not None:
380
+ T = prepare_maxlens(cu_seqlens)
381
+ N = len(cu_seqlens) - 1
382
+ else:
383
+ N = B
384
+
385
+ if output_cache:
386
+ cache_out = torch.empty((N, D), device=x.device, dtype=x.dtype)
387
+ else:
388
+ cache_out = None
389
+
390
+ if use_short_kernel:
391
+ if cu_seqlens is not None:
392
+ N = len(cu_seqlens) - 1
393
+ else:
394
+ N = B
395
+ BD = triton.next_power_of_2(D)
396
+ grid = (N, T)
397
+ IS_DECODE = T == 1 or (B == 1 and T == N)
398
+ token_shift_fwd_kernel_short[grid](
399
+ x=x,
400
+ y=y,
401
+ cu_seqlens=cu_seqlens,
402
+ cache=cache,
403
+ cache_out=cache_out,
404
+ T=T,
405
+ D=D,
406
+ BD=BD,
407
+ STORE_FINAL_STATE=output_cache,
408
+ IS_DECODE=IS_DECODE
409
+ )
410
+ else:
411
+ BT = min(64, triton.next_power_of_2(triton.cdiv(max(16, B*T), get_multiprocessor_count(x.device.index))))
412
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
413
+ NT = len(chunk_indices) if cu_seqlens is not None else triton.cdiv(T, BT)
414
+
415
+ BD = triton.next_power_of_2(D)
416
+ NB = triton.cdiv(B*T, 1024)
417
+
418
+ def grid(meta): return (triton.cdiv(D, meta['BD']), NT, N)
419
+ token_shift_fwd_kernel_long[grid](
420
+ x,
421
+ y,
422
+ cu_seqlens,
423
+ chunk_indices,
424
+ cache,
425
+ cache_out,
426
+ T,
427
+ D=D,
428
+ BD=BD,
429
+ BT=BT,
430
+ NB=NB,
431
+ STORE_FINAL_STATE=output_cache,
432
+ )
433
+
434
+ return y, N, T, use_short_kernel, cache_out
435
+
436
+
437
+ def token_shift_bwd(
438
+ dy: torch.Tensor,
439
+ N: int,
440
+ T: int,
441
+ dcache: Optional[torch.Tensor] = None,
442
+ cu_seqlens: Optional[torch.Tensor] = None,
443
+ use_short_kernel: bool = True,
444
+ has_init_cache: bool = False
445
+ ) -> torch.Tensor:
446
+ D = dy.shape[2]
447
+ BD = triton.next_power_of_2(D)
448
+ dx = torch.empty_like(dy)
449
+ if has_init_cache:
450
+ grad_cache_out = torch.empty((N, D), device=dy.device, dtype=dy.dtype)
451
+ else:
452
+ grad_cache_out = None
453
+ if use_short_kernel:
454
+ grid = (N, T)
455
+ token_shift_bwd_kernel_short[grid](
456
+ dy=dy,
457
+ dx=dx,
458
+ cu_seqlens=cu_seqlens,
459
+ grad_cache_in=dcache,
460
+ grad_cache_out=grad_cache_out,
461
+ T=T,
462
+ D=D,
463
+ BD=BD,
464
+ )
465
+ else:
466
+ BT = min(64, triton.next_power_of_2(triton.cdiv(max(16, dy.numel() // D),
467
+ get_multiprocessor_count(dy.device.index))))
468
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
469
+ NT = len(chunk_indices) if cu_seqlens is not None else triton.cdiv(T, BT)
470
+ NB = triton.cdiv(N * dy.shape[1], 1024)
471
+ BD = triton.next_power_of_2(D)
472
+
473
+ def grid(meta): return (triton.cdiv(D, meta['BD']), NT, N)
474
+ token_shift_bwd_kernel_long[grid](
475
+ dx,
476
+ dy,
477
+ cu_seqlens,
478
+ chunk_indices,
479
+ dcache,
480
+ grad_cache_out,
481
+ T,
482
+ D=D,
483
+ BD=BD,
484
+ BT=BT,
485
+ NB=NB,
486
+ )
487
+ return dx, grad_cache_out
488
+
489
+
490
+ class TokenShift(torch.autograd.Function):
491
+
492
+ @staticmethod
493
+ @input_guard
494
+ def forward(ctx, x: torch.Tensor, cu_seqlens: Optional[torch.Tensor] = None,
495
+ cache: Optional[torch.Tensor] = None, output_cache: bool = False):
496
+ output, N, T, use_short_kernel, cache_out = token_shift_fwd(x, cu_seqlens, cache, output_cache)
497
+ ctx.cu_seqlens = cu_seqlens
498
+ ctx.N = N
499
+ ctx.T = T
500
+ ctx.use_short_kernel = use_short_kernel
501
+ ctx.has_cache = cache is not None
502
+ return output, cache_out
503
+
504
+ @staticmethod
505
+ @input_guard
506
+ def backward(ctx, dy: torch.Tensor, dcache: Optional[torch.Tensor] = None):
507
+ dx, grad_cache = token_shift_bwd(dy, ctx.N, ctx.T, dcache, ctx.cu_seqlens,
508
+ ctx.use_short_kernel, ctx.has_cache)
509
+ return dx, None, grad_cache, None
510
+
511
+
512
+ def token_shift(
513
+ x: torch.Tensor,
514
+ cu_seqlens: Optional[torch.LongTensor] = None,
515
+ cache: Optional[torch.Tensor] = None,
516
+ output_cache: bool = False
517
+ ):
518
+ """
519
+ Token-shift operation implemented with Triton kernels.
520
+
521
+ Args:
522
+ x: Input tensor of shape [B, T, D] (or [1, T, D] when `cu_seqlens` is supplied).
523
+ cu_seqlens: Optional cumulative sequence lengths of shape [B + 1].
524
+ When supplied, `x.shape[0]` must be 1 and `x.dim()` must be 3.
525
+ cache: Optional cache tensor of shape [N, D] that holds the last token
526
+ from the previous call.
527
+ output_cache: Whether to return the updated cache alongside the output.
528
+ In previous versions this parameter did not exist and the
529
+ cache was always dropped; to preserve backward compatibility
530
+ the default is False.
531
+
532
+ Returns:
533
+ output: Tensor of shape [B, T, D] after applying the token-shift.
534
+
535
+ cache_out: Tensor of shape [B, 1, D] containing the last token that
536
+ should be fed as `cache` in the next call. Only returned
537
+ when `output_cache=True`.
538
+ """
539
+ if cu_seqlens is not None:
540
+ assert x.dim() == 3, "Input must be [B, T, D]"
541
+ assert x.shape[0] == 1, "Batch size must be 1 when using cu_seqlens"
542
+
543
+ output, cache_out = TokenShift.apply(x, cu_seqlens, cache, output_cache)
544
+ if output_cache:
545
+ return output, cache_out
546
+ else:
547
+ return output
ops/__init__.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # from .abc import chunk_abc
4
+ # from .attn import parallel_attn
5
+ # from .based import fused_chunk_based, parallel_based
6
+ # from .comba import chunk_comba, fused_recurrent_comba
7
+ # from .delta_rule import chunk_delta_rule, fused_chunk_delta_rule, fused_recurrent_delta_rule
8
+ # from .forgetting_attn import parallel_forgetting_attn
9
+ # from .gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
10
+ # from .generalized_delta_rule import (
11
+ # chunk_dplr_delta_rule,
12
+ # chunk_iplr_delta_rule,
13
+ # fused_recurrent_dplr_delta_rule,
14
+ # fused_recurrent_iplr_delta_rule
15
+ # )
16
+ # from .gla import chunk_gla, fused_chunk_gla, fused_recurrent_gla
17
+ # from .gsa import chunk_gsa, fused_recurrent_gsa
18
+ # from .hgrn import fused_recurrent_hgrn
19
+ # from .lightning_attn import chunk_lightning_attn, fused_recurrent_lightning_attn
20
+ # from .linear_attn import chunk_linear_attn, fused_chunk_linear_attn, fused_recurrent_linear_attn
21
+ # from .log_linear_attn import chunk_log_linear_attn
22
+ # from .mesa_net import chunk_mesa_net
23
+ # from .nsa import parallel_nsa
24
+ # from .path_attn import parallel_path_attn
25
+ # from .retention import chunk_retention, fused_chunk_retention, fused_recurrent_retention, parallel_retention
26
+ # from .rwkv6 import chunk_rwkv6, fused_recurrent_rwkv6
27
+ # from .rwkv7 import chunk_rwkv7, fused_recurrent_rwkv7
28
+ # from .simple_gla import chunk_simple_gla, fused_chunk_simple_gla, fused_recurrent_simple_gla, parallel_simple_gla
29
+ from .mask_gated_delta_rule_t import mask_gated_chunk_delta_rule,mask_fused_recurrent_gated_delta_rule
30
+
31
+ # __all__ = [
32
+ # 'chunk_abc',
33
+ # 'parallel_attn',
34
+ # 'fused_chunk_based', 'parallel_based',
35
+ # 'chunk_delta_rule', 'fused_chunk_delta_rule', 'fused_recurrent_delta_rule',
36
+ # 'parallel_forgetting_attn',
37
+ # 'chunk_gated_delta_rule', 'fused_recurrent_gated_delta_rule',
38
+ # 'chunk_comba', 'fused_recurrent_comba',
39
+ # 'chunk_dplr_delta_rule', 'chunk_iplr_delta_rule',
40
+ # 'fused_recurrent_dplr_delta_rule', 'fused_recurrent_iplr_delta_rule',
41
+ # 'chunk_gla', 'fused_chunk_gla', 'fused_recurrent_gla',
42
+ # 'chunk_gsa', 'fused_recurrent_gsa',
43
+ # 'fused_recurrent_hgrn',
44
+ # 'chunk_lightning_attn', 'fused_recurrent_lightning_attn',
45
+ # 'chunk_linear_attn', 'fused_chunk_linear_attn', 'fused_recurrent_linear_attn',
46
+ # 'chunk_log_linear_attn',
47
+ # 'chunk_mesa_net',
48
+ # 'parallel_nsa',
49
+ # 'parallel_path_attn',
50
+ # 'chunk_retention', 'fused_chunk_retention', 'fused_recurrent_retention', 'parallel_retention',
51
+ # 'chunk_rwkv6', 'fused_recurrent_rwkv6',
52
+ # 'chunk_rwkv7', 'fused_recurrent_rwkv7',
53
+ # 'chunk_simple_gla', 'fused_chunk_simple_gla', 'fused_recurrent_simple_gla', 'parallel_simple_gla',
54
+ # 'mask_gated_chunk_delta_rule','mask_fused_recurrent_delta_rule',
55
+ # ]
ops/abc/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from .chunk import chunk_abc
4
+
5
+ __all__ = [
6
+ 'chunk_abc'
7
+ ]
ops/abc/chunk.py ADDED
@@ -0,0 +1,1117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 import softmax_bwd, softmax_fwd
11
+ from fla.ops.utils.logcumsumexp import logcumsumexp_fwd_kernel
12
+ from fla.ops.utils.op import exp
13
+ from fla.utils import input_guard
14
+
15
+
16
+ @triton.jit(do_not_specialize=['T'])
17
+ def chunk_abc_fwd_kernel_h(
18
+ k,
19
+ v,
20
+ z,
21
+ h,
22
+ h0,
23
+ ht,
24
+ T,
25
+ K: tl.constexpr,
26
+ V: tl.constexpr,
27
+ BT: tl.constexpr,
28
+ BK: tl.constexpr,
29
+ BV: tl.constexpr,
30
+ NT: tl.constexpr,
31
+ NORMK: tl.constexpr,
32
+ USE_INITIAL_STATE: tl.constexpr,
33
+ STORE_FINAL_STATE: tl.constexpr
34
+ ):
35
+ i_v, i_k, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
36
+
37
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
38
+ if USE_INITIAL_STATE:
39
+ p_h = tl.make_block_ptr(h0 + i_bh * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
40
+ b_h += tl.load(p_h, boundary_check=(0, 1)).to(tl.float32)
41
+ if NORMK:
42
+ p_z0 = tl.make_block_ptr(z + i_bh * T*K, (T * K,), (1,), (i_k * BK,), (BK,), (0,))
43
+ else:
44
+ p_z0 = tl.make_block_ptr(z + i_bh * T*V, (T * V,), (1,), (i_v * BV,), (BV,), (0,))
45
+ b_zp = tl.load(p_z0).to(tl.float32)
46
+ for i_t in range(NT):
47
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (K, T), (1, K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
48
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
49
+ p_h = tl.make_block_ptr(h + i_bh * NT*K*V + i_t * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
50
+
51
+ tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
52
+ # [BK, BT]
53
+ b_k = tl.load(p_k, boundary_check=(0, 1))
54
+ # [BT, BV]
55
+ b_v = tl.load(p_v, boundary_check=(0, 1))
56
+ if NORMK:
57
+ p_zc = tl.make_block_ptr(z + i_bh * T*K, (T * K,), (1,), ((i_t * BT + BT - 1) * K + i_k * BK,), (BK,), (0,))
58
+ # [BK,]
59
+ b_zc = tl.load(p_zc, boundary_check=(0,))
60
+ b_r, b_zp = exp(b_zp - b_zc), b_zc
61
+ # [BK, BV]
62
+ b_h = b_h * b_r[:, None]
63
+ b_k = exp(b_k - b_zc[:, None]).to(b_k.dtype)
64
+ else:
65
+ p_zc = tl.make_block_ptr(z + i_bh * T*V, (T * V,), (1,), ((i_t * BT + BT - 1) * V + i_v * BV,), (BV,), (0,))
66
+ # [BV,]
67
+ b_zc = tl.load(p_zc, boundary_check=(0,))
68
+ b_r, b_zp = exp(b_zp - b_zc), b_zc
69
+ # [BK, BV]
70
+ b_h = b_h * b_r[None, :]
71
+ b_v = exp(b_v - b_zc[None, :]).to(b_v.dtype)
72
+ # [BK, BV]
73
+ b_h += tl.dot(b_k, b_v, allow_tf32=False)
74
+
75
+ if STORE_FINAL_STATE:
76
+ p_h = tl.make_block_ptr(ht + i_bh * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
77
+ tl.store(p_h, b_h.to(p_h.dtype.element_ty), boundary_check=(0, 1))
78
+
79
+
80
+ @triton.jit(do_not_specialize=['T'])
81
+ def chunk_abc_fwd_kernel_intra_K(
82
+ v,
83
+ z,
84
+ o,
85
+ A,
86
+ T,
87
+ V: tl.constexpr,
88
+ BT: tl.constexpr,
89
+ BC: tl.constexpr,
90
+ BV: tl.constexpr,
91
+ NC: tl.constexpr
92
+ ):
93
+ i_v, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
94
+ i_t, i_i = i_c // NC, i_c % NC
95
+
96
+ p_z = tl.make_block_ptr(z + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
97
+ p_zn = tl.make_block_ptr(z + i_bh * T*V, (T * V,), (1,), ((i_t * BT + i_i * BC) * V + i_v * BV,), (BV,), (0,))
98
+ # [BV,]
99
+ b_zn = tl.load(p_zn, boundary_check=(0,))
100
+ # [BC, BV]
101
+ b_o = tl.zeros([BC, BV], dtype=tl.float32)
102
+ for i_j in range(0, i_i):
103
+ p_A = tl.make_block_ptr(A + i_bh * T * BT, (T, BT), (BT, 1), (i_t * BT + i_i * BC, i_j * BC), (BC, BC), (1, 0))
104
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_j * BC, i_v * BV), (BC, BV), (1, 0))
105
+ # [BC, BV]
106
+ b_v = tl.load(p_v, boundary_check=(0, 1))
107
+ # [BC, BC]
108
+ b_A = tl.load(p_A, boundary_check=(0, 1))
109
+ b_o += tl.dot(b_A, exp(b_v - b_zn[None, :]).to(b_v.dtype), allow_tf32=False)
110
+ b_z = tl.load(p_z, boundary_check=(0, 1))
111
+ b_o *= exp(b_zn[None, :] - b_z)
112
+
113
+ o_i = tl.arange(0, BC)
114
+ o_A = i_bh * T * BT + (i_t * BT + i_i * BC + tl.arange(0, BC)) * BT + i_i * BC
115
+ m_A = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
116
+ for j in range(0, BC):
117
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (T * V,), (1,), ((i_t * BT + i_i * BC + j) * V + i_v * BV,), (BV,), (0,))
118
+ # [BC,]
119
+ b_A = tl.load(A + o_A + j, mask=m_A, other=0)
120
+ # [BV,]
121
+ b_v = tl.load(p_v, boundary_check=(0,)).to(tl.float32)
122
+ # [BC, BV]
123
+ # avoid 0 * inf = inf
124
+ m_i = o_i[:, None] >= j
125
+ b_o += tl.where(m_i, b_A[:, None] * exp(b_v[None, :] - b_z), 0)
126
+ p_o = tl.make_block_ptr(o + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
127
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
128
+
129
+
130
+ @triton.jit(do_not_specialize=['T'])
131
+ def chunk_abc_fwd_kernel_K(
132
+ q,
133
+ k,
134
+ z,
135
+ h,
136
+ o,
137
+ A,
138
+ scale,
139
+ T,
140
+ K: tl.constexpr,
141
+ V: tl.constexpr,
142
+ BT: tl.constexpr,
143
+ BK: tl.constexpr,
144
+ BV: tl.constexpr,
145
+ NT: tl.constexpr
146
+ ):
147
+ i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
148
+ i_p = tl.maximum(i_t * BT - 1, 0)
149
+
150
+ o_i = tl.arange(0, BT)
151
+ m_s = o_i[:, None] >= o_i[None, :]
152
+
153
+ b_o = tl.zeros([BT, BV], dtype=tl.float32)
154
+ b_A = tl.zeros([BT, BT], dtype=tl.float32)
155
+ for i_k in range(tl.cdiv(K, BK)):
156
+ p_q = tl.make_block_ptr(q + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
157
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (K, T), (1, K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
158
+ p_h = tl.make_block_ptr(h + i_bh * NT*K*V + i_t * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
159
+
160
+ # [BT, BK]
161
+ b_q = tl.load(p_q, boundary_check=(0, 1))
162
+ b_q = (b_q * scale).to(b_q.dtype)
163
+ # [BK, BT]
164
+ b_k = tl.load(p_k, boundary_check=(0, 1))
165
+ # [BK, BV]
166
+ b_h = tl.load(p_h, boundary_check=(0, 1))
167
+ # [BT, BV]
168
+ b_o += tl.dot(b_q, b_h, allow_tf32=False)
169
+ # [BT, BT]
170
+ b_A += tl.dot(b_q, b_k, allow_tf32=False)
171
+ p_z = tl.make_block_ptr(z + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
172
+ p_o = tl.make_block_ptr(o + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
173
+ # [BT, BV]
174
+ b_z = tl.load(p_z, boundary_check=(0, 1))
175
+ # [BT, BV]
176
+ p_zp = tl.make_block_ptr(z + i_bh * T*V, (T * V,), (1,), (i_p * V + i_v * BV,), (BV,), (0,))
177
+ b_zp = tl.load(p_zp, boundary_check=(0,))
178
+ b_o = b_o * exp(b_zp[None, :] - b_z)
179
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
180
+
181
+ p_A = tl.make_block_ptr(A + i_bh * T * BT, (T, BT), (BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
182
+ # [BT, BT]
183
+ b_A = tl.where(m_s, b_A, 0.)
184
+ if i_v == 0:
185
+ tl.store(p_A, b_A.to(p_A.dtype.element_ty), boundary_check=(0, 1))
186
+
187
+
188
+ @triton.jit(do_not_specialize=['T'])
189
+ def chunk_abc_fwd_kernel_intra_V(
190
+ q,
191
+ k,
192
+ z,
193
+ A,
194
+ scale,
195
+ T,
196
+ K: tl.constexpr,
197
+ BT: tl.constexpr,
198
+ BC: tl.constexpr,
199
+ BK: tl.constexpr,
200
+ NC: tl.constexpr
201
+ ):
202
+ i_k, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
203
+ i_t, i_i, i_j = i_c // (NC * NC), (i_c % (NC * NC)) // NC, (i_c % (NC * NC)) % NC
204
+ n_bh = tl.num_programs(2)
205
+
206
+ if i_i > i_j:
207
+ p_q = tl.make_block_ptr(q + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
208
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (K, T), (1, K), (i_k * BK, i_t * BT + i_j * BC), (BK, BC), (0, 1))
209
+ p_z = tl.make_block_ptr(z + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
210
+ p_A = tl.make_block_ptr(A + (i_k*n_bh+i_bh)*T*BT, (T, BT), (BT, 1), (i_t * BT + i_i * BC, i_j * BC), (BC, BC), (1, 0))
211
+ p_zn = tl.make_block_ptr(z + i_bh * T*K, (T * K,), (1,), ((i_t * BT + i_i * BC) * K + i_k * BK,), (BK,), (0,))
212
+ # [BK,]
213
+ b_zn = tl.load(p_zn, boundary_check=(0,))
214
+ # [BC, BK]
215
+ b_q = tl.load(p_q, boundary_check=(0, 1))
216
+ b_z = tl.load(p_z, boundary_check=(0, 1))
217
+ b_q = (b_q * exp(b_zn[None, :] - b_z) * scale).to(b_q.dtype)
218
+ # [BK, BC]
219
+ b_k = tl.load(p_k, boundary_check=(0, 1))
220
+ b_k = exp(b_k - b_zn[:, None]).to(b_k.dtype)
221
+ # [BC, BC]
222
+ b_A = tl.dot(b_q, b_k, allow_tf32=False)
223
+ tl.store(p_A, b_A.to(A.dtype.element_ty), boundary_check=(0, 1))
224
+ elif i_i == i_j:
225
+ p_q = tl.make_block_ptr(q + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
226
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (T * K,), (1,), ((i_t * BT + i_j * BC) * K + i_k * BK,), (BK,), (0,))
227
+ p_z = tl.make_block_ptr(z + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
228
+ # [BC, BK]
229
+ b_q = tl.load(p_q, boundary_check=(0, 1))
230
+ b_z = tl.load(p_z, boundary_check=(0, 1))
231
+
232
+ o_i = tl.arange(0, BC)
233
+ o_A = (i_bh + i_k * n_bh) * T * BT + (i_t * BT + i_i * BC + tl.arange(0, BC)) * BT + i_j * BC
234
+ m_A = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
235
+ for j in range(0, BC):
236
+ # [BK,]
237
+ b_k = tl.load(p_k, boundary_check=(0,)).to(tl.float32)
238
+ # [BC,]
239
+ b_A = tl.sum(b_q * exp(b_k[None, :] - b_z) * scale, 1)
240
+ b_A = tl.where(o_i >= j, b_A, 0.)
241
+ tl.store(A + o_A + j, b_A.to(b_q.dtype), mask=m_A)
242
+
243
+ p_k = tl.advance(p_k, (K,))
244
+
245
+
246
+ @triton.jit(do_not_specialize=['T'])
247
+ def chunk_abc_fwd_kernel_V(
248
+ q,
249
+ v,
250
+ z,
251
+ h,
252
+ o,
253
+ A,
254
+ scale,
255
+ T,
256
+ K: tl.constexpr,
257
+ V: tl.constexpr,
258
+ BT: tl.constexpr,
259
+ BK: tl.constexpr,
260
+ BV: tl.constexpr,
261
+ NT: tl.constexpr
262
+ ):
263
+ i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
264
+ i_p = tl.maximum(i_t * BT - 1, 0)
265
+
266
+ b_o = tl.zeros([BT, BV], dtype=tl.float32)
267
+ for i_k in range(tl.cdiv(K, BK)):
268
+ p_q = tl.make_block_ptr(q + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
269
+ p_z = tl.make_block_ptr(z + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
270
+ p_h = tl.make_block_ptr(h + i_bh * NT*K*V + i_t * K * V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
271
+ p_zp = tl.make_block_ptr(z + i_bh * T*K, (T * K,), (1,), (i_p * K + i_k * BK,), (BK,), (0,))
272
+
273
+ # [BT, BK]
274
+ b_q = tl.load(p_q, boundary_check=(0, 1))
275
+ b_q = (b_q * scale).to(b_q.dtype)
276
+ # [BT, BK]
277
+ b_z = tl.load(p_z, boundary_check=(0, 1))
278
+ # [BT, BK]
279
+ b_zp = tl.load(p_zp, boundary_check=(0,))
280
+ b_q = (b_q * exp(b_zp[None, :] - b_z)).to(b_q.dtype)
281
+ # [BK, BV]
282
+ b_h = tl.load(p_h, boundary_check=(0, 1))
283
+ # works but dkw, owing to divine benevolence
284
+ # [BT, BV]
285
+ if i_k >= 0:
286
+ b_o += tl.dot(b_q, b_h, allow_tf32=False)
287
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
288
+ p_o = tl.make_block_ptr(o + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
289
+ p_A = tl.make_block_ptr(A + i_bh * T * BT, (T, BT), (BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
290
+ # [BT, BV]
291
+ b_v = tl.load(p_v, boundary_check=(0, 1))
292
+ # [BT, BT]
293
+ b_A = tl.load(p_A, boundary_check=(0, 1))
294
+ b_o += tl.dot(b_A.to(b_v.dtype), b_v, allow_tf32=False)
295
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
296
+
297
+
298
+ @triton.jit(do_not_specialize=['T'])
299
+ def chunk_abc_bwd_kernel_dh(
300
+ q,
301
+ z,
302
+ do,
303
+ dh,
304
+ scale,
305
+ T,
306
+ K: tl.constexpr,
307
+ V: tl.constexpr,
308
+ BT: tl.constexpr,
309
+ BK: tl.constexpr,
310
+ BV: tl.constexpr,
311
+ NT: tl.constexpr,
312
+ NORMK: tl.constexpr
313
+ ):
314
+ i_k, i_v, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
315
+
316
+ b_dh = tl.zeros([BK, BV], dtype=tl.float32)
317
+ b_zp = tl.full([BK if NORMK else BV], float('inf'), dtype=tl.float32)
318
+ for i_t in range(NT - 1, -1, -1):
319
+ i_p = tl.maximum(i_t * BT - 1, 0)
320
+ p_q = tl.make_block_ptr(q + i_bh * T*K, (K, T), (1, K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
321
+ p_do = tl.make_block_ptr(do + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
322
+ p_dh = tl.make_block_ptr(dh + i_bh * NT*K*V + i_t * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
323
+
324
+ # [BK, BT]
325
+ b_q = tl.load(p_q, boundary_check=(0, 1))
326
+ b_q = (b_q * scale).to(b_q.dtype)
327
+ # [BT, BV]
328
+ b_do = tl.load(p_do, boundary_check=(0, 1))
329
+
330
+ tl.store(p_dh, b_dh.to(p_dh.dtype.element_ty), boundary_check=(0, 1))
331
+ if NORMK:
332
+ p_z = tl.make_block_ptr(z + i_bh * T*K, (K, T), (1, K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
333
+ p_zc = tl.make_block_ptr(z + i_bh * T*K, (T * K,), (1,), (i_p * K + i_k * BK,), (BK,), (0,))
334
+ # [BK,]
335
+ b_zc = tl.load(p_zc, boundary_check=(0,))
336
+ b_r, b_zp = exp(b_zc - b_zp), b_zc
337
+ # [BK, BT]
338
+ b_z = tl.load(p_z, boundary_check=(0, 1))
339
+ b_q = (b_q * exp(b_zc[:, None] - b_z)).to(b_q.dtype)
340
+ # [BK, BV]
341
+ b_dh = b_dh * b_r[:, None]
342
+ else:
343
+ p_z = tl.make_block_ptr(z + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
344
+ p_zc = tl.make_block_ptr(z + i_bh * T*V, (T * V,), (1,), (i_p * V + i_v * BV,), (BV,), (0,))
345
+ # [BV,]
346
+ b_zc = tl.load(p_zc, boundary_check=(0,))
347
+ b_r, b_zp = exp(b_zc - b_zp), b_zc
348
+ # [BT, BV]
349
+ b_z = tl.load(p_z, boundary_check=(0,))
350
+ b_do = (b_do * exp(b_zc[None, :] - b_z)).to(b_do.dtype)
351
+ # [BK, BV]
352
+ b_dh = b_dh * b_r[None, :]
353
+ # [BK, BV]
354
+ b_dh += tl.dot(b_q, b_do, allow_tf32=False)
355
+
356
+
357
+ @triton.jit(do_not_specialize=['T'])
358
+ def chunk_abc_bwd_kernel_V(
359
+ k,
360
+ v,
361
+ z,
362
+ h,
363
+ A,
364
+ do,
365
+ dh,
366
+ dq,
367
+ dk,
368
+ dv,
369
+ dA,
370
+ scale,
371
+ T,
372
+ K: tl.constexpr,
373
+ V: tl.constexpr,
374
+ BT: tl.constexpr,
375
+ BK: tl.constexpr,
376
+ BV: tl.constexpr,
377
+ NT: tl.constexpr
378
+ ):
379
+ i_k, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
380
+ i_p = tl.maximum(i_t * BT - 1, 0)
381
+ n_bh = tl.num_programs(2)
382
+
383
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
384
+ p_zc = tl.make_block_ptr(z + i_bh * T*K, (T * K,), (1,), ((i_t * BT + BT - 1) * K + i_k * BK,), (BK,), (0,))
385
+ p_A = tl.make_block_ptr(A + i_bh * T * BT, (BT, T), (1, BT), (0, i_t * BT), (BT, BT), (0, 1))
386
+
387
+ # [BK,]
388
+ b_zc = tl.load(p_zc, boundary_check=(0,))
389
+ # [BT, BK]
390
+ b_k = tl.load(p_k, boundary_check=(0, 1))
391
+ b_k = exp(b_k - b_zc[None, :]).to(b_k.dtype)
392
+ # [BT, BT]
393
+ b_A = tl.load(p_A, boundary_check=(0, 1))
394
+
395
+ b_dq = tl.zeros([BT, BK], dtype=tl.float32)
396
+ b_dk = tl.zeros([BT, BK], dtype=tl.float32)
397
+ b_dA = tl.zeros([BT, BT], dtype=tl.float32)
398
+ for i_v in range(tl.cdiv(V, BV)):
399
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
400
+ p_h = tl.make_block_ptr(h + i_bh * NT*K*V + i_t * V * K, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
401
+ p_do = tl.make_block_ptr(do + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
402
+ p_dh = tl.make_block_ptr(dh + i_bh * NT*K*V + i_t * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
403
+ p_dv = tl.make_block_ptr(dv + (i_k*n_bh+i_bh) * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
404
+
405
+ # [BT, BV]
406
+ b_v = tl.load(p_v, boundary_check=(0, 1))
407
+ # [BV, BK]
408
+ b_h = tl.load(p_h, boundary_check=(0, 1))
409
+ # [BT, BV]
410
+ b_do = tl.load(p_do, boundary_check=(0, 1))
411
+ # [BK, BV]
412
+ b_dh = tl.load(p_dh, boundary_check=(0, 1))
413
+
414
+ # [BT, BV]
415
+ b_dv = tl.dot(b_k, b_dh, allow_tf32=False)
416
+ if i_k == 0:
417
+ b_dv += tl.dot(b_A.to(b_do.dtype), b_do, allow_tf32=False)
418
+ b_do = (b_do * scale).to(b_do.dtype)
419
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
420
+ # [BT, BT]
421
+ b_dA += tl.dot(b_do, tl.trans(b_v), allow_tf32=False)
422
+ # [BT, BK]
423
+ b_dq += tl.dot(b_do, b_h, allow_tf32=False)
424
+ # [BT, BK]
425
+ b_dk += tl.dot(b_v, tl.trans(b_dh), allow_tf32=False)
426
+ p_z = tl.make_block_ptr(z + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
427
+ p_zp = tl.make_block_ptr(z + i_bh * T*K, (T * K,), (1,), (i_p * K + i_k * BK,), (BK,), (0,))
428
+ # [BK,]
429
+ b_zp = tl.load(p_zp, boundary_check=(0,))
430
+ # [BT, BK]
431
+ b_z = tl.load(p_z, boundary_check=(0, 1))
432
+ b_z = exp(b_zp[None, :] - b_z)
433
+ # [BT, BK]
434
+ b_dq = b_dq * b_z
435
+ b_dk = b_dk * b_k
436
+
437
+ p_dq = tl.make_block_ptr(dq + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
438
+ p_dk = tl.make_block_ptr(dk + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
439
+ p_dA = tl.make_block_ptr(dA + i_bh * T * BT, (T, BT,), (BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
440
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
441
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
442
+
443
+ o_i = tl.arange(0, BT)
444
+ m_s = o_i[:, None] >= o_i[None, :]
445
+ # [BT, BT]
446
+ b_dA = tl.where(m_s, b_dA, 0.).to(b_k.dtype)
447
+ if i_k == 0:
448
+ tl.store(p_dA, b_dA.to(p_dA.dtype.element_ty), boundary_check=(0, 1))
449
+
450
+
451
+ @triton.jit(do_not_specialize=['T'])
452
+ def chunk_abc_bwd_kernel_intra_V(
453
+ q,
454
+ k,
455
+ z,
456
+ dA,
457
+ dq,
458
+ dk,
459
+ T,
460
+ K: tl.constexpr,
461
+ BT: tl.constexpr,
462
+ BC: tl.constexpr,
463
+ BK: tl.constexpr,
464
+ NC: tl.constexpr
465
+ ):
466
+ i_k, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
467
+ i_t, i_i = i_c // NC, i_c % NC
468
+
469
+ p_z = tl.make_block_ptr(z + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
470
+ p_zn = tl.make_block_ptr(z + i_bh * T*K, (T * K,), (1,), ((i_t * BT + i_i * BC) * K + i_k * BK,), (BK,), (0,))
471
+ # [BK,]
472
+ b_zn = tl.load(p_zn, boundary_check=(0,))
473
+ # [BC, BK]
474
+ b_z = tl.load(p_z, boundary_check=(0, 1))
475
+ b_zq = exp(b_zn[None, :] - b_z)
476
+ b_dq = tl.zeros([BC, BK], dtype=tl.float32)
477
+ for i_j in range(0, i_i):
478
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_j * BC, i_k * BK), (BC, BK), (1, 0))
479
+ p_dA = tl.make_block_ptr(dA + i_bh * T * BT, (T, BT), (BT, 1), (i_t * BT + i_i * BC, i_j * BC), (BC, BC), (1, 0))
480
+ # [BC, BK]
481
+ b_k = tl.load(p_k, boundary_check=(0, 1))
482
+ b_kz = exp(b_k - b_zn[None, :]).to(b_k.dtype)
483
+ # [BC, BC]
484
+ b_dA = tl.load(p_dA, boundary_check=(0, 1))
485
+ # [BC, BK]
486
+ b_dq += tl.dot(b_dA, b_kz, allow_tf32=False)
487
+ b_dq *= b_zq
488
+
489
+ o_i = tl.arange(0, BC)
490
+ o_dA = i_bh * T * BT + (i_t * BT + i_i * BC + tl.arange(0, BC)) * BT + i_i * BC
491
+ m_dA = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
492
+ for j in range(0, BC):
493
+ p_kj = tl.make_block_ptr(k + i_bh * T*K, (T * K,), (1,), ((i_t * BT + i_i*BC+j) * K + i_k * BK,), (BK,), (0,))
494
+ # [BC,]
495
+ b_dA = tl.load(dA + o_dA + j, mask=m_dA, other=0)
496
+ # [BK,]
497
+ b_kj = tl.load(p_kj, boundary_check=(0,)).to(tl.float32)
498
+ # [BC, BK]
499
+ m_i = o_i[:, None] >= j
500
+ # [BC, BK]
501
+ b_dq += tl.where(m_i, b_dA[:, None] * exp(b_kj[None, :] - b_z), 0.)
502
+ p_dq = tl.make_block_ptr(dq + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
503
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
504
+
505
+ tl.debug_barrier()
506
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
507
+ p_zn = tl.make_block_ptr(z + i_bh * T*K, (T*K,), (1,), ((i_t * BT + i_i * BC + BC - 1) * K + i_k * BK,), (BK,), (0,))
508
+ # [BK,]
509
+ b_zn = tl.load(p_zn, boundary_check=(0,))
510
+ # [BC, BK]
511
+ b_k = tl.load(p_k, boundary_check=(0, 1))
512
+ b_kz = exp(b_k - b_zn[None, :])
513
+ b_dk = tl.zeros([BC, BK], dtype=tl.float32)
514
+ for i_j in range(i_i + 1, NC):
515
+ p_q = tl.make_block_ptr(q + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_j * BC, i_k * BK), (BC, BK), (1, 0))
516
+ p_z = tl.make_block_ptr(z + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_j * BC, i_k * BK), (BC, BK), (1, 0))
517
+ p_dA = tl.make_block_ptr(dA + i_bh * T * BT, (T, BT), (BT, 1), (i_t * BT + i_j * BC, i_i * BC), (BC, BC), (1, 0))
518
+ # [BC, BK]
519
+ b_q = tl.load(p_q, boundary_check=(0, 1))
520
+ b_z = tl.load(p_z, boundary_check=(0, 1))
521
+ b_qz = (b_q * exp(b_zn[None, :] - b_z)).to(b_q.dtype)
522
+ # [BC, BC]
523
+ b_dA = tl.load(p_dA, boundary_check=(0, 1))
524
+ # [BC, BK]
525
+ b_dk += tl.dot(tl.trans(b_dA), b_qz, allow_tf32=False)
526
+ b_dk *= b_kz
527
+
528
+ o_dA = i_bh * T * BT + (i_t * BT + i_i * BC) * BT + i_i * BC + tl.arange(0, BC)
529
+ for j in range(0, BC):
530
+ p_qj = tl.make_block_ptr(q + i_bh * T*K, (T * K,), (1,), ((i_t * BT + i_i * BC + j) * K + i_k * BK,), (BK,), (0,))
531
+ p_zj = tl.make_block_ptr(z + i_bh * T*K, (T * K,), (1,), ((i_t * BT + i_i * BC + j) * K + i_k * BK,), (BK,), (0,))
532
+ # [BC,]
533
+ b_dA = tl.load(dA + o_dA + j * BT, mask=(i_t * BT + i_i * BC + j < T), other=0)
534
+ # [BK,]
535
+ b_qj = tl.load(p_qj, boundary_check=(0,)).to(tl.float32)
536
+ b_zj = tl.load(p_zj, boundary_check=(0,)).to(tl.float32)
537
+ # [BC, BK]
538
+ m_i = o_i[:, None] <= j
539
+ b_dk += tl.where(m_i, b_dA[:, None] * b_qj[None, :] * exp(b_k - b_zj[None, :]), 0.)
540
+ p_dk = tl.make_block_ptr(dk + i_bh * T*K, (T, K), (K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
541
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
542
+
543
+
544
+ @triton.jit(do_not_specialize=['T'])
545
+ def chunk_abc_bwd_kernel_intra_K(
546
+ v,
547
+ z,
548
+ do,
549
+ dA,
550
+ scale,
551
+ T,
552
+ V: tl.constexpr,
553
+ BT: tl.constexpr,
554
+ BC: tl.constexpr,
555
+ BV: tl.constexpr,
556
+ NC: tl.constexpr
557
+ ):
558
+ i_v, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
559
+ i_t, i_i, i_j = i_c // (NC * NC), (i_c % (NC * NC)) // NC, (i_c % (NC * NC)) % NC
560
+ n_bh = tl.num_programs(2)
561
+
562
+ if i_i > i_j:
563
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (V, T), (1, V), (i_v * BV, i_t * BT + i_j * BC), (BV, BC), (0, 1))
564
+ p_z = tl.make_block_ptr(z + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
565
+ p_zn = tl.make_block_ptr(z + i_bh * T*V, (T * V,), (1,), ((i_t * BT + i_i * BC) * V + i_v * BV,), (BV,), (0,))
566
+ p_do = tl.make_block_ptr(do + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
567
+ p_dA = tl.make_block_ptr(dA+(i_bh+i_v*n_bh)*T*BT, (T, BT), (BT, 1), (i_t * BT + i_i * BC, i_j * BC), (BC, BC), (1, 0))
568
+ # [BV,]
569
+ b_zn = tl.load(p_zn, boundary_check=(0,))
570
+ # [BC, BV]
571
+ b_z = tl.load(p_z, boundary_check=(0, 1))
572
+ b_do = tl.load(p_do, boundary_check=(0, 1))
573
+ b_do = (b_do * exp(b_zn[None, :] - b_z) * scale).to(b_do.dtype)
574
+ # [BV, BC]
575
+ b_v = tl.load(p_v, boundary_check=(0, 1))
576
+ b_v = exp(b_v - b_zn[:, None]).to(b_v.dtype)
577
+ # [BC, BC]
578
+ b_dA = tl.dot(b_do, b_v, allow_tf32=False)
579
+ tl.store(p_dA, b_dA.to(dA.dtype.element_ty), boundary_check=(0, 1))
580
+ elif i_i == i_j:
581
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (T * V,), (1,), ((i_t * BT + i_j * BC) * V + i_v * BV,), (BV,), (0,))
582
+ p_z = tl.make_block_ptr(z + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
583
+ p_do = tl.make_block_ptr(do + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
584
+ # [BC, BV]
585
+ b_z = tl.load(p_z, boundary_check=(0, 1))
586
+ b_do = tl.load(p_do, boundary_check=(0, 1)) * scale
587
+
588
+ o_i = tl.arange(0, BC)
589
+ o_A = (i_bh + i_v * n_bh) * T * BT + (i_t * BT + i_i * BC + tl.arange(0, BC)) * BT + i_j * BC
590
+ m_A = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
591
+ for j in range(0, BC):
592
+ # [BV,]
593
+ b_v = tl.load(p_v, boundary_check=(0,)).to(tl.float32)
594
+ # [BC,]
595
+ b_dA = tl.sum(b_do * exp(b_v[None, :] - b_z), 1)
596
+ b_dA = tl.where(o_i >= j, b_dA, 0)
597
+ tl.store(dA + o_A + j, b_dA.to(b_do.dtype), mask=m_A)
598
+
599
+ p_v = tl.advance(p_v, (V,))
600
+
601
+
602
+ @triton.jit(do_not_specialize=['T'])
603
+ def chunk_abc_bwd_kernel_K(
604
+ q,
605
+ k,
606
+ v,
607
+ z,
608
+ h,
609
+ A,
610
+ do,
611
+ dh,
612
+ dq,
613
+ dk,
614
+ dv,
615
+ dA,
616
+ scale,
617
+ T,
618
+ K: tl.constexpr,
619
+ V: tl.constexpr,
620
+ BT: tl.constexpr,
621
+ BK: tl.constexpr,
622
+ BV: tl.constexpr,
623
+ NT: tl.constexpr
624
+ ):
625
+ i_k, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
626
+ i_p = tl.maximum(i_t * BT - 1, 0)
627
+ n_bh = tl.num_programs(2)
628
+
629
+ o_i = tl.arange(0, BT)
630
+ m_s = o_i[:, None] >= o_i[None, :]
631
+
632
+ p_q = tl.make_block_ptr(q + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
633
+ p_k = tl.make_block_ptr(k + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
634
+ p_A = tl.make_block_ptr(A + (i_k*n_bh+i_bh) * T * BT, (T, BT, ), (BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
635
+
636
+ # [BT, BK]
637
+ b_q = tl.load(p_q, boundary_check=(0, 1))
638
+ b_k = tl.load(p_k, boundary_check=(0, 1))
639
+ # [BT, BT]
640
+ b_A = tl.dot((b_q * scale).to(b_q.dtype), tl.trans(b_k), allow_tf32=False)
641
+ b_A = tl.where(m_s, b_A, 0.)
642
+ tl.store(p_A, b_A.to(p_A.dtype.element_ty), boundary_check=(0, 1))
643
+
644
+ b_dq = tl.zeros([BT, BK], dtype=tl.float32)
645
+ b_dk = tl.zeros([BT, BK], dtype=tl.float32)
646
+ for i_v in range(tl.cdiv(V, BV)):
647
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
648
+ p_z = tl.make_block_ptr(z + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
649
+ p_zp = tl.make_block_ptr(z + i_bh * T*V, (T * V,), (1,), (i_p * V + i_v * BV,), (BV,), (0,))
650
+ p_zc = tl.make_block_ptr(z + i_bh * T*V, (T * V,), (1,), ((i_t * BT + BT - 1) * V + i_v * BV,), (BV,), (0,))
651
+ p_h = tl.make_block_ptr(h + i_bh * NT*K*V + i_t * K*V, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
652
+
653
+ p_do = tl.make_block_ptr(do + i_bh * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
654
+ p_dh = tl.make_block_ptr(dh + i_bh * NT*K*V + i_t * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
655
+ p_dv = tl.make_block_ptr(dv + (i_k*n_bh+i_bh) * T*V, (T, V), (V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
656
+
657
+ # [BV,]
658
+ b_zp = tl.load(p_zp, boundary_check=(0,))
659
+ b_zc = tl.load(p_zc, boundary_check=(0,))
660
+ # [BT, BV]
661
+ b_v = tl.load(p_v, boundary_check=(0, 1))
662
+ b_v = exp(b_v - b_zc[None, :]).to(b_v.dtype)
663
+ b_z = tl.load(p_z, boundary_check=(0, 1))
664
+ b_z = exp(b_zp[None, :] - b_z)
665
+ # [BV, BK]
666
+ b_h = tl.load(p_h, boundary_check=(0, 1))
667
+ # [BT, BV]
668
+ b_do = tl.load(p_do, boundary_check=(0, 1))
669
+ b_do = (b_do * b_z * scale).to(b_do.dtype)
670
+ # [BK, BV]
671
+ b_dh = tl.load(p_dh, boundary_check=(0, 1))
672
+
673
+ # [BT, BK]
674
+ b_dq += tl.dot(b_do, b_h, allow_tf32=False)
675
+ b_dk += tl.dot(b_v, tl.trans(b_dh), allow_tf32=False)
676
+ # [BT, BV]
677
+ b_dv = b_v * tl.dot(b_k, b_dh, allow_tf32=False)
678
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
679
+ p_dA = tl.make_block_ptr(dA + i_bh * T * BT, (T, BT, ), (BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
680
+ # [BT, BT]
681
+ b_dA = tl.load(p_dA, boundary_check=(0, 1))
682
+ # [BT, BK]
683
+ b_dq += tl.dot(b_dA, b_k, allow_tf32=False)
684
+ b_dk += tl.dot(tl.trans(b_dA).to(b_k.dtype), b_q, allow_tf32=False)
685
+
686
+ p_dq = tl.make_block_ptr(dq + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
687
+ p_dk = tl.make_block_ptr(dk + i_bh * T*K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
688
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
689
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
690
+
691
+
692
+ @triton.jit(do_not_specialize=['T'])
693
+ def chunk_abc_bwd_kernel_intra_KV(
694
+ v,
695
+ z,
696
+ A,
697
+ do,
698
+ dv,
699
+ T,
700
+ V: tl.constexpr,
701
+ BT: tl.constexpr,
702
+ BC: tl.constexpr,
703
+ BV: tl.constexpr,
704
+ NC: tl.constexpr
705
+ ):
706
+ i_v, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
707
+ i_t, i_i = i_c // NC, i_c % NC
708
+
709
+ p_v = tl.make_block_ptr(v + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
710
+ p_zn = tl.make_block_ptr(z + i_bh * T*V, (T*V,), (1,), ((i_t * BT + i_i * BC + BC - 1) * V + i_v * BV,), (BV,), (0,))
711
+ # [BV,]
712
+ b_zn = tl.load(p_zn, boundary_check=(0,))
713
+ # [BC, BV]
714
+ b_v = tl.load(p_v, boundary_check=(0, 1))
715
+ b_dv = tl.zeros([BC, BV], dtype=tl.float32)
716
+ for i_j in range(i_i + 1, NC):
717
+ p_z = tl.make_block_ptr(z + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_j * BC, i_v * BV), (BC, BV), (1, 0))
718
+ p_A = tl.make_block_ptr(A + i_bh * T * BT, (BT, T), (1, BT), (i_i * BC, i_t * BT + i_j * BC), (BC, BC), (0, 1))
719
+ p_do = tl.make_block_ptr(do + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_j * BC, i_v * BV), (BC, BV), (1, 0))
720
+ # [BC, BV]
721
+ b_z = tl.load(p_z, boundary_check=(0, 1))
722
+ b_do = tl.load(p_do, boundary_check=(0, 1))
723
+ b_do = (b_do * exp(b_zn[None, :] - b_z)).to(b_do.dtype)
724
+ # [BC, BC]
725
+ b_A = tl.load(p_A, boundary_check=(0, 1))
726
+ b_dv += tl.dot(b_A, b_do, allow_tf32=False)
727
+ b_dv *= exp(b_v - b_zn[None, :])
728
+
729
+ o_i = tl.arange(0, BC)
730
+ for j in range(0, BC):
731
+ p_z = tl.make_block_ptr(z + i_bh * T*V, (T * V,), (1,), ((i_t * BT + i_i * BC + j) * V + i_v * BV,), (BV,), (0,))
732
+ p_A = tl.make_block_ptr(A + i_bh * T * BT, (T * BT,), (1,), ((i_t * BT + i_i * BC + j) * BT + i_i * BC,), (BC,), (0,))
733
+ p_do = tl.make_block_ptr(do + i_bh * T*V, (T * V,), (1,), ((i_t * BT + i_i * BC + j) * V + i_v * BV,), (BV,), (0,))
734
+ # [BC,]
735
+ b_A = tl.load(p_A, boundary_check=(0,))
736
+ # [BV,]
737
+ b_z = tl.load(p_z, boundary_check=(0,))
738
+ b_do = tl.load(p_do, boundary_check=(0,))
739
+ # [BC, BV]
740
+ m_i = o_i[:, None] <= j
741
+ b_dv += tl.where(m_i, exp(b_v - b_z[None, :]) * b_A[:, None] * b_do[None, :], 0.)
742
+ p_dv = tl.make_block_ptr(dv + i_bh * T*V, (T, V), (V, 1), (i_t * BT + i_i * BC, i_v * BV), (BC, BV), (1, 0))
743
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
744
+
745
+
746
+ @triton.jit(do_not_specialize=['T'])
747
+ def chunk_abc_bwd_kernel_rcum_inter(
748
+ s,
749
+ z,
750
+ ss,
751
+ doo,
752
+ T,
753
+ S: tl.constexpr,
754
+ BT: tl.constexpr,
755
+ BS: tl.constexpr,
756
+ NT: tl.constexpr
757
+ ):
758
+ i_m, i_bh = tl.program_id(0), tl.program_id(1)
759
+
760
+ b_sp = tl.zeros([BS,], dtype=tl.float32)
761
+ b_zp = tl.full([BS,], float('inf'), dtype=tl.float32)
762
+ for i_t in range(NT - 1, -1, -1):
763
+ p_s = tl.make_block_ptr(s + i_bh * T*S, (T, S), (S, 1), (i_t * BT, i_m * BS), (BT, BS), (1, 0))
764
+ p_z = tl.make_block_ptr(z + i_bh * T*S, (T, S), (S, 1), (i_t * BT, i_m * BS), (BT, BS), (1, 0))
765
+ p_zc = tl.make_block_ptr(z + i_bh * T*S, (T*S,), (1,), ((i_t * BT) * S + i_m * BS,), (BS,), (0,))
766
+ p_ss = tl.make_block_ptr(ss + i_bh * T*S, (T, S), (S, 1), (i_t * BT, i_m * BS), (BT, BS), (1, 0))
767
+ p_doo = tl.make_block_ptr(doo + i_bh * T*S, (T, S), (S, 1), (i_t * BT, i_m * BS), (BT, BS), (1, 0))
768
+ # [BS,]
769
+ b_zc = tl.load(p_zc, boundary_check=(0,))
770
+ # [BT, BS]
771
+ b_s = tl.load(p_s, boundary_check=(0, 1))
772
+ b_z = tl.load(p_z, boundary_check=(0, 1))
773
+ b_ss = tl.load(p_ss, boundary_check=(0, 1))
774
+
775
+ b_doo = exp(b_s - b_zp[None, :]) * b_sp[None, :]
776
+ tl.store(p_doo, b_doo.to(p_doo.dtype.element_ty), boundary_check=(0, 1))
777
+ # [BS,]
778
+ b_sp = b_sp * exp(b_zc - b_zp) + tl.sum(b_ss * exp(b_zc[None, :] - b_z), 0)
779
+ b_zp = b_zc
780
+
781
+
782
+ @triton.jit(do_not_specialize=['T'])
783
+ def chunk_abc_bwd_kernel_rcum_intra(
784
+ s,
785
+ z,
786
+ ss,
787
+ doo,
788
+ T,
789
+ S: tl.constexpr,
790
+ BT: tl.constexpr,
791
+ BC: tl.constexpr,
792
+ BS: tl.constexpr,
793
+ NC: tl.constexpr
794
+ ):
795
+ i_s, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
796
+ i_t, i_i = i_c // NC, i_c % NC
797
+
798
+ o_i = tl.arange(0, BC)
799
+ m_o = tl.full([BC, BC], 1., dtype=tl.float32)
800
+
801
+ p_s = tl.make_block_ptr(s + i_bh * T*S, (T, S), (S, 1), (i_t * BT + i_i * BC, i_s * BS), (BC, BS), (1, 0))
802
+ p_zn = tl.make_block_ptr(z + i_bh * T*S, (T*S,), (1,), ((i_t * BT + i_i * BC + BC - 1) * S + i_s * BS,), (BS,), (0,))
803
+ p_doo = tl.make_block_ptr(doo + i_bh * T*S, (T, S), (S, 1), (i_t * BT + i_i * BC, i_s * BS), (BC, BS), (1, 0))
804
+ # [BC, BS]
805
+ b_s = tl.load(p_s, boundary_check=(0, 1))
806
+ # [BS,]
807
+ b_zn = tl.load(p_zn, boundary_check=(0,))
808
+
809
+ b_doo = tl.zeros([BC, BS], dtype=tl.float32)
810
+ for i_j in range(i_i + 1, NC):
811
+ p_z = tl.make_block_ptr(z + i_bh * T*S, (T, S), (S, 1), (i_t * BT + i_j * BC, i_s * BS), (BC, BS), (1, 0))
812
+ p_ss = tl.make_block_ptr(ss + i_bh * T*S, (T, S), (S, 1), (i_t * BT + i_j * BC, i_s * BS), (BC, BS), (1, 0))
813
+ # [BC, BS]
814
+ b_z = tl.load(p_z, boundary_check=(0, 1))
815
+ b_ss = tl.load(p_ss, boundary_check=(0, 1))
816
+ # [BC, BS]
817
+ b_doo += b_ss * exp(b_zn[None, :] - b_z)
818
+ b_doo = exp(b_s - b_zn[None, :]) * tl.dot(m_o.to(b_s.dtype), b_doo.to(b_s.dtype), allow_tf32=False)
819
+
820
+ for j in range(0, BC):
821
+ p_z = tl.make_block_ptr(z + i_bh * T*S, (T*S,), (1,), ((i_t * BT + i_i * BC + j) * S + i_s * BS,), (BS,), (0,))
822
+ p_ss = tl.make_block_ptr(ss + i_bh * T*S, (T*S,), (1,), ((i_t * BT + i_i * BC + j) * S + i_s * BS,), (BS,), (0,))
823
+ # [BS,]
824
+ b_z = tl.load(p_z, boundary_check=(0,))
825
+ b_ss = tl.load(p_ss, boundary_check=(0,))
826
+ # [BC, BS]
827
+ m_i = o_i[:, None] <= j
828
+ b_doo += tl.where(m_i, exp(b_s - b_z[None, :]) * b_ss[None, :], 0.)
829
+ b_doo += tl.load(p_doo, boundary_check=(0, 1))
830
+ tl.store(p_doo, b_doo.to(p_doo.dtype.element_ty), boundary_check=(0, 1))
831
+
832
+
833
+ class ChunkABCFunction(torch.autograd.Function):
834
+
835
+ @staticmethod
836
+ @input_guard
837
+ def forward(ctx, q, k, v, s, initial_state, output_final_state):
838
+ B, H, T, K, V, M = *q.shape, v.shape[-1], s.shape[-1]
839
+ BT, BC = 64, 16
840
+ BK = min(64, triton.next_power_of_2(K))
841
+ BV = min(64, triton.next_power_of_2(V))
842
+ BM = min(64, triton.next_power_of_2(M))
843
+ NT, NC = triton.cdiv(T, BT), triton.cdiv(BT, BC)
844
+ NV, NM = triton.cdiv(V, BV), triton.cdiv(M, BM)
845
+ num_warps = 4 if BK == 64 else 2
846
+ num_stages = 1
847
+
848
+ def fwd_pre(s, B, H, T, S):
849
+ # keep cummulative normalizer in fp32
850
+ z = torch.empty_like(s, dtype=torch.float)
851
+ grid = (B * H,)
852
+ logcumsumexp_fwd_kernel[grid](
853
+ s, z,
854
+ T=T, S=S
855
+ )
856
+ return z
857
+
858
+ def fwd_inner(q, k, v, z, B, H, T, K, V, BT, BK, BV, NT, normk=False, h0=None, ht=None):
859
+ NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
860
+ h = q.new_empty(B, H, NT * K, V)
861
+ grid = (NV, NK, B * H)
862
+ chunk_abc_fwd_kernel_h[grid](
863
+ k, v, z, h, h0, ht,
864
+ T=T, K=K, V=V, BT=BT, BK=BK, BV=BV, NT=NT,
865
+ NORMK=normk,
866
+ USE_INITIAL_STATE=h0 is not None,
867
+ STORE_FINAL_STATE=ht is not None,
868
+ num_warps=num_warps,
869
+ num_stages=num_stages
870
+ )
871
+ return h
872
+
873
+ final_state = None
874
+ if output_final_state:
875
+ final_state = (q.new_empty(B, H, K, M, dtype=torch.float),
876
+ q.new_empty(B, H, M, V, dtype=torch.float))
877
+
878
+ z = fwd_pre(s, B, H, T, M)
879
+ scale = K ** -0.5
880
+ hk = fwd_inner(
881
+ q=q, k=k, v=s, z=z,
882
+ B=B, H=H, T=T, K=K, V=M, BT=BT, BK=BK, BV=BM, NT=NT,
883
+ normk=False,
884
+ h0=initial_state[0] if initial_state is not None else None,
885
+ ht=final_state[0] if final_state is not None else None
886
+ )
887
+ ok1 = torch.empty_like(s)
888
+ Ak = q.new_empty(B, H, T, BT)
889
+ grid = (NM, NT, B * H)
890
+ chunk_abc_fwd_kernel_K[grid](
891
+ q, k, z, hk, ok1, Ak,
892
+ scale=scale,
893
+ T=T, K=K, V=M, BT=BT, BK=BK, BV=BM, NT=NT,
894
+ num_warps=num_warps,
895
+ num_stages=num_stages
896
+ )
897
+ ok0 = torch.empty_like(s)
898
+ grid = (NM, NT * NC, B * H)
899
+ chunk_abc_fwd_kernel_intra_K[grid](
900
+ s, z, ok0, Ak,
901
+ T=T, V=M, BT=BT, BC=BC, BV=BM, NC=NC,
902
+ num_warps=2,
903
+ num_stages=num_stages
904
+ )
905
+ ok = ok0.add_(ok1)
906
+
907
+ scale = 1.
908
+ # p is kept in fp32 for safe softmax backward
909
+ p = softmax_fwd(ok, dtype=torch.float)
910
+ qv = p.to(q.dtype)
911
+
912
+ scale = 1.
913
+ hv = fwd_inner(
914
+ q=qv, k=s, v=v, z=z,
915
+ B=B, H=H, T=T, K=M, V=V, BT=BT, BK=BM, BV=BV, NT=NT,
916
+ normk=True,
917
+ h0=initial_state[1] if initial_state is not None else None,
918
+ ht=final_state[1] if final_state is not None else None
919
+ )
920
+ Av = q.new_zeros(NM, B, H, T, BT)
921
+ grid = (NM, NT * NC * NC, B * H)
922
+ chunk_abc_fwd_kernel_intra_V[grid](
923
+ qv, s, z, Av,
924
+ scale=scale,
925
+ T=T, K=M, BT=BT, BC=BC, BK=BM, NC=NC,
926
+ num_warps=2,
927
+ num_stages=num_stages
928
+ )
929
+ Av = Av.sum(0)
930
+ ov = torch.empty_like(v)
931
+ grid = (NV, NT, B * H)
932
+ chunk_abc_fwd_kernel_V[grid](
933
+ qv, v, z, hv, ov, Av,
934
+ scale=scale,
935
+ T=T,
936
+ K=M,
937
+ V=V,
938
+ BT=BT,
939
+ BK=BM,
940
+ BV=BV,
941
+ NT=NT,
942
+ num_warps=num_warps,
943
+ num_stages=num_stages
944
+ )
945
+ ctx.save_for_backward(q, k, v, s, z, ok, p, hk, hv, Av)
946
+ ctx.BT = BT
947
+ return ov, final_state
948
+
949
+ @staticmethod
950
+ @input_guard
951
+ def backward(ctx, dov, dht=None):
952
+ q, k, v, s, z, ok, p, hk, hv, Av = ctx.saved_tensors
953
+ B, H, T, K, V, M = *q.shape, v.shape[-1], s.shape[-1]
954
+ BT, BC = ctx.BT, 16
955
+ BK = min(64, triton.next_power_of_2(K))
956
+ BV = min(64, triton.next_power_of_2(V))
957
+ BM = min(64, triton.next_power_of_2(M))
958
+ NT, NC = triton.cdiv(T, BT), triton.cdiv(BT, BC)
959
+ NK, NM = triton.cdiv(K, BK), triton.cdiv(M, BM)
960
+ num_warps = 4 if BK == 64 else 2
961
+ num_stages = 1
962
+
963
+ def bwd_inner(q, z, do, B, H, T, K, V, BT, BK, BV, NT, scale, normk=False):
964
+ NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
965
+ dh = q.new_empty(B, H, NT * K, V)
966
+ grid = (NK, NV, B * H)
967
+ chunk_abc_bwd_kernel_dh[grid](
968
+ q, z, do, dh,
969
+ scale=scale,
970
+ T=T, K=K, V=V, BT=BT, BK=BK, BV=BV, NT=NT,
971
+ NORMK=normk,
972
+ num_warps=num_warps,
973
+ num_stages=num_stages
974
+ )
975
+ return dh
976
+
977
+ def bwd_post(s, z, ss, B, H, T, S, BT, BC, BS, NT, NC, NS):
978
+ doo = torch.empty_like(s)
979
+ grid = (NS, B * H)
980
+ chunk_abc_bwd_kernel_rcum_inter[grid](
981
+ s, z, ss, doo,
982
+ T=T, S=S, BT=BT, BS=BS, NT=NT,
983
+ num_warps=num_warps,
984
+ num_stages=num_stages
985
+ )
986
+ grid = (NS, NT * NC, B * H)
987
+ chunk_abc_bwd_kernel_rcum_intra[grid](
988
+ s, z, ss, doo,
989
+ T=T, S=S, BT=BT, BC=BC, BS=BS, NC=NC,
990
+ num_warps=num_warps,
991
+ num_stages=num_stages
992
+ )
993
+ return doo
994
+
995
+ scale = 1.
996
+ qv = p.to(q.dtype)
997
+ dhv = bwd_inner(
998
+ qv, z, dov,
999
+ B=B, H=H, T=T, K=M, V=V, BT=BT, BK=BM, BV=BV, NT=NT,
1000
+ scale=scale,
1001
+ normk=True
1002
+ )
1003
+ dp1 = torch.empty_like(p)
1004
+ dsv1 = torch.empty_like(s, dtype=torch.float)
1005
+ dv = v.new_empty(NM, *v.shape)
1006
+ dAv = q.new_zeros(B, H, T, BT)
1007
+ grid = (NM, NT, B * H)
1008
+ chunk_abc_bwd_kernel_V[grid](
1009
+ s, v, z, hv, Av, dov, dhv, dp1, dsv1, dv, dAv,
1010
+ scale=scale,
1011
+ T=T, K=M, V=V, BT=BT, BK=BM, BV=BV, NT=NT,
1012
+ num_warps=num_warps,
1013
+ num_stages=num_stages
1014
+ )
1015
+ dv = dv.sum(0)
1016
+ dp0 = torch.empty_like(p)
1017
+ dsv0 = s.new_zeros(s.shape, dtype=torch.float)
1018
+ grid = (NM, NT * NC, B * H)
1019
+ chunk_abc_bwd_kernel_intra_V[grid](
1020
+ qv, s, z, dAv, dp0, dsv0,
1021
+ T=T, K=M, BT=BT, BC=BC, BK=BM, NC=NC,
1022
+ num_warps=2,
1023
+ num_stages=num_stages
1024
+ )
1025
+ dp = dp1.add_(dp0)
1026
+ dsv = dsv1.add_(dsv0)
1027
+
1028
+ # softmax gradient, equivalent to:
1029
+ # dok = p * (dp - (p * dp).sum(-1, True))
1030
+ dok = softmax_bwd(p, dp, dtype=ok.dtype)
1031
+
1032
+ scale = K ** -0.5
1033
+ dhk = bwd_inner(
1034
+ q, z, dok,
1035
+ B=B, H=H, T=T, K=K, V=M, BT=BT, BK=BK, BV=BM, NT=NT,
1036
+ scale=scale,
1037
+ normk=False
1038
+ )
1039
+ dAk = q.new_zeros(NM, B, H, T, BT)
1040
+ grid = (NM, NT * NC * NC, B * H)
1041
+ chunk_abc_bwd_kernel_intra_K[grid](
1042
+ s, z, dok, dAk,
1043
+ scale=scale,
1044
+ T=T, V=M, BT=BT, BC=BC, BV=BM, NC=NC,
1045
+ num_warps=2,
1046
+ num_stages=num_stages
1047
+ )
1048
+ dAk = dAk.sum(0)
1049
+
1050
+ Ak = q.new_zeros(NK, B, H, T, BT)
1051
+ dq = torch.empty_like(q)
1052
+ dk = torch.empty_like(k)
1053
+ dsk1 = s.new_empty(NK, *s.shape, dtype=torch.float)
1054
+ grid = (NK, NT, B * H)
1055
+ chunk_abc_bwd_kernel_K[grid](
1056
+ q, k, s, z, hk, Ak, dok, dhk, dq, dk, dsk1, dAk,
1057
+ scale=scale,
1058
+ T=T, K=K, V=M, BT=BT, BK=BK, BV=BM, NT=NT,
1059
+ num_warps=num_warps,
1060
+ num_stages=num_stages
1061
+ )
1062
+ Ak = Ak.sum(0)
1063
+ dsk1 = dsk1.sum(0)
1064
+ dsk0 = torch.empty_like(s, dtype=torch.float)
1065
+ grid = (NM, NT * NC, B * H)
1066
+ chunk_abc_bwd_kernel_intra_KV[grid](
1067
+ s, z, Ak, dok, dsk0,
1068
+ T=T, V=M, BT=BT, BC=BC, BV=BM, NC=NC,
1069
+ num_warps=2,
1070
+ num_stages=num_stages
1071
+ )
1072
+ ds = dsv.add_(dsk1.add_(dsk0))
1073
+ ds -= bwd_post(s, z, ok * dok + p * dp, B, H, T, M, BT, BC, BM, NT, NC, NM)
1074
+ ds = ds.to(s.dtype)
1075
+ return dq, dk, dv, ds, None, None
1076
+
1077
+
1078
+ @torch.compiler.disable
1079
+ def chunk_abc(
1080
+ q: torch.Tensor,
1081
+ k: torch.Tensor,
1082
+ v: torch.Tensor,
1083
+ s: torch.Tensor,
1084
+ initial_state: Optional[Tuple[torch.Tensor]] = None,
1085
+ output_final_state: bool = False,
1086
+ head_first: bool = False
1087
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
1088
+ r"""
1089
+ Args:
1090
+ q (torch.Tensor):
1091
+ queries of shape `[B, T, H, K]`.
1092
+ k (torch.Tensor):
1093
+ keys of shape `[B, T, H, K]`.
1094
+ v (torch.Tensor):
1095
+ values of shape `[B, T, H, V]`.
1096
+ s (torch.Tensor):
1097
+ slot representations of shape `[B, T, H, M]`.
1098
+ initial_state (Optional[Tuple[torch.Tensor, torch.Tensor]]):
1099
+ Initial states of shape `[B, H, K, M]` and `[B, H, M, V]`. Default: `None`.
1100
+ output_final_state (Optional[bool]):
1101
+ Whether to output the final state of shape `[B, H, K, M]` and `[B, H, M, V]`. Default: `False`.
1102
+ head_first (Optional[bool]):
1103
+ Whether the inputs are in the head-first format. Default: `False`.
1104
+ This argument has been deprecated.
1105
+
1106
+ Returns:
1107
+ o (torch.Tensor):
1108
+ Outputs of shape `[B, T, H, V]`.
1109
+ final_state (torch.Tensor):
1110
+ Final state of shape `[B, H, K, M]` and `[B, H, M, V]` if `output_final_state=True` else `None`.
1111
+ """
1112
+ if not head_first:
1113
+ q, k, v, s = map(lambda x: x.transpose(1, 2), (q, k, v, s))
1114
+ o, final_state = ChunkABCFunction.apply(q, k, v, s, initial_state, output_final_state)
1115
+ if not head_first:
1116
+ o = o.transpose(1, 2)
1117
+ return o, final_state