Maxtimer97 commited on
Commit
2495dfe
·
verified ·
1 Parent(s): 5046ee8

Upload tokenizer

Browse files
added_tokens.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<eop>": 151334,
3
+ "<sop>": 151333,
4
+ "<|assistant|>": 151337,
5
+ "<|begin_of_image|>": 151339,
6
+ "<|begin_of_video|>": 151341,
7
+ "<|end_of_image|>": 151340,
8
+ "<|end_of_video|>": 151342,
9
+ "<|endoftext|>": 151329,
10
+ "<|observation|>": 151338,
11
+ "<|system|>": 151335,
12
+ "<|user|>": 151336,
13
+ "[MASK]": 151330,
14
+ "[gMASK]": 151331,
15
+ "[sMASK]": 151332
16
+ }
chat_template.jinja ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gMASK]<sop>{% for item in messages %}{% if item['tools'] is defined %}<|system|>
2
+ 你是一个名为 ChatGLM 的人工智能助手。你是基于智谱AI训练的语言模型 GLM-4 模型开发的,你的任务是针对用户的问题和要求提供适当的答复和支持。
3
+
4
+ # 可用工具{% set tools = item['tools'] %}{% for tool in tools %}{% if tool['type'] == 'function' %}
5
+
6
+ ## {{ tool['function']['name'] }}
7
+
8
+ {{ tool['function'] | tojson(indent=4) }}
9
+ 在调用上述函数时,请使用 Json 格式表示调用的参数。{% elif tool['type'] == 'python' %}
10
+
11
+ ## python
12
+
13
+ 当你向 `python` 发送包含 Python 代码的消息时,该代码将会在一个有状态的 Jupyter notebook 环境中执行。
14
+ `python` 返回代码执行的输出,或在执行 60 秒后返回超时。
15
+ `/mnt/data` 将会持久化存储你的文件。在此会话中,`python` 无法访问互联网。不要使用 `python` 进行任何网络请求或者在线 API 调用,这些在线内容的访问将不会成功。{% elif tool['type'] == 'simple_browser' %}
16
+
17
+ ## simple_browser
18
+
19
+ 你可以使用 `simple_browser` 工具。该工具支持以下函数:
20
+ `search(query: str, recency_days: int)`:使用搜索引擎进行查询并显示结果,可以使用 `recency_days` 参数控制搜索内容的时效性。
21
+ `mclick(ids: list[int])`:获取一系列指定 id 的页面内容。每次调用时,须选择3-10个页面。选择多个角度的页面,同时尽可能选择可信任的信息来源。考虑到部分页面是无法加载的,你也可以多打开一些可能有用的页面而不用担心内容过多。
22
+ `open_url(url: str)`:打开指定的 URL。
23
+
24
+ 使用 `【{引用 id}†{引用文本}】` 来引用内容。
25
+
26
+ 操作步骤:1. 使用 `search` 来获得信息列表; 2. 使用 `mclick` 来获取指定 ID 页面的内容; 3. 根据获得的内容进行回复。在回复中应当引用信息来源。
27
+ 如果用户提供了 URL,也可以用 `open_url` 直接打开页面。
28
+ 如果初次搜索结果没有找到合适的信息,也可以再次使用 `search` 进行搜索。{% elif tool['type'] == 'cogview' %}
29
+
30
+ ## cogview
31
+
32
+ 如果用户的请求中包含了对图像的描述,你可以使用 `cogview` 来生成图像并展示给用户。你需要向 `cogview` 发送图像描述,规则:
33
+ - 发送给 `cogview` 的消息必须使用英语。用户的中文描述必须完全翻译为英语。
34
+ - 应当尽可能详细地描述图像生成的需求,需求描述约 100 英文单词。
35
+ - 保持用户原始描述的意图。不要虚构内容或者没见过的人物。
36
+ - 如无特殊说明,所在地为中国,持有中国立场并遵循中国社会主义价值观。{% endif %}{% endfor %}{% endif %}{% if item['content'] %}<|{{ item['role'] }}|>{{ item['metadata'] }}
37
+ {{ item['content'] }}{% endif %}{% endfor %}{% if add_generation_prompt %}<|assistant|>{% endif %}
special_tokens_map.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|endoftext|>",
4
+ "[MASK]",
5
+ "[gMASK]",
6
+ "[sMASK]",
7
+ "<sop>",
8
+ "<eop>",
9
+ "<|system|>",
10
+ "<|user|>",
11
+ "<|assistant|>",
12
+ "<|observation|>",
13
+ "<|begin_of_image|>",
14
+ "<|end_of_image|>",
15
+ "<|begin_of_video|>",
16
+ "<|end_of_video|>"
17
+ ],
18
+ "eos_token": {
19
+ "content": "<|endoftext|>",
20
+ "lstrip": false,
21
+ "normalized": false,
22
+ "rstrip": false,
23
+ "single_word": false
24
+ },
25
+ "pad_token": {
26
+ "content": "<|endoftext|>",
27
+ "lstrip": false,
28
+ "normalized": false,
29
+ "rstrip": false,
30
+ "single_word": false
31
+ }
32
+ }
tokenization_chatglm.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import regex as re
2
+ import base64
3
+ import os
4
+ import tiktoken
5
+ from typing import List, Optional, Union, Dict
6
+ from transformers import PreTrainedTokenizer
7
+ from transformers.utils import PaddingStrategy
8
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
9
+
10
+
11
+ class ChatGLM4Tokenizer(PreTrainedTokenizer):
12
+ vocab_files_names = {"vocab_file": "tokenizer.model"}
13
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
14
+
15
+ def __init__(
16
+ self,
17
+ vocab_file,
18
+ clean_up_tokenization_spaces=False,
19
+ **kwargs
20
+ ):
21
+ self.name = "GLM4Tokenizer"
22
+ self.vocab_file = vocab_file
23
+ 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+"
24
+ self.pat_str = re.compile(pat_str)
25
+
26
+ mergeable_ranks = {}
27
+ with open(vocab_file) as f:
28
+ for line in f:
29
+ token, rank = line.strip().split()
30
+ rank = int(rank)
31
+ token = base64.b64decode(token)
32
+ mergeable_ranks[token] = rank
33
+
34
+ self.mergeable_ranks = mergeable_ranks
35
+
36
+ self.tokenizer = tiktoken.Encoding(
37
+ name="my_tokenizer",
38
+ pat_str=pat_str,
39
+ mergeable_ranks=mergeable_ranks,
40
+ special_tokens={}
41
+ )
42
+ self.decoder = {rank: token for token, rank in mergeable_ranks.items()}
43
+ self.n_words = len(self.decoder)
44
+
45
+ super().__init__(
46
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
47
+ **kwargs
48
+ )
49
+
50
+ @property
51
+ def vocab_size(self):
52
+ return self.n_words
53
+
54
+ def get_vocab(self):
55
+ """ Returns vocab as a dict """
56
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
57
+ vocab.update(self.added_tokens_encoder)
58
+ return vocab
59
+
60
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str, int]]) -> str:
61
+ """
62
+ Converts a sequence of tokens in a single string.
63
+ """
64
+ text = ""
65
+ temp = b""
66
+ for t in tokens:
67
+ if isinstance(t, int):
68
+ t = chr(t)
69
+ if isinstance(t, str):
70
+ if temp:
71
+ text += temp.decode("utf-8", errors="replace")
72
+ elif isinstance(t, bytes):
73
+ temp += t
74
+ else:
75
+ raise TypeError("token should only be of type int, bytes or str")
76
+ if temp:
77
+ text += temp.decode("utf-8", errors="replace")
78
+ return text
79
+
80
+ def _tokenize(self, text, **kwargs):
81
+ tokens = []
82
+ ids = self.tokenizer.encode(text)
83
+ for t in ids:
84
+ tokens.append(self.decoder[t])
85
+ return tokens
86
+
87
+ def _convert_token_to_id(self, token):
88
+ """ Converts a token (str) in an id using the vocab. """
89
+ return self.mergeable_ranks[token]
90
+
91
+ def _convert_id_to_token(self, index):
92
+ """Converts an index (integer) in a token (str) using the vocab."""
93
+ return self.decoder.get(index, "")
94
+
95
+ def save_vocabulary(self, save_directory, filename_prefix=None):
96
+ """
97
+ Save the vocabulary and special tokens file to a directory.
98
+
99
+ Args:
100
+ save_directory (`str`):
101
+ The directory in which to save the vocabulary.
102
+ filename_prefix (`str`, *optional*):
103
+ An optional prefix to add to the named of the saved files.
104
+
105
+ Returns:
106
+ `Tuple(str)`: Paths to the files saved.
107
+ """
108
+ if os.path.isdir(save_directory):
109
+ vocab_file = os.path.join(
110
+ save_directory, self.vocab_files_names["vocab_file"]
111
+ )
112
+ else:
113
+ vocab_file = save_directory
114
+
115
+ with open(self.vocab_file, 'rb') as fin:
116
+ proto_str = fin.read()
117
+
118
+ with open(vocab_file, "wb") as writer:
119
+ writer.write(proto_str)
120
+
121
+ return (vocab_file,)
122
+
123
+ def get_prefix_tokens(self):
124
+ prefix_tokens = [self.convert_tokens_to_ids("[gMASK]"), self.convert_tokens_to_ids("<sop>")]
125
+ return prefix_tokens
126
+
127
+ def build_single_message(self, role, metadata, message, tokenize=True):
128
+ assert role in ["system", "user", "assistant", "observation"], role
129
+ if tokenize:
130
+ role_tokens = [self.convert_tokens_to_ids(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n",
131
+ disallowed_special=())
132
+ message_tokens = self.tokenizer.encode(message, disallowed_special=())
133
+ tokens = role_tokens + message_tokens
134
+ return tokens
135
+ else:
136
+ return str(f"<|{role}|>{metadata}\n{message}")
137
+
138
+ def build_inputs_with_special_tokens(
139
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
140
+ ) -> List[int]:
141
+ """
142
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
143
+ adding special tokens. A BERT sequence has the following format:
144
+
145
+ - single sequence: `[CLS] X [SEP]`
146
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
147
+
148
+ Args:
149
+ token_ids_0 (`List[int]`):
150
+ List of IDs to which the special tokens will be added.
151
+ token_ids_1 (`List[int]`, *optional*):
152
+ Optional second list of IDs for sequence pairs.
153
+
154
+ Returns:
155
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
156
+ """
157
+ prefix_tokens = self.get_prefix_tokens()
158
+ token_ids_0 = prefix_tokens + token_ids_0
159
+ if token_ids_1 is not None:
160
+ token_ids_0 = token_ids_0 + token_ids_1 + [self.convert_tokens_to_ids("<eos>")]
161
+ return token_ids_0
162
+
163
+ def _pad(
164
+ self,
165
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
166
+ max_length: Optional[int] = None,
167
+ padding_side: str = "left",
168
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
169
+ pad_to_multiple_of: Optional[int] = None,
170
+ return_attention_mask: Optional[bool] = None,
171
+ ) -> dict:
172
+ """
173
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
174
+
175
+ Args:
176
+ encoded_inputs:
177
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
178
+ max_length: maximum length of the returned list and optionally padding length (see below).
179
+ Will truncate by taking into account the special tokens.
180
+ padding_strategy: PaddingStrategy to use for padding.
181
+
182
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
183
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
184
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
185
+ The tokenizer padding sides are defined in self.padding_side:
186
+
187
+ - 'left': pads on the left of the sequences
188
+ - 'right': pads on the right of the sequences
189
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
190
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
191
+ `>= 7.5` (Volta).
192
+ return_attention_mask:
193
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
194
+ """
195
+ # Load from model defaults
196
+
197
+ required_input = encoded_inputs[self.model_input_names[0]]
198
+ seq_length = len(required_input)
199
+
200
+ if padding_strategy == PaddingStrategy.LONGEST:
201
+ max_length = len(required_input)
202
+
203
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
204
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
205
+
206
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
207
+
208
+ # Initialize attention mask if not present.
209
+ if "attention_mask" not in encoded_inputs:
210
+ encoded_inputs["attention_mask"] = [1] * seq_length
211
+
212
+ if "position_ids" not in encoded_inputs:
213
+ encoded_inputs["position_ids"] = list(range(seq_length))
214
+
215
+ if needs_to_be_padded:
216
+ difference = max_length - len(required_input)
217
+
218
+ if "attention_mask" in encoded_inputs:
219
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
220
+ if "position_ids" in encoded_inputs:
221
+ encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
222
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
223
+
224
+ 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,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "151329": {
4
+ "content": "<|endoftext|>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "151330": {
12
+ "content": "[MASK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "151331": {
20
+ "content": "[gMASK]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "151332": {
28
+ "content": "[sMASK]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "151333": {
36
+ "content": "<sop>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "151334": {
44
+ "content": "<eop>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "151335": {
52
+ "content": "<|system|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "151336": {
60
+ "content": "<|user|>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "151337": {
68
+ "content": "<|assistant|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "151338": {
76
+ "content": "<|observation|>",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "151339": {
84
+ "content": "<|begin_of_image|>",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "151340": {
92
+ "content": "<|end_of_image|>",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "151341": {
100
+ "content": "<|begin_of_video|>",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "151342": {
108
+ "content": "<|end_of_video|>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ }
115
+ },
116
+ "additional_special_tokens": [
117
+ "<|endoftext|>",
118
+ "[MASK]",
119
+ "[gMASK]",
120
+ "[sMASK]",
121
+ "<sop>",
122
+ "<eop>",
123
+ "<|system|>",
124
+ "<|user|>",
125
+ "<|assistant|>",
126
+ "<|observation|>",
127
+ "<|begin_of_image|>",
128
+ "<|end_of_image|>",
129
+ "<|begin_of_video|>",
130
+ "<|end_of_video|>"
131
+ ],
132
+ "auto_map": {
133
+ "AutoTokenizer": [
134
+ "tokenization_chatglm.ChatGLM4Tokenizer",
135
+ null
136
+ ]
137
+ },
138
+ "clean_up_tokenization_spaces": false,
139
+ "do_lower_case": false,
140
+ "eos_token": "<|endoftext|>",
141
+ "extra_special_tokens": {},
142
+ "model_max_length": 128000,
143
+ "pad_token": "<|endoftext|>",
144
+ "padding_side": "left",
145
+ "remove_space": false,
146
+ "tokenizer_class": "ChatGLM4Tokenizer"
147
+ }