zRzRzRzRzRzRzR commited on
Commit
7f6bdd1
1 Parent(s): c312c32
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ .idea
README.md CHANGED
@@ -1,3 +1,73 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## zR-Llama-1B-chatglm2-6b-tokenizer
2
+
3
+ 本模型是基于 [build_MiniLLM_from_scratch 开源框架](https://github.com/Tongjilibo/build_MiniLLM_from_scratch) 自行训练的一个1B模型。
4
+
5
+ ## 模型参数
6
+ + 1B 参数量
7
+ + 训练语料670亿。
8
+ + 模型支持token长度 896
9
+
10
+
11
+ ## 预训练模型
12
+
13
+ + 使用 [build_MiniLLM_from_scratch 开源框架](https://github.com/Tongjilibo/build_MiniLLM_from_scratch) 的预训练数据集,自己完成 Tokenize 过程。
14
+ + 使用 8 x 80GB A800 GPU 训练。
15
+ + 训练 1 Epoch,bs=32 (每张卡) , lr=1.5e-4。
16
+ + 共耗时 1 天。
17
+
18
+ ## SFT模型
19
+ + 使用 [build_MiniLLM_from_scratch 开源框架](https://github.com/Tongjilibo/build_MiniLLM_from_scratch) 提供的全部数据集
20
+ + 使用 单卡A800 微调。
21
+ + 微调 5 Epoch, bs=8, lr=2e-5。
22
+ + 共耗时 3 天 12 小时。
23
+
24
+ ## 使用模型
25
+
26
+ ```python
27
+ import os
28
+ import torch
29
+ from transformers import AutoTokenizer, LlamaForCausalLM
30
+
31
+ max_length = 896
32
+ HUMAN = '<human>'
33
+ ROBOT = '<robot>'
34
+ def build_prompt(query, history) -> str:
35
+ texts = ''
36
+ for user_input, response in history:
37
+ texts += f'{HUMAN}{user_input}{ROBOT}{response}'
38
+
39
+ texts += f'{HUMAN}{query}{ROBOT}'
40
+ return texts
41
+
42
+ def build_cli_history(history):
43
+ prompt = ''
44
+ for query, response in history:
45
+ prompt += f"\n\nUser:{query.strip()}"
46
+ prompt += f"\n\nRobot:{response.strip()}"
47
+ return prompt
48
+
49
+
50
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
51
+ tokenizer = AutoTokenizer.from_pretrained("zRzRzRzRzRzRzR/zR-Llama-1b-ChatGLM2-6b-tokenizer", trust_remote_code=True)
52
+ model = LlamaForCausalLM.from_pretrained("zRzRzRzRzRzRzR/zR-Llama-1b-ChatGLM2-6b-tokenizer").to(device)
53
+
54
+ history = []
55
+ clear_command = 'cls' if os.name == 'nt' else 'clear'
56
+ while True:
57
+ query = input('\n输入:')
58
+ if query.strip() == "stop":
59
+ break
60
+ if query.strip() == "clear":
61
+ history = []
62
+ os.system(clear_command)
63
+ continue
64
+
65
+ inputs = tokenizer.encode(build_prompt(query, history), return_tensors='pt', add_special_tokens=False).to(device)
66
+ response = model.generate(inputs)
67
+ response = tokenizer.decode(response[0].cpu(), skip_special_tokens=True)
68
+
69
+ os.system(clear_command)
70
+ print(build_cli_history(history + [(query, response)]), flush=True)
71
+ ```
72
+
73
+
config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LlamaForCausalLM"
4
+ ],
5
+ "model_type": "llama",
6
+ "bos_token_id": 1,
7
+ "eos_token_id": 2,
8
+ "hidden_size": 2048,
9
+ "max_position_embeddings": 896,
10
+ "intermediate_size": 5632,
11
+ "num_attention_heads": 32,
12
+ "num_key_value_heads": 4,
13
+ "num_hidden_layers": 22,
14
+ "hidden_act": "silu",
15
+ "vocab_size": 64793,
16
+ "rms_norm_eps": 1e-06,
17
+ "tie_emb_prj_weight": true,
18
+ "use_cache": true,
19
+ "do_sample": true,
20
+ "max_length": 896
21
+ }
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0
6
+ }
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e238728a3661fa4c1f213ea815e159de11c6afe579938fdbe2a3042586d5ef42
3
+ size 4406772078
tokenization_chatglm.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from typing import List, Optional, Union, Dict
4
+ from sentencepiece import SentencePieceProcessor
5
+ from transformers import PreTrainedTokenizer
6
+ from transformers.utils import logging, PaddingStrategy
7
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
8
+
9
+
10
+ class SPTokenizer:
11
+ def __init__(self, model_path: str):
12
+ # reload tokenizer
13
+ assert os.path.isfile(model_path), model_path
14
+ self.sp_model = SentencePieceProcessor(model_file=model_path)
15
+
16
+ # BOS / EOS token IDs
17
+ self.n_words: int = self.sp_model.vocab_size()
18
+ self.bos_id: int = self.sp_model.bos_id()
19
+ self.eos_id: int = self.sp_model.eos_id()
20
+ self.pad_id: int = self.sp_model.unk_id()
21
+ assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
22
+
23
+ special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop"]
24
+ self.special_tokens = {}
25
+ self.index_special_tokens = {}
26
+ for token in special_tokens:
27
+ self.special_tokens[token] = self.n_words
28
+ self.index_special_tokens[self.n_words] = token
29
+ self.n_words += 1
30
+
31
+ def tokenize(self, s: str):
32
+ return self.sp_model.EncodeAsPieces(s)
33
+
34
+ def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]:
35
+ assert type(s) is str
36
+ t = self.sp_model.encode(s)
37
+ if bos:
38
+ t = [self.bos_id] + t
39
+ if eos:
40
+ t = t + [self.eos_id]
41
+ return t
42
+
43
+ def decode(self, t: List[int]) -> str:
44
+ return self.sp_model.decode(t)
45
+
46
+ def decode_tokens(self, tokens: List[str]) -> str:
47
+ text = self.sp_model.DecodePieces(tokens)
48
+ return text
49
+
50
+ def convert_token_to_id(self, token):
51
+ """ Converts a token (str) in an id using the vocab. """
52
+ if token in self.special_tokens:
53
+ return self.special_tokens[token]
54
+ return self.sp_model.PieceToId(token)
55
+
56
+ def convert_id_to_token(self, index):
57
+ """Converts an index (integer) in a token (str) using the vocab."""
58
+ if index in self.index_special_tokens or index in [self.eos_id, self.bos_id, self.pad_id] or index < 0:
59
+ return ""
60
+ return self.sp_model.IdToPiece(index)
61
+
62
+
63
+ class ChatGLMTokenizer(PreTrainedTokenizer):
64
+ vocab_files_names = {"vocab_file": "tokenizer.model"}
65
+
66
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
67
+
68
+ def __init__(self, vocab_file, padding_side="left", clean_up_tokenization_spaces=False, **kwargs):
69
+ self.name = "GLMTokenizer"
70
+
71
+ self.vocab_file = vocab_file
72
+ self.tokenizer = SPTokenizer(vocab_file)
73
+ self.special_tokens = {
74
+ "<bos>": self.tokenizer.bos_id,
75
+ "<eos>": self.tokenizer.eos_id,
76
+ "<pad>": self.tokenizer.pad_id
77
+ }
78
+ super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs)
79
+
80
+ def get_command(self, token):
81
+ if token in self.special_tokens:
82
+ return self.special_tokens[token]
83
+ assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
84
+ return self.tokenizer.special_tokens[token]
85
+
86
+ @property
87
+ def unk_token(self) -> str:
88
+ return "<unk>"
89
+
90
+ @property
91
+ def pad_token(self) -> str:
92
+ return "<unk>"
93
+
94
+ @property
95
+ def pad_token_id(self):
96
+ return self.get_command("<pad>")
97
+
98
+ @property
99
+ def eos_token(self) -> str:
100
+ return "</s>"
101
+
102
+ @property
103
+ def eos_token_id(self):
104
+ return self.get_command("<eos>")
105
+
106
+ @property
107
+ def vocab_size(self):
108
+ return self.tokenizer.n_words
109
+
110
+ def get_vocab(self):
111
+ """ Returns vocab as a dict """
112
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
113
+ vocab.update(self.added_tokens_encoder)
114
+ return vocab
115
+
116
+ def _tokenize(self, text, **kwargs):
117
+ return self.tokenizer.tokenize(text)
118
+
119
+ def _convert_token_to_id(self, token):
120
+ """ Converts a token (str) in an id using the vocab. """
121
+ return self.tokenizer.convert_token_to_id(token)
122
+
123
+ def _convert_id_to_token(self, index):
124
+ """Converts an index (integer) in a token (str) using the vocab."""
125
+ return self.tokenizer.convert_id_to_token(index)
126
+
127
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
128
+ return self.tokenizer.decode_tokens(tokens)
129
+
130
+ def save_vocabulary(self, save_directory, filename_prefix=None):
131
+ """
132
+ Save the vocabulary and special tokens file to a directory.
133
+ Args:
134
+ save_directory (`str`):
135
+ The directory in which to save the vocabulary.
136
+ filename_prefix (`str`, *optional*):
137
+ An optional prefix to add to the named of the saved files.
138
+ Returns:
139
+ `Tuple(str)`: Paths to the files saved.
140
+ """
141
+ if os.path.isdir(save_directory):
142
+ vocab_file = os.path.join(
143
+ save_directory, self.vocab_files_names["vocab_file"]
144
+ )
145
+ else:
146
+ vocab_file = save_directory
147
+
148
+ with open(self.vocab_file, 'rb') as fin:
149
+ proto_str = fin.read()
150
+
151
+ with open(vocab_file, "wb") as writer:
152
+ writer.write(proto_str)
153
+
154
+ return (vocab_file,)
155
+
156
+ def get_prefix_tokens(self):
157
+ prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]
158
+ return prefix_tokens
159
+
160
+ def build_prompt(self, query, history=None):
161
+ if history is None:
162
+ history = []
163
+ prompt = ""
164
+ for i, (old_query, response) in enumerate(history):
165
+ prompt += "[Round {}]\n\n问:{}\n\n答:{}\n\n".format(i + 1, old_query, response)
166
+ prompt += "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
167
+ return prompt
168
+
169
+ def build_inputs_with_special_tokens(
170
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
171
+ ) -> List[int]:
172
+ """
173
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
174
+ adding special tokens. A BERT sequence has the following format:
175
+ - single sequence: `[CLS] X [SEP]`
176
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
177
+ Args:
178
+ token_ids_0 (`List[int]`):
179
+ List of IDs to which the special tokens will be added.
180
+ token_ids_1 (`List[int]`, *optional*):
181
+ Optional second list of IDs for sequence pairs.
182
+ Returns:
183
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
184
+ """
185
+ prefix_tokens = self.get_prefix_tokens()
186
+ token_ids_0 = prefix_tokens + token_ids_0
187
+ if token_ids_1 is not None:
188
+ token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("<eos>")]
189
+ return token_ids_0
190
+
191
+ def _pad(
192
+ self,
193
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
194
+ max_length: Optional[int] = None,
195
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
196
+ pad_to_multiple_of: Optional[int] = None,
197
+ return_attention_mask: Optional[bool] = None,
198
+ ) -> dict:
199
+ """
200
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
201
+ Args:
202
+ encoded_inputs:
203
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
204
+ max_length: maximum length of the returned list and optionally padding length (see below).
205
+ Will truncate by taking into account the special tokens.
206
+ padding_strategy: PaddingStrategy to use for padding.
207
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
208
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
209
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
210
+ The tokenizer padding sides are defined in self.padding_side:
211
+ - 'left': pads on the left of the sequences
212
+ - 'right': pads on the right of the sequences
213
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
214
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
215
+ `>= 7.5` (Volta).
216
+ return_attention_mask:
217
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
218
+ """
219
+ # Load from model defaults
220
+ assert self.padding_side == "left"
221
+
222
+ required_input = encoded_inputs[self.model_input_names[0]]
223
+ seq_length = len(required_input)
224
+
225
+ if padding_strategy == PaddingStrategy.LONGEST:
226
+ max_length = len(required_input)
227
+
228
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
229
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
230
+
231
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
232
+
233
+ # Initialize attention mask if not present.
234
+ if "attention_mask" not in encoded_inputs:
235
+ encoded_inputs["attention_mask"] = [1] * seq_length
236
+
237
+ if "position_ids" not in encoded_inputs:
238
+ encoded_inputs["position_ids"] = list(range(seq_length))
239
+
240
+ if needs_to_be_padded:
241
+ difference = max_length - len(required_input)
242
+
243
+ if "attention_mask" in encoded_inputs:
244
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
245
+ if "position_ids" in encoded_inputs:
246
+ encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
247
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
248
+
249
+ return encoded_inputs
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7dc4c393423b76e4373e5157ddc34803a0189ba96b21ddbb40269d31468a6f2
3
+ size 1018370
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "THUDM/chatglm2-6b",
3
+ "remove_space": false,
4
+ "do_lower_case": false,
5
+ "tokenizer_class": "ChatGLMTokenizer",
6
+ "auto_map": {
7
+ "AutoTokenizer": [
8
+ "tokenization_chatglm.ChatGLMTokenizer",
9
+ null
10
+ ]
11
+ }
12
+ }