TheBloke commited on
Commit
a7cb522
1 Parent(s): 8cb3df9

GPTQ model commit

Browse files
License_Agreement_for_Large_Language_Models_Nanbeige.pdf ADDED
Binary file (181 kB). View file
 
config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/workspace/process/nanbeige_nanbeige-16b-base-32k/source",
3
+ "architectures": [
4
+ "NanbeigeForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_nanbeige.NanbeigeConfig",
8
+ "AutoModelForCausalLM": "modeling_nanbeige.NanbeigeForCausalLM"
9
+ },
10
+ "bos_token_id": 1,
11
+ "eos_token_id": 2,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 5120,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 13824,
16
+ "max_length": 4096,
17
+ "max_position_embeddings": 4096,
18
+ "model_type": "nanbeige",
19
+ "num_attention_heads": 40,
20
+ "num_hidden_layers": 48,
21
+ "num_key_value_heads": 40,
22
+ "pad_token_id": 0,
23
+ "pretraining_tp": 1,
24
+ "quantization_config": {
25
+ "batch_size": 1,
26
+ "bits": 4,
27
+ "block_name_to_quantize": "model.layers",
28
+ "cache_block_outputs": true,
29
+ "damp_percent": 0.1,
30
+ "desc_act": true,
31
+ "exllama_config": {
32
+ "version": 1
33
+ },
34
+ "group_size": 128,
35
+ "max_input_length": null,
36
+ "model_seqlen": 4096,
37
+ "module_name_preceding_first_block": [
38
+ "model.embed_tokens"
39
+ ],
40
+ "pad_token_id": null,
41
+ "quant_method": "gptq",
42
+ "sym": true,
43
+ "tokenizer": null,
44
+ "true_sequential": true,
45
+ "use_cuda_fp16": false,
46
+ "use_exllama": true
47
+ },
48
+ "rms_norm_eps": 1e-05,
49
+ "rope_scaling": null,
50
+ "tie_word_embeddings": false,
51
+ "torch_dtype": "bfloat16",
52
+ "transformers_version": "4.35.2",
53
+ "use_cache": true,
54
+ "vocab_size": 59392,
55
+ "yarn_scale": 8
56
+ }
configuration_nanbeige.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Nanbeige LLM Lab All Rights Reserved.
2
+
3
+ """ Nanbeige model configuration"""
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+ from transformers.utils import logging
7
+
8
+
9
+ logger = logging.get_logger(__name__)
10
+
11
+ NANBEIGE_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
12
+
13
+
14
+ class NanbeigeConfig(PretrainedConfig):
15
+ model_type = "nanbeige"
16
+
17
+ def __init__(
18
+ self,
19
+ vocab_size=59392,
20
+ hidden_size=4096,
21
+ intermediate_size=11008,
22
+ num_hidden_layers=48,
23
+ num_attention_heads=32,
24
+ hidden_act="silu",
25
+ max_position_embeddings=2048,
26
+ initializer_range=0.02,
27
+ rms_norm_eps=1e-6,
28
+ use_cache=True,
29
+ pad_token_id=0,
30
+ bos_token_id=1,
31
+ eos_token_id=2,
32
+ tie_word_embeddings=False,
33
+ yarn_scale=1.,
34
+ **kwargs,
35
+ ):
36
+ self.vocab_size = vocab_size
37
+ self.max_position_embeddings = max_position_embeddings
38
+ self.hidden_size = hidden_size
39
+ self.intermediate_size = intermediate_size
40
+ self.num_hidden_layers = num_hidden_layers
41
+ self.num_attention_heads = num_attention_heads
42
+ self.hidden_act = hidden_act
43
+ self.initializer_range = initializer_range
44
+ self.rms_norm_eps = rms_norm_eps
45
+ self.use_cache = use_cache
46
+ self.yarn_scale = yarn_scale
47
+ super().__init__(
48
+ pad_token_id=pad_token_id,
49
+ bos_token_id=bos_token_id,
50
+ eos_token_id=eos_token_id,
51
+ tie_word_embeddings=tie_word_embeddings,
52
+ **kwargs,
53
+ )
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "max_length": 4096,
6
+ "pad_token_id": 0,
7
+ "temperature": 0.9,
8
+ "top_p": 0.6,
9
+ "transformers_version": "4.28.1"
10
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00d59afba6bcf60ccda3f66a2e4b6fdbf904b71d391ead1917ed9d83dc4e01ea
3
+ size 4992265936
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7227a4560a36ebf284377ff0ebea45fa22e848e1ce2485a70472186040f1dc83
3
+ size 4148988128
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_nanbeige.py ADDED
@@ -0,0 +1,946 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import queue
3
+ import threading
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ import torch.utils.checkpoint
8
+ from torch import nn
9
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
10
+ from transformers.activations import ACT2FN
11
+ from transformers.generation.streamers import BaseStreamer
12
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, \
13
+ SequenceClassifierOutputWithPast
14
+ from transformers.modeling_utils import PreTrainedModel
15
+ from transformers.utils import logging
16
+
17
+ from .configuration_nanbeige import NanbeigeConfig
18
+
19
+ logger = logging.get_logger(__name__)
20
+ NANBEIGE_SYSTEM_PROMPT = "你是一个名为\"南北阁\"的人工智能助手,正在与人类用户进行交谈。你的目标是以最有帮助和最逻辑的方式回答问题,同时确保内容的安全性。你的回答中不应包含任何有害、政治化、宗教化、不道德、种族主义、性别歧视、有毒、危险或非法的内容。请确保你的回答不带有社会偏见,并且始终积极正面,符合社会主义价值观。如果遇到的问题无意义或事实上不连贯,请不要回答错误的内容,而是解释问题为何无效或不连贯。如果你不知道问题的答案,也请勿提供错误的信息。你是由南北阁大模型实验室的LLM团队训练的。知识截止日期是2023年9月。"
21
+
22
+ try:
23
+ import flash_attn
24
+ from flash_attn import flash_attn_func
25
+
26
+ if int(flash_attn.__version__.split(".")[0]) >= 2 and int(flash_attn.__version__.split(".")[1]) >= 1:
27
+ Version_ = True
28
+ else:
29
+ Version_ = False
30
+ except:
31
+ logger.warn(
32
+ "Warning: import flash_attn fail, please install FlashAttention to get higher efficiency "
33
+ "https://github.com/Dao-AILab/flash-attention"
34
+ )
35
+ Version_ = False
36
+ flash_attn_func = None
37
+
38
+
39
+ def _make_causal_mask(
40
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
41
+ ):
42
+ """
43
+ Make causal mask used for bi-directional self-attention.
44
+ """
45
+ bsz, tgt_len = input_ids_shape
46
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
47
+ mask_cond = torch.arange(mask.size(-1), device=device)
48
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
49
+ mask = mask.to(dtype)
50
+
51
+ if past_key_values_length > 0:
52
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
53
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
54
+
55
+
56
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
57
+ """
58
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
59
+ """
60
+ bsz, src_len = mask.size()
61
+ tgt_len = tgt_len if tgt_len is not None else src_len
62
+
63
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
64
+
65
+ inverted_mask = 1.0 - expanded_mask
66
+
67
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
68
+
69
+
70
+ def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
71
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base))
72
+
73
+
74
+ def find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
75
+ low = math.floor(find_correction_dim(
76
+ low_rot, dim, base, max_position_embeddings))
77
+ high = math.ceil(find_correction_dim(
78
+ high_rot, dim, base, max_position_embeddings))
79
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
80
+
81
+
82
+ def linear_ramp_mask(min, max, dim):
83
+ if min == max:
84
+ max += 0.001 # Prevent singularity
85
+
86
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
87
+ ramp_func = torch.clamp(linear_func, 0, 1)
88
+ return ramp_func
89
+
90
+
91
+ def get_mscale(scale=1):
92
+ if scale <= 1:
93
+ return 1.0
94
+ return 0.1 * math.log(scale) + 1.0
95
+
96
+
97
+ class YaRNScaledRotaryEmbedding(torch.nn.Module):
98
+ def __init__(self, dim, base=10000, scale=1, original_max_position_embeddings=4096,
99
+ extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
100
+ super().__init__()
101
+ self.dim = dim
102
+ self.max_position_embeddings = original_max_position_embeddings * scale
103
+ self.base = base
104
+ self.scale = scale
105
+ self.original_max_position_embeddings = original_max_position_embeddings
106
+ self.extrapolation_factor = extrapolation_factor
107
+ self.attn_factor = attn_factor
108
+ self.beta_fast = beta_fast
109
+ self.beta_slow = beta_slow
110
+
111
+ self.yarn(device)
112
+
113
+ # Build here to make `torch.jit.trace` work.
114
+ self.max_seq_len_cached = original_max_position_embeddings*scale
115
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
116
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
117
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
118
+ emb = torch.cat((freqs, freqs), dim=-1)
119
+ dtype = torch.get_default_dtype()
120
+
121
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale)[None, None, :, :].to(dtype), persistent=False)
122
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale)[None, None, :, :].to(dtype), persistent=False)
123
+
124
+ def forward(self, x, seq_len=None):
125
+ # x: [bs, num_attention_heads, seq_len, head_size]
126
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
127
+ if seq_len > self.max_seq_len_cached:
128
+ self.max_seq_len_cached = seq_len
129
+
130
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
131
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
132
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
133
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
134
+
135
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale)[None, None, :, :].to(x.dtype),
136
+ persistent=False)
137
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale)[None, None, :, :].to(x.dtype),
138
+ persistent=False)
139
+ return (
140
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
141
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
142
+ )
143
+
144
+ def yarn(self, device):
145
+ pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
146
+ inv_freq_extrapolation = 1.0 / pos_freqs
147
+ inv_freq_interpolation = 1.0 / (self.scale * pos_freqs)
148
+
149
+ low, high = find_correction_range(self.beta_fast, self.beta_slow, self.dim, self.base,
150
+ self.original_max_position_embeddings)
151
+ inv_freq_mask = (1 - linear_ramp_mask(low, high, self.dim // 2).float().to(
152
+ device)) * self.extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
153
+ inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
154
+
155
+ self.register_buffer("inv_freq", inv_freq)
156
+ self.mscale = float(
157
+ get_mscale(self.scale) * self.attn_factor) # Get n-d magnitude scaling corrected for interpolation
158
+
159
+
160
+ class RMSNorm(nn.Module):
161
+ def __init__(self, hidden_size, eps=1e-6):
162
+ super().__init__()
163
+ self.weight = nn.Parameter(torch.ones(hidden_size))
164
+ self.variance_epsilon = eps
165
+
166
+ def forward(self, hidden_states):
167
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
168
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
169
+
170
+ # convert into half-precision if necessary
171
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
172
+ hidden_states = hidden_states.to(self.weight.dtype)
173
+
174
+ return self.weight * hidden_states
175
+
176
+
177
+ class RotaryEmbedding(torch.nn.Module):
178
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
179
+ super().__init__()
180
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
181
+ self.register_buffer("inv_freq", inv_freq)
182
+ self.max_seq_len_cached = max_position_embeddings
183
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
184
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
185
+ emb = torch.cat((freqs, freqs), dim=-1)
186
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
187
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
188
+
189
+ def forward(self, x, seq_len=None):
190
+ # x: [bs, num_attention_heads, seq_len, head_size]
191
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
192
+ if seq_len > self.max_seq_len_cached:
193
+ self.max_seq_len_cached = seq_len
194
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
195
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
196
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
197
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
198
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
199
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
200
+ return (
201
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
202
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
203
+ )
204
+
205
+
206
+ def rotate_half(x):
207
+ """Rotates half the hidden dims of the input."""
208
+ x1 = x[..., : x.shape[-1] // 2]
209
+ x2 = x[..., x.shape[-1] // 2:]
210
+ return torch.cat((-x2, x1), dim=-1)
211
+
212
+
213
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
214
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
215
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
216
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
217
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
218
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
219
+ q_embed = (q * cos) + (rotate_half(q) * sin)
220
+ k_embed = (k * cos) + (rotate_half(k) * sin)
221
+ return q_embed, k_embed
222
+
223
+
224
+ class NanbeigeMLP(nn.Module):
225
+ def __init__(
226
+ self,
227
+ hidden_size: int,
228
+ intermediate_size: int,
229
+ hidden_act: str,
230
+ ):
231
+ super().__init__()
232
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
233
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
234
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
235
+ self.act_fn = ACT2FN[hidden_act]
236
+
237
+ def forward(self, x):
238
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
239
+
240
+
241
+ class NanbeigeAttention(nn.Module):
242
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
243
+
244
+ def __init__(self, config: NanbeigeConfig):
245
+ super().__init__()
246
+ self.config = config
247
+ self.hidden_size = config.hidden_size
248
+ self.num_heads = config.num_attention_heads
249
+ self.head_dim = self.hidden_size // self.num_heads
250
+ self.max_position_embeddings = config.max_position_embeddings
251
+
252
+ if (self.head_dim * self.num_heads) != self.hidden_size:
253
+ raise ValueError(
254
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
255
+ f" and `num_heads`: {self.num_heads})."
256
+ )
257
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
258
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
259
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
260
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
261
+ if self.config.yarn_scale > 1:
262
+ self.rotary_emb = YaRNScaledRotaryEmbedding(self.head_dim, scale=self.config.yarn_scale,
263
+ original_max_position_embeddings=self.max_position_embeddings)
264
+ else:
265
+ self.rotary_emb = RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
266
+
267
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
268
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
269
+
270
+ def forward(
271
+ self,
272
+ hidden_states: torch.Tensor,
273
+ attention_mask: Optional[torch.Tensor] = None,
274
+ position_ids: Optional[torch.LongTensor] = None,
275
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
276
+ output_attentions: bool = False,
277
+ use_cache: bool = False,
278
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
279
+ bsz, q_len, _ = hidden_states.size()
280
+
281
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
282
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
283
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
284
+
285
+ kv_seq_len = key_states.shape[-2]
286
+ if past_key_value is not None:
287
+ kv_seq_len += past_key_value[0].shape[-2]
288
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
289
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
290
+
291
+ if past_key_value is not None:
292
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
293
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
294
+
295
+ past_key_value = (key_states, value_states) if use_cache else None
296
+
297
+ if Version_ or (flash_attn_func and query_states.size() == key_states.size()):
298
+ attn_output = flash_attn_func(query_states.transpose(1, 2), key_states.transpose(1, 2),
299
+ value_states.transpose(1, 2), dropout_p=0.0, softmax_scale=None, causal=True)
300
+ else:
301
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
302
+
303
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
304
+ raise ValueError(
305
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
306
+ f" {attn_weights.size()}"
307
+ )
308
+
309
+ if attention_mask is not None:
310
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
311
+ raise ValueError(
312
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
313
+ )
314
+ attn_weights = attn_weights + attention_mask
315
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
316
+
317
+ # upcast attention to fp32
318
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
319
+ attn_output = torch.matmul(attn_weights, value_states)
320
+
321
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
322
+ raise ValueError(
323
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
324
+ f" {attn_output.size()}"
325
+ )
326
+
327
+ attn_output = attn_output.transpose(1, 2)
328
+
329
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
330
+
331
+ attn_output = self.o_proj(attn_output)
332
+
333
+ if not output_attentions:
334
+ attn_weights = None
335
+
336
+ return attn_output, attn_weights, past_key_value
337
+
338
+
339
+ class NanbeigeDecoderLayer(nn.Module):
340
+ def __init__(self, config: NanbeigeConfig):
341
+ super().__init__()
342
+ self.hidden_size = config.hidden_size
343
+ self.self_attn = NanbeigeAttention(config=config)
344
+ self.mlp = NanbeigeMLP(
345
+ hidden_size=self.hidden_size,
346
+ intermediate_size=config.intermediate_size,
347
+ hidden_act=config.hidden_act,
348
+ )
349
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
350
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
351
+
352
+ def forward(
353
+ self,
354
+ hidden_states: torch.Tensor,
355
+ attention_mask: Optional[torch.Tensor] = None,
356
+ position_ids: Optional[torch.LongTensor] = None,
357
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
358
+ output_attentions: Optional[bool] = False,
359
+ use_cache: Optional[bool] = False,
360
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
361
+ """
362
+ Args:
363
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
364
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
365
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
366
+ output_attentions (`bool`, *optional*):
367
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
368
+ returned tensors for more detail.
369
+ use_cache (`bool`, *optional*):
370
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
371
+ (see `past_key_values`).
372
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
373
+ """
374
+
375
+ residual = hidden_states
376
+
377
+ hidden_states = self.input_layernorm(hidden_states)
378
+
379
+ # Self Attention
380
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
381
+ hidden_states=hidden_states,
382
+ attention_mask=attention_mask,
383
+ position_ids=position_ids,
384
+ past_key_value=past_key_value,
385
+ output_attentions=output_attentions,
386
+ use_cache=use_cache,
387
+ )
388
+ hidden_states = residual + hidden_states
389
+
390
+ # Fully Connected
391
+ residual = hidden_states
392
+ hidden_states = self.post_attention_layernorm(hidden_states)
393
+ hidden_states = self.mlp(hidden_states)
394
+ hidden_states = residual + hidden_states
395
+
396
+ outputs = (hidden_states,)
397
+
398
+ if output_attentions:
399
+ outputs += (self_attn_weights,)
400
+
401
+ if use_cache:
402
+ outputs += (present_key_value,)
403
+
404
+ return outputs
405
+
406
+
407
+ class NanbeigePreTrainedModel(PreTrainedModel):
408
+ config_class = NanbeigeConfig
409
+ base_model_prefix = "model"
410
+ supports_gradient_checkpointing = True
411
+ _no_split_modules = ["NanbeigeDecoderLayer"]
412
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
413
+
414
+ def _init_weights(self, module):
415
+ std = self.config.initializer_range
416
+ if isinstance(module, nn.Linear):
417
+ module.weight.data.normal_(mean=0.0, std=std)
418
+ if module.bias is not None:
419
+ module.bias.data.zero_()
420
+ elif isinstance(module, nn.Embedding):
421
+ module.weight.data.normal_(mean=0.0, std=std)
422
+ if module.padding_idx is not None:
423
+ module.weight.data[module.padding_idx].zero_()
424
+
425
+ def _set_gradient_checkpointing(self, module, value=False):
426
+ if isinstance(module, NanbeigeModel):
427
+ module.gradient_checkpointing = value
428
+
429
+
430
+ class NanbeigeModel(NanbeigePreTrainedModel):
431
+ def __init__(self, config: NanbeigeConfig):
432
+ super().__init__(config)
433
+ self.padding_idx = config.pad_token_id
434
+ self.vocab_size = config.vocab_size
435
+
436
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
437
+ self.layers = nn.ModuleList([NanbeigeDecoderLayer(config) for _ in range(config.num_hidden_layers)])
438
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
439
+
440
+ self.gradient_checkpointing = False
441
+ # Initialize weights and apply final processing
442
+ self.post_init()
443
+
444
+ def get_input_embeddings(self):
445
+ return self.embed_tokens
446
+
447
+ def set_input_embeddings(self, value):
448
+ self.embed_tokens = value
449
+
450
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
451
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
452
+ # create causal mask
453
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
454
+ combined_attention_mask = None
455
+ if input_shape[-1] > 1:
456
+ combined_attention_mask = _make_causal_mask(
457
+ input_shape,
458
+ inputs_embeds.dtype,
459
+ device=inputs_embeds.device,
460
+ past_key_values_length=past_key_values_length,
461
+ )
462
+
463
+ if attention_mask is not None:
464
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
465
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
466
+ inputs_embeds.device
467
+ )
468
+ combined_attention_mask = (
469
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
470
+ )
471
+
472
+ return combined_attention_mask
473
+
474
+ def forward(
475
+ self,
476
+ input_ids: torch.LongTensor = None,
477
+ attention_mask: Optional[torch.Tensor] = None,
478
+ position_ids: Optional[torch.LongTensor] = None,
479
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
480
+ inputs_embeds: Optional[torch.FloatTensor] = None,
481
+ use_cache: Optional[bool] = None,
482
+ output_attentions: Optional[bool] = None,
483
+ output_hidden_states: Optional[bool] = None,
484
+ return_dict: Optional[bool] = None,
485
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
486
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
487
+ output_hidden_states = (
488
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
489
+ )
490
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
491
+
492
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
493
+
494
+ # retrieve input_ids and inputs_embeds
495
+ if input_ids is not None and inputs_embeds is not None:
496
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
497
+ elif input_ids is not None:
498
+ batch_size, seq_length = input_ids.shape
499
+ elif inputs_embeds is not None:
500
+ batch_size, seq_length, _ = inputs_embeds.shape
501
+ else:
502
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
503
+
504
+ seq_length_with_past = seq_length
505
+ past_key_values_length = 0
506
+
507
+ if past_key_values is not None:
508
+ past_key_values_length = past_key_values[0][0].shape[2]
509
+ seq_length_with_past = seq_length_with_past + past_key_values_length
510
+ else:
511
+ past_key_values = [None for _ in range(len(self.layers))]
512
+
513
+ if position_ids is None:
514
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
515
+ position_ids = torch.arange(
516
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
517
+ )
518
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
519
+ else:
520
+ position_ids = position_ids.view(-1, seq_length).long()
521
+
522
+ if inputs_embeds is None:
523
+ inputs_embeds = self.embed_tokens(input_ids)
524
+ # embed positions
525
+ if attention_mask is None:
526
+ attention_mask = torch.ones(
527
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
528
+ )
529
+ attention_mask = self._prepare_decoder_attention_mask(
530
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
531
+ )
532
+
533
+ hidden_states = inputs_embeds
534
+
535
+ if self.gradient_checkpointing and self.training:
536
+ if use_cache:
537
+ logger.warning_once(
538
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
539
+ )
540
+ use_cache = False
541
+
542
+ # decoder layers
543
+ all_hidden_states = () if output_hidden_states else None
544
+ all_self_attns = () if output_attentions else None
545
+ next_cache = [] if use_cache else None
546
+
547
+ for idx, decoder_layer in enumerate(self.layers):
548
+ if output_hidden_states:
549
+ all_hidden_states += (hidden_states,)
550
+
551
+ past_key_value = past_key_values.pop(0) if past_key_values is not None else None
552
+
553
+ if self.gradient_checkpointing and self.training:
554
+
555
+ def create_custom_forward(module):
556
+ def custom_forward(*inputs):
557
+ # None for past_key_value
558
+ return module(*inputs, output_attentions, None)
559
+
560
+ return custom_forward
561
+
562
+ layer_outputs = torch.utils.checkpoint.checkpoint(
563
+ create_custom_forward(decoder_layer),
564
+ hidden_states,
565
+ attention_mask,
566
+ position_ids,
567
+ None,
568
+ )
569
+ else:
570
+ layer_outputs = decoder_layer(
571
+ hidden_states,
572
+ attention_mask=attention_mask,
573
+ position_ids=position_ids,
574
+ past_key_value=past_key_value,
575
+ output_attentions=output_attentions,
576
+ use_cache=use_cache,
577
+ )
578
+
579
+ hidden_states = layer_outputs[0]
580
+
581
+ if use_cache:
582
+ next_cache.append(layer_outputs[2 if output_attentions else 1])
583
+
584
+ if output_attentions:
585
+ all_self_attns += (layer_outputs[1],)
586
+
587
+ hidden_states = self.norm(hidden_states)
588
+
589
+ # add hidden states from the last decoder layer
590
+ if output_hidden_states:
591
+ all_hidden_states += (hidden_states,)
592
+
593
+ if not return_dict:
594
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
595
+ return BaseModelOutputWithPast(
596
+ last_hidden_state=hidden_states,
597
+ past_key_values=next_cache,
598
+ hidden_states=all_hidden_states,
599
+ attentions=all_self_attns,
600
+ )
601
+
602
+
603
+ class NanbeigeForCausalLM(NanbeigePreTrainedModel):
604
+ def __init__(self, config):
605
+ super().__init__(config)
606
+ self.model = NanbeigeModel(config)
607
+
608
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
609
+
610
+ # Initialize weights and apply final processing
611
+ self.post_init()
612
+
613
+ def get_input_embeddings(self):
614
+ return self.model.embed_tokens
615
+
616
+ def set_input_embeddings(self, value):
617
+ self.model.embed_tokens = value
618
+
619
+ def get_output_embeddings(self):
620
+ return self.lm_head
621
+
622
+ def set_output_embeddings(self, new_embeddings):
623
+ self.lm_head = new_embeddings
624
+
625
+ def set_decoder(self, decoder):
626
+ self.model = decoder
627
+
628
+ def get_decoder(self):
629
+ return self.model
630
+
631
+ def forward(
632
+ self,
633
+ input_ids: torch.LongTensor = None,
634
+ attention_mask: Optional[torch.Tensor] = None,
635
+ position_ids: Optional[torch.LongTensor] = None,
636
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
637
+ inputs_embeds: Optional[torch.FloatTensor] = None,
638
+ labels: Optional[torch.LongTensor] = None,
639
+ use_cache: Optional[bool] = None,
640
+ output_attentions: Optional[bool] = None,
641
+ output_hidden_states: Optional[bool] = None,
642
+ return_dict: Optional[bool] = None,
643
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
644
+
645
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
646
+ output_hidden_states = (
647
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
648
+ )
649
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
650
+
651
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
652
+ outputs = self.model(
653
+ input_ids=input_ids,
654
+ attention_mask=attention_mask,
655
+ position_ids=position_ids,
656
+ past_key_values=past_key_values,
657
+ inputs_embeds=inputs_embeds,
658
+ use_cache=use_cache,
659
+ output_attentions=output_attentions,
660
+ output_hidden_states=output_hidden_states,
661
+ return_dict=return_dict,
662
+ )
663
+
664
+ hidden_states = outputs[0]
665
+ logits = self.lm_head(hidden_states)
666
+
667
+ loss = None
668
+ if labels is not None:
669
+ # Shift so that tokens < n predict n
670
+ shift_logits = logits[..., :-1, :].contiguous()
671
+ shift_labels = labels[..., 1:].contiguous()
672
+ # Flatten the tokens
673
+ loss_fct = CrossEntropyLoss()
674
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
675
+ shift_labels = shift_labels.view(-1)
676
+ # Enable model parallelism
677
+ shift_labels = shift_labels.to(shift_logits.device)
678
+ loss = loss_fct(shift_logits, shift_labels)
679
+
680
+ if not return_dict:
681
+ output = (logits,) + outputs[1:]
682
+ return (loss,) + output if loss is not None else output
683
+
684
+ return CausalLMOutputWithPast(
685
+ loss=loss,
686
+ logits=logits,
687
+ past_key_values=outputs.past_key_values,
688
+ hidden_states=outputs.hidden_states,
689
+ attentions=outputs.attentions,
690
+ )
691
+
692
+ def prepare_inputs_for_generation(
693
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
694
+ ):
695
+ if past_key_values:
696
+ input_ids = input_ids[:, -1:]
697
+
698
+ position_ids = kwargs.get("position_ids", None)
699
+ if attention_mask is not None and position_ids is None:
700
+ # create position_ids on the fly for batch generation
701
+ position_ids = attention_mask.long().cumsum(-1) - 1
702
+ position_ids.masked_fill_(attention_mask == 0, 1)
703
+ if past_key_values:
704
+ position_ids = position_ids[:, -1].unsqueeze(-1)
705
+
706
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
707
+ if inputs_embeds is not None and past_key_values is None:
708
+ model_inputs = {"inputs_embeds": inputs_embeds}
709
+ else:
710
+ model_inputs = {"input_ids": input_ids}
711
+
712
+ model_inputs.update(
713
+ {
714
+ "position_ids": position_ids,
715
+ "past_key_values": past_key_values,
716
+ "use_cache": kwargs.get("use_cache"),
717
+ "attention_mask": attention_mask,
718
+ }
719
+ )
720
+ return model_inputs
721
+
722
+ @staticmethod
723
+ def _reorder_cache(past_key_values, beam_idx):
724
+ reordered_past = ()
725
+ for layer_past in past_key_values:
726
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
727
+ return reordered_past
728
+
729
+ def build_prompt_input(self, tokenizer, query, messages):
730
+ prompt = ""
731
+ for message in messages:
732
+ if message['role'] == 'human':
733
+ prompt += f"""### Human: \n{message['content']}\n\n"""
734
+ elif message['role'] == 'assistant':
735
+ prompt += f"""### Assistant: {message['content']}</s>"""
736
+ elif message['role'] == 'system':
737
+ prompt += f"""### System:{message['content']}\n</s>"""
738
+ prompt += f"""### Human: \n{query}\n\n### Assistant: """
739
+ return tokenizer([prompt], return_tensors="pt")
740
+
741
+ @torch.no_grad()
742
+ def chat(self,
743
+ tokenizer,
744
+ query: str,
745
+ messages: List[dict] = None,
746
+ streamer: Optional[BaseStreamer] = None,
747
+ max_new_tokens: int = 512,
748
+ do_sample: bool = True,
749
+ temperature: float = 0.3,
750
+ top_p: float = 0.9,
751
+ **kwargs):
752
+ if messages is None:
753
+ messages = [{'role': 'system', 'content': NANBEIGE_SYSTEM_PROMPT}]
754
+
755
+ inputs = self.build_prompt_input(tokenizer, query, messages)
756
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
757
+ outputs = self.generate(**inputs,
758
+ streamer=streamer,
759
+ max_new_tokens=max_new_tokens,
760
+ do_sample=do_sample,
761
+ temperature=temperature,
762
+ top_p=top_p,
763
+ **kwargs)
764
+ outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]):]
765
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
766
+ response = response.split("</s>")[0]
767
+ messages.append({'role': 'human', 'content': query})
768
+ messages.append({'role': 'assistant', 'content': response})
769
+ return response, messages
770
+
771
+ @torch.no_grad()
772
+ def stream_chat(self,
773
+ tokenizer,
774
+ query: str,
775
+ messages: List[dict] = None,
776
+ max_new_tokens: int = 1024,
777
+ do_sample: bool = True,
778
+ temperature: float = 0.8,
779
+ top_p: float = 0.8,
780
+ **kwargs):
781
+
782
+ response_queue = queue.Queue(maxsize=20)
783
+ if messages is None:
784
+ messages = [{'role': 'system', 'content': NANBEIGE_SYSTEM_PROMPT}]
785
+
786
+ class ChatStreamer(BaseStreamer):
787
+ def __init__(self, tokenizer) -> None:
788
+ super().__init__()
789
+ self.tokenizer = tokenizer
790
+ self.queue = response_queue
791
+ self.query = query
792
+ self.messages = messages
793
+ self.response = ""
794
+ self.received_inputs = False
795
+ self.queue.put((self.response, messages + [{'role': 'human', 'content': self.query},
796
+ {'role': 'assistant', 'content': self.response}]))
797
+
798
+ def put(self, value):
799
+ if len(value.shape) > 1 and value.shape[0] > 1:
800
+ raise ValueError("ChatStreamer only supports batch size 1")
801
+ elif len(value.shape) > 1:
802
+ value = value[0]
803
+
804
+ if not self.received_inputs:
805
+ # The first received value is input_ids, ignore here
806
+ self.received_inputs = True
807
+ return
808
+
809
+ token = self.tokenizer.decode([value[-1]], skip_special_tokens=True)
810
+ if token.strip() != "</s>":
811
+ self.response = self.response + token
812
+ messages = self.messages + [{'role': 'human', 'content': self.query},
813
+ {'role': 'assistant', 'content': self.response}]
814
+ self.queue.put((self.response, messages))
815
+
816
+ def end(self):
817
+ self.queue.put(None)
818
+
819
+ def stream_task():
820
+ return self.chat(
821
+ tokenizer=tokenizer,
822
+ query=query,
823
+ messages=messages,
824
+ streamer=ChatStreamer(tokenizer=tokenizer),
825
+ max_new_tokens=max_new_tokens,
826
+ do_sample=do_sample,
827
+ temperature=temperature,
828
+ top_p=top_p,
829
+ **kwargs
830
+ )
831
+
832
+ def consumer():
833
+ threading.Thread(target=stream_task).start()
834
+ while True:
835
+ res = response_queue.get()
836
+ if res is None:
837
+ return
838
+ yield res
839
+
840
+ return consumer()
841
+
842
+
843
+ class NanbeigeForSequenceClassification(NanbeigePreTrainedModel):
844
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
845
+
846
+ def __init__(self, config):
847
+ super().__init__(config)
848
+ self.num_labels = config.num_labels
849
+ self.model = NanbeigeModel(config)
850
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
851
+
852
+ # Initialize weights and apply final processing
853
+ self.post_init()
854
+
855
+ def get_input_embeddings(self):
856
+ return self.model.embed_tokens
857
+
858
+ def set_input_embeddings(self, value):
859
+ self.model.embed_tokens = value
860
+
861
+ def forward(
862
+ self,
863
+ input_ids: torch.LongTensor = None,
864
+ attention_mask: Optional[torch.Tensor] = None,
865
+ position_ids: Optional[torch.LongTensor] = None,
866
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
867
+ inputs_embeds: Optional[torch.FloatTensor] = None,
868
+ labels: Optional[torch.LongTensor] = None,
869
+ use_cache: Optional[bool] = None,
870
+ output_attentions: Optional[bool] = None,
871
+ output_hidden_states: Optional[bool] = None,
872
+ return_dict: Optional[bool] = None,
873
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
874
+ r"""
875
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
876
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
877
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
878
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
879
+ """
880
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
881
+
882
+ transformer_outputs = self.model(
883
+ input_ids,
884
+ attention_mask=attention_mask,
885
+ position_ids=position_ids,
886
+ past_key_values=past_key_values,
887
+ inputs_embeds=inputs_embeds,
888
+ use_cache=use_cache,
889
+ output_attentions=output_attentions,
890
+ output_hidden_states=output_hidden_states,
891
+ return_dict=return_dict,
892
+ )
893
+ hidden_states = transformer_outputs[0]
894
+ logits = self.score(hidden_states)
895
+
896
+ if input_ids is not None:
897
+ batch_size = input_ids.shape[0]
898
+ else:
899
+ batch_size = inputs_embeds.shape[0]
900
+
901
+ if self.config.pad_token_id is None and batch_size != 1:
902
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
903
+ if self.config.pad_token_id is None:
904
+ sequence_lengths = -1
905
+ else:
906
+ if input_ids is not None:
907
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
908
+ else:
909
+ sequence_lengths = -1
910
+
911
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
912
+
913
+ loss = None
914
+ if labels is not None:
915
+ labels = labels.to(logits.device)
916
+ if self.config.problem_type is None:
917
+ if self.num_labels == 1:
918
+ self.config.problem_type = "regression"
919
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
920
+ self.config.problem_type = "single_label_classification"
921
+ else:
922
+ self.config.problem_type = "multi_label_classification"
923
+
924
+ if self.config.problem_type == "regression":
925
+ loss_fct = MSELoss()
926
+ if self.num_labels == 1:
927
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
928
+ else:
929
+ loss = loss_fct(pooled_logits, labels)
930
+ elif self.config.problem_type == "single_label_classification":
931
+ loss_fct = CrossEntropyLoss()
932
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
933
+ elif self.config.problem_type == "multi_label_classification":
934
+ loss_fct = BCEWithLogitsLoss()
935
+ loss = loss_fct(pooled_logits, labels)
936
+ if not return_dict:
937
+ output = (pooled_logits,) + transformer_outputs[1:]
938
+ return ((loss,) + output) if loss is not None else output
939
+
940
+ return SequenceClassifierOutputWithPast(
941
+ loss=loss,
942
+ logits=pooled_logits,
943
+ past_key_values=transformer_outputs.past_key_values,
944
+ hidden_states=transformer_outputs.hidden_states,
945
+ attentions=transformer_outputs.attentions,
946
+ )
quantize_config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bits": [
3
+ 4
4
+ ],
5
+ "group_size": [
6
+ 128
7
+ ],
8
+ "damp_percent": [
9
+ 0.1
10
+ ],
11
+ "desc_act": [
12
+ true
13
+ ],
14
+ "sym": true,
15
+ "true_sequential": true
16
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenization_nanbeige.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Nanbeige LLM Lab All Rights Reserved.
2
+
3
+ """Tokenization classes for Nanbeige."""
4
+ import os
5
+ from shutil import copyfile
6
+ from typing import Any, Dict, List, Optional, Tuple
7
+
8
+ import sentencepiece as spm
9
+
10
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
11
+ from transformers.utils import logging
12
+
13
+
14
+ logger = logging.get_logger(__name__)
15
+
16
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
17
+
18
+ PRETRAINED_VOCAB_FILES_MAP = {
19
+ "vocab_file": {},
20
+ "tokenizer_file": {},
21
+ }
22
+
23
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
24
+
25
+
26
+ class NanbeigeTokenizer(PreTrainedTokenizer):
27
+ """
28
+ Construct a Nanbeige tokenizer. Based on byte-level Byte-Pair-Encoding.
29
+
30
+ Args:
31
+ vocab_file (`str`):
32
+ Path to the vocabulary file.
33
+ """
34
+
35
+ vocab_files_names = VOCAB_FILES_NAMES
36
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
37
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
38
+ model_input_names = ["input_ids", "attention_mask"]
39
+
40
+ def __init__(
41
+ self,
42
+ vocab_file,
43
+ unk_token="<unk>",
44
+ bos_token="<s>",
45
+ eos_token="</s>",
46
+ pad_token=None,
47
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
48
+ add_bos_token=True,
49
+ add_eos_token=False,
50
+ clean_up_tokenization_spaces=False,
51
+ **kwargs,
52
+ ):
53
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
54
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
55
+ self.sp_model.Load(vocab_file)
56
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
57
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
58
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
59
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
60
+ super().__init__(
61
+ bos_token=bos_token,
62
+ eos_token=eos_token,
63
+ unk_token=unk_token,
64
+ pad_token=pad_token,
65
+ add_bos_token=add_bos_token,
66
+ add_eos_token=add_eos_token,
67
+ sp_model_kwargs=self.sp_model_kwargs,
68
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
69
+ **kwargs,
70
+ )
71
+ self.vocab_file = vocab_file
72
+ self.add_bos_token = add_bos_token
73
+ self.add_eos_token = add_eos_token
74
+
75
+ def __getstate__(self):
76
+ state = self.__dict__.copy()
77
+ state["sp_model"] = None
78
+ return state
79
+
80
+ def __setstate__(self, d):
81
+ self.__dict__ = d
82
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
83
+ self.sp_model.Load(self.vocab_file)
84
+
85
+ @property
86
+ def vocab_size(self):
87
+ """Returns vocab size"""
88
+ return self.sp_model.get_piece_size()
89
+
90
+ def get_vocab(self):
91
+ """Returns vocab as a dict"""
92
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
93
+ vocab.update(self.added_tokens_encoder)
94
+ return vocab
95
+
96
+ def _tokenize(self, text):
97
+ """Returns a tokenized string."""
98
+ return self.sp_model.encode(text, out_type=str)
99
+
100
+ def _convert_token_to_id(self, token):
101
+ """Converts a token (str) in an id using the vocab."""
102
+ return self.sp_model.piece_to_id(token)
103
+
104
+ def _convert_id_to_token(self, index):
105
+ """Converts an index (integer) in a token (str) using the vocab."""
106
+ token = self.sp_model.IdToPiece(index)
107
+ return token
108
+
109
+ def convert_tokens_to_string(self, tokens):
110
+ """Converts a sequence of tokens (string) in a single string."""
111
+ current_sub_tokens = []
112
+ out_string = ""
113
+ prev_is_special = False
114
+ for i, token in enumerate(tokens):
115
+ # make sure that special tokens are not decoded using sentencepiece model
116
+ if token in self.all_special_tokens:
117
+ if not prev_is_special and i != 0:
118
+ out_string += " "
119
+ out_string += self.sp_model.decode(current_sub_tokens) + token
120
+ prev_is_special = True
121
+ current_sub_tokens = []
122
+ else:
123
+ current_sub_tokens.append(token)
124
+ prev_is_special = False
125
+ out_string += self.sp_model.decode(current_sub_tokens)
126
+ return out_string
127
+
128
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
129
+ """
130
+ Save the vocabulary and special tokens file to a directory.
131
+
132
+ Args:
133
+ save_directory (`str`):
134
+ The directory in which to save the vocabulary.
135
+
136
+ Returns:
137
+ `Tuple(str)`: Paths to the files saved.
138
+ """
139
+ if not os.path.isdir(save_directory):
140
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
141
+ return
142
+ out_vocab_file = os.path.join(
143
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
144
+ )
145
+
146
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
147
+ copyfile(self.vocab_file, out_vocab_file)
148
+ elif not os.path.isfile(self.vocab_file):
149
+ with open(out_vocab_file, "wb") as fi:
150
+ content_spiece_model = self.sp_model.serialized_model_proto()
151
+ fi.write(content_spiece_model)
152
+
153
+ return (out_vocab_file,)
154
+
155
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
156
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
157
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
158
+
159
+ output = bos_token_id + token_ids_0 + eos_token_id
160
+
161
+ if token_ids_1 is not None:
162
+ output = output + bos_token_id + token_ids_1 + eos_token_id
163
+
164
+ return output
165
+
166
+ def get_special_tokens_mask(
167
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
168
+ ) -> List[int]:
169
+ """
170
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
171
+ special tokens using the tokenizer `prepare_for_model` method.
172
+
173
+ Args:
174
+ token_ids_0 (`List[int]`):
175
+ List of IDs.
176
+ token_ids_1 (`List[int]`, *optional*):
177
+ Optional second list of IDs for sequence pairs.
178
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
179
+ Whether or not the token list is already formatted with special tokens for the model.
180
+
181
+ Returns:
182
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
183
+ """
184
+ if already_has_special_tokens:
185
+ return super().get_special_tokens_mask(
186
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
187
+ )
188
+
189
+ bos_token_id = [1] if self.add_bos_token else []
190
+ eos_token_id = [1] if self.add_eos_token else []
191
+
192
+ if token_ids_1 is None:
193
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
194
+ return (
195
+ bos_token_id
196
+ + ([0] * len(token_ids_0))
197
+ + eos_token_id
198
+ + bos_token_id
199
+ + ([0] * len(token_ids_1))
200
+ + eos_token_id
201
+ )
202
+
203
+ def create_token_type_ids_from_sequences(
204
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
205
+ ) -> List[int]:
206
+ """
207
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
208
+ sequence pair mask has the following format:
209
+
210
+ ```
211
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
212
+ | first sequence | second sequence |
213
+ ```
214
+
215
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
216
+
217
+ Args:
218
+ token_ids_0 (`List[int]`):
219
+ List of ids.
220
+ token_ids_1 (`List[int]`, *optional*):
221
+ Optional second list of IDs for sequence pairs.
222
+
223
+ Returns:
224
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
225
+ """
226
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
227
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
228
+
229
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
230
+
231
+ if token_ids_1 is not None:
232
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
233
+
234
+ return output
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ede13db1d0956ec033608741b0fd83d149a5ec54306af70e2ba829242f75b73b
3
+ size 851705
tokenizer_config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": ["tokenization_nanbeige.NanbeigeTokenizer", null]
4
+ },
5
+ "add_bos_token": true,
6
+ "add_eos_token": false,
7
+ "bos_token": {
8
+ "__type": "AddedToken",
9
+ "content": "<s>",
10
+ "lstrip": false,
11
+ "normalized": true,
12
+ "rstrip": false,
13
+ "single_word": false
14
+ },
15
+ "clean_up_tokenization_spaces": false,
16
+ "eos_token": {
17
+ "__type": "AddedToken",
18
+ "content": "</s>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "model_max_length": 1000000000000000019884624838656,
25
+ "pad_token": null,
26
+ "sp_model_kwargs": {},
27
+ "tokenizer_class": "NanbeigeTokenizer",
28
+ "unk_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": true,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ }
36
+ }