OpenNLPLab commited on
Commit
80b34f4
1 Parent(s): ccc080b

Upload 15 files

Browse files
config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "tnl1-385m-10b-token_no-act"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_transnormer.TransnormerConfig",
7
+ "AutoModelForCausalLM": "modeling_transnormer.TransnormerForCausalLM"
8
+ },
9
+ "bos_token_id": 50260,
10
+ "eos_token_id": 50260,
11
+ "vocab_size": 50272,
12
+ "use_cache": true,
13
+ "init_std": 0.02,
14
+ "decoder_embed_dim": 1024,
15
+ "decoder_layers": 24,
16
+ "decoder_attention_heads": 8,
17
+ "no_scale_embedding": false,
18
+ "add_bos_token": false,
19
+ "norm_type": "simplermsnorm",
20
+ "linear_use_lrpe_list": [
21
+ 1,
22
+ 0,
23
+ 0,
24
+ 0,
25
+ 0,
26
+ 0,
27
+ 0,
28
+ 0,
29
+ 0,
30
+ 0,
31
+ 0,
32
+ 0,
33
+ 0,
34
+ 0,
35
+ 0,
36
+ 0,
37
+ 0,
38
+ 0,
39
+ 0,
40
+ 0,
41
+ 0,
42
+ 0,
43
+ 0,
44
+ 0
45
+ ],
46
+ "hidden_dim": 1024,
47
+ "linear_act_fun": "none",
48
+ "glu_dim": 2816,
49
+ "bias": false,
50
+ "torch_dtype": "bfloat16",
51
+ "transformers_version": "4.38.2"
52
+ }
configuration_transnormer.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 OpenNLPLab
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # coding=utf-8
16
+ """ Transnormer configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class TransnormerConfig(PretrainedConfig):
25
+ model_type = "transnormer"
26
+ keys_to_ignore_at_inference = ["past_key_values"]
27
+
28
+ def __init__(
29
+ self,
30
+ pad_token_id=0,
31
+ bos_token_id=1,
32
+ eos_token_id=2,
33
+ vocab_size=64000,
34
+ use_cache=True,
35
+ init_std=0.02,
36
+ # model config
37
+ decoder_embed_dim=1024,
38
+ decoder_layers=24,
39
+ decoder_attention_heads=8,
40
+ no_scale_embedding=False,
41
+ add_bos_token=False,
42
+ norm_type="simplermsnorm",
43
+ linear_use_lrpe_list=[],
44
+ hidden_dim=1024,
45
+ linear_act_fun="silu",
46
+ glu_dim=2816,
47
+ bias=False,
48
+ **kwargs,
49
+ ):
50
+ super().__init__(
51
+ pad_token_id=pad_token_id,
52
+ bos_token_id=bos_token_id,
53
+ eos_token_id=eos_token_id,
54
+ **kwargs,
55
+ )
56
+ # hf origin
57
+ self.vocab_size = vocab_size
58
+ self.use_cache = use_cache
59
+ self.init_std = init_std
60
+ # add
61
+ self.decoder_embed_dim = decoder_embed_dim
62
+ self.decoder_layers = decoder_layers
63
+ self.decoder_attention_heads = decoder_attention_heads
64
+ self.no_scale_embedding = no_scale_embedding
65
+ self.add_bos_token = add_bos_token
66
+ self.norm_type = norm_type
67
+ self.linear_use_lrpe_list = linear_use_lrpe_list
68
+ self.hidden_dim = hidden_dim
69
+ self.linear_act_fun = linear_act_fun
70
+ self.glu_dim = glu_dim
71
+ self.bias = bias
generation_config copy.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "pad_token_id": 0,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "max_new_tokens": 2048,
6
+ "temperature": 1.0,
7
+ "repetition_penalty": 1.03,
8
+ "do_sample": true
9
+ }
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 50260,
4
+ "eos_token_id": 50260,
5
+ "transformers_version": "4.38.2"
6
+ }
lightning_attention.py ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 OpenNLPLab
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ import triton
17
+ import triton.language as tl
18
+
19
+
20
+ @triton.jit
21
+ def _fwd_kernel(
22
+ Q,
23
+ K,
24
+ V,
25
+ Out,
26
+ S,
27
+ stride_qz,
28
+ stride_qh,
29
+ stride_qm,
30
+ stride_qk,
31
+ stride_kz,
32
+ stride_kh,
33
+ stride_kn,
34
+ stride_kk,
35
+ stride_vz,
36
+ stride_vh,
37
+ stride_vn,
38
+ stride_ve,
39
+ stride_oz,
40
+ stride_oh,
41
+ stride_om,
42
+ stride_oe,
43
+ stride_sh,
44
+ Z,
45
+ H,
46
+ N_CTX,
47
+ BLOCK_M: tl.constexpr,
48
+ BLOCK_DMODEL_QK: tl.constexpr,
49
+ BLOCK_N: tl.constexpr,
50
+ BLOCK_DMODEL_V: tl.constexpr,
51
+ IS_CAUSAL: tl.constexpr,
52
+ USE_DECAY: tl.constexpr,
53
+ ):
54
+ start_m = tl.program_id(0)
55
+ off_hz = tl.program_id(1)
56
+ off_h = off_hz % H
57
+ # initialize offsets
58
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
59
+ offs_n = tl.arange(0, BLOCK_N)
60
+ offs_k = tl.arange(0, BLOCK_DMODEL_QK)
61
+ offs_e = tl.arange(0, BLOCK_DMODEL_V)
62
+ # get current offset of q k v
63
+ off_q = (off_hz * stride_qh + offs_m[:, None] * stride_qm +
64
+ offs_k[None, :] * stride_qk)
65
+ off_k = (off_hz * stride_kh + offs_n[:, None] * stride_kn +
66
+ offs_k[None, :] * stride_kk)
67
+ off_v = (off_hz * stride_vh + offs_n[:, None] * stride_vn +
68
+ offs_e[None, :] * stride_ve)
69
+ off_o = (off_hz * stride_oh + offs_m[:, None] * stride_om +
70
+ offs_e[None, :] * stride_oe)
71
+
72
+ # Initialize pointers to Q, K, V
73
+ q_ptrs = Q + off_q
74
+ k_ptrs = K + off_k
75
+ v_ptrs = V + off_v
76
+
77
+ # initialize pointer to m and l
78
+ acc = tl.zeros([BLOCK_M, BLOCK_DMODEL_V], dtype=tl.float32)
79
+ # load q: it will stay in SRAM throughout
80
+ q = tl.load(q_ptrs, mask=offs_m[:, None] < N_CTX, other=0.0)
81
+ # loop over k, v and update accumulator
82
+ lo = 0
83
+ # print(start_m)
84
+ hi = (start_m + 1) * BLOCK_M if IS_CAUSAL else N_CTX
85
+ for start_n in range(lo, hi, BLOCK_N):
86
+ # -- load k, v --
87
+ k = tl.load(
88
+ k_ptrs + start_n * stride_kn,
89
+ mask=(start_n + offs_n)[:, None] < N_CTX,
90
+ other=0.0,
91
+ )
92
+ v = tl.load(
93
+ v_ptrs + start_n * stride_vn,
94
+ mask=(start_n + offs_n)[:, None] < N_CTX,
95
+ other=0.0,
96
+ )
97
+ # -- compute qk ---
98
+ # qk = tl.dot(q, k)
99
+ qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
100
+ # qk += tl.dot(q, k, trans_b=True)
101
+ qk += tl.dot(q, tl.trans(k))
102
+ if IS_CAUSAL:
103
+ index = offs_m[:, None] - (start_n + offs_n[None, :])
104
+ if USE_DECAY:
105
+ S_block_ptr = S + off_h * stride_sh
106
+ s = tl.load(S_block_ptr)
107
+ s_index = s * index
108
+ s_index = tl.where(s_index >= 0, -s_index, float("-inf"))
109
+ qk = tl.exp(s_index) * qk
110
+ else:
111
+ qk = tl.where(index >= 0, qk, 0)
112
+ acc += tl.dot(qk, v.to(qk.dtype))
113
+
114
+ out_ptrs = Out + off_o
115
+ tl.store(out_ptrs, acc.to(q.dtype), mask=offs_m[:, None] < N_CTX)
116
+
117
+
118
+ @triton.jit
119
+ def _bwd_kernel_kv(
120
+ Q,
121
+ K,
122
+ V,
123
+ S,
124
+ DO,
125
+ DQ,
126
+ DK,
127
+ DV,
128
+ stride_qz,
129
+ stride_qh,
130
+ stride_qm,
131
+ stride_qk,
132
+ stride_kz,
133
+ stride_kh,
134
+ stride_kn,
135
+ stride_kk,
136
+ stride_vz,
137
+ stride_vh,
138
+ stride_vn,
139
+ stride_ve,
140
+ stride_oz,
141
+ stride_oh,
142
+ stride_om,
143
+ stride_oe,
144
+ stride_sh,
145
+ Z,
146
+ H,
147
+ N_CTX,
148
+ num_block,
149
+ BLOCK_M: tl.constexpr,
150
+ BLOCK_DMODEL_QK: tl.constexpr,
151
+ BLOCK_N: tl.constexpr,
152
+ BLOCK_DMODEL_V: tl.constexpr,
153
+ CAUSAL: tl.constexpr,
154
+ USE_DECAY: tl.constexpr,
155
+ ):
156
+ start_n = tl.program_id(0)
157
+ off_hz = tl.program_id(1)
158
+
159
+ off_z = off_hz // H
160
+ off_h = off_hz % H
161
+ # offset pointers for batch/head
162
+ Q += off_z * stride_qz + off_h * stride_qh
163
+ K += off_z * stride_kz + off_h * stride_kh
164
+ V += off_z * stride_vz + off_h * stride_vh
165
+ DO += off_z * stride_oz + off_h * stride_oh
166
+ DQ += off_z * stride_qz + off_h * stride_qh
167
+ DK += off_z * stride_kz + off_h * stride_kh
168
+ DV += off_z * stride_vz + off_h * stride_vh
169
+
170
+ # start of q
171
+ if CAUSAL:
172
+ lo = start_n * BLOCK_M
173
+ else:
174
+ lo = 0
175
+ # initialize row/col offsets
176
+ # seqlence offset
177
+ offs_qm = lo + tl.arange(0, BLOCK_M)
178
+ offs_kvn = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
179
+ # feature offset
180
+ offs_qkk = tl.arange(0, BLOCK_DMODEL_QK)
181
+ offs_ve = tl.arange(0, BLOCK_DMODEL_V)
182
+ # row block index
183
+ offs_m = tl.arange(0, BLOCK_M)
184
+ # initialize pointers to value-like data
185
+ q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_qkk[None, :] * stride_qk)
186
+ k_ptrs = K + (offs_kvn[:, None] * stride_kn +
187
+ offs_qkk[None, :] * stride_kk)
188
+ v_ptrs = V + (offs_kvn[:, None] * stride_vn + offs_ve[None, :] * stride_ve)
189
+ do_ptrs = DO + (offs_qm[:, None] * stride_om +
190
+ offs_ve[None, :] * stride_oe)
191
+ dq_ptrs = DQ + (offs_qm[:, None] * stride_qm +
192
+ offs_qkk[None, :] * stride_qk)
193
+ # initialize dv amd dk
194
+ dv = tl.zeros([BLOCK_N, BLOCK_DMODEL_V], dtype=tl.float32)
195
+ dk = tl.zeros([BLOCK_N, BLOCK_DMODEL_QK], dtype=tl.float32)
196
+ # k and v stay in SRAM throughout
197
+ k = tl.load(k_ptrs, mask=offs_kvn[:, None] < N_CTX, other=0.0)
198
+ v = tl.load(v_ptrs, mask=offs_kvn[:, None] < N_CTX, other=0.0)
199
+ # loop over rows
200
+ for start_m in range(lo, num_block * BLOCK_M, BLOCK_M):
201
+ offs_m_curr = start_m + offs_m
202
+ # load q, k, v, do on-chip
203
+ q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < N_CTX, other=0.0)
204
+ qk = tl.dot(q, tl.trans(k))
205
+ # qk = tl.dot(q, k, trans_b=True)
206
+ if CAUSAL:
207
+ index = offs_m_curr[:, None] - offs_kvn[None, :]
208
+ if USE_DECAY:
209
+ S_block_ptr = S + off_h * stride_sh
210
+ s = tl.load(S_block_ptr)
211
+ s_index = s * index
212
+ s_index = tl.where(s_index >= 0, -s_index, float("-inf"))
213
+ s = tl.exp(s_index)
214
+ qk = qk * s
215
+ else:
216
+ qk = tl.where(index >= 0, qk, 0)
217
+
218
+ p = qk
219
+ # compute dv
220
+ do = tl.load(do_ptrs, mask=offs_m_curr[:, None] < N_CTX, other=0.0)
221
+ dv += tl.dot(tl.trans(p.to(do.dtype)), do)
222
+ dp = tl.dot(do, tl.trans(v).to(do.dtype))
223
+ if CAUSAL:
224
+ if USE_DECAY:
225
+ dp = dp * s
226
+ else:
227
+ dp = tl.where(index >= 0, dp, 0)
228
+
229
+ dk += tl.dot(tl.trans(dp.to(q.dtype)), q).to(tl.float32)
230
+
231
+ # increment pointers
232
+ q_ptrs += BLOCK_M * stride_qm
233
+ do_ptrs += BLOCK_M * stride_om
234
+ # write-back
235
+ dv_ptrs = DV + (offs_kvn[:, None] * stride_vn +
236
+ offs_ve[None, :] * stride_ve)
237
+ dk_ptrs = DK + (offs_kvn[:, None] * stride_kn +
238
+ offs_qkk[None, :] * stride_kk)
239
+ tl.store(dv_ptrs, dv, mask=offs_kvn[:, None] < N_CTX)
240
+ tl.store(dk_ptrs, dk, mask=offs_kvn[:, None] < N_CTX)
241
+
242
+
243
+ @triton.jit
244
+ def _bwd_kernel_q(
245
+ Q,
246
+ K,
247
+ V,
248
+ S,
249
+ DO,
250
+ DQ,
251
+ DK,
252
+ DV,
253
+ stride_qz,
254
+ stride_qh,
255
+ stride_qm,
256
+ stride_qk,
257
+ stride_kz,
258
+ stride_kh,
259
+ stride_kn,
260
+ stride_kk,
261
+ stride_vz,
262
+ stride_vh,
263
+ stride_vn,
264
+ stride_ve,
265
+ stride_oz,
266
+ stride_oh,
267
+ stride_om,
268
+ stride_oe,
269
+ stride_sh,
270
+ Z,
271
+ H,
272
+ N_CTX,
273
+ num_block,
274
+ BLOCK_M: tl.constexpr,
275
+ BLOCK_DMODEL_QK: tl.constexpr,
276
+ BLOCK_N: tl.constexpr,
277
+ BLOCK_DMODEL_V: tl.constexpr,
278
+ CAUSAL: tl.constexpr,
279
+ USE_DECAY: tl.constexpr,
280
+ ):
281
+ start_m = tl.program_id(0)
282
+ off_hz = tl.program_id(1)
283
+ off_z = off_hz // H
284
+ off_h = off_hz % H
285
+ # offset pointers for batch/head
286
+ K += off_z * stride_kz + off_h * stride_kh
287
+ V += off_z * stride_vz + off_h * stride_vh
288
+ DO += off_z * stride_oz + off_h * stride_oh
289
+ DQ += off_z * stride_qz + off_h * stride_qh
290
+ # feature offset
291
+ offs_qkk = tl.arange(0, BLOCK_DMODEL_QK)
292
+ offs_ve = tl.arange(0, BLOCK_DMODEL_V)
293
+ # row block index
294
+ offs_m = tl.arange(0, BLOCK_M)
295
+ # row block index
296
+ offs_qm = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
297
+ # do
298
+ do_ptrs = DO + (offs_qm[:, None] * stride_om +
299
+ offs_ve[None, :] * stride_oe)
300
+ dq_ptrs = DQ + (offs_qm[:, None] * stride_qm +
301
+ offs_qkk[None, :] * stride_qk)
302
+
303
+ do = tl.load(do_ptrs, mask=offs_qm[:, None] < N_CTX, other=0.0)
304
+
305
+ dq = tl.zeros([BLOCK_M, BLOCK_DMODEL_QK], dtype=tl.float32)
306
+ lo = 0
307
+ hi = (start_m + 1) * BLOCK_M if CAUSAL else N_CTX
308
+
309
+ offs_m_curr = start_m * BLOCK_M + offs_m
310
+
311
+ for start_n in range(0, num_block):
312
+ offs_kvn = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
313
+ k_ptrs = K + (offs_kvn[:, None] * stride_kn +
314
+ offs_qkk[None, :] * stride_kk)
315
+ v_ptrs = V + (offs_kvn[:, None] * stride_vn +
316
+ offs_ve[None, :] * stride_ve)
317
+ # k and v stay in SRAM throughout
318
+ k = tl.load(k_ptrs, mask=offs_kvn[:, None] < N_CTX, other=0.0)
319
+ v = tl.load(v_ptrs, mask=offs_kvn[:, None] < N_CTX, other=0.0)
320
+ # dp = do vT
321
+ dp = tl.dot(do, tl.trans(v).to(do.dtype))
322
+ if CAUSAL:
323
+ index = offs_m_curr[:, None] - offs_kvn[None, :]
324
+ if USE_DECAY:
325
+ S_block_ptr = S + off_h * stride_sh
326
+ s = tl.load(S_block_ptr)
327
+ s_index = s * index
328
+ s_index = tl.where(s_index >= 0, -s_index, float("-inf"))
329
+ s = tl.exp(s_index)
330
+ dp = dp * s
331
+ else:
332
+ dp = tl.where(index >= 0, dp, 0)
333
+ # dq = dq + dp k
334
+ dq += tl.dot(dp.to(k.dtype), k)
335
+
336
+ tl.store(dq_ptrs, dq, mask=offs_qm[:, None] < N_CTX)
337
+
338
+
339
+ class _attention(torch.autograd.Function):
340
+
341
+ @staticmethod
342
+ def forward(ctx, q, k, v, causal, s):
343
+ q = q.contiguous()
344
+ k = k.contiguous()
345
+ v = v.contiguous()
346
+ s = s.contiguous()
347
+ # only support for Ampere now
348
+ capability = torch.cuda.get_device_capability()
349
+ if capability[0] < 8:
350
+ raise RuntimeError(
351
+ "Flash attention currently only supported for compute capability >= 80"
352
+ )
353
+ # shape constraints
354
+ Lq, Lk, Lv = q.shape[-1], k.shape[-1], v.shape[-1]
355
+ # right
356
+ o = torch.empty(
357
+ (q.shape[0], q.shape[1], q.shape[2], v.shape[-1]),
358
+ dtype=q.dtype,
359
+ device=q.device,
360
+ )
361
+
362
+ BLOCK_M = 128
363
+ BLOCK_N = 64
364
+ num_warps = 4 if Lk <= 64 else 8
365
+ num_stages = 1
366
+
367
+ grid = (triton.cdiv(q.shape[2], BLOCK_M), q.shape[0] * q.shape[1], 1)
368
+ use_decay = s.shape[0] > 0
369
+
370
+ _fwd_kernel[grid](
371
+ q,
372
+ k,
373
+ v,
374
+ o,
375
+ s,
376
+ q.stride(0),
377
+ q.stride(1),
378
+ q.stride(2),
379
+ q.stride(3),
380
+ k.stride(0),
381
+ k.stride(1),
382
+ k.stride(2),
383
+ k.stride(3),
384
+ v.stride(0),
385
+ v.stride(1),
386
+ v.stride(2),
387
+ v.stride(3),
388
+ o.stride(0),
389
+ o.stride(1),
390
+ o.stride(2),
391
+ o.stride(3),
392
+ s.stride(0),
393
+ q.shape[0],
394
+ q.shape[1],
395
+ q.shape[2],
396
+ BLOCK_M=BLOCK_M,
397
+ BLOCK_DMODEL_QK=Lk,
398
+ BLOCK_N=BLOCK_N,
399
+ BLOCK_DMODEL_V=Lv,
400
+ IS_CAUSAL=causal,
401
+ USE_DECAY=use_decay,
402
+ num_warps=num_warps,
403
+ num_stages=num_stages,
404
+ )
405
+
406
+ ctx.save_for_backward(q, k, v, s)
407
+ ctx.grid = grid
408
+ ctx.BLOCK_M = BLOCK_M
409
+ ctx.BLOCK_DMODEL_QK = Lk
410
+ ctx.BLOCK_N = BLOCK_N
411
+ ctx.BLOCK_DMODEL_V = Lv
412
+ ctx.causal = causal
413
+ ctx.use_decay = use_decay
414
+ return o
415
+
416
+ @staticmethod
417
+ def backward(ctx, do):
418
+ q, k, v, s = ctx.saved_tensors
419
+ BLOCK_M = 32
420
+ BLOCK_N = 32
421
+ num_warps = 4
422
+ num_stages = 1
423
+
424
+ do = do.contiguous()
425
+ dq = torch.zeros_like(q, dtype=torch.float32)
426
+ dk = torch.empty_like(k)
427
+ dv = torch.empty_like(v)
428
+
429
+ grid_kv = (triton.cdiv(k.shape[2],
430
+ BLOCK_N), k.shape[0] * k.shape[1], 1)
431
+ _bwd_kernel_kv[grid_kv](
432
+ q,
433
+ k,
434
+ v,
435
+ s,
436
+ do,
437
+ dq,
438
+ dk,
439
+ dv,
440
+ q.stride(0),
441
+ q.stride(1),
442
+ q.stride(2),
443
+ q.stride(3),
444
+ k.stride(0),
445
+ k.stride(1),
446
+ k.stride(2),
447
+ k.stride(3),
448
+ v.stride(0),
449
+ v.stride(1),
450
+ v.stride(2),
451
+ v.stride(3),
452
+ do.stride(0),
453
+ do.stride(1),
454
+ do.stride(2),
455
+ do.stride(3),
456
+ s.stride(0),
457
+ q.shape[0],
458
+ q.shape[1],
459
+ q.shape[2],
460
+ grid_kv[0],
461
+ BLOCK_M=BLOCK_M,
462
+ BLOCK_DMODEL_QK=ctx.BLOCK_DMODEL_QK,
463
+ BLOCK_N=BLOCK_N,
464
+ BLOCK_DMODEL_V=ctx.BLOCK_DMODEL_V,
465
+ CAUSAL=ctx.causal,
466
+ USE_DECAY=ctx.use_decay,
467
+ num_warps=num_warps,
468
+ num_stages=num_stages,
469
+ )
470
+
471
+ grid_q = (triton.cdiv(q.shape[2], BLOCK_M), q.shape[0] * q.shape[1], 1)
472
+
473
+ _bwd_kernel_q[grid_q](
474
+ q,
475
+ k,
476
+ v,
477
+ s,
478
+ do,
479
+ dq,
480
+ dk,
481
+ dv,
482
+ q.stride(0),
483
+ q.stride(1),
484
+ q.stride(2),
485
+ q.stride(3),
486
+ k.stride(0),
487
+ k.stride(1),
488
+ k.stride(2),
489
+ k.stride(3),
490
+ v.stride(0),
491
+ v.stride(1),
492
+ v.stride(2),
493
+ v.stride(3),
494
+ do.stride(0),
495
+ do.stride(1),
496
+ do.stride(2),
497
+ do.stride(3),
498
+ s.stride(0),
499
+ q.shape[0],
500
+ q.shape[1],
501
+ q.shape[2],
502
+ grid_q[0],
503
+ BLOCK_M=BLOCK_M,
504
+ BLOCK_DMODEL_QK=ctx.BLOCK_DMODEL_QK,
505
+ BLOCK_N=BLOCK_N,
506
+ BLOCK_DMODEL_V=ctx.BLOCK_DMODEL_V,
507
+ CAUSAL=ctx.causal,
508
+ USE_DECAY=ctx.use_decay,
509
+ num_warps=num_warps,
510
+ num_stages=num_stages,
511
+ )
512
+
513
+ return dq.to(q.dtype), dk, dv, None, None
514
+
515
+
516
+ attention = _attention.apply
517
+
518
+
519
+ def lightning_attention(q, k, v, causal, ed):
520
+ d = q.shape[-1]
521
+ e = v.shape[-1]
522
+ # arr = f(d)
523
+ if d >= 128:
524
+ m = 128
525
+ else:
526
+ m = 64
527
+ arr = [m * i for i in range(d // m + 1)]
528
+ if arr[-1] != d:
529
+ arr.append(d)
530
+ n = len(arr)
531
+ output = 0
532
+ for i in range(n - 1):
533
+ s = arr[i]
534
+ e = arr[i + 1]
535
+ q1 = q[..., s:e]
536
+ k1 = k[..., s:e]
537
+ o = attention(q1, k1, v, causal, ed)
538
+ output = output + o
539
+
540
+ return output
lightning_attention2.py ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 OpenNLPLab
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # coding=utf-8
16
+ import torch
17
+ import triton
18
+ import triton.language as tl
19
+
20
+
21
+ @triton.jit
22
+ def _fwd_kernel(
23
+ Q,
24
+ K,
25
+ V,
26
+ Out,
27
+ S,
28
+ stride_qz,
29
+ stride_qh,
30
+ stride_qm,
31
+ stride_qk,
32
+ stride_kz,
33
+ stride_kh,
34
+ stride_kn,
35
+ stride_kk,
36
+ stride_vz,
37
+ stride_vh,
38
+ stride_vn,
39
+ stride_ve,
40
+ stride_oz,
41
+ stride_oh,
42
+ stride_om,
43
+ stride_oe,
44
+ stride_sh,
45
+ Z,
46
+ H,
47
+ N_CTX,
48
+ BLOCK_M: tl.constexpr,
49
+ BLOCK_DMODEL_QK: tl.constexpr,
50
+ BLOCK_N: tl.constexpr,
51
+ BLOCK_DMODEL_V: tl.constexpr,
52
+ IS_CAUSAL: tl.constexpr,
53
+ USE_DECAY: tl.constexpr,
54
+ ):
55
+ start_m = tl.program_id(0)
56
+ off_hz = tl.program_id(1)
57
+ off_h = off_hz % H
58
+ # initialize offsets
59
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
60
+ offs_n = tl.arange(0, BLOCK_N)
61
+ offs_k = tl.arange(0, BLOCK_DMODEL_QK)
62
+ offs_e = tl.arange(0, BLOCK_DMODEL_V)
63
+ # get current offset of q k v
64
+ off_q = (off_hz * stride_qh + offs_m[:, None] * stride_qm
65
+ + offs_k[None, :] * stride_qk)
66
+ off_k = (off_hz * stride_kh + offs_n[:, None] * stride_kn
67
+ + offs_k[None, :] * stride_kk)
68
+ off_v = (off_hz * stride_vh + offs_n[:, None] * stride_vn
69
+ + offs_e[None, :] * stride_ve)
70
+ off_o = (off_hz * stride_oh + offs_m[:, None] * stride_om
71
+ + offs_e[None, :] * stride_oe)
72
+
73
+ # Initialize pointers to Q, K, V
74
+ q_ptrs = Q + off_q
75
+ k_ptrs = K + off_k
76
+ v_ptrs = V + off_v
77
+
78
+ # initialize pointer to m and l
79
+ acc = tl.zeros([BLOCK_M, BLOCK_DMODEL_V], dtype=tl.float32)
80
+ # load q: it will stay in SRAM throughout
81
+ q = tl.load(q_ptrs, mask=offs_m[:, None] < N_CTX, other=0.0)
82
+ # loop over k, v and update accumulator
83
+ lo = 0
84
+ # print(start_m)
85
+ hi = (start_m + 1) * BLOCK_M if IS_CAUSAL else N_CTX
86
+ for start_n in range(lo, hi, BLOCK_N):
87
+ # -- load k, v --
88
+ k = tl.load(
89
+ k_ptrs + start_n * stride_kn,
90
+ mask=(start_n + offs_n)[:, None] < N_CTX,
91
+ other=0.0,
92
+ )
93
+ v = tl.load(
94
+ v_ptrs + start_n * stride_vn,
95
+ mask=(start_n + offs_n)[:, None] < N_CTX,
96
+ other=0.0,
97
+ )
98
+ # -- compute qk ---
99
+ # qk = tl.dot(q, k)
100
+ qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
101
+ # qk += tl.dot(q, k, trans_b=True)
102
+ qk += tl.dot(q, tl.trans(k))
103
+ if IS_CAUSAL:
104
+ index = offs_m[:, None] - (start_n + offs_n[None, :])
105
+ if USE_DECAY:
106
+ S_block_ptr = S + off_h * stride_sh
107
+ s = tl.load(S_block_ptr)
108
+ s_index = s * index
109
+ s_index = tl.where(s_index >= 0, -s_index, float("-inf"))
110
+ qk = tl.exp(s_index) * qk
111
+ else:
112
+ qk = tl.where(index >= 0, qk, 0)
113
+ acc += tl.dot(qk, v.to(qk.dtype))
114
+
115
+ out_ptrs = Out + off_o
116
+ tl.store(out_ptrs, acc.to(q.dtype), mask=offs_m[:, None] < N_CTX)
117
+
118
+
119
+ @triton.jit
120
+ def _bwd_kernel_kv(
121
+ Q,
122
+ K,
123
+ V,
124
+ S,
125
+ DO,
126
+ DQ,
127
+ DK,
128
+ DV,
129
+ stride_qz,
130
+ stride_qh,
131
+ stride_qm,
132
+ stride_qk,
133
+ stride_kz,
134
+ stride_kh,
135
+ stride_kn,
136
+ stride_kk,
137
+ stride_vz,
138
+ stride_vh,
139
+ stride_vn,
140
+ stride_ve,
141
+ stride_oz,
142
+ stride_oh,
143
+ stride_om,
144
+ stride_oe,
145
+ stride_sh,
146
+ Z,
147
+ H,
148
+ N_CTX,
149
+ num_block,
150
+ BLOCK_M: tl.constexpr,
151
+ BLOCK_DMODEL_QK: tl.constexpr,
152
+ BLOCK_N: tl.constexpr,
153
+ BLOCK_DMODEL_V: tl.constexpr,
154
+ CAUSAL: tl.constexpr,
155
+ USE_DECAY: tl.constexpr,
156
+ ):
157
+ start_n = tl.program_id(0)
158
+ off_hz = tl.program_id(1)
159
+
160
+ off_z = off_hz // H
161
+ off_h = off_hz % H
162
+ # offset pointers for batch/head
163
+ Q += off_z * stride_qz + off_h * stride_qh
164
+ K += off_z * stride_kz + off_h * stride_kh
165
+ V += off_z * stride_vz + off_h * stride_vh
166
+ DO += off_z * stride_oz + off_h * stride_oh
167
+ DQ += off_z * stride_qz + off_h * stride_qh
168
+ DK += off_z * stride_kz + off_h * stride_kh
169
+ DV += off_z * stride_vz + off_h * stride_vh
170
+
171
+ # start of q
172
+ if CAUSAL:
173
+ lo = start_n * BLOCK_M
174
+ else:
175
+ lo = 0
176
+ # initialize row/col offsets
177
+ # seqlence offset
178
+ offs_qm = lo + tl.arange(0, BLOCK_M)
179
+ offs_kvn = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
180
+ # feature offset
181
+ offs_qkk = tl.arange(0, BLOCK_DMODEL_QK)
182
+ offs_ve = tl.arange(0, BLOCK_DMODEL_V)
183
+ # row block index
184
+ offs_m = tl.arange(0, BLOCK_M)
185
+ # initialize pointers to value-like data
186
+ q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_qkk[None, :] * stride_qk)
187
+ k_ptrs = K + (offs_kvn[:, None] * stride_kn
188
+ + offs_qkk[None, :] * stride_kk)
189
+ v_ptrs = V + (offs_kvn[:, None] * stride_vn + offs_ve[None, :] * stride_ve)
190
+ do_ptrs = DO + (offs_qm[:, None] * stride_om
191
+ + offs_ve[None, :] * stride_oe)
192
+ dq_ptrs = DQ + (offs_qm[:, None] * stride_qm
193
+ + offs_qkk[None, :] * stride_qk)
194
+ # initialize dv amd dk
195
+ dv = tl.zeros([BLOCK_N, BLOCK_DMODEL_V], dtype=tl.float32)
196
+ dk = tl.zeros([BLOCK_N, BLOCK_DMODEL_QK], dtype=tl.float32)
197
+ # k and v stay in SRAM throughout
198
+ k = tl.load(k_ptrs, mask=offs_kvn[:, None] < N_CTX, other=0.0)
199
+ v = tl.load(v_ptrs, mask=offs_kvn[:, None] < N_CTX, other=0.0)
200
+ # loop over rows
201
+ for start_m in range(lo, num_block * BLOCK_M, BLOCK_M):
202
+ offs_m_curr = start_m + offs_m
203
+ # load q, k, v, do on-chip
204
+ q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < N_CTX, other=0.0)
205
+ qk = tl.dot(q, tl.trans(k))
206
+ # qk = tl.dot(q, k, trans_b=True)
207
+ if CAUSAL:
208
+ index = offs_m_curr[:, None] - offs_kvn[None, :]
209
+ if USE_DECAY:
210
+ S_block_ptr = S + off_h * stride_sh
211
+ s = tl.load(S_block_ptr)
212
+ s_index = s * index
213
+ s_index = tl.where(s_index >= 0, -s_index, float("-inf"))
214
+ s = tl.exp(s_index)
215
+ qk = qk * s
216
+ else:
217
+ qk = tl.where(index >= 0, qk, 0)
218
+
219
+ p = qk
220
+ # compute dv
221
+ do = tl.load(do_ptrs, mask=offs_m_curr[:, None] < N_CTX, other=0.0)
222
+ dv += tl.dot(tl.trans(p.to(do.dtype)), do)
223
+ dp = tl.dot(do, tl.trans(v).to(do.dtype))
224
+ if CAUSAL:
225
+ if USE_DECAY:
226
+ dp = dp * s
227
+ else:
228
+ dp = tl.where(index >= 0, dp, 0)
229
+
230
+ dk += tl.dot(tl.trans(dp.to(q.dtype)), q).to(tl.float32)
231
+
232
+ # increment pointers
233
+ q_ptrs += BLOCK_M * stride_qm
234
+ do_ptrs += BLOCK_M * stride_om
235
+ # write-back
236
+ dv_ptrs = DV + (offs_kvn[:, None] * stride_vn
237
+ + offs_ve[None, :] * stride_ve)
238
+ dk_ptrs = DK + (offs_kvn[:, None] * stride_kn
239
+ + offs_qkk[None, :] * stride_kk)
240
+ tl.store(dv_ptrs, dv, mask=offs_kvn[:, None] < N_CTX)
241
+ tl.store(dk_ptrs, dk, mask=offs_kvn[:, None] < N_CTX)
242
+
243
+
244
+ @triton.jit
245
+ def _bwd_kernel_q(
246
+ Q,
247
+ K,
248
+ V,
249
+ S,
250
+ DO,
251
+ DQ,
252
+ DK,
253
+ DV,
254
+ stride_qz,
255
+ stride_qh,
256
+ stride_qm,
257
+ stride_qk,
258
+ stride_kz,
259
+ stride_kh,
260
+ stride_kn,
261
+ stride_kk,
262
+ stride_vz,
263
+ stride_vh,
264
+ stride_vn,
265
+ stride_ve,
266
+ stride_oz,
267
+ stride_oh,
268
+ stride_om,
269
+ stride_oe,
270
+ stride_sh,
271
+ Z,
272
+ H,
273
+ N_CTX,
274
+ num_block,
275
+ BLOCK_M: tl.constexpr,
276
+ BLOCK_DMODEL_QK: tl.constexpr,
277
+ BLOCK_N: tl.constexpr,
278
+ BLOCK_DMODEL_V: tl.constexpr,
279
+ CAUSAL: tl.constexpr,
280
+ USE_DECAY: tl.constexpr,
281
+ ):
282
+ start_m = tl.program_id(0)
283
+ off_hz = tl.program_id(1)
284
+ off_z = off_hz // H
285
+ off_h = off_hz % H
286
+ # offset pointers for batch/head
287
+ K += off_z * stride_kz + off_h * stride_kh
288
+ V += off_z * stride_vz + off_h * stride_vh
289
+ DO += off_z * stride_oz + off_h * stride_oh
290
+ DQ += off_z * stride_qz + off_h * stride_qh
291
+ # feature offset
292
+ offs_qkk = tl.arange(0, BLOCK_DMODEL_QK)
293
+ offs_ve = tl.arange(0, BLOCK_DMODEL_V)
294
+ # row block index
295
+ offs_m = tl.arange(0, BLOCK_M)
296
+ # row block index
297
+ offs_qm = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
298
+ # do
299
+ do_ptrs = DO + (offs_qm[:, None] * stride_om
300
+ + offs_ve[None, :] * stride_oe)
301
+ dq_ptrs = DQ + (offs_qm[:, None] * stride_qm
302
+ + offs_qkk[None, :] * stride_qk)
303
+
304
+ do = tl.load(do_ptrs, mask=offs_qm[:, None] < N_CTX, other=0.0)
305
+
306
+ dq = tl.zeros([BLOCK_M, BLOCK_DMODEL_QK], dtype=tl.float32)
307
+ lo = 0
308
+ hi = (start_m + 1) * BLOCK_M if CAUSAL else N_CTX
309
+
310
+ offs_m_curr = start_m * BLOCK_M + offs_m
311
+
312
+ for start_n in range(0, num_block):
313
+ offs_kvn = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
314
+ k_ptrs = K + (offs_kvn[:, None] * stride_kn
315
+ + offs_qkk[None, :] * stride_kk)
316
+ v_ptrs = V + (offs_kvn[:, None] * stride_vn
317
+ + offs_ve[None, :] * stride_ve)
318
+ # k and v stay in SRAM throughout
319
+ k = tl.load(k_ptrs, mask=offs_kvn[:, None] < N_CTX, other=0.0)
320
+ v = tl.load(v_ptrs, mask=offs_kvn[:, None] < N_CTX, other=0.0)
321
+ # dp = do vT
322
+ dp = tl.dot(do, tl.trans(v).to(do.dtype))
323
+ if CAUSAL:
324
+ index = offs_m_curr[:, None] - offs_kvn[None, :]
325
+ if USE_DECAY:
326
+ S_block_ptr = S + off_h * stride_sh
327
+ s = tl.load(S_block_ptr)
328
+ s_index = s * index
329
+ s_index = tl.where(s_index >= 0, -s_index, float("-inf"))
330
+ s = tl.exp(s_index)
331
+ dp = dp * s
332
+ else:
333
+ dp = tl.where(index >= 0, dp, 0)
334
+ # dq = dq + dp k
335
+ dq += tl.dot(dp.to(k.dtype), k)
336
+
337
+ tl.store(dq_ptrs, dq, mask=offs_qm[:, None] < N_CTX)
338
+
339
+
340
+ class _attention(torch.autograd.Function):
341
+
342
+ @staticmethod
343
+ def forward(ctx, q, k, v, causal, s):
344
+ q = q.contiguous()
345
+ k = k.contiguous()
346
+ v = v.contiguous()
347
+ s = s.contiguous()
348
+ # only support for Ampere now
349
+ capability = torch.cuda.get_device_capability()
350
+ if capability[0] < 8:
351
+ raise RuntimeError(
352
+ "Lightning attention currently only supported for compute capability >= 80"
353
+ )
354
+ # shape constraints
355
+ Lq, Lk, Lv = q.shape[-1], k.shape[-1], v.shape[-1]
356
+ # right
357
+ o = torch.empty(
358
+ (q.shape[0], q.shape[1], q.shape[2], v.shape[-1]),
359
+ dtype=q.dtype,
360
+ device=q.device,
361
+ )
362
+
363
+ BLOCK_M = 128
364
+ BLOCK_N = 64
365
+ num_warps = 4 if Lk <= 64 else 8
366
+ num_stages = 1
367
+
368
+ grid = (triton.cdiv(q.shape[2], BLOCK_M), q.shape[0] * q.shape[1], 1)
369
+ use_decay = s.shape[0] > 0
370
+ _fwd_kernel[grid](
371
+ q,
372
+ k,
373
+ v,
374
+ o,
375
+ s,
376
+ q.stride(0),
377
+ q.stride(1),
378
+ q.stride(2),
379
+ q.stride(3),
380
+ k.stride(0),
381
+ k.stride(1),
382
+ k.stride(2),
383
+ k.stride(3),
384
+ v.stride(0),
385
+ v.stride(1),
386
+ v.stride(2),
387
+ v.stride(3),
388
+ o.stride(0),
389
+ o.stride(1),
390
+ o.stride(2),
391
+ o.stride(3),
392
+ s.stride(0),
393
+ q.shape[0],
394
+ q.shape[1],
395
+ q.shape[2],
396
+ BLOCK_M=BLOCK_M,
397
+ BLOCK_DMODEL_QK=Lk,
398
+ BLOCK_N=BLOCK_N,
399
+ BLOCK_DMODEL_V=Lv,
400
+ IS_CAUSAL=causal,
401
+ USE_DECAY=use_decay,
402
+ num_warps=num_warps,
403
+ num_stages=num_stages,
404
+ )
405
+
406
+ ctx.save_for_backward(q, k, v, s)
407
+ ctx.grid = grid
408
+ ctx.BLOCK_M = BLOCK_M
409
+ ctx.BLOCK_DMODEL_QK = Lk
410
+ ctx.BLOCK_N = BLOCK_N
411
+ ctx.BLOCK_DMODEL_V = Lv
412
+ ctx.causal = causal
413
+ ctx.use_decay = use_decay
414
+ return o
415
+
416
+ @staticmethod
417
+ def backward(ctx, do):
418
+ q, k, v, s = ctx.saved_tensors
419
+ BLOCK_M = 32
420
+ BLOCK_N = 32
421
+ num_warps = 4
422
+ num_stages = 1
423
+
424
+ do = do.contiguous()
425
+ dq = torch.zeros_like(q, dtype=torch.float32)
426
+ dk = torch.empty_like(k)
427
+ dv = torch.empty_like(v)
428
+
429
+ grid_kv = (triton.cdiv(k.shape[2],
430
+ BLOCK_N), k.shape[0] * k.shape[1], 1)
431
+ _bwd_kernel_kv[grid_kv](
432
+ q,
433
+ k,
434
+ v,
435
+ s,
436
+ do,
437
+ dq,
438
+ dk,
439
+ dv,
440
+ q.stride(0),
441
+ q.stride(1),
442
+ q.stride(2),
443
+ q.stride(3),
444
+ k.stride(0),
445
+ k.stride(1),
446
+ k.stride(2),
447
+ k.stride(3),
448
+ v.stride(0),
449
+ v.stride(1),
450
+ v.stride(2),
451
+ v.stride(3),
452
+ do.stride(0),
453
+ do.stride(1),
454
+ do.stride(2),
455
+ do.stride(3),
456
+ s.stride(0),
457
+ q.shape[0],
458
+ q.shape[1],
459
+ q.shape[2],
460
+ grid_kv[0],
461
+ BLOCK_M=BLOCK_M,
462
+ BLOCK_DMODEL_QK=ctx.BLOCK_DMODEL_QK,
463
+ BLOCK_N=BLOCK_N,
464
+ BLOCK_DMODEL_V=ctx.BLOCK_DMODEL_V,
465
+ CAUSAL=ctx.causal,
466
+ USE_DECAY=ctx.use_decay,
467
+ num_warps=num_warps,
468
+ num_stages=num_stages,
469
+ )
470
+
471
+ grid_q = (triton.cdiv(q.shape[2], BLOCK_M), q.shape[0] * q.shape[1], 1)
472
+
473
+ _bwd_kernel_q[grid_q](
474
+ q,
475
+ k,
476
+ v,
477
+ s,
478
+ do,
479
+ dq,
480
+ dk,
481
+ dv,
482
+ q.stride(0),
483
+ q.stride(1),
484
+ q.stride(2),
485
+ q.stride(3),
486
+ k.stride(0),
487
+ k.stride(1),
488
+ k.stride(2),
489
+ k.stride(3),
490
+ v.stride(0),
491
+ v.stride(1),
492
+ v.stride(2),
493
+ v.stride(3),
494
+ do.stride(0),
495
+ do.stride(1),
496
+ do.stride(2),
497
+ do.stride(3),
498
+ s.stride(0),
499
+ q.shape[0],
500
+ q.shape[1],
501
+ q.shape[2],
502
+ grid_q[0],
503
+ BLOCK_M=BLOCK_M,
504
+ BLOCK_DMODEL_QK=ctx.BLOCK_DMODEL_QK,
505
+ BLOCK_N=BLOCK_N,
506
+ BLOCK_DMODEL_V=ctx.BLOCK_DMODEL_V,
507
+ CAUSAL=ctx.causal,
508
+ USE_DECAY=ctx.use_decay,
509
+ num_warps=num_warps,
510
+ num_stages=num_stages,
511
+ )
512
+
513
+ return dq.to(q.dtype), dk, dv, None, None
514
+
515
+
516
+ attention = _attention.apply
517
+
518
+
519
+ def lightning_attention(q, k, v, causal, ed):
520
+ d = q.shape[-1]
521
+ e = v.shape[-1]
522
+ # arr = f(d)
523
+ if d >= 128:
524
+ m = 128
525
+ else:
526
+ m = 64
527
+ arr = [m * i for i in range(d // m + 1)]
528
+ if arr[-1] != d:
529
+ arr.append(d)
530
+ n = len(arr)
531
+ output = 0
532
+ for i in range(n - 1):
533
+ s = arr[i]
534
+ e = arr[i + 1]
535
+ q1 = q[..., s:e]
536
+ k1 = k[..., s:e]
537
+ o = attention(q1, k1, v, causal, ed)
538
+ output = output + o
539
+
540
+ return output
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f02c524d2f9374fe6aa8ae63d13064be3625423be672ac653bc40a071c17e3bd
3
+ size 769867776
modeling_transnormer.py ADDED
@@ -0,0 +1,933 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 OpenNLPLab
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # coding=utf-8
16
+ """ PyTorch Transnormer model."""
17
+ import math
18
+ import os
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ from einops import rearrange
22
+ import numpy as np
23
+ import torch
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from transformers.activations import ACT2FN
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ )
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (
35
+ add_start_docstrings,
36
+ add_start_docstrings_to_model_forward,
37
+ logging,
38
+ replace_return_docstrings,
39
+ )
40
+
41
+ from .configuration_transnormer import TransnormerConfig
42
+ from .norm import SimpleRMSNorm as SimpleRMSNorm_torch
43
+ from .srmsnorm_triton import SimpleRMSNorm as SimpleRMSNorm_triton
44
+ from .utils import (
45
+ get_activation_fn,
46
+ get_norm_fn,
47
+ logging_info,
48
+ print_module,
49
+ print_params,
50
+ )
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+ _CONFIG_FOR_DOC = "TransnormerConfig"
55
+
56
+ # TODO: fix environment: https://huggingface.co/OpenNLPLab/TransNormerLLM-7B/discussions/1
57
+ use_triton = eval(os.environ.get("use_triton", default="True"))
58
+ debug = eval(os.environ.get("debug", default="False"))
59
+ do_eval = eval(os.environ.get("do_eval", default="False"))
60
+ eval_and_not_generate = eval(
61
+ os.environ.get("eval_and_not_generate", default="False"))
62
+ BLOCK = 256
63
+
64
+ if use_triton:
65
+ try:
66
+ from .lightning_attention2 import lightning_attention
67
+
68
+ has_lightning_attention = True
69
+ except (ImportError, ModuleNotFoundError):
70
+ has_lightning_attention = False
71
+ else:
72
+ has_lightning_attention = False
73
+
74
+ if debug:
75
+ logger.info(f"Use triton: {use_triton}")
76
+ logger.info(f"Use lightning attention: {has_lightning_attention}")
77
+ logger.info(f"Debug mode: {debug}, {type(debug)}")
78
+
79
+ if not has_lightning_attention:
80
+
81
+ def linear_attention(q, k, v, attn_mask):
82
+ energy = torch.einsum("... n d, ... m d -> ... n m", q, k)
83
+ energy = energy * attn_mask
84
+ output = torch.einsum("... n m, ... m d -> ... n d", energy, v)
85
+
86
+ return output
87
+
88
+
89
+ ########## start Transnormer
90
+ ##### Linearized Relative Positional Encoding: https://openreview.net/forum?id=xoLyps2qWc&referrer=%5BAuthor%20Console%5D(%2Fgroup%3Fid%3DTMLR%2FAuthors%23your-submissions)
91
+ class Lrpe(nn.Module):
92
+
93
+ def __init__(
94
+ self,
95
+ num_heads=8,
96
+ embed_dim=64,
97
+ ):
98
+ super().__init__()
99
+ d = num_heads * embed_dim
100
+
101
+ self.index = torch.empty(0)
102
+ self.theta = nn.Parameter(10000**(-2 / d * torch.arange(d)).reshape(
103
+ num_heads, 1, -1))
104
+
105
+ def extra_repr(self):
106
+ return print_module(self)
107
+
108
+ def forward(self, x, offset=0):
109
+ # x: b, h, n, d
110
+ # offset: for k, v cache
111
+ n = x.shape[-2]
112
+ if self.index.shape[0] < n:
113
+ self.index = torch.arange(n).reshape(1, -1, 1).to(x)
114
+ index = self.index[:, :n] + offset
115
+ theta = self.theta * index
116
+ x = torch.concat([x * torch.cos(theta), x * torch.sin(theta)], dim=-1)
117
+
118
+ return x
119
+
120
+
121
+ class GLU(nn.Module):
122
+
123
+ def __init__(self, d1, d2, bias=False):
124
+ super().__init__()
125
+ if debug:
126
+ # get local varables
127
+ params = locals()
128
+ # print params
129
+ print_params(**params)
130
+
131
+ self.l1 = nn.Linear(d1, d2, bias=bias)
132
+ self.l2 = nn.Linear(d1, d2, bias=bias)
133
+ self.l3 = nn.Linear(d2, d1, bias=bias)
134
+
135
+ def forward(self, x):
136
+ o1 = self.l1(x)
137
+ o2 = self.l2(x)
138
+ output = o1 * o2
139
+ output = self.l3(output)
140
+
141
+ return output
142
+
143
+
144
+ class NormLinearAttention(nn.Module):
145
+
146
+ def __init__(
147
+ self,
148
+ embed_dim,
149
+ hidden_dim,
150
+ num_heads,
151
+ linear_act_fun="silu",
152
+ norm_type="simplermsnorm",
153
+ linear_use_lrpe=False,
154
+ bias=False,
155
+ ):
156
+ super().__init__()
157
+ if debug:
158
+ # get local varables
159
+ params = locals()
160
+ # print params
161
+ print_params(**params)
162
+
163
+ self.out_proj = nn.Linear(hidden_dim, embed_dim, bias=bias)
164
+ self.act = get_activation_fn(linear_act_fun)
165
+ self.num_heads = num_heads
166
+ self.embed_dim = embed_dim
167
+ self.head_dim = self.embed_dim // self.num_heads
168
+ self.norm = get_norm_fn(norm_type)(hidden_dim)
169
+
170
+ self.linear_use_lrpe = linear_use_lrpe
171
+ if self.linear_use_lrpe:
172
+ self.lrpe = Lrpe(
173
+ num_heads=self.num_heads,
174
+ embed_dim=self.head_dim,
175
+ )
176
+
177
+ self.qkvu_proj = nn.Linear(embed_dim, 4 * hidden_dim, bias=bias)
178
+
179
+ # for inference only
180
+ self.offset = 0
181
+
182
+ def forward(
183
+ self,
184
+ x,
185
+ attn_mask: Optional[torch.Tensor] = None, # (b, h, n, m)
186
+ attn_padding_mask: Optional[torch.Tensor] = None, # (b, m)
187
+ output_attentions: bool = False,
188
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
189
+ use_cache: bool = False,
190
+ slope_rate: Optional[torch.Tensor] = None,
191
+ ):
192
+ if (not self.training) and (not do_eval):
193
+ return self.inference(
194
+ x,
195
+ attn_mask,
196
+ attn_padding_mask,
197
+ output_attentions,
198
+ past_key_value,
199
+ use_cache,
200
+ slope_rate,
201
+ )
202
+ # x: b n d
203
+ n = x.shape[-2]
204
+ # linear map
205
+ q, k, v, u = self.qkvu_proj(x).chunk(4, dim=-1)
206
+ # reshape
207
+ q, k, v = map(
208
+ lambda x: rearrange(x, "b n (h d) -> b h n d", h=self.num_heads),
209
+ [q, k, v])
210
+ # act
211
+ q = self.act(q)
212
+ k = self.act(k)
213
+
214
+ q_offset = 0
215
+ # lrpe relys on position, get cache first
216
+ if past_key_value is not None:
217
+ # reuse k, v, for evaluation only
218
+ k = torch.cat([past_key_value[0], k], dim=-2)
219
+ v = torch.cat([past_key_value[1], v], dim=-2)
220
+ q_offset = past_key_value[0].shape[-2]
221
+
222
+ past_key_value = (k, v) if use_cache else None
223
+
224
+ # lrpe
225
+ if self.linear_use_lrpe:
226
+ q = self.lrpe(q, offset=q_offset)
227
+ k = self.lrpe(k, offset=q_offset)
228
+
229
+ if attn_mask == None:
230
+ attn_mask = (torch.tril(torch.ones(n, n))).to(q)
231
+
232
+ if attn_padding_mask is not None:
233
+ v = v.masked_fill(
234
+ (1 - attn_padding_mask).unsqueeze(1).unsqueeze(-1).to(
235
+ torch.bool), 0)
236
+
237
+ if not has_lightning_attention:
238
+ if slope_rate != None:
239
+ attn_mask = torch.exp(slope_rate * attn_mask)
240
+ output = linear_attention(q, k, v, attn_mask)
241
+ else:
242
+ output = lightning_attention(q, k, v, True,
243
+ slope_rate.squeeze(-1).squeeze(-1))
244
+
245
+ # reshape
246
+ output = rearrange(output, "b h n d -> b n (h d)")
247
+ # normalize
248
+ output = self.norm(output)
249
+ # gate
250
+ output = u * output
251
+ # outproj
252
+ output = self.out_proj(output)
253
+
254
+ if not output_attentions:
255
+ attn_weights = None
256
+ else:
257
+ attn_weights = torch.einsum("... n d, ... m d -> ... n m", q, k)
258
+
259
+ return output, attn_weights, past_key_value
260
+
261
+ def inference(
262
+ self,
263
+ x,
264
+ attn_mask: Optional[torch.Tensor] = None, # (b, h, n, m)
265
+ attn_padding_mask: Optional[torch.Tensor] = None, # (b, m)
266
+ output_attentions: bool = False,
267
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
268
+ use_cache: bool = False,
269
+ slope_rate: Optional[torch.Tensor] = None, # (h, 1, 1)
270
+ ):
271
+ # x: b n d
272
+ n = x.shape[-2]
273
+ # linear map
274
+ q, k, v, u = self.qkvu_proj(x).chunk(4, dim=-1)
275
+ # reshape
276
+ q, k, v = map(
277
+ lambda x: rearrange(x, "b n (h d) -> b h n d", h=self.num_heads),
278
+ [q, k, v])
279
+ # act
280
+ q = self.act(q)
281
+ k = self.act(k)
282
+
283
+ # rpe
284
+ if self.linear_use_lrpe:
285
+ q = self.lrpe(q, offset=self.offset)
286
+ k = self.lrpe(k, offset=self.offset)
287
+
288
+ if past_key_value == None:
289
+ self.offset = q.shape[-2]
290
+ else:
291
+ self.offset += 1
292
+
293
+ ratio = torch.exp(-slope_rate)
294
+
295
+ # only use for the first time
296
+ if past_key_value == None:
297
+ slope_rate = slope_rate.to(torch.float32)
298
+ if attn_padding_mask is not None:
299
+ v = v.masked_fill(
300
+ (1 - attn_padding_mask).unsqueeze(1).unsqueeze(-1).to(
301
+ torch.bool), 0)
302
+ NUM_BLOCK = (n + BLOCK - 1) // BLOCK
303
+ b, h, n, d = q.shape
304
+ e = v.shape[-1]
305
+ # other
306
+ array = torch.arange(BLOCK).to(q) + 1 ## !!!! important
307
+ q_decay = torch.exp(-slope_rate * array.reshape(-1, 1))
308
+ k_decay = torch.exp(-slope_rate * (BLOCK - array.reshape(-1, 1)))
309
+ index = array[:, None] - array[None, :]
310
+ s_index = slope_rate * index[
311
+ None,
312
+ None,
313
+ ]
314
+ s_index = torch.where(index >= 0, -s_index, float("-inf"))
315
+ diag_decay = torch.exp(s_index)
316
+
317
+ kv = torch.zeros(b, h, d, e).to(torch.float32).to(q.device)
318
+ output = torch.empty((b, h, n, e), dtype=q.dtype, device=q.device)
319
+ for i in range(NUM_BLOCK):
320
+ si = i * BLOCK
321
+ ei = min(si + BLOCK, n)
322
+ m = ei - si
323
+
324
+ qi = q[:, :, si:ei].contiguous()
325
+ ki = k[:, :, si:ei].contiguous()
326
+ vi = v[:, :, si:ei].contiguous()
327
+ qkv_none_diag = torch.matmul(qi * q_decay[:, :m],
328
+ kv).to(torch.float32)
329
+
330
+ # diag
331
+ qk = torch.matmul(qi, ki.transpose(-1, -2)).to(
332
+ torch.float32) * diag_decay[:, :, :m, :m]
333
+ qkv_diag = torch.matmul(qk, vi.to(torch.float32))
334
+ block_decay = torch.exp(-slope_rate * m)
335
+ output[:, :, si:ei] = qkv_none_diag + qkv_diag
336
+ kv = block_decay * kv + torch.matmul(
337
+ (ki * k_decay[:, -m:]).transpose(-1, -2).to(vi.dtype), vi)
338
+ else:
339
+ kv = past_key_value
340
+
341
+ output = []
342
+ for i in range(n):
343
+ kv = ratio * kv + torch.einsum(
344
+ "... n d, ... n e -> ... d e",
345
+ k[:, :, i:i + 1],
346
+ v[:, :, i:i + 1],
347
+ )
348
+ qkv = torch.einsum("... n e, ... e d -> ... n d", q[:, :,
349
+ i:i + 1],
350
+ kv.to(q.dtype))
351
+ output.append(qkv)
352
+ output = torch.concat(output, dim=-2)
353
+
354
+ # reshape
355
+ output = rearrange(output, "b h n d -> b n (h d)")
356
+ # normalize
357
+ output = self.norm(output)
358
+ # gate
359
+ output = u * output
360
+ # outproj
361
+ output = self.out_proj(output)
362
+
363
+ attn_weights = None
364
+
365
+ return output, attn_weights, kv
366
+
367
+
368
+ class TransnormerDecoderLayer(nn.Module):
369
+
370
+ def __init__(self, config: TransnormerConfig):
371
+ super().__init__()
372
+ self.embed_dim = config.decoder_embed_dim
373
+ ##### normalize
374
+ norm_type = config.norm_type
375
+ if debug:
376
+ logging_info(f"Decoder Norm Type: {norm_type}")
377
+ self.token_norm = get_norm_fn(norm_type)(self.embed_dim)
378
+ self.channel_norm = get_norm_fn(norm_type)(self.embed_dim)
379
+
380
+ ##### token mixer
381
+ self.token_mixer = self.build_token_mixer(
382
+ self.embed_dim,
383
+ config,
384
+ )
385
+
386
+ ##### channel mixer
387
+ self.glu_dim = config.glu_dim
388
+ if self.glu_dim == -1:
389
+ self.glu_dim = self.embed_dim
390
+ bias = config.bias
391
+ self.channel_mixer = GLU(self.embed_dim, self.glu_dim, bias)
392
+
393
+ def build_token_mixer(self, embed_dim, config):
394
+ return NormLinearAttention(
395
+ embed_dim=embed_dim,
396
+ hidden_dim=config.hidden_dim,
397
+ num_heads=config.decoder_attention_heads,
398
+ linear_act_fun=config.linear_act_fun,
399
+ norm_type=config.norm_type,
400
+ linear_use_lrpe=config.linear_use_lrpe,
401
+ bias=config.bias,
402
+ )
403
+
404
+ def residual_connection(self, x, residual):
405
+ return residual + x
406
+
407
+ def forward(
408
+ self,
409
+ x,
410
+ attn_mask: Optional[torch.Tensor] = None,
411
+ attn_padding_mask: Optional[torch.Tensor] = None,
412
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
413
+ output_attentions: Optional[bool] = False,
414
+ use_cache: Optional[bool] = False,
415
+ slope_rate: Optional[torch.Tensor] = None, # (h, 1, 1)
416
+ ):
417
+ residual = x
418
+ x = self.token_norm(x)
419
+ x, self_attn_weights, present_key_value = self.token_mixer(
420
+ x=x,
421
+ attn_mask=attn_mask,
422
+ attn_padding_mask=attn_padding_mask,
423
+ past_key_value=past_key_value,
424
+ output_attentions=output_attentions,
425
+ use_cache=use_cache,
426
+ slope_rate=slope_rate,
427
+ )
428
+ x = self.residual_connection(x, residual)
429
+
430
+ residual = x
431
+ x = self.channel_norm(x)
432
+ x = self.channel_mixer(x)
433
+ x = self.residual_connection(x, residual)
434
+
435
+ outputs = (x, )
436
+
437
+ if output_attentions:
438
+ outputs += (self_attn_weights, )
439
+
440
+ if use_cache:
441
+ outputs += (present_key_value, )
442
+
443
+ return outputs
444
+
445
+
446
+ TRANSNORMER_START_DOCSTRING = r"""
447
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
448
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
449
+ etc.)
450
+
451
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
452
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
453
+ and behavior.
454
+
455
+ Parameters:
456
+ config ([`TransnormerConfig`]):
457
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
458
+ load the weights associated with the model, only the configuration. Check out the
459
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
460
+ """
461
+
462
+
463
+ @add_start_docstrings(TRANSNORMER_START_DOCSTRING, )
464
+ class TransnormerPreTrainedModel(PreTrainedModel):
465
+ config_class = TransnormerConfig
466
+ base_model_prefix = "model"
467
+ supports_gradient_checkpointing = True
468
+ _no_split_modules = ["TransnormerDecoderLayer"]
469
+ _skip_keys_device_placement = "past_key_values"
470
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
471
+
472
+ def _init_weights(self, module):
473
+ std = self.config.init_std
474
+ if isinstance(module, nn.Linear):
475
+ module.weight.data.normal_(mean=0.0, std=std)
476
+ if module.bias is not None:
477
+ module.bias.data.zero_()
478
+ elif isinstance(module, nn.Embedding):
479
+ module.weight.data.normal_(mean=0.0, std=std)
480
+ if module.padding_idx is not None:
481
+ module.weight.data[module.padding_idx].zero_()
482
+
483
+ def _set_gradient_checkpointing(self, module, value=False):
484
+ if isinstance(module, TransnormerModel):
485
+ module.gradient_checkpointing = value
486
+
487
+
488
+ TRANSNORMER_INPUTS_DOCSTRING = r"""
489
+ Args:
490
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
491
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
492
+ it.
493
+
494
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
495
+ [`PreTrainedTokenizer.__call__`] for details.
496
+
497
+ [What are input IDs?](../glossary#input-ids)
498
+ attn_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
499
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
500
+
501
+ - 1 for tokens that are **not masked**,
502
+ - 0 for tokens that are **masked**.
503
+
504
+ [What are attention masks?](../glossary#attention-mask)
505
+
506
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
507
+ [`PreTrainedTokenizer.__call__`] for details.
508
+
509
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
510
+ `past_key_values`).
511
+
512
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attn_mask`]
513
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
514
+ information on the default strategy.
515
+
516
+ - 1 indicates the head is **not masked**,
517
+ - 0 indicates the head is **masked**.
518
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
519
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
520
+ config.n_positions - 1]`.
521
+
522
+ [What are position IDs?](../glossary#position-ids)
523
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
524
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
525
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
526
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
527
+
528
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
529
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
530
+
531
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
532
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
533
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
534
+ use_cache (`bool`, *optional*):
535
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
536
+ `past_key_values`).
537
+ output_attentions (`bool`, *optional*):
538
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
539
+ tensors for more detail.
540
+ output_hidden_states (`bool`, *optional*):
541
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
542
+ more detail.
543
+ return_dict (`bool`, *optional*):
544
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
545
+ """
546
+
547
+
548
+ @add_start_docstrings(TRANSNORMER_START_DOCSTRING, )
549
+ class TransnormerModel(TransnormerPreTrainedModel):
550
+ """
551
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TransnormerDecoderLayer`]
552
+
553
+ Args:
554
+ config: TransnormerConfig
555
+ """
556
+
557
+ def __init__(self, config: TransnormerConfig):
558
+ super().__init__(config)
559
+ # hf origin
560
+ self.padding_idx = config.pad_token_id
561
+ self.vocab_size = config.vocab_size
562
+ self.gradient_checkpointing = False
563
+ # mask
564
+ self._linear_attn_mask = torch.empty(0)
565
+ # config
566
+ self.linear_use_lrpe_list = config.linear_use_lrpe_list
567
+ self.num_layers = config.decoder_layers
568
+ # h, 1, 1
569
+ self.slopes = self._build_slope_tensor(config.decoder_attention_heads)
570
+
571
+ # params
572
+ self.embed_tokens = nn.Embedding(config.vocab_size,
573
+ config.decoder_embed_dim,
574
+ self.padding_idx)
575
+ self.layers = nn.ModuleList([])
576
+ for i in range(config.decoder_layers):
577
+ if len(self.linear_use_lrpe_list) > 0:
578
+ config.linear_use_lrpe = self.linear_use_lrpe_list[i]
579
+ self.layers.append(TransnormerDecoderLayer(config))
580
+
581
+ self.final_norm = get_norm_fn(config.norm_type)(
582
+ config.decoder_embed_dim)
583
+ self.embed_dim = config.decoder_embed_dim
584
+ self.embed_scale = (1.0 if config.no_scale_embedding else math.sqrt(
585
+ self.embed_dim))
586
+
587
+ # Initialize weights and apply final processing
588
+ self.post_init()
589
+
590
+ @staticmethod
591
+ def _build_slope_tensor(n_attention_heads: int):
592
+
593
+ def get_slopes(n):
594
+
595
+ def get_slopes_power_of_2(n):
596
+ start = 2**(-(2**-(math.log2(n) - 3)))
597
+ ratio = start
598
+ return [start * ratio**i for i in range(n)]
599
+
600
+ if math.log2(n).is_integer():
601
+ return get_slopes_power_of_2(
602
+ n
603
+ ) # In the paper, we only train models that have 2^a heads for some a. This function has
604
+ else: # some good properties that only occur when the input is a power of 2. To maintain that even
605
+ closest_power_of_2 = 2**math.floor(
606
+ math.log2(n)
607
+ ) # when the number of heads is not a power of 2, we use this workaround.
608
+ return (get_slopes_power_of_2(closest_power_of_2) + get_slopes(
609
+ 2 * closest_power_of_2)[0::2][:n - closest_power_of_2])
610
+
611
+ # h, 1, 1
612
+ slopes = torch.tensor(get_slopes(n_attention_heads)).reshape(
613
+ n_attention_heads, 1, 1)
614
+
615
+ return slopes
616
+
617
+ def extra_repr(self):
618
+ return print_module(self)
619
+
620
+ def get_input_embeddings(self):
621
+ return self.embed_tokens
622
+
623
+ def set_input_embeddings(self, value):
624
+ self.embed_tokens = value
625
+
626
+ def _prepare_decoder_linear_attn_mask(self, input_shape, inputs_embeds,
627
+ past_key_values_length):
628
+ bsz, tgt_len = input_shape
629
+ src_len = tgt_len + past_key_values_length
630
+
631
+ def power_log(x):
632
+ return 2**(math.ceil(math.log(x, 2)))
633
+
634
+ n = power_log(max(tgt_len, src_len))
635
+ if self._linear_attn_mask.shape[-1] < n:
636
+
637
+ def get_mask(n):
638
+ mask = torch.triu(
639
+ torch.zeros(n, n).float().fill_(float("-inf")), 1)
640
+ # no slope version
641
+ # -n, ..., -2, -1, 0
642
+ for i in range(n):
643
+ x = torch.arange(i + 1)
644
+ y = x
645
+ mask[i, :i + 1] = -torch.flip(y, [0])
646
+
647
+ return mask
648
+
649
+ arr = []
650
+ for slope in self.slopes:
651
+ arr.append(get_mask(n))
652
+ self._linear_attn_mask = torch.stack(arr, dim=0).to(inputs_embeds)
653
+
654
+ linear_attn_mask = self._linear_attn_mask[:, -tgt_len:, -src_len:]
655
+ num_heads = linear_attn_mask.shape[0]
656
+
657
+ return linear_attn_mask[None, :, :, :].expand(bsz, num_heads, tgt_len,
658
+ src_len)
659
+
660
+ @add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)
661
+ def forward(
662
+ self,
663
+ input_ids: torch.LongTensor = None,
664
+ attn_padding_mask: Optional[torch.Tensor] = None,
665
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
666
+ inputs_embeds: Optional[torch.FloatTensor] = None,
667
+ use_cache: Optional[bool] = None,
668
+ output_attentions: Optional[bool] = None,
669
+ output_hidden_states: Optional[bool] = None,
670
+ return_dict: Optional[bool] = None,
671
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
672
+ output_attentions = (output_attentions if output_attentions is not None
673
+ else self.config.output_attentions)
674
+ output_hidden_states = (output_hidden_states
675
+ if output_hidden_states is not None else
676
+ self.config.output_hidden_states)
677
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
678
+
679
+ return_dict = (return_dict if return_dict is not None else
680
+ self.config.use_return_dict)
681
+
682
+ # retrieve input_ids and inputs_embeds
683
+ if input_ids is not None and inputs_embeds is not None:
684
+ raise ValueError(
685
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
686
+ )
687
+ elif input_ids is not None:
688
+ batch_size, seq_length = input_ids.shape
689
+ elif inputs_embeds is not None:
690
+ batch_size, seq_length, _ = inputs_embeds.shape
691
+ else:
692
+ raise ValueError(
693
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
694
+ )
695
+
696
+ seq_length_with_past = seq_length
697
+ past_key_values_length = 0
698
+
699
+ if past_key_values is not None:
700
+ past_key_values_length = past_key_values[0][0].shape[-2]
701
+ seq_length_with_past = seq_length_with_past + past_key_values_length
702
+
703
+ if inputs_embeds is None:
704
+ # !!! use embed_scale
705
+ inputs_embeds = self.embed_scale * self.embed_tokens(input_ids)
706
+
707
+ hidden_states = inputs_embeds
708
+
709
+ if self.gradient_checkpointing and self.training:
710
+ if use_cache:
711
+ logger.warning_once(
712
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
713
+ )
714
+ use_cache = False
715
+
716
+ # decoder layers
717
+ all_hidden_states = () if output_hidden_states else None
718
+ all_self_attns = () if output_attentions else None
719
+ next_decoder_cache = () if use_cache else None
720
+
721
+ ##### norm linear layers
722
+ linear_attn_padding_mask = attn_padding_mask
723
+ linear_attn_mask = self._prepare_decoder_linear_attn_mask(
724
+ (batch_size, seq_length), inputs_embeds, past_key_values_length)
725
+
726
+ slope_rates = [
727
+ self.slopes.to(input_ids.device) for _ in range(self.num_layers)
728
+ ]
729
+
730
+ for idx, layer in enumerate(self.layers):
731
+ if output_hidden_states:
732
+ all_hidden_states += (hidden_states, )
733
+
734
+ past_key_value = (past_key_values[idx]
735
+ if past_key_values is not None else None)
736
+
737
+ slope_rate = slope_rates[idx]
738
+ slope_rate = slope_rate * (1 - idx / (self.num_layers - 1) + 1e-5)
739
+ mask = linear_attn_mask
740
+
741
+ layer_outputs = layer(
742
+ hidden_states,
743
+ attn_mask=mask,
744
+ attn_padding_mask=linear_attn_padding_mask,
745
+ past_key_value=past_key_value,
746
+ output_attentions=output_attentions,
747
+ use_cache=use_cache,
748
+ slope_rate=slope_rate,
749
+ )
750
+
751
+ hidden_states = layer_outputs[0]
752
+
753
+ if use_cache:
754
+ next_decoder_cache += (
755
+ layer_outputs[2 if output_attentions else 1], )
756
+
757
+ if output_attentions:
758
+ all_self_attns += (layer_outputs[1], )
759
+
760
+ hidden_states = self.final_norm(hidden_states)
761
+
762
+ # add hidden states from the last decoder layer
763
+ if output_hidden_states:
764
+ all_hidden_states += (hidden_states, )
765
+
766
+ next_cache = next_decoder_cache if use_cache else None
767
+ if not return_dict:
768
+ return tuple(
769
+ v for v in
770
+ [hidden_states, next_cache, all_hidden_states, all_self_attns]
771
+ if v is not None)
772
+ return BaseModelOutputWithPast(
773
+ last_hidden_state=hidden_states,
774
+ past_key_values=next_cache,
775
+ hidden_states=all_hidden_states,
776
+ attentions=all_self_attns,
777
+ )
778
+
779
+
780
+ class TransnormerForCausalLM(TransnormerPreTrainedModel):
781
+
782
+ def __init__(self, config):
783
+ super().__init__(config)
784
+ self.model = TransnormerModel(config)
785
+ if debug:
786
+ logging_info(self.model)
787
+
788
+ # the lm_head weight is automatically tied to the embed tokens weight
789
+ self.lm_head = nn.Linear(config.decoder_embed_dim,
790
+ config.vocab_size,
791
+ bias=False)
792
+
793
+ # Initialize weights and apply final processing
794
+ self.post_init()
795
+
796
+ def get_input_embeddings(self):
797
+ return self.model.embed_tokens
798
+
799
+ def set_input_embeddings(self, value):
800
+ self.model.embed_tokens = value
801
+
802
+ def get_output_embeddings(self):
803
+ return self.lm_head
804
+
805
+ def set_output_embeddings(self, new_embeddings):
806
+ self.lm_head = new_embeddings
807
+
808
+ def set_decoder(self, decoder):
809
+ self.model = decoder
810
+
811
+ def get_decoder(self):
812
+ return self.model
813
+
814
+ @add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)
815
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast,
816
+ config_class=_CONFIG_FOR_DOC)
817
+ def forward(
818
+ self,
819
+ input_ids: torch.LongTensor = None,
820
+ attention_mask: Optional[torch.Tensor] = None,
821
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
822
+ inputs_embeds: Optional[torch.FloatTensor] = None,
823
+ labels: Optional[torch.LongTensor] = None,
824
+ use_cache: Optional[bool] = None,
825
+ output_attentions: Optional[bool] = None,
826
+ output_hidden_states: Optional[bool] = None,
827
+ return_dict: Optional[bool] = None,
828
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
829
+ r"""
830
+ Args:
831
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
832
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
833
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
834
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
835
+
836
+ Returns:
837
+
838
+ Example:
839
+
840
+ ```python
841
+ >>> from transformers import AutoTokenizer, TransnormerForCausalLM
842
+
843
+ >>> model = TransnormerForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
844
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
845
+
846
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
847
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
848
+
849
+ >>> # Generate
850
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
851
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
852
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
853
+ ```"""
854
+ output_attentions = (output_attentions if output_attentions is not None
855
+ else self.config.output_attentions)
856
+ output_hidden_states = (output_hidden_states
857
+ if output_hidden_states is not None else
858
+ self.config.output_hidden_states)
859
+ return_dict = (return_dict if return_dict is not None else
860
+ self.config.use_return_dict)
861
+
862
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
863
+ outputs = self.model(
864
+ input_ids=input_ids,
865
+ attn_padding_mask=attention_mask,
866
+ past_key_values=past_key_values,
867
+ inputs_embeds=inputs_embeds,
868
+ use_cache=use_cache,
869
+ output_attentions=output_attentions,
870
+ output_hidden_states=output_hidden_states,
871
+ return_dict=return_dict,
872
+ )
873
+
874
+ hidden_states = outputs[0]
875
+ logits = self.lm_head(hidden_states)
876
+
877
+ loss = None
878
+ if labels is not None:
879
+ # Shift so that tokens < n predict n
880
+ shift_logits = logits[..., :-1, :].contiguous()
881
+ shift_labels = labels[..., 1:].contiguous()
882
+ # Flatten the tokens
883
+ loss_fct = CrossEntropyLoss()
884
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
885
+ shift_labels = shift_labels.view(-1)
886
+ # Enable model parallelism
887
+ shift_labels = shift_labels.to(shift_logits.device)
888
+ loss = loss_fct(shift_logits, shift_labels)
889
+
890
+ if not return_dict:
891
+ output = (logits, ) + outputs[1:]
892
+ return (loss, ) + output if loss is not None else output
893
+
894
+ return CausalLMOutputWithPast(
895
+ loss=loss,
896
+ logits=logits,
897
+ past_key_values=outputs.past_key_values,
898
+ hidden_states=outputs.hidden_states,
899
+ attentions=outputs.attentions,
900
+ )
901
+
902
+ def prepare_inputs_for_generation(
903
+ self,
904
+ input_ids,
905
+ past_key_values=None,
906
+ attention_mask=None,
907
+ inputs_embeds=None,
908
+ **kwargs,
909
+ ):
910
+ if past_key_values:
911
+ input_ids = input_ids[:, -1:]
912
+
913
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
914
+ if inputs_embeds is not None and past_key_values is None:
915
+ model_inputs = {"inputs_embeds": inputs_embeds}
916
+ else:
917
+ model_inputs = {"input_ids": input_ids}
918
+
919
+ model_inputs.update({
920
+ "past_key_values": past_key_values,
921
+ "use_cache": kwargs.get("use_cache"),
922
+ "attention_mask": attention_mask,
923
+ })
924
+ return model_inputs
925
+
926
+ @staticmethod
927
+ def _reorder_cache(past_key_values, beam_idx):
928
+ reordered_past = ()
929
+ for layer_past in past_key_values:
930
+ reordered_past += (tuple(
931
+ past_state.index_select(0, beam_idx)
932
+ for past_state in layer_past), )
933
+ return reordered_past
norm.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 OpenNLPLab
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ import os
17
+ import sys
18
+
19
+ import torch
20
+ from torch import nn
21
+
22
+ logging.basicConfig(
23
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
24
+ datefmt="%Y-%m-%d %H:%M:%S",
25
+ level=os.environ.get("LOGLEVEL", "INFO").upper(),
26
+ stream=sys.stdout,
27
+ )
28
+ logger = logging.getLogger("srmsnorm")
29
+
30
+
31
+ class SimpleRMSNorm(nn.Module):
32
+
33
+ def __init__(self, dim: int, eps: float = 1e-6):
34
+ super().__init__()
35
+ self.eps = eps
36
+
37
+ def _norm(self, x):
38
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
39
+
40
+ def forward(self, x):
41
+ output = self._norm(x.float()).type_as(x)
42
+
43
+ return output
special_tokens_map copy.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
srmsnorm_triton.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CREDITS: This comes almost as-is from the Triton layer norm tutorial
2
+ # https://github.com/openai/triton/blob/master/python/tutorials/05-layer-norm.py
3
+ # Copyright 2023 OpenNLPLab
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+ import triton
20
+ import triton.language as tl
21
+
22
+
23
+ # fmt: off
24
+ @triton.jit
25
+ def srms_norm_fw(X, Y, V, stride, N, eps, BLOCK_SIZE_N: tl.constexpr):
26
+ # fmt: on
27
+ row = tl.program_id(0)
28
+ cols = tl.arange(0, BLOCK_SIZE_N)
29
+ mask = cols < N
30
+
31
+ # Move to this row
32
+ x_ptrs = X + row * stride + cols
33
+ x = tl.load(x_ptrs, mask=mask, other=0.0).to(tl.float32)
34
+
35
+ x_zm = tl.where(mask, x, 0.0)
36
+
37
+ x_var = tl.sum(x_zm * x_zm, axis=0) / N
38
+ rstd = 1.0 / tl.sqrt(x_var + eps)
39
+
40
+ # Normalize, optionally affine
41
+ y = x_zm * rstd
42
+ tl.store(V + row, rstd)
43
+
44
+ y_ptrs = Y + row * stride + cols
45
+ tl.store(y_ptrs, y, mask=mask)
46
+
47
+
48
+ # Backward pass (DX + partial DW + partial DB)
49
+ # fmt: off
50
+ @triton.jit
51
+ def srms_norm_bwd_dx_fused(
52
+ DX, DY,
53
+ X, V,
54
+ stride, N,
55
+ # META-parameters
56
+ BLOCK_SIZE_N: tl.constexpr,
57
+ ):
58
+ # fmt: on
59
+
60
+ # position of elements processed by this program
61
+ row = tl.program_id(0)
62
+ cols = tl.arange(0, BLOCK_SIZE_N)
63
+ mask = cols < N
64
+
65
+ # offset data pointers to start at the row of interest
66
+ x_ptrs = X + row * stride + cols
67
+ dy_ptrs = DY + row * stride + cols
68
+
69
+ # load data to SRAM
70
+ x = tl.load(x_ptrs, mask=mask, other=0)
71
+ dy = tl.load(dy_ptrs, mask=mask, other=0)
72
+ rstd = tl.load(V + row)
73
+
74
+ # compute dx
75
+ xhat = x * rstd
76
+ wdy = dy
77
+
78
+ xhat = tl.where(mask, xhat, 0.)
79
+ wdy = tl.where(mask, wdy, 0.)
80
+ mean1 = tl.sum(xhat * wdy, axis=0) / N
81
+ dx = (wdy - (xhat * mean1)) * rstd
82
+
83
+ # write-back dx
84
+ mask = cols < N # re-materialize the mask to save registers
85
+ dx_ptrs = DX + row * stride + cols
86
+ tl.store(dx_ptrs, dx, mask=mask)
87
+
88
+
89
+ class _SrmsNorm(torch.autograd.Function):
90
+
91
+ @staticmethod
92
+ def forward(ctx, x, eps):
93
+ # catch eps being too small if the tensors are fp16
94
+ if x.dtype == torch.float16:
95
+ eps = max(eps, 1.6e-5)
96
+
97
+ # allocate output
98
+ y = torch.empty_like(x)
99
+
100
+ # reshape input data into 2D tensor
101
+ x_arg = x.reshape(-1, x.shape[-1])
102
+ M, N = x_arg.shape
103
+
104
+ # allocate mean and std, they'll be used in the backward pass
105
+ rstd = torch.empty((M, ), dtype=torch.float32, device=x.device)
106
+
107
+ # Less than 64KB per feature: enqueue fused kernel
108
+ MAX_FUSED_SIZE = 65536 // x.element_size()
109
+ BLOCK_SIZE_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
110
+ if N > BLOCK_SIZE_N:
111
+ raise RuntimeError(
112
+ "This layer norm doesn't support feature dim >= 64KB.")
113
+
114
+ if not x_arg.is_contiguous() or not y.is_contiguous():
115
+ x_arg = x_arg.contiguous()
116
+ y = y.contiguous()
117
+
118
+ # heuristics for number of warps.
119
+ num_warps = min(max(BLOCK_SIZE_N // 256, 1), 16)
120
+
121
+ # enqueue kernel
122
+ # fmt: off
123
+ srms_norm_fw[(M,)](
124
+ x_arg, y, rstd,
125
+ x_arg.stride(0),
126
+ N,
127
+ eps,
128
+ num_warps=num_warps,
129
+ BLOCK_SIZE_N=BLOCK_SIZE_N,
130
+ )
131
+ # fmt: on
132
+
133
+ ctx.save_for_backward(x, rstd)
134
+ ctx.BLOCK_SIZE_N = BLOCK_SIZE_N
135
+ ctx.num_warps = num_warps
136
+
137
+ return y.reshape_as(x)
138
+
139
+ @staticmethod
140
+ def backward(
141
+ ctx, dy
142
+ ): # pragma: no cover # this is covered, but called directly from C++
143
+ x, rstd = ctx.saved_tensors
144
+
145
+ # flatten the batch dimension, if any.
146
+ # We're interested in 'samples' x norm_dimension
147
+ x = x.reshape(-1, x.size(-1))
148
+ M, N = x.size()
149
+
150
+ # heuristics for amount of parallel reduction stream for DG/DB
151
+ GROUP_SIZE_M = 32
152
+ if N <= 8192:
153
+ GROUP_SIZE_M = 64
154
+ if N <= 4096:
155
+ GROUP_SIZE_M = 96
156
+ if N <= 2048:
157
+ GROUP_SIZE_M = 128
158
+ if N <= 1024:
159
+ GROUP_SIZE_M = 256
160
+
161
+ if dy.dtype == torch.float32:
162
+ GROUP_SIZE_M = GROUP_SIZE_M // 2
163
+
164
+ # allocate output
165
+ dy = dy.contiguous()
166
+ dx = torch.empty_like(dy)
167
+
168
+ # Check the tensor shapes and layouts
169
+ # we suppose in the kernel that they have the same size and are contiguous
170
+ assert (
171
+ dy.numel() == x.numel()
172
+ ), "Something is wrong in the backward graph, possibly because of an inplace operation after the layernorm"
173
+
174
+ # enqueue kernel using forward pass heuristics
175
+ # also compute partial sums for DW and DB
176
+ num_warps = min(max(ctx.BLOCK_SIZE_N // 256, 1), 16)
177
+
178
+ # fmt: off
179
+ srms_norm_bwd_dx_fused[(M,)](
180
+ dx, dy, x,
181
+ rstd,
182
+ x.stride(0),
183
+ N,
184
+ BLOCK_SIZE_N=ctx.BLOCK_SIZE_N,
185
+ num_warps=num_warps
186
+ )
187
+ # fmt: on
188
+
189
+ dx = dx.reshape_as(dy)
190
+ return dx, None, None
191
+
192
+
193
+ class SimpleRMSNorm(torch.nn.Module):
194
+
195
+ def __init__(self, dim: int, eps: float = 1e-6):
196
+ super().__init__()
197
+ self.eps = eps
198
+ self.dim = dim
199
+
200
+ def forward(self, x):
201
+ return _SrmsNorm.apply(x, self.eps)
tokenizer_config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": true,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|endoftext|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "errors": "replace",
22
+ "model_max_length": 1000000000000000019884624838656,
23
+ "pad_token": null,
24
+ "tokenizer_class": "GPT2Tokenizer",
25
+ "unk_token": {
26
+ "__type": "AddedToken",
27
+ "content": "<|endoftext|>",
28
+ "lstrip": false,
29
+ "normalized": true,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ }
33
+ }
utils.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import sys
4
+
5
+ import torch
6
+ from torch import nn
7
+ import torch.distributed as dist
8
+ import torch.nn.functional as F
9
+
10
+ from .norm import SimpleRMSNorm as SimpleRMSNormTorch
11
+ from .srmsnorm_triton import SimpleRMSNorm as SimpleRMSNormTriton
12
+
13
+ use_triton = eval(os.environ.get("use_triton", default="True"))
14
+ debug = eval(os.environ.get("debug", default="False"))
15
+
16
+ if use_triton:
17
+ SimpleRMSNorm = SimpleRMSNormTriton
18
+ else:
19
+ SimpleRMSNorm = SimpleRMSNormTorch
20
+
21
+ logging.basicConfig(
22
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
23
+ datefmt="%Y-%m-%d %H:%M:%S",
24
+ level=os.environ.get("LOGLEVEL", "INFO").upper(),
25
+ stream=sys.stdout,
26
+ )
27
+ logger = logging.getLogger("print_config")
28
+
29
+ BASE_DIM = 256
30
+
31
+
32
+ def is_dist_avail_and_initialized():
33
+ if not dist.is_available():
34
+ return False
35
+ if not dist.is_initialized():
36
+ return False
37
+ return True
38
+
39
+
40
+ def get_world_size():
41
+ if not is_dist_avail_and_initialized():
42
+ return 1
43
+ return dist.get_world_size()
44
+
45
+
46
+ def get_rank():
47
+ if not is_dist_avail_and_initialized():
48
+ return 0
49
+ return dist.get_rank()
50
+
51
+
52
+ def is_main_process():
53
+ return get_rank() == 0
54
+
55
+
56
+ def logging_info(string):
57
+ if is_main_process():
58
+ logger.info(string)
59
+
60
+
61
+ def print_params(**kwargs):
62
+ if is_main_process():
63
+ logger.info(f"start print config of {kwargs['__class__']}")
64
+ for key in kwargs:
65
+ if key in ["__class__", "self"]:
66
+ continue
67
+ logger.info(f"{key}: {kwargs[key]}")
68
+ logger.info(f"end print config of {kwargs['__class__']}")
69
+
70
+
71
+ def print_config(config):
72
+ if is_main_process():
73
+ logger.info(f"start print config of {config['__class__']}")
74
+ for key in config:
75
+ if key in ["__class__", "self"]:
76
+ continue
77
+ logger.info(f"{key}: {config[key]}")
78
+ logger.info(f"end print config of {config['__class__']}")
79
+
80
+
81
+ def print_module(module):
82
+ named_modules = set()
83
+ for p in module.named_modules():
84
+ named_modules.update([p[0]])
85
+ named_modules = list(named_modules)
86
+
87
+ string_repr = ""
88
+ for p in module.named_parameters():
89
+ name = p[0].split(".")[0]
90
+ if name not in named_modules:
91
+ string_repr = (string_repr + "(" + name + "): " + "Tensor(" +
92
+ str(tuple(p[1].shape)) + ", requires_grad=" +
93
+ str(p[1].requires_grad) + ")\n")
94
+
95
+ return string_repr.rstrip("\n")
96
+
97
+
98
+ def get_activation_fn(activation):
99
+ if debug:
100
+ logger.info(f"activation: {activation}")
101
+ if activation == "gelu":
102
+ return F.gelu
103
+ elif activation == "relu":
104
+ return F.relu
105
+ elif activation == "elu":
106
+ return F.elu
107
+ elif activation == "sigmoid":
108
+ return F.sigmoid
109
+ elif activation == "exp":
110
+
111
+ def f(x):
112
+ with torch.no_grad():
113
+ x_max = torch.max(x, dim=-1, keepdims=True).values
114
+ y = torch.exp(x - x_max)
115
+
116
+ return y
117
+
118
+ return f
119
+ elif activation == "leak":
120
+ return F.leaky_relu
121
+ elif activation == "1+elu":
122
+
123
+ def f(x):
124
+ return 1 + F.elu(x)
125
+
126
+ return f
127
+ elif activation == "2+elu":
128
+
129
+ def f(x):
130
+ return 2 + F.elu(x)
131
+
132
+ return f
133
+ elif activation == "silu" or activation == "swish":
134
+ return F.silu
135
+ elif activation == "sine":
136
+ return torch.sin
137
+ else:
138
+ logger.info(
139
+ f"activation: does not support {activation}, use Identity!!!")
140
+ return lambda x: x
141
+
142
+
143
+ def get_norm_fn(norm_type):
144
+ if norm_type == "simplermsnorm":
145
+ return SimpleRMSNorm
146
+ else:
147
+ return nn.LayerNorm
148
+
149
+
150
+ def convert_to_multiple_of_base(x):
151
+ return BASE_DIM * ((x + BASE_DIM - 1) // BASE_DIM)
vocab.json ADDED
The diff for this file is too large to render. See raw diff