vcadillo commited on
Commit
5cf41b2
1 Parent(s): e8d6592

Upload 3 files

Browse files
Files changed (3) hide show
  1. tokenization_chatglm.py +361 -0
  2. tokenizer.model +3 -0
  3. tokenizer_config.json +134 -0
tokenization_chatglm.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import regex as re
2
+ import base64
3
+ import os
4
+ import json
5
+ import tiktoken
6
+ import torch
7
+ from torch import TensorType
8
+ from typing import List, Optional, Union, Dict, Any
9
+ from torchvision import transforms
10
+ from transformers import PreTrainedTokenizer
11
+ from transformers.utils import logging, PaddingStrategy
12
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
13
+
14
+
15
+ class ChatGLM4Tokenizer(PreTrainedTokenizer):
16
+ vocab_files_names = {"vocab_file": "tokenizer.model"}
17
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
18
+
19
+ def __init__(
20
+ self,
21
+ vocab_file,
22
+ padding_side="left",
23
+ clean_up_tokenization_spaces=False,
24
+ encode_special_tokens=False,
25
+ image_size=None,
26
+ **kwargs
27
+ ):
28
+ self.name = "GLM4Tokenizer"
29
+ self.vocab_file = vocab_file
30
+ pat_str = "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
31
+ self.pat_str = re.compile(pat_str)
32
+ self.encode_special_tokens = encode_special_tokens
33
+ self.image_size = image_size
34
+
35
+ mergeable_ranks = {}
36
+ with open(vocab_file) as f:
37
+ for line in f:
38
+ token, rank = line.strip().split()
39
+ rank = int(rank)
40
+ token = base64.b64decode(token)
41
+ mergeable_ranks[token] = rank
42
+
43
+ self.mergeable_ranks = mergeable_ranks
44
+
45
+ self.tokenizer = tiktoken.Encoding(
46
+ name="my_tokenizer",
47
+ pat_str=pat_str,
48
+ mergeable_ranks=mergeable_ranks,
49
+ special_tokens={}
50
+ )
51
+ self.decoder = {rank: token for token, rank in mergeable_ranks.items()}
52
+ self.n_words = len(self.decoder)
53
+
54
+ super().__init__(
55
+ padding_side=padding_side,
56
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
57
+ **kwargs
58
+ )
59
+
60
+ @property
61
+ def vocab_size(self):
62
+ return self.n_words
63
+
64
+ def get_vocab(self):
65
+ """ Returns vocab as a dict """
66
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
67
+ vocab.update(self.added_tokens_encoder)
68
+ return vocab
69
+
70
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
71
+ """
72
+ Converts a sequence of tokens in a single string.
73
+ """
74
+ text = ""
75
+ temp = b""
76
+ for t in tokens:
77
+ if isinstance(t, str):
78
+ if temp:
79
+ text += temp.decode("utf-8", errors="replace")
80
+ temp = b""
81
+ text += t
82
+ elif isinstance(t, bytes):
83
+ temp += t
84
+ else:
85
+ raise TypeError("token should only be of type types or str")
86
+ if temp:
87
+ text += temp.decode("utf-8", errors="replace")
88
+ return text
89
+
90
+ def _tokenize(self, text, **kwargs):
91
+ tokens = []
92
+ ids = self.tokenizer.encode(text)
93
+ for t in ids:
94
+ tokens.append(self.decoder[t])
95
+ return tokens
96
+
97
+ def _convert_token_to_id(self, token):
98
+ """ Converts a token (str) in an id using the vocab. """
99
+ return self.mergeable_ranks[token]
100
+
101
+ def _convert_id_to_token(self, index):
102
+ """Converts an index (integer) in a token (str) using the vocab."""
103
+ return self.decoder.get(index, "")
104
+
105
+ def save_vocabulary(self, save_directory, filename_prefix=None):
106
+ """
107
+ Save the vocabulary and special tokens file to a directory.
108
+
109
+ Args:
110
+ save_directory (`str`):
111
+ The directory in which to save the vocabulary.
112
+ filename_prefix (`str`, *optional*):
113
+ An optional prefix to add to the named of the saved files.
114
+
115
+ Returns:
116
+ `Tuple(str)`: Paths to the files saved.
117
+ """
118
+ if os.path.isdir(save_directory):
119
+ vocab_file = os.path.join(
120
+ save_directory, self.vocab_files_names["vocab_file"]
121
+ )
122
+ else:
123
+ vocab_file = save_directory
124
+
125
+ with open(self.vocab_file, 'rb') as fin:
126
+ proto_str = fin.read()
127
+
128
+ with open(vocab_file, "wb") as writer:
129
+ writer.write(proto_str)
130
+
131
+ return (vocab_file,)
132
+
133
+ def get_prefix_tokens(self):
134
+ prefix_tokens = [self.convert_tokens_to_ids("[gMASK]"), self.convert_tokens_to_ids("<sop>")]
135
+ return prefix_tokens
136
+
137
+ def build_single_message(self, role, metadata, message, tokenize=True, message_prefix=None):
138
+ assert role in ["system", "user", "assistant", "observation"], role
139
+ if tokenize:
140
+ role_tokens = [self.convert_tokens_to_ids(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n",
141
+ disallowed_special=())
142
+ message_tokens = self.tokenizer.encode(message, disallowed_special=())
143
+ if message_prefix is not None:
144
+ message_tokens = message_prefix + message_tokens
145
+ tokens = role_tokens + message_tokens
146
+ return tokens
147
+ else:
148
+ return str(f"<|{role}|>{metadata}\n{message}")
149
+
150
+ def apply_chat_template(
151
+ self,
152
+ conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]], "Conversation"],
153
+ add_generation_prompt: bool = False,
154
+ tokenize: bool = True,
155
+ padding: bool = False,
156
+ truncation: bool = False,
157
+ max_length: Optional[int] = None,
158
+ return_tensors: Optional[Union[str, TensorType]] = None,
159
+ return_dict: bool = False,
160
+ tokenizer_kwargs: Optional[Dict[str, Any]] = None,
161
+ add_special_tokens: bool = True,
162
+ **kwargs,
163
+ ) -> Union[str, List[int], List[str], List[List[int]], BatchEncoding]:
164
+
165
+ if return_dict and not tokenize:
166
+ raise ValueError(
167
+ "`return_dict=True` is incompatible with `tokenize=False`, because there is no dict "
168
+ "of tokenizer outputs to return."
169
+ )
170
+
171
+ def handle_single_conversation(conversation):
172
+ input_ids = self.get_prefix_tokens() if add_special_tokens else []
173
+ input_message = "[gMASK]<sop>" if add_special_tokens else ""
174
+ input_image = None
175
+ transform = transforms.Compose(
176
+ [
177
+ transforms.Resize(
178
+ (self.image_size, self.image_size), interpolation=transforms.InterpolationMode.BICUBIC
179
+ ),
180
+ transforms.ToTensor(),
181
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
182
+ ]
183
+ )
184
+ for item in conversation:
185
+ if item.get("tools"):
186
+ tools = item["tools"]
187
+ content = "你是一个名为 GLM-4 的人工智能助手。你是基于智谱AI训练的语言模型 GLM-4 模型开发的,你的任务是针对用户的问题和要求提供适当的答复和支持。"
188
+ for tool in tools:
189
+ if tool["type"] == "function":
190
+ function = tool["function"]
191
+ content += f"\n\n## {function['name']}\n\n{json.dumps(function, ensure_ascii=False, indent=4)}"
192
+ content += "\n在调用上述函数时,请使用 Json 格式表示调用的参数。"
193
+ elif tool["type"] == "python":
194
+ content += "\n\n## python\n\n当你向 `python` 发送包含 Python 代码的消息时,该代码将会在一个有状态的 Jupyter notebook 环境中执行。\n`python` 返回代码执行的输出,或在执行 60 秒后返回超时。\n`/mnt/data` 将会持久化存储你的文件。在此会话中,`python` 无法访问互联网。不要使用 `python` 进行任何网络请求或者在线 API 调用,这些在线内容的访问将不会成功。"
195
+ elif tool["type"] == "simple_browser":
196
+ content += "\n\n## simple_browser\n\n你可以使用 `simple_browser` 工具。该工具支持以下函数:\n`search(query: str, recency_days: int)`:使用搜索引擎进行查询并显示结果,可以使用 `recency_days` 参数控制搜索内容的时效性。\n`mclick(ids: list[int])`:获取一系列指定 id 的页面内容。每次调用时,须选择3-10个页面。选择多个角度的页面,同时尽可能选择可信任的信息来源。考虑到部分页面是无法加载的,你也可以多打开一些可能有用的页面而不用担心内容过多。\n`open_url(url: str)`:打开指定的 URL。\n\n使用 `【{引用 id}†{引用文本}】` 来引用内容。\n\n操作步骤:1. 使用 `search` 来获得信息列表; 2. 使用 `mclick` 来获取指定 ID 页面的内容; 3. 根据获得的内容进行回复。在回复中应当引用信息来源。\n 如果用户提供了 URL,也可以用 `open_url` 直接打开页面。\n如果初次搜索结果没有找到合适的信息,也可以再次使用 `search` 进行搜索。"
197
+ elif tool["type"] == "cogview":
198
+ content += "\n\n## cogview\n\n如果用户的请求中包含了对图像的描述,你可以使用 `cogview` 来生成图像并展示给用户。你需要向 `cogview` 发送图像描述,规则:\n- 发送给 `cogview` 的消息必须使用英语。用户的中文描述必须完全翻译为英语。\n- 应当尽可能详细地描述图像生成的需求,需求描述约 100 英文单词。\n- 保持用户原始描述的意图。不要虚构内容或者没见过的人物。\n- 如无特殊说明,所在地为中国,持有中国立场并遵循中国社会主义价值观。"
199
+ else:
200
+ raise NotImplementedError(f"Unknown tool type {tool['type']}")
201
+ input = self.build_single_message("system", "", content, tokenize=tokenize)
202
+ if tokenize:
203
+ input_ids.extend(input)
204
+ else:
205
+ input_message += input
206
+ message = ""
207
+ message_prefix = None
208
+ if item.get("image"):
209
+ assert input_image is None, "Multiple images are not supported"
210
+ input_image = transform(item["image"])
211
+ message_prefix = self.convert_tokens_to_ids(
212
+ ["<|begin_of_image|>", "<|endoftext|>", "<|end_of_image|>"])
213
+ if item.get("content"):
214
+ message += item["content"]
215
+ if message or message_prefix:
216
+ input = self.build_single_message(
217
+ item["role"],
218
+ item.get("metadata", ""),
219
+ message,
220
+ tokenize=tokenize,
221
+ message_prefix=message_prefix
222
+ )
223
+ if tokenize:
224
+ input_ids.extend(input)
225
+ else:
226
+ input_message += input
227
+ if add_generation_prompt:
228
+ if tokenize:
229
+ input_ids.extend([self.convert_tokens_to_ids("<|assistant|>")])
230
+ else:
231
+ input_message += "<|assistant|>"
232
+ return {"input": input_ids if tokenize else input_message, "image": input_image}
233
+
234
+ # Main logic to handle different conversation formats
235
+ if isinstance(conversation, list) and all(isinstance(i, dict) for i in conversation):
236
+ result = handle_single_conversation(conversation)
237
+ input_ids = result["input"]
238
+ input_images = [result["image"]]
239
+ elif isinstance(conversation, list) and all(isinstance(i, list) for i in conversation):
240
+ results = [handle_single_conversation(c) for c in conversation]
241
+ input_ids = [item["input"] for item in results]
242
+ input_images = [item["image"] for item in results]
243
+ elif hasattr(conversation, "messages"):
244
+ result = handle_single_conversation(conversation.messages)
245
+ input_ids = result["input"]
246
+ input_images = [result["image"]]
247
+ else:
248
+ raise ValueError("Invalid conversation format")
249
+
250
+ if tokenize:
251
+ output = self.batch_encode_plus(
252
+ [input_ids] if isinstance(input_ids[0], int) else input_ids,
253
+ padding=padding,
254
+ truncation=truncation,
255
+ max_length=max_length,
256
+ return_tensors=return_tensors,
257
+ is_split_into_words=True,
258
+ add_special_tokens=False
259
+ )
260
+ if return_dict:
261
+ found_image = False
262
+ for image in input_images:
263
+ if image is not None:
264
+ found_image = True
265
+ break
266
+ if found_image:
267
+ output["images"] = torch.stack(input_images)
268
+ return output
269
+ else:
270
+ return output["input_ids"]
271
+ else:
272
+ return input_ids
273
+
274
+
275
+ def build_inputs_with_special_tokens(
276
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
277
+ ) -> List[int]:
278
+ """
279
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
280
+ adding special tokens. A BERT sequence has the following format:
281
+
282
+ - single sequence: `[CLS] X [SEP]`
283
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
284
+
285
+ Args:
286
+ token_ids_0 (`List[int]`):
287
+ List of IDs to which the special tokens will be added.
288
+ token_ids_1 (`List[int]`, *optional*):
289
+ Optional second list of IDs for sequence pairs.
290
+
291
+ Returns:
292
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
293
+ """
294
+ prefix_tokens = self.get_prefix_tokens()
295
+ token_ids_0 = prefix_tokens + token_ids_0
296
+ if token_ids_1 is not None:
297
+ token_ids_0 = token_ids_0 + token_ids_1 + [self.convert_tokens_to_ids("<eos>")]
298
+ return token_ids_0
299
+
300
+ def _pad(
301
+ self,
302
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
303
+ max_length: Optional[int] = None,
304
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
305
+ pad_to_multiple_of: Optional[int] = None,
306
+ return_attention_mask: Optional[bool] = None,
307
+ ) -> dict:
308
+ """
309
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
310
+
311
+ Args:
312
+ encoded_inputs:
313
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
314
+ max_length: maximum length of the returned list and optionally padding length (see below).
315
+ Will truncate by taking into account the special tokens.
316
+ padding_strategy: PaddingStrategy to use for padding.
317
+
318
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
319
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
320
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
321
+ The tokenizer padding sides are defined in self.padding_side:
322
+
323
+ - 'left': pads on the left of the sequences
324
+ - 'right': pads on the right of the sequences
325
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
326
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
327
+ `>= 7.5` (Volta).
328
+ return_attention_mask:
329
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
330
+ """
331
+ # Load from model defaults
332
+ assert self.padding_side == "left"
333
+
334
+ required_input = encoded_inputs[self.model_input_names[0]]
335
+ seq_length = len(required_input)
336
+
337
+ if padding_strategy == PaddingStrategy.LONGEST:
338
+ max_length = len(required_input)
339
+
340
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
341
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
342
+
343
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
344
+
345
+ # Initialize attention mask if not present.
346
+ if "attention_mask" not in encoded_inputs:
347
+ encoded_inputs["attention_mask"] = [1] * seq_length
348
+
349
+ if "position_ids" not in encoded_inputs:
350
+ encoded_inputs["position_ids"] = list(range(seq_length))
351
+
352
+ if needs_to_be_padded:
353
+ difference = max_length - len(required_input)
354
+
355
+ if "attention_mask" in encoded_inputs:
356
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
357
+ if "position_ids" in encoded_inputs:
358
+ encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
359
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
360
+
361
+ return encoded_inputs
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a493598071550244b2ee7f26118f3edec2150b9dfa967929a99052ac83fe716
3
+ size 2623634
tokenizer_config.json ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": [
4
+ "tokenization_chatglm.ChatGLM4Tokenizer",
5
+ null
6
+ ]
7
+ },
8
+ "added_tokens_decoder": {
9
+ "151329": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false,
15
+ "special": true
16
+ },
17
+ "151330": {
18
+ "content": "[MASK]",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false,
23
+ "special": true
24
+ },
25
+ "151331": {
26
+ "content": "[gMASK]",
27
+ "lstrip": false,
28
+ "normalized": false,
29
+ "rstrip": false,
30
+ "single_word": false,
31
+ "special": true
32
+ },
33
+ "151332": {
34
+ "content": "[sMASK]",
35
+ "lstrip": false,
36
+ "normalized": false,
37
+ "rstrip": false,
38
+ "single_word": false,
39
+ "special": true
40
+ },
41
+ "151333": {
42
+ "content": "<sop>",
43
+ "lstrip": false,
44
+ "normalized": false,
45
+ "rstrip": false,
46
+ "single_word": false,
47
+ "special": true
48
+ },
49
+ "151334": {
50
+ "content": "<eop>",
51
+ "lstrip": false,
52
+ "normalized": false,
53
+ "rstrip": false,
54
+ "single_word": false,
55
+ "special": true
56
+ },
57
+ "151335": {
58
+ "content": "<|system|>",
59
+ "lstrip": false,
60
+ "normalized": false,
61
+ "rstrip": false,
62
+ "single_word": false,
63
+ "special": true
64
+ },
65
+ "151336": {
66
+ "content": "<|user|>",
67
+ "lstrip": false,
68
+ "normalized": false,
69
+ "rstrip": false,
70
+ "single_word": false,
71
+ "special": true
72
+ },
73
+ "151337": {
74
+ "content": "<|assistant|>",
75
+ "lstrip": false,
76
+ "normalized": false,
77
+ "rstrip": false,
78
+ "single_word": false,
79
+ "special": true
80
+ },
81
+ "151338": {
82
+ "content": "<|observation|>",
83
+ "lstrip": false,
84
+ "normalized": false,
85
+ "rstrip": false,
86
+ "single_word": false,
87
+ "special": true
88
+ },
89
+ "151339": {
90
+ "content": "<|begin_of_image|>",
91
+ "lstrip": false,
92
+ "normalized": false,
93
+ "rstrip": false,
94
+ "single_word": false,
95
+ "special": true
96
+ },
97
+ "151340": {
98
+ "content": "<|end_of_image|>",
99
+ "lstrip": false,
100
+ "normalized": false,
101
+ "rstrip": false,
102
+ "single_word": false,
103
+ "special": true
104
+ },
105
+ "151341": {
106
+ "content": "<|begin_of_video|>",
107
+ "lstrip": false,
108
+ "normalized": false,
109
+ "rstrip": false,
110
+ "single_word": false,
111
+ "special": true
112
+ },
113
+ "151342": {
114
+ "content": "<|end_of_video|>",
115
+ "lstrip": false,
116
+ "normalized": false,
117
+ "rstrip": false,
118
+ "single_word": false,
119
+ "special": true
120
+ }
121
+ },
122
+ "additional_special_tokens": ["<|endoftext|>", "[MASK]", "[gMASK]", "[sMASK]", "<sop>", "<eop>", "<|system|>",
123
+ "<|user|>", "<|assistant|>", "<|observation|>", "<|begin_of_image|>", "<|end_of_image|>",
124
+ "<|begin_of_video|>", "<|end_of_video|>"],
125
+ "clean_up_tokenization_spaces": false,
126
+ "do_lower_case": false,
127
+ "eos_token": "<|endoftext|>",
128
+ "pad_token": "<|endoftext|>",
129
+ "model_max_length": 1000000000000000019884624838656,
130
+ "padding_side": "left",
131
+ "remove_space": false,
132
+ "tokenizer_class": "ChatGLM4Tokenizer",
133
+ "image_size": 1120
134
+ }