FrankL commited on
Commit
d72142e
·
verified ·
1 Parent(s): 12a2f50

Upload 7 files

Browse files
LMConfig.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+ from typing import List
3
+
4
+
5
+ class LMConfig(PretrainedConfig):
6
+ model_type = "word"
7
+
8
+ def __init__(
9
+ self,
10
+ dim: int = 512,
11
+ n_layers: int = 8,
12
+ n_heads: int = 16,
13
+ n_kv_heads: int = 8,
14
+ vocab_size: int = 6400,
15
+ hidden_dim: int = None,
16
+ multiple_of: int = 64,
17
+ norm_eps: float = 1e-5,
18
+ max_seq_len: int = 512,
19
+ dropout: float = 0.0,
20
+ flash_attn: bool = True,
21
+ ####################################################
22
+ # Here are the specific configurations of MOE
23
+ # When use_moe is false, the following is invalid
24
+ ####################################################
25
+ use_moe: bool = False,
26
+ num_experts_per_tok=2,
27
+ n_routed_experts=4,
28
+ n_shared_experts: bool = True,
29
+ scoring_func='softmax',
30
+ aux_loss_alpha=0.01,
31
+ seq_aux=True,
32
+ norm_topk_prob=True,
33
+ **kwargs,
34
+ ):
35
+ self.dim = dim
36
+ self.n_layers = n_layers
37
+ self.n_heads = n_heads
38
+ self.n_kv_heads = n_kv_heads
39
+ self.vocab_size = vocab_size
40
+ self.hidden_dim = hidden_dim
41
+ self.multiple_of = multiple_of
42
+ self.norm_eps = norm_eps
43
+ self.max_seq_len = max_seq_len
44
+ self.dropout = dropout
45
+ self.flash_attn = flash_attn
46
+ ####################################################
47
+ # Here are the specific configurations of MOE
48
+ # When use_moe is false, the following is invalid
49
+ ####################################################
50
+ self.use_moe = use_moe
51
+ self.num_experts_per_tok = num_experts_per_tok # 每个token选择的专家数量
52
+ self.n_routed_experts = n_routed_experts # 总的专家数量
53
+ self.n_shared_experts = n_shared_experts # 共享专家
54
+ self.scoring_func = scoring_func # 评分函数,默认为'softmax'
55
+ self.aux_loss_alpha = aux_loss_alpha # 辅助损失的alpha参数
56
+ self.seq_aux = seq_aux # 是否在序列级别上计算辅助损失
57
+ self.norm_topk_prob = norm_topk_prob # 是否标准化top-k概率
58
+ super().__init__(**kwargs)
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "word-v1",
3
+ "architectures": [
4
+ "Transformer"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "LMConfig.LMConfig",
8
+ "AutoModelForCausalLM": "model.Transformer"
9
+ },
10
+ "aux_loss_alpha": 0.01,
11
+ "dim": 512,
12
+ "dropout": 0.0,
13
+ "flash_attn": true,
14
+ "hidden_dim": null,
15
+ "max_seq_len": 512,
16
+ "model_type": "word",
17
+ "multiple_of": 64,
18
+ "n_heads": 16,
19
+ "n_kv_heads": 8,
20
+ "n_layers": 8,
21
+ "n_routed_experts": 4,
22
+ "n_shared_experts": true,
23
+ "norm_eps": 1e-05,
24
+ "norm_topk_prob": true,
25
+ "num_experts_per_tok": 2,
26
+ "scoring_func": "softmax",
27
+ "seq_aux": true,
28
+ "torch_dtype": "float32",
29
+ "transformers_version": "4.44.0",
30
+ "use_moe": false,
31
+ "vocab_size": 6400
32
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.44.0"
4
+ }
model.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import struct
3
+ import inspect
4
+ import time
5
+
6
+ from .LMConfig import LMConfig
7
+ from typing import Any, Optional, Tuple
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from torch import nn
12
+ from transformers import PreTrainedModel
13
+ from transformers.modeling_outputs import CausalLMOutputWithPast
14
+
15
+
16
+ class RMSNorm(torch.nn.Module):
17
+ def __init__(self, dim: int, eps: float):
18
+ super().__init__()
19
+ self.eps = eps
20
+ self.weight = nn.Parameter(torch.ones(dim))
21
+
22
+ def _norm(self, x):
23
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
24
+
25
+ def forward(self, x):
26
+ output = self._norm(x.float()).type_as(x)
27
+ return output * self.weight
28
+
29
+
30
+ def precompute_pos_cis(dim: int, end: int, theta: float = 10000.0):
31
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
32
+ t = torch.arange(end, device=freqs.device) # type: ignore
33
+ freqs = torch.outer(t, freqs).float() # type: ignore
34
+ pos_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
35
+ return pos_cis
36
+
37
+
38
+ def apply_rotary_emb(xq, xk, pos_cis):
39
+ def unite_shape(pos_cis, x):
40
+ ndim = x.ndim
41
+ assert 0 <= 1 < ndim
42
+ assert pos_cis.shape == (x.shape[1], x.shape[-1])
43
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
44
+ return pos_cis.view(*shape)
45
+
46
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
47
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
48
+ pos_cis = unite_shape(pos_cis, xq_)
49
+ xq_out = torch.view_as_real(xq_ * pos_cis).flatten(3)
50
+ xk_out = torch.view_as_real(xk_ * pos_cis).flatten(3)
51
+ return xq_out.type_as(xq), xk_out.type_as(xk)
52
+
53
+
54
+ def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
55
+ """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
56
+ bs, slen, n_kv_heads, head_dim = x.shape
57
+ if n_rep == 1:
58
+ return x
59
+ return (
60
+ x[:, :, :, None, :]
61
+ .expand(bs, slen, n_kv_heads, n_rep, head_dim)
62
+ .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
63
+ )
64
+
65
+
66
+ class Attention(nn.Module):
67
+ def __init__(self, args: LMConfig):
68
+ super().__init__()
69
+ self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
70
+ assert args.n_heads % self.n_kv_heads == 0
71
+ self.n_local_heads = args.n_heads
72
+ self.n_local_kv_heads = self.n_kv_heads
73
+ self.n_rep = self.n_local_heads // self.n_local_kv_heads
74
+ self.head_dim = args.dim // args.n_heads
75
+ self.wq = nn.Linear(args.dim, args.n_heads * self.head_dim, bias=False)
76
+ self.wk = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
77
+ self.wv = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
78
+ self.wo = nn.Linear(args.n_heads * self.head_dim, args.dim, bias=False)
79
+ self.k_cache, self.v_cache = None, None
80
+ self.attn_dropout = nn.Dropout(args.dropout)
81
+ self.resid_dropout = nn.Dropout(args.dropout)
82
+ self.dropout = args.dropout
83
+ self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
84
+
85
+ # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
86
+ mask = torch.full((1, 1, args.max_seq_len, args.max_seq_len), float("-inf"))
87
+ mask = torch.triu(mask, diagonal=1)
88
+ self.register_buffer("mask", mask, persistent=False)
89
+
90
+ def forward(self, x: torch.Tensor, pos_cis: torch.Tensor, kv_cache=False):
91
+ bsz, seqlen, _ = x.shape
92
+
93
+ xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
94
+
95
+ xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
96
+ xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
97
+ xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
98
+
99
+ xq, xk = apply_rotary_emb(xq, xk, pos_cis)
100
+
101
+ # 更高效的kv_cache实现
102
+ if kv_cache and self.eval():
103
+ if seqlen == 1 and all(cache is not None for cache in (self.k_cache, self.v_cache)):
104
+ xk = torch.cat((self.k_cache, xk), dim=1)
105
+ xv = torch.cat((self.v_cache, xv), dim=1)
106
+ self.k_cache, self.v_cache = xk, xv
107
+
108
+ xk = repeat_kv(xk, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
109
+ xv = repeat_kv(xv, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
110
+
111
+ xq = xq.transpose(1, 2)
112
+ xk = xk.transpose(1, 2)
113
+ xv = xv.transpose(1, 2)
114
+
115
+ if self.flash and seqlen != 1:
116
+ output = torch.nn.functional.scaled_dot_product_attention(xq, xk, xv, attn_mask=None,
117
+ dropout_p=self.dropout if self.training else 0.0,
118
+ is_causal=True)
119
+ else:
120
+ scores = torch.matmul(xq, xk.transpose(2, 3)) / math.sqrt(self.head_dim)
121
+ scores = scores + self.mask[:, :, :seqlen, :seqlen] # (bs, n_local_heads, seqlen, cache_len + seqlen)
122
+ scores = F.softmax(scores.float(), dim=-1).type_as(xq)
123
+ scores = self.attn_dropout(scores)
124
+ output = torch.matmul(scores, xv) # (bs, n_local_heads, seqlen, head_dim)
125
+
126
+ output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
127
+
128
+ output = self.wo(output)
129
+ output = self.resid_dropout(output)
130
+ return output
131
+
132
+
133
+ class FeedForward(nn.Module):
134
+ def __init__(self, dim: int, hidden_dim: int, multiple_of: int, dropout: float):
135
+ super().__init__()
136
+ if hidden_dim is None:
137
+ hidden_dim = 4 * dim
138
+ hidden_dim = int(2 * hidden_dim / 3)
139
+ hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
140
+ self.w1 = nn.Linear(dim, hidden_dim, bias=False)
141
+ self.w2 = nn.Linear(hidden_dim, dim, bias=False)
142
+ self.w3 = nn.Linear(dim, hidden_dim, bias=False)
143
+ self.dropout = nn.Dropout(dropout)
144
+
145
+ def forward(self, x):
146
+ return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
147
+
148
+
149
+ class MoEGate(nn.Module):
150
+ def __init__(self, config: LMConfig):
151
+ super().__init__()
152
+ self.config = config
153
+ self.top_k = config.num_experts_per_tok
154
+ self.n_routed_experts = config.n_routed_experts
155
+
156
+ self.scoring_func = config.scoring_func
157
+ self.alpha = config.aux_loss_alpha
158
+ self.seq_aux = config.seq_aux
159
+
160
+ self.norm_topk_prob = config.norm_topk_prob
161
+ self.gating_dim = config.dim
162
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
163
+ self.reset_parameters()
164
+
165
+ def reset_parameters(self) -> None:
166
+ import torch.nn.init as init
167
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
168
+
169
+ def forward(self, hidden_states):
170
+ bsz, seq_len, h = hidden_states.shape
171
+
172
+ hidden_states = hidden_states.view(-1, h)
173
+ logits = F.linear(hidden_states, self.weight, None)
174
+ if self.scoring_func == 'softmax':
175
+ scores = logits.softmax(dim=-1)
176
+ else:
177
+ raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
178
+
179
+ topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
180
+
181
+ if self.top_k > 1 and self.norm_topk_prob:
182
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
183
+ topk_weight = topk_weight / denominator
184
+
185
+ if self.training and self.alpha > 0.0:
186
+ scores_for_aux = scores
187
+ aux_topk = self.top_k
188
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
189
+ if self.seq_aux:
190
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
191
+ ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
192
+ ce.scatter_add_(1, topk_idx_for_aux_loss,
193
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
194
+ seq_len * aux_topk / self.n_routed_experts)
195
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
196
+ else:
197
+ mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
198
+ ce = mask_ce.float().mean(0)
199
+ Pi = scores_for_aux.mean(0)
200
+ fi = ce * self.n_routed_experts
201
+ aux_loss = (Pi * fi).sum() * self.alpha
202
+ else:
203
+ aux_loss = None
204
+ return topk_idx, topk_weight, aux_loss
205
+
206
+
207
+ class MOEFeedForward(nn.Module):
208
+ def __init__(self, config: LMConfig):
209
+ super().__init__()
210
+ self.config = config
211
+ self.experts = nn.ModuleList([
212
+ FeedForward(
213
+ dim=config.dim,
214
+ hidden_dim=config.hidden_dim,
215
+ multiple_of=config.multiple_of,
216
+ dropout=config.dropout,
217
+ )
218
+ for _ in range(config.n_routed_experts)
219
+ ])
220
+
221
+ self.gate = MoEGate(config)
222
+ if config.n_shared_experts is not None:
223
+ self.shared_experts = FeedForward(
224
+ dim=config.dim,
225
+ hidden_dim=config.hidden_dim,
226
+ multiple_of=config.multiple_of,
227
+ dropout=config.dropout,
228
+ )
229
+
230
+ def forward(self, x):
231
+ identity = x
232
+ orig_shape = x.shape
233
+ bsz, seq_len, _ = x.shape
234
+
235
+ # 使用门控机制选择专家
236
+ topk_idx, topk_weight, aux_loss = self.gate(x)
237
+
238
+ x = x.view(-1, x.shape[-1])
239
+ flat_topk_idx = topk_idx.view(-1)
240
+
241
+ if self.training:
242
+ # 训练模式下,重复输入数据
243
+ x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
244
+ y = torch.empty_like(x, dtype=torch.float16)
245
+ for i, expert in enumerate(self.experts):
246
+ y[flat_topk_idx == i] = expert(x[flat_topk_idx == i])
247
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
248
+ y = y.view(*orig_shape)
249
+ else:
250
+ # 推理模式下,只选择最优专家
251
+ y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
252
+
253
+ if self.config.n_shared_experts is not None:
254
+ y = y + self.shared_experts(identity)
255
+
256
+ return y
257
+
258
+ @torch.no_grad()
259
+ def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
260
+ expert_cache = torch.zeros_like(x)
261
+ idxs = flat_expert_indices.argsort()
262
+ tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
263
+ token_idxs = idxs // self.config.num_experts_per_tok
264
+ # 例如当tokens_per_expert=[6, 15, 20, 26, 33, 38, 46, 52]
265
+ # 当token_idxs=[3, 7, 19, 21, 24, 25, 4, 5, 6, 10, 11, 12...]
266
+ # 意味着当token_idxs[:6] -> [3, 7, 19, 21, 24, 25, 4]位置的token都由专家0处理,token_idxs[6:15]位置的token都由专家1处理......
267
+ for i, end_idx in enumerate(tokens_per_expert):
268
+ start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
269
+ if start_idx == end_idx:
270
+ continue
271
+ expert = self.experts[i]
272
+ exp_token_idx = token_idxs[start_idx:end_idx]
273
+ expert_tokens = x[exp_token_idx]
274
+ expert_out = expert(expert_tokens)
275
+ expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
276
+ # 使用 scatter_add_ 进行 sum 操作
277
+ expert_cache.scatter_add_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out)
278
+
279
+ return expert_cache
280
+
281
+
282
+ class TransformerBlock(nn.Module):
283
+ def __init__(self, layer_id: int, args: LMConfig):
284
+ super().__init__()
285
+ self.n_heads = args.n_heads
286
+ self.dim = args.dim
287
+ self.head_dim = args.dim // args.n_heads
288
+ self.attention = Attention(args)
289
+
290
+ self.layer_id = layer_id
291
+ self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
292
+ self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
293
+
294
+ if args.use_moe:
295
+ self.feed_forward = MOEFeedForward(args)
296
+ else:
297
+ self.feed_forward = FeedForward(
298
+ dim=args.dim,
299
+ hidden_dim=args.hidden_dim,
300
+ multiple_of=args.multiple_of,
301
+ dropout=args.dropout,
302
+ )
303
+
304
+ def forward(self, x, pos_cis, kv_cache=False):
305
+ h = x + self.attention(self.attention_norm(x), pos_cis, kv_cache)
306
+ out = h + self.feed_forward(self.ffn_norm(h))
307
+ return out
308
+
309
+
310
+ class Transformer(PreTrainedModel):
311
+ config_class = LMConfig
312
+ last_loss: Optional[torch.Tensor]
313
+
314
+ def __init__(self, params: LMConfig = None):
315
+ super().__init__(params)
316
+ if not params:
317
+ params = LMConfig()
318
+ self.params = params
319
+ self.vocab_size = params.vocab_size
320
+ self.n_layers = params.n_layers
321
+
322
+ self.tok_embeddings = nn.Embedding(params.vocab_size, params.dim)
323
+ self.dropout = nn.Dropout(params.dropout)
324
+ self.layers = torch.nn.ModuleList()
325
+ for layer_id in range(self.n_layers):
326
+ self.layers.append(TransformerBlock(layer_id, params))
327
+ self.norm = RMSNorm(params.dim, eps=params.norm_eps)
328
+ self.output = nn.Linear(params.dim, params.vocab_size, bias=False)
329
+ self.tok_embeddings.weight = self.output.weight
330
+ pos_cis = precompute_pos_cis(self.params.dim // self.params.n_heads, self.params.max_seq_len)
331
+ self.register_buffer("pos_cis", pos_cis, persistent=False)
332
+
333
+ self.apply(self._init_weights)
334
+
335
+ for pn, p in self.named_parameters():
336
+ if pn.endswith('w3.weight') or pn.endswith('wo.weight'):
337
+ torch.nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * params.n_layers))
338
+
339
+ self.last_loss = None
340
+ self.OUT = CausalLMOutputWithPast()
341
+ self._no_split_modules = [name for name, _ in self.named_modules()]
342
+
343
+ def _init_weights(self, module):
344
+ if isinstance(module, nn.Linear):
345
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
346
+ if module.bias is not None:
347
+ torch.nn.init.zeros_(module.bias)
348
+ elif isinstance(module, nn.Embedding):
349
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
350
+
351
+ def forward(self, tokens: Optional[torch.Tensor] = None, targets: Optional[torch.Tensor] = None,
352
+ kv_cache=False, **keyargs):
353
+ current_idx = 0
354
+ if 'input_ids' in keyargs:
355
+ tokens = keyargs['input_ids']
356
+ if 'attention_mask' in keyargs:
357
+ targets = keyargs['attention_mask']
358
+ if 'current_idx' in keyargs:
359
+ current_idx = int(keyargs['current_idx'])
360
+
361
+ _bsz, seqlen = tokens.shape
362
+ h = self.tok_embeddings(tokens)
363
+ h = self.dropout(h)
364
+ pos_cis = self.pos_cis[current_idx:current_idx + seqlen]
365
+ for idx, layer in enumerate(self.layers):
366
+ h = layer(h, pos_cis, kv_cache)
367
+
368
+ h = self.norm(h)
369
+
370
+ if targets is not None:
371
+ logits = self.output(h)
372
+ self.last_loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1),
373
+ ignore_index=0, reduction='none')
374
+ else:
375
+ logits = self.output(h[:, [-1], :])
376
+ self.last_loss = None
377
+
378
+ self.OUT.__setitem__('logits', logits)
379
+ self.OUT.__setitem__('last_loss', self.last_loss)
380
+ return self.OUT
381
+
382
+ @torch.inference_mode()
383
+ def generate(self, idx, eos, max_new_tokens, temperature=0.7, top_k=8, stream=True, rp=1., kv_cache=True):
384
+ # rp: repetition_penalty
385
+ index = idx.shape[1]
386
+ init_inference = True
387
+ while idx.shape[1] < max_new_tokens - 1:
388
+ if init_inference or not kv_cache:
389
+ inference_res, init_inference = self(idx, kv_cache=kv_cache), False
390
+ else:
391
+ inference_res = self(idx[:, -1:], kv_cache=kv_cache, current_idx=idx.shape[1] - 1)
392
+
393
+ logits = inference_res.logits
394
+ logits = logits[:, -1, :]
395
+
396
+ for token in set(idx.tolist()[0]):
397
+ logits[:, token] /= rp
398
+
399
+ if temperature == 0.0:
400
+ _, idx_next = torch.topk(logits, k=1, dim=-1)
401
+ else:
402
+ logits = logits / temperature
403
+ if top_k is not None:
404
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
405
+ logits[logits < v[:, [-1]]] = -float('Inf')
406
+
407
+ probs = F.softmax(logits, dim=-1)
408
+ idx_next = torch.multinomial(probs, num_samples=1, generator=None)
409
+
410
+ if idx_next == eos:
411
+ break
412
+
413
+ idx = torch.cat((idx, idx_next), dim=1)
414
+ if stream:
415
+ yield idx[:, index:]
416
+
417
+ if not stream:
418
+ yield idx[:, index:]
419
+
420
+ @torch.inference_mode()
421
+ def eval_answer(self, idx):
422
+ idx_cond = idx if idx.size(1) <= self.params.max_seq_len else idx[:, -self.params.max_seq_len:]
423
+ inference_res = self(idx_cond)
424
+ logits = inference_res.logits
425
+ logits = logits[:, -1, :]
426
+ return logits
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ }
30
+ },
31
+ "additional_special_tokens": [],
32
+ "bos_token": "<s>",
33
+ "chat_template": "{% if messages[0]['role'] == 'system' %}{% set system_message = messages[0]['content'] %}{% endif %}{% if system_message is defined %}{{ system_message }}{% endif %}{% for message in messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<s>user\\n' + content + '</s>\\n<s>assistant\\n' }}{% elif message['role'] == 'assistant' %}{{ content + '</s>' + '\\n' }}{% endif %}{% endfor %}",
34
+ "clean_up_tokenization_spaces": false,
35
+ "eos_token": "</s>",
36
+ "legacy": true,
37
+ "model_max_length": 1000000000000000019884624838656,
38
+ "pad_token": null,
39
+ "sp_model_kwargs": {},
40
+ "spaces_between_special_tokens": false,
41
+ "tokenizer_class": "PreTrainedTokenizerFast",
42
+ "unk_token": "<unk>",
43
+ "use_default_system_prompt": false
44
+ }