dwdcth commited on
Commit
7f913e1
1 Parent(s): 139f24b

Upload 3 files

Browse files
Files changed (3) hide show
  1. tokenization_chatglm.py +283 -0
  2. tokenizer.model +3 -0
  3. tokenizer_config.json +12 -0
tokenization_chatglm.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import torch
4
+ from typing import List, Optional, Union, Dict
5
+ from sentencepiece import SentencePieceProcessor
6
+ from transformers import PreTrainedTokenizer
7
+ from transformers.utils import logging, PaddingStrategy
8
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
9
+
10
+
11
+ class SPTokenizer:
12
+ def __init__(self, model_path: str):
13
+ # reload tokenizer
14
+ assert os.path.isfile(model_path), model_path
15
+ self.sp_model = SentencePieceProcessor(model_file=model_path)
16
+
17
+ # BOS / EOS token IDs
18
+ self.n_words: int = self.sp_model.vocab_size()
19
+ self.bos_id: int = self.sp_model.bos_id()
20
+ self.eos_id: int = self.sp_model.eos_id()
21
+ self.pad_id: int = self.sp_model.unk_id()
22
+ assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
23
+
24
+ special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop", "<|system|>", "<|user|>", "<|assistant|>",
25
+ "<|observation|>"]
26
+ self.special_tokens = {}
27
+ self.index_special_tokens = {}
28
+ for token in special_tokens:
29
+ self.special_tokens[token] = self.n_words
30
+ self.index_special_tokens[self.n_words] = token
31
+ self.n_words += 1
32
+
33
+ def tokenize(self, s: str):
34
+ return self.sp_model.EncodeAsPieces(s)
35
+
36
+ def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]:
37
+ assert type(s) is str
38
+ t = self.sp_model.encode(s)
39
+ if bos:
40
+ t = [self.bos_id] + t
41
+ if eos:
42
+ t = t + [self.eos_id]
43
+ return t
44
+
45
+ def decode(self, t: List[int]) -> str:
46
+ text, buffer = "", []
47
+ for token in t:
48
+ if token in self.index_special_tokens:
49
+ if buffer:
50
+ text += self.sp_model.decode(buffer)
51
+ buffer = []
52
+ text += self.index_special_tokens[token]
53
+ else:
54
+ buffer.append(token)
55
+ if buffer:
56
+ text += self.sp_model.decode(buffer)
57
+ return text
58
+
59
+ def decode_tokens(self, tokens: List[str]) -> str:
60
+ text = self.sp_model.DecodePieces(tokens)
61
+ return text
62
+
63
+ def convert_token_to_id(self, token):
64
+ """ Converts a token (str) in an id using the vocab. """
65
+ if token in self.special_tokens:
66
+ return self.special_tokens[token]
67
+ return self.sp_model.PieceToId(token)
68
+
69
+ def convert_id_to_token(self, index):
70
+ """Converts an index (integer) in a token (str) using the vocab."""
71
+ if index in self.index_special_tokens:
72
+ return self.index_special_tokens[index]
73
+ if index in [self.eos_id, self.bos_id, self.pad_id] or index < 0:
74
+ return ""
75
+ return self.sp_model.IdToPiece(index)
76
+
77
+
78
+ class ChatGLMTokenizer(PreTrainedTokenizer):
79
+ vocab_files_names = {"vocab_file": "tokenizer.model"}
80
+
81
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
82
+
83
+ def __init__(self, vocab_file, padding_side="left", clean_up_tokenization_spaces=False, **kwargs):
84
+ self.name = "GLMTokenizer"
85
+
86
+ self.vocab_file = vocab_file
87
+ self.tokenizer = SPTokenizer(vocab_file)
88
+ self.special_tokens = {
89
+ "<bos>": self.tokenizer.bos_id,
90
+ "<eos>": self.tokenizer.eos_id,
91
+ "<pad>": self.tokenizer.pad_id
92
+ }
93
+ super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs)
94
+
95
+ def get_command(self, token):
96
+ if token in self.special_tokens:
97
+ return self.special_tokens[token]
98
+ assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
99
+ return self.tokenizer.special_tokens[token]
100
+
101
+ @property
102
+ def unk_token(self) -> str:
103
+ return "<unk>"
104
+
105
+ @property
106
+ def pad_token(self) -> str:
107
+ return "<unk>"
108
+
109
+ @property
110
+ def pad_token_id(self):
111
+ return self.get_command("<pad>")
112
+
113
+ @property
114
+ def eos_token(self) -> str:
115
+ return "</s>"
116
+
117
+ @property
118
+ def eos_token_id(self):
119
+ return self.get_command("<eos>")
120
+
121
+ @property
122
+ def vocab_size(self):
123
+ return self.tokenizer.n_words
124
+
125
+ def get_vocab(self):
126
+ """ Returns vocab as a dict """
127
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
128
+ vocab.update(self.added_tokens_encoder)
129
+ return vocab
130
+
131
+ def _tokenize(self, text, **kwargs):
132
+ return self.tokenizer.tokenize(text)
133
+
134
+ def _convert_token_to_id(self, token):
135
+ """ Converts a token (str) in an id using the vocab. """
136
+ return self.tokenizer.convert_token_to_id(token)
137
+
138
+ def _convert_id_to_token(self, index):
139
+ """Converts an index (integer) in a token (str) using the vocab."""
140
+ return self.tokenizer.convert_id_to_token(index)
141
+
142
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
143
+ return self.tokenizer.decode_tokens(tokens)
144
+
145
+ def save_vocabulary(self, save_directory, filename_prefix=None):
146
+ """
147
+ Save the vocabulary and special tokens file to a directory.
148
+
149
+ Args:
150
+ save_directory (`str`):
151
+ The directory in which to save the vocabulary.
152
+ filename_prefix (`str`, *optional*):
153
+ An optional prefix to add to the named of the saved files.
154
+
155
+ Returns:
156
+ `Tuple(str)`: Paths to the files saved.
157
+ """
158
+ if os.path.isdir(save_directory):
159
+ vocab_file = os.path.join(
160
+ save_directory, self.vocab_files_names["vocab_file"]
161
+ )
162
+ else:
163
+ vocab_file = save_directory
164
+
165
+ with open(self.vocab_file, 'rb') as fin:
166
+ proto_str = fin.read()
167
+
168
+ with open(vocab_file, "wb") as writer:
169
+ writer.write(proto_str)
170
+
171
+ return (vocab_file,)
172
+
173
+ def get_prefix_tokens(self):
174
+ prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]
175
+ return prefix_tokens
176
+
177
+ def build_single_message(self, role, metadata, message):
178
+ assert role in ["system", "user", "assistant", "observation"], role
179
+ role_tokens = [self.get_command(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n")
180
+ message_tokens = self.tokenizer.encode(message)
181
+ tokens = role_tokens + message_tokens
182
+ return tokens
183
+
184
+ def build_chat_input(self, query, history=None, role="user"):
185
+ if history is None:
186
+ history = []
187
+ input_ids = []
188
+ for item in history:
189
+ content = item["content"]
190
+ if item["role"] == "system" and "tools" in item:
191
+ content = content + "\n" + json.dumps(item["tools"], indent=4, ensure_ascii=False)
192
+ input_ids.extend(self.build_single_message(item["role"], item.get("metadata", ""), content))
193
+ input_ids.extend(self.build_single_message(role, "", query))
194
+ input_ids.extend([self.get_command("<|assistant|>")])
195
+ return self.batch_encode_plus([input_ids], return_tensors="pt", is_split_into_words=True)
196
+
197
+ def build_inputs_with_special_tokens(
198
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
199
+ ) -> List[int]:
200
+ """
201
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
202
+ adding special tokens. A BERT sequence has the following format:
203
+
204
+ - single sequence: `[CLS] X [SEP]`
205
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
206
+
207
+ Args:
208
+ token_ids_0 (`List[int]`):
209
+ List of IDs to which the special tokens will be added.
210
+ token_ids_1 (`List[int]`, *optional*):
211
+ Optional second list of IDs for sequence pairs.
212
+
213
+ Returns:
214
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
215
+ """
216
+ prefix_tokens = self.get_prefix_tokens()
217
+ token_ids_0 = prefix_tokens + token_ids_0
218
+ if token_ids_1 is not None:
219
+ token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("<eos>")]
220
+ return token_ids_0
221
+
222
+ def _pad(
223
+ self,
224
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
225
+ max_length: Optional[int] = None,
226
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
227
+ pad_to_multiple_of: Optional[int] = None,
228
+ return_attention_mask: Optional[bool] = None,
229
+ ) -> dict:
230
+ """
231
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
232
+
233
+ Args:
234
+ encoded_inputs:
235
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
236
+ max_length: maximum length of the returned list and optionally padding length (see below).
237
+ Will truncate by taking into account the special tokens.
238
+ padding_strategy: PaddingStrategy to use for padding.
239
+
240
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
241
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
242
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
243
+ The tokenizer padding sides are defined in self.padding_side:
244
+
245
+ - 'left': pads on the left of the sequences
246
+ - 'right': pads on the right of the sequences
247
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
248
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
249
+ `>= 7.5` (Volta).
250
+ return_attention_mask:
251
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
252
+ """
253
+ # Load from model defaults
254
+ assert self.padding_side == "left"
255
+
256
+ required_input = encoded_inputs[self.model_input_names[0]]
257
+ seq_length = len(required_input)
258
+
259
+ if padding_strategy == PaddingStrategy.LONGEST:
260
+ max_length = len(required_input)
261
+
262
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
263
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
264
+
265
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
266
+
267
+ # Initialize attention mask if not present.
268
+ if "attention_mask" not in encoded_inputs:
269
+ encoded_inputs["attention_mask"] = [1] * seq_length
270
+
271
+ if "position_ids" not in encoded_inputs:
272
+ encoded_inputs["position_ids"] = list(range(seq_length))
273
+
274
+ if needs_to_be_padded:
275
+ difference = max_length - len(required_input)
276
+
277
+ if "attention_mask" in encoded_inputs:
278
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
279
+ if "position_ids" in encoded_inputs:
280
+ encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
281
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
282
+
283
+ 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/chatglm3-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
+ }