OpenNLPLab commited on
Commit
bc6e7dd
1 Parent(s): 7397626

Upload codebase

Browse files
config.json ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "15b-50B",
3
+ "add_bos_token": false,
4
+ "architectures": [
5
+ "TransnormerForCausalLM"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_transnormer.TransnormerConfig",
9
+ "AutoModelForCausalLM": "modeling_transnormer.TransnormerForCausalLM"
10
+ },
11
+ "bias": false,
12
+ "bos_token_id": 100261,
13
+ "decoder_attention_heads": 40,
14
+ "decoder_embed_dim": 5120,
15
+ "decoder_layers": 42,
16
+ "eos_token_id": 100257,
17
+ "gate_dim": 16,
18
+ "glu_dim": 15360,
19
+ "hidden_dim": 5120,
20
+ "init_std": 0.02,
21
+ "linear_act_fun": "swish",
22
+ "linear_use_lrpe": 0,
23
+ "linear_use_lrpe_list": [
24
+ 1,
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
+ 0,
54
+ 0,
55
+ 0,
56
+ 0,
57
+ 0,
58
+ 0,
59
+ 0,
60
+ 0,
61
+ 0,
62
+ 0,
63
+ 0,
64
+ 0,
65
+ 0
66
+ ],
67
+ "model_type": "transnormer",
68
+ "no_scale_embedding": false,
69
+ "norm_type": "simplermsnorm",
70
+ "pad_token_id": 100262,
71
+ "torch_dtype": "bfloat16",
72
+ "transformers_version": "4.33.1",
73
+ "use_cache": true,
74
+ "vocab_size": 100280
75
+ }
configuration_transnormer.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ 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
+ gate_dim=16,
49
+ **kwargs,
50
+ ):
51
+ super().__init__(
52
+ pad_token_id=pad_token_id,
53
+ bos_token_id=bos_token_id,
54
+ eos_token_id=eos_token_id,
55
+ **kwargs,
56
+ )
57
+ # hf origin
58
+ self.vocab_size = vocab_size
59
+ self.use_cache = use_cache
60
+ self.init_std = init_std
61
+ # add
62
+ self.decoder_embed_dim = decoder_embed_dim
63
+ self.decoder_layers = decoder_layers
64
+ self.decoder_attention_heads = decoder_attention_heads
65
+ self.no_scale_embedding = no_scale_embedding
66
+ self.add_bos_token = add_bos_token
67
+ self.norm_type = norm_type
68
+ self.linear_use_lrpe_list = linear_use_lrpe_list
69
+ self.hidden_dim = hidden_dim
70
+ self.linear_act_fun = linear_act_fun
71
+ self.glu_dim = glu_dim
72
+ self.bias = bias
73
+ self.gate_dim = gate_dim
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 100261,
4
+ "do_sample": true,
5
+ "eos_token_id": 100257,
6
+ "max_new_tokens": 8192,
7
+ "pad_token_id": 100262,
8
+ "repetition_penalty": 1.03,
9
+ "transformers_version": "4.33.1"
10
+ }
lightning_attention.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
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
modeling_transnormer.py ADDED
@@ -0,0 +1,943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ use_triton = eval(os.environ.get("use_triton", default="True"))
57
+ debug = eval(os.environ.get("debug", default="False"))
58
+
59
+ if use_triton:
60
+ try:
61
+ from .lightning_attention2 import lightning_attention
62
+
63
+ has_lightning_attention = True
64
+ except (ImportError, ModuleNotFoundError):
65
+ has_lightning_attention = False
66
+ else:
67
+ has_lightning_attention = False
68
+
69
+ if debug:
70
+ logger.info(f"Use triton: {use_triton}")
71
+ logger.info(f"Use lightning attention: {has_lightning_attention}")
72
+ logger.info(f"Debug mode: {debug}, {type(debug)}")
73
+
74
+ if not has_lightning_attention:
75
+
76
+ def linear_attention(q, k, v, attn_mask):
77
+ energy = torch.einsum("... n d, ... m d -> ... n m", q, k)
78
+ energy = energy * attn_mask
79
+ output = torch.einsum("... n m, ... m d -> ... n d", energy, v)
80
+
81
+ return output
82
+
83
+
84
+ ########## start Transnormer
85
+ ##### Linearized Relative Positional Encoding: https://openreview.net/forum?id=xoLyps2qWc&referrer=%5BAuthor%20Console%5D(%2Fgroup%3Fid%3DTMLR%2FAuthors%23your-submissions)
86
+ class Lrpe(nn.Module):
87
+ def __init__(
88
+ self,
89
+ num_heads=8,
90
+ embed_dim=64,
91
+ ):
92
+ super().__init__()
93
+ d = num_heads * embed_dim
94
+
95
+ self.index = torch.empty(0)
96
+ self.theta = nn.Parameter(
97
+ 10000 ** (-2 / d * torch.arange(d)).reshape(num_heads, 1, -1)
98
+ )
99
+
100
+ def extra_repr(self):
101
+ return print_module(self)
102
+
103
+ def forward(self, x, offset=0):
104
+ # x: b, h, n, d
105
+ # offset: for k, v cache
106
+ n = x.shape[-2]
107
+ if self.index.shape[0] < n:
108
+ self.index = torch.arange(n).reshape(1, -1, 1).to(x)
109
+ index = self.index[:, :n] + offset
110
+ theta = self.theta * index
111
+ x = torch.concat([x * torch.cos(theta), x * torch.sin(theta)], dim=-1)
112
+
113
+ return x
114
+
115
+
116
+ class GLU(nn.Module):
117
+ def __init__(self, d1, d2, bias=False):
118
+ super().__init__()
119
+ if debug:
120
+ # get local varables
121
+ params = locals()
122
+ # print params
123
+ print_params(**params)
124
+
125
+ self.l1 = nn.Linear(d1, d2, bias=bias)
126
+ self.l2 = nn.Linear(d1, d2, bias=bias)
127
+ self.l3 = nn.Linear(d2, d1, bias=bias)
128
+
129
+ def forward(self, x):
130
+ o1 = self.l1(x)
131
+ o2 = self.l2(x)
132
+ output = o1 * o2
133
+ output = self.l3(output)
134
+
135
+ return output
136
+
137
+
138
+ class NormLinearAttention(nn.Module):
139
+ def __init__(
140
+ self,
141
+ embed_dim,
142
+ hidden_dim,
143
+ num_heads,
144
+ gate_dim=16,
145
+ linear_act_fun="silu",
146
+ norm_type="simplermsnorm",
147
+ linear_use_lrpe=False,
148
+ bias=False,
149
+ ):
150
+ super().__init__()
151
+ if debug:
152
+ # get local varables
153
+ params = locals()
154
+ # print params
155
+ print_params(**params)
156
+
157
+ self.out_proj = nn.Linear(hidden_dim, embed_dim, bias=bias)
158
+ self.act = get_activation_fn(linear_act_fun)
159
+ self.num_heads = num_heads
160
+ self.embed_dim = embed_dim
161
+ self.head_dim = self.embed_dim // self.num_heads
162
+ self.norm = get_norm_fn(norm_type)(hidden_dim)
163
+
164
+ self.linear_use_lrpe = linear_use_lrpe
165
+ if self.linear_use_lrpe:
166
+ self.lrpe = Lrpe(
167
+ num_heads=self.num_heads,
168
+ embed_dim=self.head_dim,
169
+ )
170
+
171
+ self.qkv_proj = nn.Linear(embed_dim, 3 * hidden_dim, bias=bias)
172
+ self.output_gate = nn.Sequential(
173
+ nn.Linear(embed_dim, gate_dim, bias=bias),
174
+ nn.Linear(gate_dim, hidden_dim, bias=bias),
175
+ )
176
+
177
+ # for inference only
178
+ self.offset = 0
179
+
180
+ def forward(
181
+ self,
182
+ x,
183
+ attn_mask: Optional[torch.Tensor] = None, # (b, h, n, m)
184
+ attn_padding_mask: Optional[torch.Tensor] = None, # (b, m)
185
+ output_attentions: bool = False,
186
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
187
+ use_cache: bool = False,
188
+ slope_rate: Optional[torch.Tensor] = None,
189
+ ):
190
+ do_eval = eval(os.environ.get("do_eval", default="False"))
191
+ if (not self.training) and (not do_eval):
192
+ return self.inference(
193
+ x,
194
+ attn_mask,
195
+ attn_padding_mask,
196
+ output_attentions,
197
+ past_key_value,
198
+ use_cache,
199
+ slope_rate,
200
+ )
201
+ # x: b n d
202
+ b, n, d = x.shape
203
+ # linear map
204
+ qkv = self.act(self.qkv_proj(x))
205
+ q, k, v = qkv.split([d, d, d], dim=-1)
206
+
207
+ # reshape
208
+ q, k, v = map(
209
+ lambda x: rearrange(x, "b n (h d) -> b h n d", h=self.num_heads), [q, k, v]
210
+ )
211
+
212
+ q_offset = 0
213
+ # lrpe relys on position, get cache first
214
+ if past_key_value is not None:
215
+ # reuse k, v, for evaluation only
216
+ k = torch.cat([past_key_value[0], k], dim=-2)
217
+ v = torch.cat([past_key_value[1], v], dim=-2)
218
+ q_offset = past_key_value[0].shape[-2]
219
+
220
+ past_key_value = (k, v) if use_cache else None
221
+
222
+ # lrpe
223
+ if self.linear_use_lrpe:
224
+ q = self.lrpe(q, offset=q_offset)
225
+ k = self.lrpe(k)
226
+
227
+ if attn_padding_mask is not None:
228
+ v = v.masked_fill(
229
+ (1 - attn_padding_mask).unsqueeze(1).unsqueeze(-1).to(torch.bool), 0
230
+ )
231
+
232
+ if not has_lightning_attention:
233
+ if attn_mask == None:
234
+ attn_mask = (torch.tril(torch.ones(n, n))).to(q)
235
+ if slope_rate != None:
236
+ attn_mask = torch.exp(slope_rate * attn_mask)
237
+ output = linear_attention(q, k, v, attn_mask)
238
+ else:
239
+ output = lightning_attention(
240
+ q, k, v, True, slope_rate.squeeze(-1).squeeze(-1)
241
+ )
242
+
243
+ # reshape
244
+ output = rearrange(output, "b h n d -> b n (h d)")
245
+ # normalize
246
+ output = self.norm(output)
247
+ # gate
248
+ output = F.sigmoid(self.output_gate(x)) * output
249
+ # outproj
250
+ output = self.out_proj(output)
251
+
252
+ if not output_attentions:
253
+ attn_weights = None
254
+ else:
255
+ attn_weights = torch.einsum("... n d, ... m d -> ... n m", q, k)
256
+
257
+ return output, attn_weights, past_key_value
258
+
259
+ def inference(
260
+ self,
261
+ x,
262
+ attn_mask: Optional[torch.Tensor] = None, # (b, h, n, m)
263
+ attn_padding_mask: Optional[torch.Tensor] = None, # (b, m)
264
+ output_attentions: bool = False,
265
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
266
+ use_cache: bool = False,
267
+ slope_rate: Optional[torch.Tensor] = None, # (h, 1, 1)
268
+ ):
269
+ # x: b n d
270
+ b, n, d = x.shape
271
+ # linear map
272
+ qkv = self.act(self.qkv_proj(x))
273
+ q, k, v = qkv.split([d, d, d], dim=-1)
274
+ # reshape
275
+ q, k, v = map(
276
+ lambda x: rearrange(x, "b n (h d) -> b h n d", h=self.num_heads), [q, k, v]
277
+ )
278
+
279
+ # rpe
280
+ if self.linear_use_lrpe:
281
+ q = self.lrpe(q, offset=self.offset)
282
+ k = self.lrpe(k)
283
+
284
+ if past_key_value == None:
285
+ self.offset = q.shape[-2]
286
+ else:
287
+ self.offset += 1
288
+
289
+ ratio = torch.exp(-slope_rate)
290
+
291
+ # only use for the first time
292
+ if past_key_value == None:
293
+ if attn_mask == None:
294
+ attn_mask = (torch.tril(torch.ones(n, n))).to(q)
295
+ if slope_rate != None:
296
+ attn_mask = torch.exp(slope_rate * attn_mask)
297
+
298
+ if attn_padding_mask is not None:
299
+ attn_mask = attn_mask.masked_fill(
300
+ (1 - attn_padding_mask).unsqueeze(1).unsqueeze(2).to(torch.bool),
301
+ 0,
302
+ )
303
+ energy = torch.einsum("... n d, ... m d -> ... n m", q, k)
304
+
305
+ if attn_mask != None:
306
+ energy = energy * attn_mask
307
+
308
+ output = torch.einsum("... n m, ... m d -> ... n d", energy, v)
309
+
310
+ eval_and_not_generate = eval(
311
+ os.environ.get("eval_and_not_generate", default="False")
312
+ )
313
+ if eval_and_not_generate:
314
+ kv = None
315
+ else:
316
+ # b, h, n, e, d
317
+ kv_outproduct = torch.einsum("... n e, ... n d -> ... n e d", k, v)
318
+ # 1, 1, n, 1, 1
319
+ index = torch.arange(n - 1, -1, -1).reshape(1, 1, -1, 1, 1).to(x)
320
+ # (h, 1, 1) -> (1, h, 1, 1, 1); (1, h, 1, 1, 1), (1, 1, n, 1, 1) -> (1, h, n, 1, 1)
321
+ decay = ratio.unsqueeze(0).unsqueeze(-1) ** index
322
+
323
+ kv_outproduct_with_decay = kv_outproduct * decay
324
+ kv = torch.sum(kv_outproduct_with_decay, dim=-3)
325
+ else:
326
+ kv = past_key_value
327
+
328
+ output = []
329
+ for i in range(n):
330
+ kv = ratio * kv + torch.einsum(
331
+ "... n d, ... n e -> ... d e",
332
+ k[:, :, i : i + 1],
333
+ v[:, :, i : i + 1],
334
+ )
335
+ qkv = torch.einsum(
336
+ "... n e, ... e d -> ... n d", q[:, :, i : i + 1], kv
337
+ )
338
+ output.append(qkv)
339
+ output = torch.concat(output, dim=-2)
340
+
341
+ # reshape
342
+ output = rearrange(output, "b h n d -> b n (h d)")
343
+ # normalize
344
+ output = self.norm(output)
345
+ # gate
346
+ output = F.sigmoid(self.output_gate(x)) * output
347
+ # outproj
348
+ output = self.out_proj(output)
349
+
350
+ attn_weights = None
351
+
352
+ return output, attn_weights, kv
353
+
354
+
355
+ class TransnormerDecoderLayer(nn.Module):
356
+ def __init__(self, config: TransnormerConfig):
357
+ super().__init__()
358
+ self.embed_dim = config.decoder_embed_dim
359
+ ##### normalize
360
+ norm_type = config.norm_type
361
+ if debug:
362
+ logging_info(f"Decoder Norm Type: {norm_type}")
363
+ self.token_norm = get_norm_fn(norm_type)(self.embed_dim)
364
+ self.channel_norm = get_norm_fn(norm_type)(self.embed_dim)
365
+
366
+ ##### token mixer
367
+ self.token_mixer = self.build_token_mixer(
368
+ self.embed_dim,
369
+ config,
370
+ )
371
+
372
+ ##### channel mixer
373
+ self.glu_dim = config.glu_dim
374
+ if self.glu_dim == -1:
375
+ self.glu_dim = self.embed_dim
376
+ bias = config.bias
377
+ self.channel_mixer = GLU(self.embed_dim, self.glu_dim, bias)
378
+
379
+ def build_token_mixer(self, embed_dim, config):
380
+ return NormLinearAttention(
381
+ embed_dim=embed_dim,
382
+ hidden_dim=config.hidden_dim,
383
+ num_heads=config.decoder_attention_heads,
384
+ gate_dim=config.gate_dim,
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
+ layer_outputs = layer(
739
+ hidden_states,
740
+ attn_mask=mask,
741
+ attn_padding_mask=linear_attn_padding_mask,
742
+ past_key_value=past_key_value,
743
+ output_attentions=output_attentions,
744
+ use_cache=use_cache,
745
+ slope_rate=slope_rate,
746
+ )
747
+
748
+ hidden_states = layer_outputs[0]
749
+
750
+ if use_cache:
751
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
752
+
753
+ if output_attentions:
754
+ all_self_attns += (layer_outputs[1],)
755
+
756
+ # if idx == 0:
757
+ # break
758
+
759
+ hidden_states = self.final_norm(hidden_states)
760
+
761
+ # add hidden states from the last decoder layer
762
+ if output_hidden_states:
763
+ all_hidden_states += (hidden_states,)
764
+
765
+ next_cache = next_decoder_cache if use_cache else None
766
+ if not return_dict:
767
+ return tuple(
768
+ v
769
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
770
+ if v is not None
771
+ )
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
+ def __init__(self, config):
782
+ super().__init__(config)
783
+ self.model = TransnormerModel(config)
784
+ if debug:
785
+ logging_info(self.model)
786
+
787
+ # the lm_head weight is automatically tied to the embed tokens weight
788
+ self.lm_head = nn.Linear(
789
+ config.decoder_embed_dim, config.vocab_size, bias=False
790
+ )
791
+
792
+ # Initialize weights and apply final processing
793
+ self.post_init()
794
+
795
+ def get_input_embeddings(self):
796
+ return self.model.embed_tokens
797
+
798
+ def set_input_embeddings(self, value):
799
+ self.model.embed_tokens = value
800
+
801
+ def get_output_embeddings(self):
802
+ return self.lm_head
803
+
804
+ def set_output_embeddings(self, new_embeddings):
805
+ self.lm_head = new_embeddings
806
+
807
+ def set_decoder(self, decoder):
808
+ self.model = decoder
809
+
810
+ def get_decoder(self):
811
+ return self.model
812
+
813
+ @add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)
814
+ @replace_return_docstrings(
815
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
816
+ )
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 = (
855
+ output_attentions
856
+ if output_attentions is not None
857
+ else self.config.output_attentions
858
+ )
859
+ output_hidden_states = (
860
+ output_hidden_states
861
+ if output_hidden_states is not None
862
+ else self.config.output_hidden_states
863
+ )
864
+ return_dict = (
865
+ return_dict if return_dict is not None else self.config.use_return_dict
866
+ )
867
+
868
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
869
+ outputs = self.model(
870
+ input_ids=input_ids,
871
+ attn_padding_mask=attention_mask,
872
+ past_key_values=past_key_values,
873
+ inputs_embeds=inputs_embeds,
874
+ use_cache=use_cache,
875
+ output_attentions=output_attentions,
876
+ output_hidden_states=output_hidden_states,
877
+ return_dict=return_dict,
878
+ )
879
+
880
+ hidden_states = outputs[0]
881
+ logits = self.lm_head(hidden_states)
882
+
883
+ loss = None
884
+ if labels is not None:
885
+ # Shift so that tokens < n predict n
886
+ shift_logits = logits[..., :-1, :].contiguous()
887
+ shift_labels = labels[..., 1:].contiguous()
888
+ # Flatten the tokens
889
+ loss_fct = CrossEntropyLoss()
890
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
891
+ shift_labels = shift_labels.view(-1)
892
+ # Enable model parallelism
893
+ shift_labels = shift_labels.to(shift_logits.device)
894
+ loss = loss_fct(shift_logits, shift_labels)
895
+
896
+ if not return_dict:
897
+ output = (logits,) + outputs[1:]
898
+ return (loss,) + output if loss is not None else output
899
+
900
+ return CausalLMOutputWithPast(
901
+ loss=loss,
902
+ logits=logits,
903
+ past_key_values=outputs.past_key_values,
904
+ hidden_states=outputs.hidden_states,
905
+ attentions=outputs.attentions,
906
+ )
907
+
908
+ def prepare_inputs_for_generation(
909
+ self,
910
+ input_ids,
911
+ past_key_values=None,
912
+ attention_mask=None,
913
+ inputs_embeds=None,
914
+ **kwargs,
915
+ ):
916
+ if past_key_values:
917
+ input_ids = input_ids[:, -1:]
918
+
919
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
920
+ if inputs_embeds is not None and past_key_values is None:
921
+ model_inputs = {"inputs_embeds": inputs_embeds}
922
+ else:
923
+ model_inputs = {"input_ids": input_ids}
924
+
925
+ model_inputs.update(
926
+ {
927
+ "past_key_values": past_key_values,
928
+ "use_cache": kwargs.get("use_cache"),
929
+ "attention_mask": attention_mask,
930
+ }
931
+ )
932
+ return model_inputs
933
+
934
+ @staticmethod
935
+ def _reorder_cache(past_key_values, beam_idx):
936
+ reordered_past = ()
937
+ for layer_past in past_key_values:
938
+ reordered_past += (
939
+ tuple(
940
+ past_state.index_select(0, beam_idx) for past_state in layer_past
941
+ ),
942
+ )
943
+ return reordered_past
norm.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 logging
17
+ import os
18
+ import sys
19
+
20
+ import torch
21
+ from torch import nn
22
+
23
+ logging.basicConfig(
24
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
25
+ datefmt="%Y-%m-%d %H:%M:%S",
26
+ level=os.environ.get("LOGLEVEL", "INFO").upper(),
27
+ stream=sys.stdout,
28
+ )
29
+ logger = logging.getLogger("srmsnorm")
30
+
31
+
32
+ class SimpleRMSNorm(nn.Module):
33
+
34
+ def __init__(self, dim: int, eps: float = 1e-6):
35
+ super().__init__()
36
+ self.eps = eps
37
+
38
+ def _norm(self, x):
39
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
40
+
41
+ def forward(self, x):
42
+ output = self._norm(x.float()).type_as(x)
43
+
44
+ return output
srmsnorm_triton.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 2024 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
+ # coding=utf-8
18
+ import torch
19
+ import torch.nn.functional as F
20
+ import triton
21
+ import triton.language as tl
22
+
23
+
24
+ # fmt: off
25
+ @triton.jit
26
+ def srms_norm_fw(X, Y, V, stride, N, eps, BLOCK_SIZE_N: tl.constexpr):
27
+ # fmt: on
28
+ row = tl.program_id(0)
29
+ cols = tl.arange(0, BLOCK_SIZE_N)
30
+ mask = cols < N
31
+
32
+ # Move to this row
33
+ x_ptrs = X + row * stride + cols
34
+ x = tl.load(x_ptrs, mask=mask, other=0.0).to(tl.float32)
35
+
36
+ x_zm = tl.where(mask, x, 0.0)
37
+
38
+ x_var = tl.sum(x_zm * x_zm, axis=0) / N
39
+ rstd = 1.0 / tl.sqrt(x_var + eps)
40
+
41
+ # Normalize, optionally affine
42
+ y = x_zm * rstd
43
+ tl.store(V + row, rstd)
44
+
45
+ y_ptrs = Y + row * stride + cols
46
+ tl.store(y_ptrs, y, mask=mask)
47
+
48
+
49
+ # Backward pass (DX + partial DW + partial DB)
50
+ # fmt: off
51
+ @triton.jit
52
+ def srms_norm_bwd_dx_fused(
53
+ DX, DY,
54
+ X, V,
55
+ stride, N,
56
+ # META-parameters
57
+ BLOCK_SIZE_N: tl.constexpr,
58
+ ):
59
+ # fmt: on
60
+
61
+ # position of elements processed by this program
62
+ row = tl.program_id(0)
63
+ cols = tl.arange(0, BLOCK_SIZE_N)
64
+ mask = cols < N
65
+
66
+ # offset data pointers to start at the row of interest
67
+ x_ptrs = X + row * stride + cols
68
+ dy_ptrs = DY + row * stride + cols
69
+
70
+ # load data to SRAM
71
+ x = tl.load(x_ptrs, mask=mask, other=0)
72
+ dy = tl.load(dy_ptrs, mask=mask, other=0)
73
+ rstd = tl.load(V + row)
74
+
75
+ # compute dx
76
+ xhat = x * rstd
77
+ wdy = dy
78
+
79
+ xhat = tl.where(mask, xhat, 0.)
80
+ wdy = tl.where(mask, wdy, 0.)
81
+ mean1 = tl.sum(xhat * wdy, axis=0) / N
82
+ dx = (wdy - (xhat * mean1)) * rstd
83
+
84
+ # write-back dx
85
+ mask = cols < N # re-materialize the mask to save registers
86
+ dx_ptrs = DX + row * stride + cols
87
+ tl.store(dx_ptrs, dx, mask=mask)
88
+
89
+
90
+ class _SrmsNorm(torch.autograd.Function):
91
+
92
+ @staticmethod
93
+ def forward(ctx, x, eps):
94
+ # catch eps being too small if the tensors are fp16
95
+ if x.dtype == torch.float16:
96
+ eps = max(eps, 1.6e-5)
97
+
98
+ # allocate output
99
+ y = torch.empty_like(x)
100
+
101
+ # reshape input data into 2D tensor
102
+ x_arg = x.reshape(-1, x.shape[-1])
103
+ M, N = x_arg.shape
104
+
105
+ # allocate mean and std, they'll be used in the backward pass
106
+ rstd = torch.empty((M, ), dtype=torch.float32, device=x.device)
107
+
108
+ # Less than 64KB per feature: enqueue fused kernel
109
+ MAX_FUSED_SIZE = 65536 // x.element_size()
110
+ BLOCK_SIZE_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
111
+ if N > BLOCK_SIZE_N:
112
+ raise RuntimeError(
113
+ "This layer norm doesn't support feature dim >= 64KB.")
114
+
115
+ if not x_arg.is_contiguous() or not y.is_contiguous():
116
+ x_arg = x_arg.contiguous()
117
+ y = y.contiguous()
118
+
119
+ # heuristics for number of warps.
120
+ num_warps = min(max(BLOCK_SIZE_N // 256, 1), 16)
121
+
122
+ # enqueue kernel
123
+ # fmt: off
124
+ srms_norm_fw[(M,)](
125
+ x_arg, y, rstd,
126
+ x_arg.stride(0),
127
+ N,
128
+ eps,
129
+ num_warps=num_warps,
130
+ BLOCK_SIZE_N=BLOCK_SIZE_N,
131
+ )
132
+ # fmt: on
133
+
134
+ ctx.save_for_backward(x, rstd)
135
+ ctx.BLOCK_SIZE_N = BLOCK_SIZE_N
136
+ ctx.num_warps = num_warps
137
+
138
+ return y.reshape_as(x)
139
+
140
+ @staticmethod
141
+ def backward(
142
+ ctx, dy
143
+ ): # pragma: no cover # this is covered, but called directly from C++
144
+ x, rstd = ctx.saved_tensors
145
+
146
+ # flatten the batch dimension, if any.
147
+ # We're interested in 'samples' x norm_dimension
148
+ x = x.reshape(-1, x.size(-1))
149
+ M, N = x.size()
150
+
151
+ # heuristics for amount of parallel reduction stream for DG/DB
152
+ GROUP_SIZE_M = 32
153
+ if N <= 8192:
154
+ GROUP_SIZE_M = 64
155
+ if N <= 4096:
156
+ GROUP_SIZE_M = 96
157
+ if N <= 2048:
158
+ GROUP_SIZE_M = 128
159
+ if N <= 1024:
160
+ GROUP_SIZE_M = 256
161
+
162
+ if dy.dtype == torch.float32:
163
+ GROUP_SIZE_M = GROUP_SIZE_M // 2
164
+
165
+ # allocate output
166
+ dy = dy.contiguous()
167
+ dx = torch.empty_like(dy)
168
+
169
+ # Check the tensor shapes and layouts
170
+ # we suppose in the kernel that they have the same size and are contiguous
171
+ assert (
172
+ dy.numel() == x.numel()
173
+ ), "Something is wrong in the backward graph, possibly because of an inplace operation after the layernorm"
174
+
175
+ # enqueue kernel using forward pass heuristics
176
+ # also compute partial sums for DW and DB
177
+ num_warps = min(max(ctx.BLOCK_SIZE_N // 256, 1), 16)
178
+
179
+ # fmt: off
180
+ srms_norm_bwd_dx_fused[(M,)](
181
+ dx, dy, x,
182
+ rstd,
183
+ x.stride(0),
184
+ N,
185
+ BLOCK_SIZE_N=ctx.BLOCK_SIZE_N,
186
+ num_warps=num_warps
187
+ )
188
+ # fmt: on
189
+
190
+ dx = dx.reshape_as(dy)
191
+ return dx, None, None
192
+
193
+
194
+ class SimpleRMSNorm(torch.nn.Module):
195
+
196
+ def __init__(self, dim: int, eps: float = 1e-6):
197
+ super().__init__()
198
+ self.eps = eps
199
+ self.dim = dim
200
+
201
+ def forward(self, x):
202
+ return _SrmsNorm.apply(x, self.eps)
tokenization_transnormerllm.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CREDITS: tiktoken @openai
2
+ # https://github.com/openai/tiktoken
3
+ #
4
+ # Copyright 2024 OpenNLPLab
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ # coding=utf-8
19
+ import base64
20
+ import logging
21
+ import os
22
+ from typing import Collection, Dict, List, Set, Tuple, Union
23
+ import unicodedata
24
+
25
+ import tiktoken
26
+ from transformers import AddedToken, AutoTokenizer, PreTrainedTokenizer
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ VOCAB_FILES_NAMES = {"vocab_file": "transnormer_100k.tiktoken"}
32
+ PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
33
+ SPECIAL_TOKENS_DICT = {'<|endoftext|>': 100257, '<|fim_prefix|>': 100258, '<|fim_middle|>': 100259, '<|fim_suffix|>': 100260, '<|endofprompt|>': 100276, '<|J2PM|>': 100256, '<s>': 100261, '<pad>': 100262, '<unk>': 100263, '<mask>': 100264}
34
+ SPECIAL_TOKENS_SET = set(SPECIAL_TOKENS_DICT.keys())
35
+
36
+ # as the default behavior is changed to allow special tokens in
37
+ # regular texts, the surface forms of special tokens need to be
38
+ # as different as possible to minimize the impact
39
+ # changed to use actual index to avoid misconfiguration with vocabulary expansion
40
+
41
+ def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
42
+ with open(tiktoken_bpe_file, "rb") as f:
43
+ contents = f.read()
44
+ return {
45
+ base64.b64decode(token): int(rank)
46
+ for token, rank in (line.split() for line in contents.splitlines() if line)
47
+ }
48
+
49
+
50
+ class GPT4Tokenizer(PreTrainedTokenizer):
51
+ vocab_files_names = VOCAB_FILES_NAMES
52
+ def __init__(
53
+ self,
54
+ vocab_file,
55
+ errors="replace",
56
+ extra_vocab_file=None,
57
+ **kwargs,
58
+ ):
59
+ super().__init__(**kwargs)
60
+
61
+ # how to handle errors in decoding UTF-8 byte sequences
62
+ # use ignore if you are in streaming inference
63
+ self.errors = errors
64
+
65
+ self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: Dict[bytes, int]
66
+ self.special_tokens = SPECIAL_TOKENS_DICT
67
+
68
+ enc = tiktoken.Encoding(
69
+ "transnormer_100k",
70
+ pat_str=PAT_STR,
71
+ mergeable_ranks=self.mergeable_ranks,
72
+ special_tokens=self.special_tokens,
73
+ )
74
+ self.decoder = {
75
+ v: k for k, v in self.mergeable_ranks.items()
76
+ } # type: dict[int, bytes|str]
77
+ self.decoder.update({v: k for k, v in self.special_tokens.items()})
78
+
79
+ self.tokenizer = enc # type: tiktoken.Encoding
80
+
81
+ self.eod_id = self.tokenizer.eot_token
82
+ self.pad_token_id = 100262
83
+ self.bos_token_id = 100261
84
+ self.eos_token_id = self.eod_id
85
+
86
+ def __getstate__(self):
87
+ # for pickle lovers
88
+ state = self.__dict__.copy()
89
+ del state["tokenizer"]
90
+ return state
91
+
92
+ def __setstate__(self, state):
93
+ # tokenizer is not python native; don't pass it; rebuild it
94
+ self.__dict__.update(state)
95
+ enc = tiktoken.Encoding(
96
+ "transnormer_100k",
97
+ pat_str=PAT_STR,
98
+ mergeable_ranks=self.mergeable_ranks,
99
+ special_tokens=self.special_tokens,
100
+ )
101
+ self.tokenizer = enc
102
+
103
+ def __len__(self) -> int:
104
+ return self.tokenizer.n_vocab
105
+
106
+ def get_vocab(self) -> Dict[bytes, int]:
107
+ return self.mergeable_ranks
108
+
109
+ def convert_tokens_to_ids(
110
+ self, tokens: Union[bytes, str, List[Union[bytes, str]]]
111
+ ) -> List[int]:
112
+ ids = []
113
+ if isinstance(tokens, (str, bytes)):
114
+ if tokens in self.special_tokens:
115
+ return self.special_tokens[tokens]
116
+ else:
117
+ return self.mergeable_ranks.get(tokens)
118
+ for token in tokens:
119
+ if token in self.special_tokens:
120
+ ids.append(self.special_tokens[token])
121
+ else:
122
+ ids.append(self.mergeable_ranks.get(token))
123
+ return ids
124
+
125
+ def _add_tokens(
126
+ self,
127
+ new_tokens: Union[List[str], List[AddedToken]],
128
+ special_tokens: bool = False,
129
+ ) -> int:
130
+ if not special_tokens and new_tokens:
131
+ raise ValueError("Adding regular tokens is not supported")
132
+ for token in new_tokens:
133
+ surface_form = token.content if isinstance(token, AddedToken) else token
134
+ if surface_form not in SPECIAL_TOKENS_SET:
135
+ raise ValueError("Adding unknown special tokens is not supported")
136
+ return 0
137
+
138
+ def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
139
+ """
140
+ Save only the vocabulary of the tokenizer (vocabulary).
141
+ Returns:
142
+ `Tuple(str)`: Paths to the files saved.
143
+ """
144
+ file_path = os.path.join(save_directory, "transnormer_100k.tiktoken")
145
+ with open(file_path, "w", encoding="utf8") as w:
146
+ for k, v in self.mergeable_ranks.items():
147
+ line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
148
+ w.write(line)
149
+ return (file_path,)
150
+
151
+ def tokenize(
152
+ self,
153
+ text: str,
154
+ allowed_special: Union[Set, str] = "all",
155
+ disallowed_special: Union[Collection, str] = (),
156
+ **kwargs,
157
+ ) -> List[Union[bytes, str]]:
158
+ """
159
+ Converts a string in a sequence of tokens.
160
+ Args:
161
+ text (`str`):
162
+ The sequence to be encoded.
163
+ allowed_special (`Literal["all"]` or `set`):
164
+ The surface forms of the tokens to be encoded as special tokens in regular texts.
165
+ Default to "all".
166
+ disallowed_special (`Literal["all"]` or `Collection`):
167
+ The surface forms of the tokens that should not be in regular texts and trigger errors.
168
+ Default to an empty tuple.
169
+ kwargs (additional keyword arguments, *optional*):
170
+ Will be passed to the underlying model specific encode method.
171
+ Returns:
172
+ `List[bytes|str]`: The list of tokens.
173
+ """
174
+ tokens = []
175
+
176
+ # this implementation takes a detour: text -> token id -> token surface forms
177
+ for t in self.tokenizer.encode(
178
+ text, allowed_special=allowed_special, disallowed_special=disallowed_special
179
+ ):
180
+ tokens.append(self.decoder[t])
181
+ return tokens
182
+
183
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
184
+ """
185
+ Converts a sequence of tokens in a single string.
186
+ """
187
+ text = ""
188
+ temp = b""
189
+ for t in tokens:
190
+ if isinstance(t, str):
191
+ if temp:
192
+ text += temp.decode("utf-8", errors=self.errors)
193
+ temp = b""
194
+ text += t
195
+ elif isinstance(t, bytes):
196
+ temp += t
197
+ else:
198
+ raise TypeError("token should only be of type types or str")
199
+ if temp:
200
+ text += temp.decode("utf-8", errors=self.errors)
201
+ return text
202
+
203
+ @property
204
+ def vocab_size(self):
205
+ return self.tokenizer.n_vocab
206
+
207
+ def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
208
+ """Converts an id to a token, special tokens included"""
209
+ if index in self.decoder:
210
+ return self.decoder[index]
211
+ raise ValueError("unknown ids")
212
+
213
+ def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
214
+ """Converts a token to an id using the vocab, special tokens included"""
215
+ if token in self.special_tokens:
216
+ return self.special_tokens[token]
217
+ if token in self.mergeable_ranks:
218
+ return self.mergeable_ranks[token]
219
+ raise ValueError("unknown token")
220
+
221
+ def _tokenize(self, text: str, **kwargs):
222
+ """
223
+ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
224
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
225
+ Do NOT take care of added tokens.
226
+ """
227
+ raise NotImplementedError
228
+
229
+ def _decode(
230
+ self,
231
+ token_ids: Union[int, List[int]],
232
+ skip_special_tokens: bool = False,
233
+ errors: str = None,
234
+ **kwargs,
235
+ ) -> str:
236
+ if isinstance(token_ids, int):
237
+ token_ids = [token_ids]
238
+ if skip_special_tokens:
239
+ token_ids = [i for i in token_ids if i < self.eod_id]
240
+ return self.tokenizer.decode(token_ids, errors=errors or self.errors)
tokenizer_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_max_length": 65536,
3
+ "tokenizer_class": "GPT4Tokenizer",
4
+ "auto_map": {
5
+ "AutoTokenizer": [
6
+ "tokenization_transnormerllm.GPT4Tokenizer",
7
+ null
8
+ ]
9
+ }
10
+ }
transnormer_100k.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
utils.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 logging
17
+ import os
18
+ import sys
19
+
20
+ import torch
21
+ from torch import nn
22
+ import torch.distributed as dist
23
+ import torch.nn.functional as F
24
+
25
+ from .norm import SimpleRMSNorm as SimpleRMSNormTorch
26
+ from .srmsnorm_triton import SimpleRMSNorm as SimpleRMSNormTriton
27
+
28
+ use_triton = eval(os.environ.get("use_triton", default="True"))
29
+ debug = eval(os.environ.get("debug", default="False"))
30
+
31
+ if use_triton:
32
+ SimpleRMSNorm = SimpleRMSNormTriton
33
+ else:
34
+ SimpleRMSNorm = SimpleRMSNormTorch
35
+
36
+ logging.basicConfig(
37
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
38
+ datefmt="%Y-%m-%d %H:%M:%S",
39
+ level=os.environ.get("LOGLEVEL", "INFO").upper(),
40
+ stream=sys.stdout,
41
+ )
42
+ logger = logging.getLogger("print_config")
43
+
44
+ BASE_DIM = 256
45
+
46
+
47
+ def is_dist_avail_and_initialized():
48
+ if not dist.is_available():
49
+ return False
50
+ if not dist.is_initialized():
51
+ return False
52
+ return True
53
+
54
+
55
+ def get_world_size():
56
+ if not is_dist_avail_and_initialized():
57
+ return 1
58
+ return dist.get_world_size()
59
+
60
+
61
+ def get_rank():
62
+ if not is_dist_avail_and_initialized():
63
+ return 0
64
+ return dist.get_rank()
65
+
66
+
67
+ def is_main_process():
68
+ return get_rank() == 0
69
+
70
+
71
+ def logging_info(string):
72
+ if is_main_process():
73
+ logger.info(string)
74
+
75
+
76
+ def print_params(**kwargs):
77
+ if is_main_process():
78
+ logger.info(f"start print config of {kwargs['__class__']}")
79
+ for key in kwargs:
80
+ if key in ["__class__", "self"]:
81
+ continue
82
+ logger.info(f"{key}: {kwargs[key]}")
83
+ logger.info(f"end print config of {kwargs['__class__']}")
84
+
85
+
86
+ def print_config(config):
87
+ if is_main_process():
88
+ logger.info(f"start print config of {config['__class__']}")
89
+ for key in config:
90
+ if key in ["__class__", "self"]:
91
+ continue
92
+ logger.info(f"{key}: {config[key]}")
93
+ logger.info(f"end print config of {config['__class__']}")
94
+
95
+
96
+ def print_module(module):
97
+ named_modules = set()
98
+ for p in module.named_modules():
99
+ named_modules.update([p[0]])
100
+ named_modules = list(named_modules)
101
+
102
+ string_repr = ""
103
+ for p in module.named_parameters():
104
+ name = p[0].split(".")[0]
105
+ if name not in named_modules:
106
+ string_repr = (string_repr + "(" + name + "): " + "Tensor(" +
107
+ str(tuple(p[1].shape)) + ", requires_grad=" +
108
+ str(p[1].requires_grad) + ")\n")
109
+
110
+ return string_repr.rstrip("\n")
111
+
112
+
113
+ def get_activation_fn(activation):
114
+ if debug:
115
+ logger.info(f"activation: {activation}")
116
+ if activation == "gelu":
117
+ return F.gelu
118
+ elif activation == "relu":
119
+ return F.relu
120
+ elif activation == "elu":
121
+ return F.elu
122
+ elif activation == "sigmoid":
123
+ return F.sigmoid
124
+ elif activation == "exp":
125
+
126
+ def f(x):
127
+ with torch.no_grad():
128
+ x_max = torch.max(x, dim=-1, keepdims=True).values
129
+ y = torch.exp(x - x_max)
130
+
131
+ return y
132
+
133
+ return f
134
+ elif activation == "leak":
135
+ return F.leaky_relu
136
+ elif activation == "1+elu":
137
+
138
+ def f(x):
139
+ return 1 + F.elu(x)
140
+
141
+ return f
142
+ elif activation == "2+elu":
143
+
144
+ def f(x):
145
+ return 2 + F.elu(x)
146
+
147
+ return f
148
+ elif activation == "silu" or activation == "swish":
149
+ return F.silu
150
+ elif activation == "sine":
151
+ return torch.sin
152
+ else:
153
+ logger.info(
154
+ f"activation: does not support {activation}, use Identity!!!")
155
+ return lambda x: x
156
+
157
+
158
+ def get_norm_fn(norm_type):
159
+ if norm_type == "simplermsnorm":
160
+ return SimpleRMSNorm
161
+ else:
162
+ return nn.LayerNorm
163
+
164
+
165
+ def convert_to_multiple_of_base(x):
166
+ return BASE_DIM * ((x + BASE_DIM - 1) // BASE_DIM)