OpenNLPLab commited on
Commit
0b12900
1 Parent(s): 9c37ff2

Publish code

Browse files
config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "TransnormerForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_transnormer.TransnormerConfig",
7
+ "AutoModelForCausalLM": "modeling_transnormer.TransnormerForCausalLM"
8
+ },
9
+ "pad_token_id": 0,
10
+ "bos_token_id": 1,
11
+ "eos_token_id": 2,
12
+ "model_max_length": 8192,
13
+ "vocab_size": 64000,
14
+ "use_cache": true,
15
+ "init_std": 0.02,
16
+ "decoder_embed_dim": 4096,
17
+ "decoder_layers": 30,
18
+ "decoder_attention_heads": 32,
19
+ "no_scale_embedding": true,
20
+ "add_bos_token": false,
21
+ "norm_type": "simplermsnorm",
22
+ "linear_use_lrpe_list": [
23
+ 1,
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
+ 0,
46
+ 0,
47
+ 0,
48
+ 0,
49
+ 0,
50
+ 0,
51
+ 0,
52
+ 0
53
+ ],
54
+ "hidden_dim": 4096,
55
+ "linear_act_fun": "swish",
56
+ "glu_dim": 11008,
57
+ "bias": false,
58
+ "torch_dtype": "bfloat16",
59
+ "transformers_version": "4.32.0"
60
+ }
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.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": 4096,
6
+ "temperature": 1.0,
7
+ "repetition_penalty": 1.03,
8
+ "do_sample": true
9
+ }
lightning_attention.py ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "Lightning 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
+ _fwd_kernel[grid](
370
+ q,
371
+ k,
372
+ v,
373
+ o,
374
+ s,
375
+ q.stride(0),
376
+ q.stride(1),
377
+ q.stride(2),
378
+ q.stride(3),
379
+ k.stride(0),
380
+ k.stride(1),
381
+ k.stride(2),
382
+ k.stride(3),
383
+ v.stride(0),
384
+ v.stride(1),
385
+ v.stride(2),
386
+ v.stride(3),
387
+ o.stride(0),
388
+ o.stride(1),
389
+ o.stride(2),
390
+ o.stride(3),
391
+ s.stride(0),
392
+ q.shape[0],
393
+ q.shape[1],
394
+ q.shape[2],
395
+ BLOCK_M=BLOCK_M,
396
+ BLOCK_DMODEL_QK=Lk,
397
+ BLOCK_N=BLOCK_N,
398
+ BLOCK_DMODEL_V=Lv,
399
+ IS_CAUSAL=causal,
400
+ USE_DECAY=use_decay,
401
+ num_warps=num_warps,
402
+ num_stages=num_stages,
403
+ )
404
+
405
+ ctx.save_for_backward(q, k, v, s)
406
+ ctx.grid = grid
407
+ ctx.BLOCK_M = BLOCK_M
408
+ ctx.BLOCK_DMODEL_QK = Lk
409
+ ctx.BLOCK_N = BLOCK_N
410
+ ctx.BLOCK_DMODEL_V = Lv
411
+ ctx.causal = causal
412
+ ctx.use_decay = use_decay
413
+ return o
414
+
415
+ @staticmethod
416
+ def backward(ctx, do):
417
+ q, k, v, s = ctx.saved_tensors
418
+ BLOCK_M = 32
419
+ BLOCK_N = 32
420
+ num_warps = 4
421
+ num_stages = 1
422
+
423
+ do = do.contiguous()
424
+ dq = torch.zeros_like(q, dtype=torch.float32)
425
+ dk = torch.empty_like(k)
426
+ dv = torch.empty_like(v)
427
+
428
+ grid_kv = (triton.cdiv(k.shape[2],
429
+ BLOCK_N), k.shape[0] * k.shape[1], 1)
430
+ _bwd_kernel_kv[grid_kv](
431
+ q,
432
+ k,
433
+ v,
434
+ s,
435
+ do,
436
+ dq,
437
+ dk,
438
+ dv,
439
+ q.stride(0),
440
+ q.stride(1),
441
+ q.stride(2),
442
+ q.stride(3),
443
+ k.stride(0),
444
+ k.stride(1),
445
+ k.stride(2),
446
+ k.stride(3),
447
+ v.stride(0),
448
+ v.stride(1),
449
+ v.stride(2),
450
+ v.stride(3),
451
+ do.stride(0),
452
+ do.stride(1),
453
+ do.stride(2),
454
+ do.stride(3),
455
+ s.stride(0),
456
+ q.shape[0],
457
+ q.shape[1],
458
+ q.shape[2],
459
+ grid_kv[0],
460
+ BLOCK_M=BLOCK_M,
461
+ BLOCK_DMODEL_QK=ctx.BLOCK_DMODEL_QK,
462
+ BLOCK_N=BLOCK_N,
463
+ BLOCK_DMODEL_V=ctx.BLOCK_DMODEL_V,
464
+ CAUSAL=ctx.causal,
465
+ USE_DECAY=ctx.use_decay,
466
+ num_warps=num_warps,
467
+ num_stages=num_stages,
468
+ )
469
+
470
+ grid_q = (triton.cdiv(q.shape[2], BLOCK_M), q.shape[0] * q.shape[1], 1)
471
+
472
+ _bwd_kernel_q[grid_q](
473
+ q,
474
+ k,
475
+ v,
476
+ s,
477
+ do,
478
+ dq,
479
+ dk,
480
+ dv,
481
+ q.stride(0),
482
+ q.stride(1),
483
+ q.stride(2),
484
+ q.stride(3),
485
+ k.stride(0),
486
+ k.stride(1),
487
+ k.stride(2),
488
+ k.stride(3),
489
+ v.stride(0),
490
+ v.stride(1),
491
+ v.stride(2),
492
+ v.stride(3),
493
+ do.stride(0),
494
+ do.stride(1),
495
+ do.stride(2),
496
+ do.stride(3),
497
+ s.stride(0),
498
+ q.shape[0],
499
+ q.shape[1],
500
+ q.shape[2],
501
+ grid_q[0],
502
+ BLOCK_M=BLOCK_M,
503
+ BLOCK_DMODEL_QK=ctx.BLOCK_DMODEL_QK,
504
+ BLOCK_N=BLOCK_N,
505
+ BLOCK_DMODEL_V=ctx.BLOCK_DMODEL_V,
506
+ CAUSAL=ctx.causal,
507
+ USE_DECAY=ctx.use_decay,
508
+ num_warps=num_warps,
509
+ num_stages=num_stages,
510
+ )
511
+
512
+ return dq.to(q.dtype), dk, dv, None, None
513
+
514
+
515
+ attention = _attention.apply
516
+
517
+
518
+ def lightning_attention(q, k, v, causal, ed):
519
+ d = q.shape[-1]
520
+ e = v.shape[-1]
521
+ # arr = f(d)
522
+ if d >= 128:
523
+ m = 128
524
+ else:
525
+ m = 64
526
+ arr = [m * i for i in range(d // m + 1)]
527
+ if arr[-1] != d:
528
+ arr.append(d)
529
+ n = len(arr)
530
+ output = 0
531
+ for i in range(n - 1):
532
+ s = arr[i]
533
+ e = arr[i + 1]
534
+ q1 = q[..., s:e]
535
+ k1 = k[..., s:e]
536
+ o = attention(q1, k1, v, causal, ed)
537
+ output = output + o
538
+
539
+ return output
modeling_transnormer.py ADDED
@@ -0,0 +1,1113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 OpenNLPLab
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # coding=utf-8
17
+ """ PyTorch Transnormer model."""
18
+ import math
19
+ import os
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ from einops import rearrange
23
+ import numpy as np
24
+ import torch
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (
31
+ BaseModelOutputWithPast,
32
+ CausalLMOutputWithPast,
33
+ SequenceClassifierOutputWithPast,
34
+ )
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.utils import (
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ logging,
40
+ replace_return_docstrings,
41
+ )
42
+
43
+ from .configuration_transnormer import TransnormerConfig
44
+ from .norm import SimpleRMSNorm as SimpleRMSNorm_torch
45
+ from .srmsnorm_triton import SimpleRMSNorm as SimpleRMSNorm_triton
46
+ from .utils import (
47
+ get_activation_fn,
48
+ get_norm_fn,
49
+ logging_info,
50
+ print_module,
51
+ print_params,
52
+ )
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+ _CONFIG_FOR_DOC = "TransnormerConfig"
57
+
58
+ use_triton = eval(os.environ.get("use_triton", default="True"))
59
+ debug = eval(os.environ.get("debug", default="False"))
60
+
61
+ if use_triton:
62
+ try:
63
+ from .lightning_attention import lightning_attention
64
+
65
+ has_lightning_attention = True
66
+ except (ImportError, ModuleNotFoundError):
67
+ has_lightning_attention = False
68
+ else:
69
+ has_lightning_attention = False
70
+
71
+ if debug:
72
+ logger.info(f"Use triton: {use_triton}")
73
+ logger.info(f"Use lightning attention: {has_lightning_attention}")
74
+ logger.info(f"Debug mode: {debug}, {type(debug)}")
75
+
76
+ if not has_lightning_attention:
77
+
78
+ def linear_attention(q, k, v, attn_mask):
79
+ energy = torch.einsum("... n d, ... m d -> ... n m", q, k)
80
+ energy = energy * attn_mask
81
+ output = torch.einsum("... n m, ... m d -> ... n d", energy, v)
82
+
83
+ return output
84
+
85
+
86
+ ########## start Transnormer
87
+ ##### Linearized Relative Positional Encoding: https://openreview.net/forum?id=xoLyps2qWc&referrer=%5BAuthor%20Console%5D(%2Fgroup%3Fid%3DTMLR%2FAuthors%23your-submissions)
88
+ class Lrpe(nn.Module):
89
+ def __init__(
90
+ self,
91
+ num_heads=8,
92
+ embed_dim=64,
93
+ ):
94
+ super().__init__()
95
+ d = num_heads * embed_dim
96
+
97
+ self.index = torch.empty(0)
98
+ self.theta = nn.Parameter(
99
+ 10000 ** (-2 / d * torch.arange(d)).reshape(num_heads, 1, -1)
100
+ )
101
+
102
+ def extra_repr(self):
103
+ return print_module(self)
104
+
105
+ def forward(self, x, offset=0):
106
+ # x: b, h, n, d
107
+ # offset: for k, v cache
108
+ n = x.shape[-2]
109
+ if self.index.shape[0] < n:
110
+ self.index = torch.arange(n).reshape(1, -1, 1).to(x)
111
+ index = self.index[:, :n] + offset
112
+ theta = self.theta * index
113
+ x = torch.concat([x * torch.cos(theta), x * torch.sin(theta)], dim=-1)
114
+
115
+ return x
116
+
117
+
118
+ class GLU(nn.Module):
119
+ def __init__(self, d1, d2, bias=False):
120
+ super().__init__()
121
+ if debug:
122
+ # get local varables
123
+ params = locals()
124
+ # print params
125
+ print_params(**params)
126
+
127
+ self.l1 = nn.Linear(d1, d2, bias=bias)
128
+ self.l2 = nn.Linear(d1, d2, bias=bias)
129
+ self.l3 = nn.Linear(d2, d1, bias=bias)
130
+
131
+ def forward(self, x):
132
+ o1 = self.l1(x)
133
+ o2 = self.l2(x)
134
+ output = o1 * o2
135
+ output = self.l3(output)
136
+
137
+ return output
138
+
139
+
140
+ class NormLinearAttention(nn.Module):
141
+ def __init__(
142
+ self,
143
+ embed_dim,
144
+ hidden_dim,
145
+ num_heads,
146
+ linear_act_fun="silu",
147
+ norm_type="simplermsnorm",
148
+ linear_use_lrpe=False,
149
+ bias=False,
150
+ ):
151
+ super().__init__()
152
+ if debug:
153
+ # get local varables
154
+ params = locals()
155
+ # print params
156
+ print_params(**params)
157
+
158
+ self.out_proj = nn.Linear(hidden_dim, embed_dim, bias=bias)
159
+ self.act = get_activation_fn(linear_act_fun)
160
+ self.num_heads = num_heads
161
+ self.embed_dim = embed_dim
162
+ self.head_dim = self.embed_dim // self.num_heads
163
+ self.norm = get_norm_fn(norm_type)(hidden_dim)
164
+
165
+ self.linear_use_lrpe = linear_use_lrpe
166
+ if self.linear_use_lrpe:
167
+ self.lrpe = Lrpe(
168
+ num_heads=self.num_heads,
169
+ embed_dim=self.head_dim,
170
+ )
171
+
172
+ self.qkvu_proj = nn.Linear(embed_dim, 4 * hidden_dim, bias=bias)
173
+
174
+ # for inference only
175
+ self.offset = 0
176
+
177
+ def forward(
178
+ self,
179
+ x,
180
+ attn_mask: Optional[torch.Tensor] = None, # (b, h, n, m)
181
+ attn_padding_mask: Optional[torch.Tensor] = None, # (b, m)
182
+ output_attentions: bool = False,
183
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
184
+ use_cache: bool = False,
185
+ slope_rate: Optional[torch.Tensor] = None,
186
+ ):
187
+ do_eval = eval(os.environ.get("do_eval", default="False"))
188
+ if (not self.training) and (not do_eval):
189
+ return self.inference(
190
+ x,
191
+ attn_mask,
192
+ attn_padding_mask,
193
+ output_attentions,
194
+ past_key_value,
195
+ use_cache,
196
+ slope_rate,
197
+ )
198
+ # x: b n d
199
+ n = x.shape[-2]
200
+ # linear map
201
+ q, k, v, u = self.qkvu_proj(x).chunk(4, dim=-1)
202
+ # reshape
203
+ q, k, v = map(
204
+ lambda x: rearrange(x, "b n (h d) -> b h n d", h=self.num_heads), [q, k, v]
205
+ )
206
+ # act
207
+ q = self.act(q)
208
+ k = self.act(k)
209
+
210
+ q_offset = 0
211
+ # lrpe relys on position, get cache first
212
+ if past_key_value is not None:
213
+ # reuse k, v, for evaluation only
214
+ k = torch.cat([past_key_value[0], k], dim=-2)
215
+ v = torch.cat([past_key_value[1], v], dim=-2)
216
+ q_offset = past_key_value[0].shape[-2]
217
+
218
+ past_key_value = (k, v) if use_cache else None
219
+
220
+ # lrpe
221
+ if self.linear_use_lrpe:
222
+ q = self.lrpe(q, offset=q_offset)
223
+ k = self.lrpe(k)
224
+
225
+ if attn_mask == None:
226
+ attn_mask = (torch.tril(torch.ones(n, n))).to(q)
227
+
228
+ if attn_padding_mask is not None:
229
+ v = v.masked_fill(
230
+ (1 - attn_padding_mask).unsqueeze(1).unsqueeze(-1).to(torch.bool), 0
231
+ )
232
+
233
+ if not has_lightning_attention:
234
+ if slope_rate != None:
235
+ attn_mask = torch.exp(slope_rate * attn_mask)
236
+ output = linear_attention(q, k, v, attn_mask)
237
+ else:
238
+ output = lightning_attention(
239
+ q, k, v, True, slope_rate.squeeze(-1).squeeze(-1)
240
+ )
241
+
242
+ # reshape
243
+ output = rearrange(output, "b h n d -> b n (h d)")
244
+ # normalize
245
+ output = self.norm(output)
246
+ # gate
247
+ output = u * output
248
+ # outproj
249
+ output = self.out_proj(output)
250
+
251
+ if not output_attentions:
252
+ attn_weights = None
253
+ else:
254
+ attn_weights = torch.einsum("... n d, ... m d -> ... n m", q, k)
255
+
256
+ return output, attn_weights, past_key_value
257
+
258
+ def inference(
259
+ self,
260
+ x,
261
+ attn_mask: Optional[torch.Tensor] = None, # (b, h, n, m)
262
+ attn_padding_mask: Optional[torch.Tensor] = None, # (b, m)
263
+ output_attentions: bool = False,
264
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
265
+ use_cache: bool = False,
266
+ slope_rate: Optional[torch.Tensor] = None, # (h, 1, 1)
267
+ ):
268
+ # x: b n d
269
+ n = x.shape[-2]
270
+ # linear map
271
+ q, k, v, u = self.qkvu_proj(x).chunk(4, dim=-1)
272
+ # reshape
273
+ q, k, v = map(
274
+ lambda x: rearrange(x, "b n (h d) -> b h n d", h=self.num_heads), [q, k, v]
275
+ )
276
+ # act
277
+ q = self.act(q)
278
+ k = self.act(k)
279
+
280
+ # rpe
281
+ if self.linear_use_lrpe:
282
+ q = self.lrpe(q, offset=self.offset)
283
+ k = self.lrpe(k)
284
+
285
+ if past_key_value == None:
286
+ self.offset = q.shape[-2]
287
+ else:
288
+ self.offset += 1
289
+
290
+ ratio = torch.exp(-slope_rate)
291
+
292
+ # only use for the first time
293
+ if past_key_value == None:
294
+ if attn_mask == None:
295
+ attn_mask = (torch.tril(torch.ones(n, n))).to(q)
296
+ if slope_rate != None:
297
+ attn_mask = torch.exp(slope_rate * attn_mask)
298
+
299
+ if attn_padding_mask is not None:
300
+ attn_mask = attn_mask.masked_fill(
301
+ (1 - attn_padding_mask).unsqueeze(1).unsqueeze(2).to(torch.bool),
302
+ 0,
303
+ )
304
+ energy = torch.einsum("... n d, ... m d -> ... n m", q, k)
305
+
306
+ if attn_mask != None:
307
+ energy = energy * attn_mask
308
+
309
+ output = torch.einsum("... n m, ... m d -> ... n d", energy, v)
310
+
311
+ eval_and_not_generate = eval(
312
+ os.environ.get("eval_and_not_generate", default="False")
313
+ )
314
+ if eval_and_not_generate:
315
+ kv = None
316
+ else:
317
+ # b, h, n, e, d
318
+ kv_outproduct = torch.einsum("... n e, ... n d -> ... n e d", k, v)
319
+ # 1, 1, n, 1, 1
320
+ index = torch.arange(n - 1, -1, -1).reshape(1, 1, -1, 1, 1).to(x)
321
+ # (h, 1, 1) -> (1, h, 1, 1, 1); (1, h, 1, 1, 1), (1, 1, n, 1, 1) -> (1, h, n, 1, 1)
322
+ decay = ratio.unsqueeze(0).unsqueeze(-1) ** index
323
+
324
+ kv_outproduct_with_decay = kv_outproduct * decay
325
+ kv = torch.sum(kv_outproduct_with_decay, dim=-3)
326
+ else:
327
+ kv = past_key_value
328
+
329
+ output = []
330
+ for i in range(n):
331
+ kv = ratio * kv + torch.einsum(
332
+ "... n d, ... n e -> ... d e",
333
+ k[:, :, i : i + 1],
334
+ v[:, :, i : i + 1],
335
+ )
336
+ qkv = torch.einsum(
337
+ "... n e, ... e d -> ... n d", q[:, :, i : i + 1], kv
338
+ )
339
+ output.append(qkv)
340
+ output = torch.concat(output, dim=-2)
341
+
342
+ # reshape
343
+ output = rearrange(output, "b h n d -> b n (h d)")
344
+ # normalize
345
+ output = self.norm(output)
346
+ # gate
347
+ output = u * output
348
+ # outproj
349
+ output = self.out_proj(output)
350
+
351
+ attn_weights = None
352
+
353
+ return output, attn_weights, kv
354
+
355
+
356
+ class TransnormerDecoderLayer(nn.Module):
357
+ def __init__(self, config: TransnormerConfig):
358
+ super().__init__()
359
+ self.embed_dim = config.decoder_embed_dim
360
+ ##### normalize
361
+ norm_type = config.norm_type
362
+ if debug:
363
+ logging_info(f"Decoder Norm Type: {norm_type}")
364
+ self.token_norm = get_norm_fn(norm_type)(self.embed_dim)
365
+ self.channel_norm = get_norm_fn(norm_type)(self.embed_dim)
366
+
367
+ ##### token mixer
368
+ self.token_mixer = self.build_token_mixer(
369
+ self.embed_dim,
370
+ config,
371
+ )
372
+
373
+ ##### channel mixer
374
+ self.glu_dim = config.glu_dim
375
+ if self.glu_dim == -1:
376
+ self.glu_dim = self.embed_dim
377
+ bias = config.bias
378
+ self.channel_mixer = GLU(self.embed_dim, self.glu_dim, bias)
379
+
380
+ def build_token_mixer(self, embed_dim, config):
381
+ return NormLinearAttention(
382
+ embed_dim=embed_dim,
383
+ hidden_dim=config.hidden_dim,
384
+ num_heads=config.decoder_attention_heads,
385
+ linear_act_fun=config.linear_act_fun,
386
+ norm_type=config.norm_type,
387
+ linear_use_lrpe=config.linear_use_lrpe,
388
+ bias=config.bias,
389
+ )
390
+
391
+ def residual_connection(self, x, residual):
392
+ return residual + x
393
+
394
+ def forward(
395
+ self,
396
+ x,
397
+ attn_mask: Optional[torch.Tensor] = None,
398
+ attn_padding_mask: Optional[torch.Tensor] = None,
399
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
400
+ output_attentions: Optional[bool] = False,
401
+ use_cache: Optional[bool] = False,
402
+ slope_rate: Optional[torch.Tensor] = None, # (h, 1, 1)
403
+ ):
404
+ residual = x
405
+ x = self.token_norm(x)
406
+ x, self_attn_weights, present_key_value = self.token_mixer(
407
+ x=x,
408
+ attn_mask=attn_mask,
409
+ attn_padding_mask=attn_padding_mask,
410
+ past_key_value=past_key_value,
411
+ output_attentions=output_attentions,
412
+ use_cache=use_cache,
413
+ slope_rate=slope_rate,
414
+ )
415
+ x = self.residual_connection(x, residual)
416
+
417
+ residual = x
418
+ x = self.channel_norm(x)
419
+ x = self.channel_mixer(x)
420
+ x = self.residual_connection(x, residual)
421
+
422
+ outputs = (x,)
423
+
424
+ if output_attentions:
425
+ outputs += (self_attn_weights,)
426
+
427
+ if use_cache:
428
+ outputs += (present_key_value,)
429
+
430
+ return outputs
431
+
432
+
433
+ TRANSNORMER_START_DOCSTRING = r"""
434
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
435
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
436
+ etc.)
437
+
438
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
439
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
440
+ and behavior.
441
+
442
+ Parameters:
443
+ config ([`TransnormerConfig`]):
444
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
445
+ load the weights associated with the model, only the configuration. Check out the
446
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
447
+ """
448
+
449
+
450
+ @add_start_docstrings(
451
+ TRANSNORMER_START_DOCSTRING,
452
+ )
453
+ class TransnormerPreTrainedModel(PreTrainedModel):
454
+ config_class = TransnormerConfig
455
+ base_model_prefix = "model"
456
+ supports_gradient_checkpointing = True
457
+ _no_split_modules = ["TransnormerDecoderLayer"]
458
+ _skip_keys_device_placement = "past_key_values"
459
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
460
+
461
+ def _init_weights(self, module):
462
+ std = self.config.init_std
463
+ if isinstance(module, nn.Linear):
464
+ module.weight.data.normal_(mean=0.0, std=std)
465
+ if module.bias is not None:
466
+ module.bias.data.zero_()
467
+ elif isinstance(module, nn.Embedding):
468
+ module.weight.data.normal_(mean=0.0, std=std)
469
+ if module.padding_idx is not None:
470
+ module.weight.data[module.padding_idx].zero_()
471
+
472
+ def _set_gradient_checkpointing(self, module, value=False):
473
+ if isinstance(module, TransnormerModel):
474
+ module.gradient_checkpointing = value
475
+
476
+
477
+ TRANSNORMER_INPUTS_DOCSTRING = r"""
478
+ Args:
479
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
480
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
481
+ it.
482
+
483
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
484
+ [`PreTrainedTokenizer.__call__`] for details.
485
+
486
+ [What are input IDs?](../glossary#input-ids)
487
+ attn_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
488
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
489
+
490
+ - 1 for tokens that are **not masked**,
491
+ - 0 for tokens that are **masked**.
492
+
493
+ [What are attention masks?](../glossary#attention-mask)
494
+
495
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
496
+ [`PreTrainedTokenizer.__call__`] for details.
497
+
498
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
499
+ `past_key_values`).
500
+
501
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attn_mask`]
502
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
503
+ information on the default strategy.
504
+
505
+ - 1 indicates the head is **not masked**,
506
+ - 0 indicates the head is **masked**.
507
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
508
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
509
+ config.n_positions - 1]`.
510
+
511
+ [What are position IDs?](../glossary#position-ids)
512
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
513
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
514
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
515
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
516
+
517
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
518
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
519
+
520
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
521
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
522
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
523
+ use_cache (`bool`, *optional*):
524
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
525
+ `past_key_values`).
526
+ output_attentions (`bool`, *optional*):
527
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
528
+ tensors for more detail.
529
+ output_hidden_states (`bool`, *optional*):
530
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
531
+ more detail.
532
+ return_dict (`bool`, *optional*):
533
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
534
+ """
535
+
536
+
537
+ @add_start_docstrings(
538
+ TRANSNORMER_START_DOCSTRING,
539
+ )
540
+ class TransnormerModel(TransnormerPreTrainedModel):
541
+ """
542
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TransnormerDecoderLayer`]
543
+
544
+ Args:
545
+ config: TransnormerConfig
546
+ """
547
+
548
+ def __init__(self, config: TransnormerConfig):
549
+ super().__init__(config)
550
+ # hf origin
551
+ self.padding_idx = config.pad_token_id
552
+ self.vocab_size = config.vocab_size
553
+ self.gradient_checkpointing = False
554
+ # mask
555
+ self._linear_attn_mask = torch.empty(0)
556
+ # config
557
+ self.linear_use_lrpe_list = config.linear_use_lrpe_list
558
+ self.num_layers = config.decoder_layers
559
+ # h, 1, 1
560
+ self.slopes = self._build_slope_tensor(config.decoder_attention_heads)
561
+
562
+ # params
563
+ self.embed_tokens = nn.Embedding(
564
+ config.vocab_size, config.decoder_embed_dim, self.padding_idx
565
+ )
566
+ self.layers = nn.ModuleList([])
567
+ for i in range(config.decoder_layers):
568
+ if len(self.linear_use_lrpe_list) > 0:
569
+ config.linear_use_lrpe = self.linear_use_lrpe_list[i]
570
+ self.layers.append(TransnormerDecoderLayer(config))
571
+
572
+ self.final_norm = get_norm_fn(config.norm_type)(config.decoder_embed_dim)
573
+ self.embed_dim = config.decoder_embed_dim
574
+ self.embed_scale = (
575
+ 1.0 if config.no_scale_embedding else math.sqrt(self.embed_dim)
576
+ )
577
+
578
+ # Initialize weights and apply final processing
579
+ self.post_init()
580
+
581
+ @staticmethod
582
+ def _build_slope_tensor(n_attention_heads: int):
583
+ def get_slopes(n):
584
+ def get_slopes_power_of_2(n):
585
+ start = 2 ** (-(2 ** -(math.log2(n) - 3)))
586
+ ratio = start
587
+ return [start * ratio**i for i in range(n)]
588
+
589
+ if math.log2(n).is_integer():
590
+ return get_slopes_power_of_2(
591
+ n
592
+ ) # In the paper, we only train models that have 2^a heads for some a. This function has
593
+ else: # some good properties that only occur when the input is a power of 2. To maintain that even
594
+ closest_power_of_2 = 2 ** math.floor(
595
+ math.log2(n)
596
+ ) # when the number of heads is not a power of 2, we use this workaround.
597
+ return (
598
+ get_slopes_power_of_2(closest_power_of_2)
599
+ + get_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]
600
+ )
601
+
602
+ # h, 1, 1
603
+ slopes = torch.tensor(get_slopes(n_attention_heads)).reshape(
604
+ n_attention_heads, 1, 1
605
+ )
606
+
607
+ return slopes
608
+
609
+ def extra_repr(self):
610
+ return print_module(self)
611
+
612
+ def get_input_embeddings(self):
613
+ return self.embed_tokens
614
+
615
+ def set_input_embeddings(self, value):
616
+ self.embed_tokens = value
617
+
618
+ def _prepare_decoder_linear_attn_mask(
619
+ self, input_shape, inputs_embeds, past_key_values_length
620
+ ):
621
+ bsz, tgt_len = input_shape
622
+ src_len = tgt_len + past_key_values_length
623
+
624
+ def power_log(x):
625
+ return 2 ** (math.ceil(math.log(x, 2)))
626
+
627
+ n = power_log(max(tgt_len, src_len))
628
+ if self._linear_attn_mask.shape[-1] < n:
629
+
630
+ def get_mask(n):
631
+ mask = torch.triu(torch.zeros(n, n).float().fill_(float("-inf")), 1)
632
+ # no slope version
633
+ # -n, ..., -2, -1, 0
634
+ for i in range(n):
635
+ x = torch.arange(i + 1)
636
+ y = x
637
+ mask[i, : i + 1] = -torch.flip(y, [0])
638
+
639
+ return mask
640
+
641
+ arr = []
642
+ for slope in self.slopes:
643
+ arr.append(get_mask(n))
644
+ self._linear_attn_mask = torch.stack(arr, dim=0).to(inputs_embeds)
645
+
646
+ linear_attn_mask = self._linear_attn_mask[:, -tgt_len:, -src_len:]
647
+ num_heads = linear_attn_mask.shape[0]
648
+
649
+ return linear_attn_mask[None, :, :, :].expand(bsz, num_heads, tgt_len, src_len)
650
+
651
+ @add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)
652
+ def forward(
653
+ self,
654
+ input_ids: torch.LongTensor = None,
655
+ attn_padding_mask: Optional[torch.Tensor] = None,
656
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
657
+ inputs_embeds: Optional[torch.FloatTensor] = None,
658
+ use_cache: Optional[bool] = None,
659
+ output_attentions: Optional[bool] = None,
660
+ output_hidden_states: Optional[bool] = None,
661
+ return_dict: Optional[bool] = None,
662
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
663
+ output_attentions = (
664
+ output_attentions
665
+ if output_attentions is not None
666
+ else self.config.output_attentions
667
+ )
668
+ output_hidden_states = (
669
+ output_hidden_states
670
+ if output_hidden_states is not None
671
+ else self.config.output_hidden_states
672
+ )
673
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
674
+
675
+ return_dict = (
676
+ return_dict if return_dict is not None else self.config.use_return_dict
677
+ )
678
+
679
+ # retrieve input_ids and inputs_embeds
680
+ if input_ids is not None and inputs_embeds is not None:
681
+ raise ValueError(
682
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
683
+ )
684
+ elif input_ids is not None:
685
+ batch_size, seq_length = input_ids.shape
686
+ elif inputs_embeds is not None:
687
+ batch_size, seq_length, _ = inputs_embeds.shape
688
+ else:
689
+ raise ValueError(
690
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
691
+ )
692
+
693
+ seq_length_with_past = seq_length
694
+ past_key_values_length = 0
695
+
696
+ if past_key_values is not None:
697
+ past_key_values_length = past_key_values[0][0].shape[-2]
698
+ seq_length_with_past = seq_length_with_past + past_key_values_length
699
+
700
+ if inputs_embeds is None:
701
+ # !!! use embed_scale
702
+ inputs_embeds = self.embed_scale * self.embed_tokens(input_ids)
703
+
704
+ hidden_states = inputs_embeds
705
+
706
+ if self.gradient_checkpointing and self.training:
707
+ if use_cache:
708
+ logger.warning_once(
709
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
710
+ )
711
+ use_cache = False
712
+
713
+ # decoder layers
714
+ all_hidden_states = () if output_hidden_states else None
715
+ all_self_attns = () if output_attentions else None
716
+ next_decoder_cache = () if use_cache else None
717
+
718
+ ##### norm linear layers
719
+ linear_attn_padding_mask = attn_padding_mask
720
+ linear_attn_mask = self._prepare_decoder_linear_attn_mask(
721
+ (batch_size, seq_length), inputs_embeds, past_key_values_length
722
+ )
723
+
724
+ slope_rates = [self.slopes.to(input_ids.device) for _ in range(self.num_layers)]
725
+
726
+ for idx, layer in enumerate(self.layers):
727
+ if output_hidden_states:
728
+ all_hidden_states += (hidden_states,)
729
+
730
+ past_key_value = (
731
+ past_key_values[idx] if past_key_values is not None else None
732
+ )
733
+
734
+ slope_rate = slope_rates[idx]
735
+ slope_rate = slope_rate * (1 - idx / (self.num_layers - 1) + 1e-5)
736
+ mask = linear_attn_mask
737
+
738
+ # if self.gradient_checkpointing and self.training:
739
+
740
+ # def create_custom_forward(module):
741
+ # def custom_forward(*inputs):
742
+ # # None for past_key_value
743
+ # return module(*inputs, output_attentions, None)
744
+
745
+ # return custom_forward
746
+
747
+ # # layer_outputs = torch.utils.checkpoint.checkpoint(
748
+ # # create_custom_forward(layer),
749
+ # # hidden_states,
750
+ # # mask,
751
+ # # linear_attn_padding_mask,
752
+ # # None,
753
+ # # )
754
+ # layer_outputs = torch.utils.checkpoint.checkpoint(
755
+ # create_custom_forward(layer),
756
+ # hidden_states,
757
+ # mask,
758
+ # linear_attn_padding_mask,
759
+ # None,
760
+ # output_attentions,
761
+ # use_cache,
762
+ # slope_rate,
763
+ # )
764
+ # else:
765
+ # layer_outputs = layer(
766
+ # hidden_states,
767
+ # attn_mask=mask,
768
+ # attn_padding_mask=linear_attn_padding_mask,
769
+ # past_key_value=past_key_value,
770
+ # output_attentions=output_attentions,
771
+ # use_cache=use_cache,
772
+ # slope_rate=slope_rate,
773
+ # )
774
+
775
+ layer_outputs = layer(
776
+ hidden_states,
777
+ attn_mask=mask,
778
+ attn_padding_mask=linear_attn_padding_mask,
779
+ past_key_value=past_key_value,
780
+ output_attentions=output_attentions,
781
+ use_cache=use_cache,
782
+ slope_rate=slope_rate,
783
+ )
784
+
785
+ hidden_states = layer_outputs[0]
786
+
787
+ if use_cache:
788
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
789
+
790
+ if output_attentions:
791
+ all_self_attns += (layer_outputs[1],)
792
+
793
+ # if idx == 0:
794
+ # break
795
+
796
+ hidden_states = self.final_norm(hidden_states)
797
+
798
+ # add hidden states from the last decoder layer
799
+ if output_hidden_states:
800
+ all_hidden_states += (hidden_states,)
801
+
802
+ next_cache = next_decoder_cache if use_cache else None
803
+ if not return_dict:
804
+ return tuple(
805
+ v
806
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
807
+ if v is not None
808
+ )
809
+ return BaseModelOutputWithPast(
810
+ last_hidden_state=hidden_states,
811
+ past_key_values=next_cache,
812
+ hidden_states=all_hidden_states,
813
+ attentions=all_self_attns,
814
+ )
815
+
816
+
817
+ class TransnormerForCausalLM(TransnormerPreTrainedModel):
818
+ def __init__(self, config):
819
+ super().__init__(config)
820
+ self.model = TransnormerModel(config)
821
+ if debug:
822
+ logging_info(self.model)
823
+
824
+ # the lm_head weight is automatically tied to the embed tokens weight
825
+ self.lm_head = nn.Linear(
826
+ config.decoder_embed_dim, config.vocab_size, bias=False
827
+ )
828
+
829
+ # Initialize weights and apply final processing
830
+ self.post_init()
831
+
832
+ def get_input_embeddings(self):
833
+ return self.model.embed_tokens
834
+
835
+ def set_input_embeddings(self, value):
836
+ self.model.embed_tokens = value
837
+
838
+ def get_output_embeddings(self):
839
+ return self.lm_head
840
+
841
+ def set_output_embeddings(self, new_embeddings):
842
+ self.lm_head = new_embeddings
843
+
844
+ def set_decoder(self, decoder):
845
+ self.model = decoder
846
+
847
+ def get_decoder(self):
848
+ return self.model
849
+
850
+ @add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)
851
+ @replace_return_docstrings(
852
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
853
+ )
854
+ def forward(
855
+ self,
856
+ input_ids: torch.LongTensor = None,
857
+ attention_mask: Optional[torch.Tensor] = None,
858
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
859
+ inputs_embeds: Optional[torch.FloatTensor] = None,
860
+ labels: Optional[torch.LongTensor] = None,
861
+ use_cache: Optional[bool] = None,
862
+ output_attentions: Optional[bool] = None,
863
+ output_hidden_states: Optional[bool] = None,
864
+ return_dict: Optional[bool] = None,
865
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
866
+ r"""
867
+ Args:
868
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
869
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
870
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
871
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
872
+
873
+ Returns:
874
+
875
+ Example:
876
+
877
+ ```python
878
+ >>> from transformers import AutoTokenizer, TransnormerForCausalLM
879
+
880
+ >>> model = TransnormerForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
881
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
882
+
883
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
884
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
885
+
886
+ >>> # Generate
887
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
888
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
889
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
890
+ ```"""
891
+ output_attentions = (
892
+ output_attentions
893
+ if output_attentions is not None
894
+ else self.config.output_attentions
895
+ )
896
+ output_hidden_states = (
897
+ output_hidden_states
898
+ if output_hidden_states is not None
899
+ else self.config.output_hidden_states
900
+ )
901
+ return_dict = (
902
+ return_dict if return_dict is not None else self.config.use_return_dict
903
+ )
904
+
905
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
906
+ outputs = self.model(
907
+ input_ids=input_ids,
908
+ attn_padding_mask=attention_mask,
909
+ past_key_values=past_key_values,
910
+ inputs_embeds=inputs_embeds,
911
+ use_cache=use_cache,
912
+ output_attentions=output_attentions,
913
+ output_hidden_states=output_hidden_states,
914
+ return_dict=return_dict,
915
+ )
916
+
917
+ hidden_states = outputs[0]
918
+ logits = self.lm_head(hidden_states)
919
+
920
+ loss = None
921
+ if labels is not None:
922
+ # Shift so that tokens < n predict n
923
+ shift_logits = logits[..., :-1, :].contiguous()
924
+ shift_labels = labels[..., 1:].contiguous()
925
+ # Flatten the tokens
926
+ loss_fct = CrossEntropyLoss()
927
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
928
+ shift_labels = shift_labels.view(-1)
929
+ # Enable model parallelism
930
+ shift_labels = shift_labels.to(shift_logits.device)
931
+ loss = loss_fct(shift_logits, shift_labels)
932
+
933
+ if not return_dict:
934
+ output = (logits,) + outputs[1:]
935
+ return (loss,) + output if loss is not None else output
936
+
937
+ return CausalLMOutputWithPast(
938
+ loss=loss,
939
+ logits=logits,
940
+ past_key_values=outputs.past_key_values,
941
+ hidden_states=outputs.hidden_states,
942
+ attentions=outputs.attentions,
943
+ )
944
+
945
+ def prepare_inputs_for_generation(
946
+ self,
947
+ input_ids,
948
+ past_key_values=None,
949
+ attention_mask=None,
950
+ inputs_embeds=None,
951
+ **kwargs,
952
+ ):
953
+ if past_key_values:
954
+ input_ids = input_ids[:, -1:]
955
+
956
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
957
+ if inputs_embeds is not None and past_key_values is None:
958
+ model_inputs = {"inputs_embeds": inputs_embeds}
959
+ else:
960
+ model_inputs = {"input_ids": input_ids}
961
+
962
+ model_inputs.update(
963
+ {
964
+ "past_key_values": past_key_values,
965
+ "use_cache": kwargs.get("use_cache"),
966
+ "attention_mask": attention_mask,
967
+ }
968
+ )
969
+ return model_inputs
970
+
971
+ @staticmethod
972
+ def _reorder_cache(past_key_values, beam_idx):
973
+ reordered_past = ()
974
+ for layer_past in past_key_values:
975
+ reordered_past += (
976
+ tuple(
977
+ past_state.index_select(0, beam_idx) for past_state in layer_past
978
+ ),
979
+ )
980
+ return reordered_past
981
+
982
+
983
+ @add_start_docstrings(
984
+ """
985
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
986
+
987
+ [`TransnormerForSequenceClassification`] uses the last token in order to do the classification, as other causal models
988
+ (e.g. GPT-2) do.
989
+
990
+ Since it does classification on the last token, it requires to know the position of the last token. If a
991
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
992
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
993
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
994
+ each row of the batch).
995
+ """,
996
+ TRANSNORMER_START_DOCSTRING,
997
+ )
998
+ class TransnormerForSequenceClassification(TransnormerPreTrainedModel):
999
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1000
+
1001
+ def __init__(self, config):
1002
+ super().__init__(config)
1003
+ self.num_labels = config.num_labels
1004
+ self.model = TransnormerModel(config)
1005
+ self.score = nn.Linear(config.decoder_embed_dim, self.num_labels, bias=False)
1006
+
1007
+ # Initialize weights and apply final processing
1008
+ self.post_init()
1009
+
1010
+ def get_input_embeddings(self):
1011
+ return self.model.embed_tokens
1012
+
1013
+ def set_input_embeddings(self, value):
1014
+ self.model.embed_tokens = value
1015
+
1016
+ @add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)
1017
+ def forward(
1018
+ self,
1019
+ input_ids: torch.LongTensor = None,
1020
+ attn_mask: Optional[torch.Tensor] = None,
1021
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1022
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1023
+ labels: Optional[torch.LongTensor] = None,
1024
+ use_cache: Optional[bool] = None,
1025
+ output_attentions: Optional[bool] = None,
1026
+ output_hidden_states: Optional[bool] = None,
1027
+ return_dict: Optional[bool] = None,
1028
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1029
+ r"""
1030
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1031
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1032
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1033
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1034
+ """
1035
+ return_dict = (
1036
+ return_dict if return_dict is not None else self.config.use_return_dict
1037
+ )
1038
+
1039
+ transformer_outputs = self.model(
1040
+ input_ids,
1041
+ attn_padding_mask=attn_mask,
1042
+ past_key_values=past_key_values,
1043
+ inputs_embeds=inputs_embeds,
1044
+ use_cache=use_cache,
1045
+ output_attentions=output_attentions,
1046
+ output_hidden_states=output_hidden_states,
1047
+ return_dict=return_dict,
1048
+ )
1049
+ hidden_states = transformer_outputs[0]
1050
+
1051
+ logits = self.score(hidden_states)
1052
+
1053
+ if input_ids is not None:
1054
+ batch_size = input_ids.shape[0]
1055
+ else:
1056
+ batch_size = inputs_embeds.shape[0]
1057
+
1058
+ if self.config.pad_token_id is None and batch_size != 1:
1059
+ raise ValueError(
1060
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1061
+ )
1062
+ if self.config.pad_token_id is None:
1063
+ sequence_lengths = -1
1064
+ else:
1065
+ if input_ids is not None:
1066
+ sequence_lengths = (
1067
+ torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
1068
+ ).to(logits.device)
1069
+ else:
1070
+ sequence_lengths = -1
1071
+
1072
+ pooled_logits = logits[
1073
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1074
+ ]
1075
+
1076
+ loss = None
1077
+ if labels is not None:
1078
+ labels = labels.to(logits.device)
1079
+ if self.config.problem_type is None:
1080
+ if self.num_labels == 1:
1081
+ self.config.problem_type = "regression"
1082
+ elif self.num_labels > 1 and (
1083
+ labels.dtype == torch.long or labels.dtype == torch.int
1084
+ ):
1085
+ self.config.problem_type = "single_label_classification"
1086
+ else:
1087
+ self.config.problem_type = "multi_label_classification"
1088
+
1089
+ if self.config.problem_type == "regression":
1090
+ loss_fct = MSELoss()
1091
+ if self.num_labels == 1:
1092
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1093
+ else:
1094
+ loss = loss_fct(pooled_logits, labels)
1095
+ elif self.config.problem_type == "single_label_classification":
1096
+ loss_fct = CrossEntropyLoss()
1097
+ loss = loss_fct(
1098
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1099
+ )
1100
+ elif self.config.problem_type == "multi_label_classification":
1101
+ loss_fct = BCEWithLogitsLoss()
1102
+ loss = loss_fct(pooled_logits, labels)
1103
+ if not return_dict:
1104
+ output = (pooled_logits,) + transformer_outputs[1:]
1105
+ return ((loss,) + output) if loss is not None else output
1106
+
1107
+ return SequenceClassifierOutputWithPast(
1108
+ loss=loss,
1109
+ logits=pooled_logits,
1110
+ past_key_values=transformer_outputs.past_key_values,
1111
+ hidden_states=transformer_outputs.hidden_states,
1112
+ attentions=transformer_outputs.attentions,
1113
+ )
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.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)
tokenization_baichuan.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ import os
22
+ from shutil import copyfile
23
+ from typing import Any, Dict, List, Optional, Tuple
24
+
25
+ import sentencepiece as spm
26
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
27
+ from transformers.utils import logging
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
32
+
33
+ PRETRAINED_VOCAB_FILES_MAP = {
34
+ "vocab_file": {},
35
+ "tokenizer_file": {},
36
+ }
37
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
38
+
39
+
40
+ class BaiChuanTokenizer(PreTrainedTokenizer):
41
+ """
42
+ Construct a BaiChuan tokenizer. Based on byte-level Byte-Pair-Encoding.
43
+
44
+ Args:
45
+ vocab_file (`str`):
46
+ Path to the vocabulary file.
47
+ """
48
+
49
+ vocab_files_names = VOCAB_FILES_NAMES
50
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
51
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
52
+ model_input_names = ["input_ids", "attention_mask"]
53
+
54
+ def __init__(
55
+ self,
56
+ vocab_file,
57
+ unk_token="<unk>",
58
+ bos_token="<s>",
59
+ eos_token="</s>",
60
+ pad_token=None,
61
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
62
+ add_bos_token=True,
63
+ add_eos_token=False,
64
+ clean_up_tokenization_spaces=False,
65
+ **kwargs,
66
+ ):
67
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
68
+ bos_token = (AddedToken(bos_token, lstrip=False, rstrip=False)
69
+ if isinstance(bos_token, str) else bos_token)
70
+ eos_token = (AddedToken(eos_token, lstrip=False, rstrip=False)
71
+ if isinstance(eos_token, str) else eos_token)
72
+ unk_token = (AddedToken(unk_token, lstrip=False, rstrip=False)
73
+ if isinstance(unk_token, str) else unk_token)
74
+ pad_token = (AddedToken(pad_token, lstrip=False, rstrip=False)
75
+ if isinstance(pad_token, str) else pad_token)
76
+ self.vocab_file = vocab_file
77
+ self.add_bos_token = add_bos_token
78
+ self.add_eos_token = add_eos_token
79
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
80
+ self.sp_model.Load(vocab_file)
81
+ super().__init__(
82
+ bos_token=bos_token,
83
+ eos_token=eos_token,
84
+ unk_token=unk_token,
85
+ pad_token=pad_token,
86
+ add_bos_token=add_bos_token,
87
+ add_eos_token=add_eos_token,
88
+ sp_model_kwargs=self.sp_model_kwargs,
89
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
90
+ **kwargs,
91
+ )
92
+
93
+ def __getstate__(self):
94
+ state = self.__dict__.copy()
95
+ state["sp_model"] = None
96
+ return state
97
+
98
+ def __setstate__(self, d):
99
+ self.__dict__ = d
100
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
101
+ self.sp_model.Load(self.vocab_file)
102
+
103
+ @property
104
+ def vocab_size(self):
105
+ """Returns vocab size"""
106
+ return self.sp_model.get_piece_size()
107
+
108
+ def get_vocab(self):
109
+ """Returns vocab as a dict"""
110
+ vocab = {
111
+ self.convert_ids_to_tokens(i): i
112
+ for i in range(self.vocab_size)
113
+ }
114
+ vocab.update(self.added_tokens_encoder)
115
+ return vocab
116
+
117
+ def _tokenize(self, text):
118
+ """Returns a tokenized string."""
119
+ return self.sp_model.encode(text, out_type=str)
120
+
121
+ def _convert_token_to_id(self, token):
122
+ """Converts a token (str) in an id using the vocab."""
123
+ return self.sp_model.piece_to_id(token)
124
+
125
+ def _convert_id_to_token(self, index):
126
+ """Converts an index (integer) in a token (str) using the vocab."""
127
+ token = self.sp_model.IdToPiece(index)
128
+ return token
129
+
130
+ def convert_tokens_to_string(self, tokens):
131
+ """Converts a sequence of tokens (string) in a single string."""
132
+ current_sub_tokens = []
133
+ out_string = ""
134
+ prev_is_special = False
135
+ for i, token in enumerate(tokens):
136
+ # make sure that special tokens are not decoded using sentencepiece model
137
+ if token in self.all_special_tokens:
138
+ if not prev_is_special and i != 0:
139
+ out_string += " "
140
+ out_string += self.sp_model.decode(current_sub_tokens) + token
141
+ prev_is_special = True
142
+ current_sub_tokens = []
143
+ else:
144
+ current_sub_tokens.append(token)
145
+ prev_is_special = False
146
+ out_string += self.sp_model.decode(current_sub_tokens)
147
+ return out_string
148
+
149
+ def save_vocabulary(self,
150
+ save_directory,
151
+ filename_prefix: Optional[str] = None) -> Tuple[str]:
152
+ """
153
+ Save the vocabulary and special tokens file to a directory.
154
+
155
+ Args:
156
+ save_directory (`str`):
157
+ The directory in which to save the vocabulary.
158
+
159
+ Returns:
160
+ `Tuple(str)`: Paths to the files saved.
161
+ """
162
+ if not os.path.isdir(save_directory):
163
+ logger.error(
164
+ f"Vocabulary path ({save_directory}) should be a directory")
165
+ return
166
+ out_vocab_file = os.path.join(
167
+ save_directory,
168
+ (filename_prefix + "-" if filename_prefix else "") +
169
+ VOCAB_FILES_NAMES["vocab_file"],
170
+ )
171
+
172
+ if os.path.abspath(self.vocab_file) != os.path.abspath(
173
+ out_vocab_file) and os.path.isfile(self.vocab_file):
174
+ copyfile(self.vocab_file, out_vocab_file)
175
+ elif not os.path.isfile(self.vocab_file):
176
+ with open(out_vocab_file, "wb") as fi:
177
+ content_spiece_model = self.sp_model.serialized_model_proto()
178
+ fi.write(content_spiece_model)
179
+
180
+ return (out_vocab_file, )
181
+
182
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
183
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
184
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
185
+
186
+ output = bos_token_id + token_ids_0 + eos_token_id
187
+
188
+ if token_ids_1 is not None:
189
+ output = output + bos_token_id + token_ids_1 + eos_token_id
190
+
191
+ return output
192
+
193
+ def get_special_tokens_mask(
194
+ self,
195
+ token_ids_0: List[int],
196
+ token_ids_1: Optional[List[int]] = None,
197
+ already_has_special_tokens: bool = False,
198
+ ) -> List[int]:
199
+ """
200
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
201
+ special tokens using the tokenizer `prepare_for_model` method.
202
+
203
+ Args:
204
+ token_ids_0 (`List[int]`):
205
+ List of IDs.
206
+ token_ids_1 (`List[int]`, *optional*):
207
+ Optional second list of IDs for sequence pairs.
208
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
209
+ Whether or not the token list is already formatted with special tokens for the model.
210
+
211
+ Returns:
212
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
213
+ """
214
+ if already_has_special_tokens:
215
+ return super().get_special_tokens_mask(
216
+ token_ids_0=token_ids_0,
217
+ token_ids_1=token_ids_1,
218
+ already_has_special_tokens=True,
219
+ )
220
+
221
+ bos_token_id = [1] if self.add_bos_token else []
222
+ eos_token_id = [1] if self.add_eos_token else []
223
+
224
+ if token_ids_1 is None:
225
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
226
+ return (bos_token_id + ([0] * len(token_ids_0)) + eos_token_id +
227
+ bos_token_id + ([0] * len(token_ids_1)) + eos_token_id)
228
+
229
+ def create_token_type_ids_from_sequences(
230
+ self,
231
+ token_ids_0: List[int],
232
+ token_ids_1: Optional[List[int]] = None) -> List[int]:
233
+ """
234
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
235
+ sequence pair mask has the following format:
236
+
237
+ ```
238
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
239
+ | first sequence | second sequence |
240
+ ```
241
+
242
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
243
+
244
+ Args:
245
+ token_ids_0 (`List[int]`):
246
+ List of ids.
247
+ token_ids_1 (`List[int]`, *optional*):
248
+ Optional second list of IDs for sequence pairs.
249
+
250
+ Returns:
251
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
252
+ """
253
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
254
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
255
+
256
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
257
+
258
+ if token_ids_1 is not None:
259
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
260
+
261
+ return output
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4be54af290d93c113bcbf421115ae9eed9d6340408f564898f1e966dc738ef01
3
+ size 1136699
tokenizer_config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": [
4
+ "tokenization_baichuan.BaiChuanTokenizer",
5
+ null
6
+ ]
7
+ },
8
+ "add_bos_token": false,
9
+ "add_eos_token": false,
10
+ "bos_token": {
11
+ "__type": "AddedToken",
12
+ "content": "<s>",
13
+ "lstrip": false,
14
+ "normalized": true,
15
+ "rstrip": false,
16
+ "single_word": false
17
+ },
18
+ "clean_up_tokenization_spaces": false,
19
+ "eos_token": {
20
+ "__type": "AddedToken",
21
+ "content": "</s>",
22
+ "lstrip": false,
23
+ "normalized": true,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "model_max_length": 1000000000000000019884624838656,
28
+ "sp_model_kwargs": {},
29
+ "tokenizer_class": "BaiChuanTokenizer",
30
+ "unk_token": {
31
+ "__type": "AddedToken",
32
+ "content": "<unk>",
33
+ "lstrip": false,
34
+ "normalized": true,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ }
38
+ }
utils.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import torch.distributed as dist
22
+ import torch.nn.functional as F
23
+
24
+ from .norm import SimpleRMSNorm as SimpleRMSNormTorch
25
+ from .srmsnorm_triton import SimpleRMSNorm as SimpleRMSNormTriton
26
+
27
+ use_triton = eval(os.environ.get("use_triton", default="True"))
28
+ debug = eval(os.environ.get("debug", default="False"))
29
+
30
+ if use_triton:
31
+ SimpleRMSNorm = SimpleRMSNormTriton
32
+ else:
33
+ SimpleRMSNorm = SimpleRMSNormTorch
34
+
35
+ logging.basicConfig(
36
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
37
+ datefmt="%Y-%m-%d %H:%M:%S",
38
+ level=os.environ.get("LOGLEVEL", "INFO").upper(),
39
+ stream=sys.stdout,
40
+ )
41
+ logger = logging.getLogger("print_config")
42
+
43
+ BASE_DIM = 256
44
+
45
+
46
+ def is_dist_avail_and_initialized():
47
+ if not dist.is_available():
48
+ return False
49
+ if not dist.is_initialized():
50
+ return False
51
+ return True
52
+
53
+
54
+ def get_world_size():
55
+ if not is_dist_avail_and_initialized():
56
+ return 1
57
+ return dist.get_world_size()
58
+
59
+
60
+ def get_rank():
61
+ if not is_dist_avail_and_initialized():
62
+ return 0
63
+ return dist.get_rank()
64
+
65
+
66
+ def is_main_process():
67
+ return get_rank() == 0
68
+
69
+
70
+ def logging_info(string):
71
+ if is_main_process():
72
+ logger.info(string)
73
+
74
+
75
+ def print_params(**kwargs):
76
+ if is_main_process():
77
+ logger.info(f"start print config of {kwargs['__class__']}")
78
+ for key in kwargs:
79
+ if key in ["__class__", "self"]:
80
+ continue
81
+ logger.info(f"{key}: {kwargs[key]}")
82
+ logger.info(f"end print config of {kwargs['__class__']}")
83
+
84
+
85
+ def print_config(config):
86
+ if is_main_process():
87
+ logger.info(f"start print config of {config['__class__']}")
88
+ for key in config:
89
+ if key in ["__class__", "self"]:
90
+ continue
91
+ logger.info(f"{key}: {config[key]}")
92
+ logger.info(f"end print config of {config['__class__']}")
93
+
94
+
95
+ def print_module(module):
96
+ named_modules = set()
97
+ for p in module.named_modules():
98
+ named_modules.update([p[0]])
99
+ named_modules = list(named_modules)
100
+
101
+ string_repr = ""
102
+ for p in module.named_parameters():
103
+ name = p[0].split(".")[0]
104
+ if name not in named_modules:
105
+ string_repr = (string_repr + "(" + name + "): " + "Tensor(" +
106
+ str(tuple(p[1].shape)) + ", requires_grad=" +
107
+ str(p[1].requires_grad) + ")\n")
108
+
109
+ return string_repr.rstrip("\n")
110
+
111
+
112
+ def get_activation_fn(activation):
113
+ if debug:
114
+ logger.info(f"activation: {activation}")
115
+ if activation == "gelu":
116
+ return F.gelu
117
+ elif activation == "relu":
118
+ return F.relu
119
+ elif activation == "elu":
120
+ return F.elu
121
+ elif activation == "sigmoid":
122
+ return F.sigmoid
123
+ elif activation == "exp":
124
+
125
+ def f(x):
126
+ with torch.no_grad():
127
+ x_max = torch.max(x, dim=-1, keepdims=True).values
128
+ y = torch.exp(x - x_max)
129
+
130
+ return y
131
+
132
+ return f
133
+ elif activation == "leak":
134
+ return F.leaky_relu
135
+ elif activation == "1+elu":
136
+
137
+ def f(x):
138
+ return 1 + F.elu(x)
139
+
140
+ return f
141
+ elif activation == "2+elu":
142
+
143
+ def f(x):
144
+ return 2 + F.elu(x)
145
+
146
+ return f
147
+ elif activation == "silu" or activation == "swish":
148
+ return F.silu
149
+ elif activation == "sine":
150
+ return torch.sin
151
+ else:
152
+ logger.info(
153
+ f"activation: does not support {activation}, use Identity!!!")
154
+ return lambda x: x
155
+
156
+
157
+ def get_norm_fn(norm_type):
158
+ if norm_type == "simplermsnorm":
159
+ return SimpleRMSNorm
160
+ else:
161
+ return nn.LayerNorm
162
+
163
+
164
+ def convert_to_multiple_of_base(x):
165
+ return BASE_DIM * ((x + BASE_DIM - 1) // BASE_DIM)