shunxing1234 commited on
Commit
bcca154
1 Parent(s): 1f048ea

Upload 3 files

Browse files
Files changed (3) hide show
  1. tokenization_telechat2.py +223 -0
  2. tokenizer.model +3 -0
  3. tokenizer_config.json +114 -0
tokenization_telechat2.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from shutil import copyfile
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+ import sentencepiece as spm
5
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
6
+ from transformers.utils import logging
7
+
8
+ logger = logging.get_logger(__name__)
9
+
10
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
11
+
12
+ # TODO: when we get download url from huggingface, refresh the map
13
+ PRETRAINED_VOCAB_FILES_MAP = {
14
+ "vocab_file": {},
15
+ "tokenizer_file": {},
16
+ }
17
+
18
+
19
+ class Telechat2Tokenizer(PreTrainedTokenizer):
20
+ vocab_files_names = VOCAB_FILES_NAMES
21
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
22
+ model_input_names = ["input_ids", "attention_mask"]
23
+
24
+ def __init__(
25
+ self,
26
+ vocab_file,
27
+ unk_token="<unk>",
28
+ bos_token="<_start>",
29
+ eos_token="<_end>",
30
+ pad_token="<_pad>",
31
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
32
+ add_bos_token=True,
33
+ add_eos_token=False,
34
+ clean_up_tokenization_spaces=False,
35
+ **kwargs,
36
+ ):
37
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
38
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
39
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
40
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
41
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
42
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
43
+ self.sp_model.Load(vocab_file)
44
+ super().__init__(
45
+ bos_token=bos_token,
46
+ eos_token=eos_token,
47
+ unk_token=unk_token,
48
+ pad_token=pad_token,
49
+ add_bos_token=add_bos_token,
50
+ add_eos_token=add_eos_token,
51
+ sp_model_kwargs=self.sp_model_kwargs,
52
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
53
+ **kwargs,
54
+ )
55
+ self.vocab_file = vocab_file
56
+ self.add_bos_token = add_bos_token
57
+ self.add_eos_token = add_eos_token
58
+
59
+ def __getstate__(self):
60
+ state = self.__dict__.copy()
61
+ state["sp_model"] = None
62
+ return state
63
+
64
+ def __setstate__(self, d):
65
+ self.__dict__ = d
66
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
67
+ self.sp_model.Load(self.vocab_file)
68
+
69
+ @property
70
+ def vocab_size(self):
71
+ """Returns vocab size"""
72
+ return self.sp_model.get_piece_size()
73
+
74
+ def get_vocab(self):
75
+ """Returns vocab as a dict"""
76
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
77
+ vocab.update(self.added_tokens_encoder)
78
+ return vocab
79
+
80
+ @property
81
+ def vocab(self):
82
+ return self.get_vocab()
83
+
84
+ def _tokenize(self, text):
85
+ """Returns a tokenized string."""
86
+ return self.sp_model.encode(text, out_type=str)
87
+
88
+ def _convert_token_to_id(self, token):
89
+ """Converts a token (str) in an id using the vocab."""
90
+ return self.sp_model.piece_to_id(token)
91
+
92
+ def _convert_id_to_token(self, index):
93
+ """Converts an index (integer) in a token (str) using the vocab."""
94
+ token = self.sp_model.IdToPiece(index)
95
+ return token
96
+
97
+ def convert_tokens_to_string(self, tokens):
98
+ """Converts a sequence of tokens (string) in a single string."""
99
+ current_sub_tokens = []
100
+ out_string = ""
101
+ # prev_is_special = False
102
+ for i, token in enumerate(tokens):
103
+ # make sure that special tokens are not decoded using sentencepiece model
104
+ if token in self.all_special_tokens:
105
+ # if not prev_is_special and i != 0:
106
+ # out_string += " "
107
+ out_string += self.sp_model.decode(current_sub_tokens) + token
108
+ # prev_is_special = True
109
+ current_sub_tokens = []
110
+ else:
111
+ current_sub_tokens.append(token)
112
+ # prev_is_special = False
113
+ out_string += self.sp_model.decode(current_sub_tokens)
114
+ return out_string
115
+
116
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
117
+ """
118
+ Save the vocabulary and special tokens file to a directory.
119
+
120
+ Args:
121
+ save_directory (`str`):
122
+ The directory in which to save the vocabulary.
123
+
124
+ Returns:
125
+ `Tuple(str)`: Paths to the files saved.
126
+ """
127
+ if not os.path.isdir(save_directory):
128
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
129
+ return
130
+ out_vocab_file = os.path.join(
131
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
132
+ )
133
+
134
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
135
+ copyfile(self.vocab_file, out_vocab_file)
136
+ elif not os.path.isfile(self.vocab_file):
137
+ with open(out_vocab_file, "wb") as fi:
138
+ content_spiece_model = self.sp_model.serialized_model_proto()
139
+ fi.write(content_spiece_model)
140
+
141
+ return (out_vocab_file,)
142
+
143
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
144
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
145
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
146
+
147
+ output = bos_token_id + token_ids_0 + eos_token_id
148
+
149
+ if token_ids_1 is not None:
150
+ output = output + bos_token_id + token_ids_1 + eos_token_id
151
+
152
+ return output
153
+
154
+ def get_special_tokens_mask(
155
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None,
156
+ already_has_special_tokens: bool = False
157
+ ) -> List[int]:
158
+ """
159
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
160
+ special tokens using the tokenizer `prepare_for_model` method.
161
+
162
+ Args:
163
+ token_ids_0 (`List[int]`):
164
+ List of IDs.
165
+ token_ids_1 (`List[int]`, *optional*):
166
+ Optional second list of IDs for sequence pairs.
167
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
168
+ Whether or not the token list is already formatted with special tokens for the model.
169
+
170
+ Returns:
171
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
172
+ """
173
+ if already_has_special_tokens:
174
+ return super().get_special_tokens_mask(
175
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
176
+ )
177
+
178
+ bos_token_id = [1] if self.add_bos_token else []
179
+ eos_token_id = [1] if self.add_eos_token else []
180
+
181
+ if token_ids_1 is None:
182
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
183
+ return (
184
+ bos_token_id
185
+ + ([0] * len(token_ids_0))
186
+ + eos_token_id
187
+ + bos_token_id
188
+ + ([0] * len(token_ids_1))
189
+ + eos_token_id
190
+ )
191
+
192
+ def create_token_type_ids_from_sequences(
193
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
194
+ ) -> List[int]:
195
+ """
196
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
197
+ sequence pair mask has the following format:
198
+
199
+ ```
200
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
201
+ | first sequence | second sequence |
202
+ ```
203
+
204
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
205
+
206
+ Args:
207
+ token_ids_0 (`List[int]`):
208
+ List of ids.
209
+ token_ids_1 (`List[int]`, *optional*):
210
+ Optional second list of IDs for sequence pairs.
211
+
212
+ Returns:
213
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
214
+ """
215
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
216
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
217
+
218
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
219
+
220
+ if token_ids_1 is not None:
221
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
222
+
223
+ return output
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7a5b465bbc9465b214e0962076c1170783a8ee88fb01454b0c33609bd3cf954
3
+ size 2197499
tokenizer_config.json ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tokenizer_class": "Telechat2Tokenizer",
3
+ "auto_map": {
4
+ "AutoTokenizer": [
5
+ "tokenization_telechat2.Telechat2Tokenizer",
6
+ null
7
+ ]
8
+ },
9
+ "added_tokens_decoder": {
10
+ "1": {
11
+ "content": "<_start>",
12
+ "lstrip": false,
13
+ "normalized": false,
14
+ "rstrip": false,
15
+ "single_word": false,
16
+ "special": true
17
+ },
18
+ "2": {
19
+ "content": "<_end>",
20
+ "lstrip": false,
21
+ "normalized": false,
22
+ "rstrip": false,
23
+ "single_word": false,
24
+ "special": true
25
+ },
26
+ "3": {
27
+ "content": "<_pad>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false,
32
+ "special": true
33
+ },
34
+ "4": {
35
+ "content": "<_user>",
36
+ "lstrip": false,
37
+ "normalized": false,
38
+ "rstrip": false,
39
+ "single_word": false,
40
+ "special": true
41
+ },
42
+ "5": {
43
+ "content": "<_bot>",
44
+ "lstrip": false,
45
+ "normalized": false,
46
+ "rstrip": false,
47
+ "single_word": false,
48
+ "special": true
49
+ },
50
+ "6": {
51
+ "content": "<_system>",
52
+ "lstrip": false,
53
+ "normalized": false,
54
+ "rstrip": false,
55
+ "single_word": false,
56
+ "special": true
57
+ },
58
+ "9": {
59
+ "content": "<tool_call>",
60
+ "lstrip": false,
61
+ "normalized": false,
62
+ "rstrip": false,
63
+ "single_word": false,
64
+ "special": true
65
+ },
66
+ "10": {
67
+ "content": "</tool_call>",
68
+ "lstrip": false,
69
+ "normalized": false,
70
+ "rstrip": false,
71
+ "single_word": false,
72
+ "special": true
73
+ },
74
+ "11": {
75
+ "content": "<tool_response>",
76
+ "lstrip": false,
77
+ "normalized": false,
78
+ "rstrip": false,
79
+ "single_word": false,
80
+ "special": true
81
+ },
82
+ "12": {
83
+ "content": "</tool_response>",
84
+ "lstrip": false,
85
+ "normalized": false,
86
+ "rstrip": false,
87
+ "single_word": false,
88
+ "special": true
89
+ }
90
+ },
91
+ "additional_special_tokens": [
92
+ "<_start>",
93
+ "<_end>",
94
+ "<_pad>",
95
+ "<_user>",
96
+ "<_bot>",
97
+ "<_system>",
98
+ "<tool_call>",
99
+ "</tool_call>",
100
+ "<tool_response>",
101
+ "</tool_response>"
102
+ ],
103
+ "add_bos_token": false,
104
+ "add_eos_token": false,
105
+ "use_fast": false,
106
+ "clean_up_tokenization_spaces": false,
107
+ "split_special_tokens": false,
108
+ "model_max_length": 100000000,
109
+ "sp_model_kwargs": {},
110
+ "bos_token": "<_start>",
111
+ "eos_token": "<_end>",
112
+ "pad_token": "<_pad>",
113
+ "chat_template": "{%- if tools %}\n {%- if messages[0]['role'] == 'system' %}\n {{-'<_system>'+messages[0]['content'] }}\n {%- else %}\n {{- '<_system>'+'你是中国电信星辰语义大模型,英文名是TeleChat,你是由中电信人工智能科技有限公司和中国电信人工智能研究院(TeleAI)研发的人工智能助手。' }}\n {%- endif %}\n {{- '\\n\\n# 可用工具\\n你可以调用<tools></tools>标签中包含的一个或多个工具来辅助你回答问题,以下是可用工具详情:\\n<tools>\\n' }}\n {%- for tool in tools %}\n {{- tool | tojson }}\n {{-'\\n'}}\n {%- endfor %}\n {{- '</tools>\\n\\n# 调用方法\\n你需要遵循工具的要求,使用json格式返回工具名称及参数,并用<tool_call></tool_call>包含。下方是一个调用模板:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call>\\n\\n' }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<_system>' + messages[0]['content'] + '\\n' }}\n {%- else %}\n {{- '<_system>'+'你是中国电信星辰语义大模型,英文名是TeleChat,你是由中电信人工智能科技有限公司和中国电信人工智能研究院(TeleAI)研发的人工智能助手。\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == 'user') %}\n {{- '<_user>' + message.content }}\n {%- elif message.role == 'bot' %}\n {{- '<_bot>' }}\n {%- if message.content %}\n {{- message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if loop.index0 == 0 %}\n {{-'<tool_call>'}}\n {%- else %}\n {{-'\\n<tool_call>'}}\n {%- endif %}\n {{- '\\n{\"name\": \"' }}{{ tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<_end>\\n' }}\n {%- elif message.role == 'tool' %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != 'tool') %}\n {{- '<_user>'+'<tool_response>\\n' }}\n {%- else %}\n {{- '\\n<tool_response>\\n' }}\n {%- endif %}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<_bot>' }}\n{%- endif %}"
114
+ }