Upload tokenizer
Browse files- README.md +201 -0
- special_tokens_map.json +18 -0
- tokenization_chatglm.py +328 -0
- tokenizer.model +3 -0
- tokenizer_config.json +40 -0
README.md
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
tags: []
|
4 |
+
---
|
5 |
+
|
6 |
+
# Model Card for Model ID
|
7 |
+
|
8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
|
14 |
+
### Model Description
|
15 |
+
|
16 |
+
<!-- Provide a longer summary of what this model is. -->
|
17 |
+
|
18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
19 |
+
|
20 |
+
- **Developed by:** [More Information Needed]
|
21 |
+
- **Funded by [optional]:** [More Information Needed]
|
22 |
+
- **Shared by [optional]:** [More Information Needed]
|
23 |
+
- **Model type:** [More Information Needed]
|
24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
25 |
+
- **License:** [More Information Needed]
|
26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
+
|
28 |
+
### Model Sources [optional]
|
29 |
+
|
30 |
+
<!-- Provide the basic links for the model. -->
|
31 |
+
|
32 |
+
- **Repository:** [More Information Needed]
|
33 |
+
- **Paper [optional]:** [More Information Needed]
|
34 |
+
- **Demo [optional]:** [More Information Needed]
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
[More Information Needed]
|
75 |
+
|
76 |
+
## Training Details
|
77 |
+
|
78 |
+
### Training Data
|
79 |
+
|
80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
+
|
82 |
+
[More Information Needed]
|
83 |
+
|
84 |
+
### Training Procedure
|
85 |
+
|
86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
+
|
88 |
+
#### Preprocessing [optional]
|
89 |
+
|
90 |
+
[More Information Needed]
|
91 |
+
|
92 |
+
|
93 |
+
#### Training Hyperparameters
|
94 |
+
|
95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
96 |
+
|
97 |
+
#### Speeds, Sizes, Times [optional]
|
98 |
+
|
99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
100 |
+
|
101 |
+
[More Information Needed]
|
102 |
+
|
103 |
+
## Evaluation
|
104 |
+
|
105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
106 |
+
|
107 |
+
### Testing Data, Factors & Metrics
|
108 |
+
|
109 |
+
#### Testing Data
|
110 |
+
|
111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
112 |
+
|
113 |
+
[More Information Needed]
|
114 |
+
|
115 |
+
#### Factors
|
116 |
+
|
117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
+
|
119 |
+
[More Information Needed]
|
120 |
+
|
121 |
+
#### Metrics
|
122 |
+
|
123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
+
|
125 |
+
[More Information Needed]
|
126 |
+
|
127 |
+
### Results
|
128 |
+
|
129 |
+
[More Information Needed]
|
130 |
+
|
131 |
+
#### Summary
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Model Examination [optional]
|
136 |
+
|
137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
138 |
+
|
139 |
+
[More Information Needed]
|
140 |
+
|
141 |
+
## Environmental Impact
|
142 |
+
|
143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
+
|
145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
+
|
147 |
+
- **Hardware Type:** [More Information Needed]
|
148 |
+
- **Hours used:** [More Information Needed]
|
149 |
+
- **Cloud Provider:** [More Information Needed]
|
150 |
+
- **Compute Region:** [More Information Needed]
|
151 |
+
- **Carbon Emitted:** [More Information Needed]
|
152 |
+
|
153 |
+
## Technical Specifications [optional]
|
154 |
+
|
155 |
+
### Model Architecture and Objective
|
156 |
+
|
157 |
+
[More Information Needed]
|
158 |
+
|
159 |
+
### Compute Infrastructure
|
160 |
+
|
161 |
+
[More Information Needed]
|
162 |
+
|
163 |
+
#### Hardware
|
164 |
+
|
165 |
+
[More Information Needed]
|
166 |
+
|
167 |
+
#### Software
|
168 |
+
|
169 |
+
[More Information Needed]
|
170 |
+
|
171 |
+
## Citation [optional]
|
172 |
+
|
173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
+
|
175 |
+
**BibTeX:**
|
176 |
+
|
177 |
+
[More Information Needed]
|
178 |
+
|
179 |
+
**APA:**
|
180 |
+
|
181 |
+
[More Information Needed]
|
182 |
+
|
183 |
+
## Glossary [optional]
|
184 |
+
|
185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
+
|
187 |
+
[More Information Needed]
|
188 |
+
|
189 |
+
## More Information [optional]
|
190 |
+
|
191 |
+
[More Information Needed]
|
192 |
+
|
193 |
+
## Model Card Authors [optional]
|
194 |
+
|
195 |
+
[More Information Needed]
|
196 |
+
|
197 |
+
## Model Card Contact
|
198 |
+
|
199 |
+
[More Information Needed]
|
200 |
+
|
201 |
+
|
special_tokens_map.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
{
|
4 |
+
"content": "<|user|>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false
|
9 |
+
},
|
10 |
+
{
|
11 |
+
"content": "<|observation|>",
|
12 |
+
"lstrip": false,
|
13 |
+
"normalized": false,
|
14 |
+
"rstrip": false,
|
15 |
+
"single_word": false
|
16 |
+
}
|
17 |
+
]
|
18 |
+
}
|
tokenization_chatglm.py
ADDED
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import re
|
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 |
+
logger = logging.get_logger(__name__)
|
12 |
+
|
13 |
+
|
14 |
+
class SPTokenizer:
|
15 |
+
def __init__(self, model_path: str):
|
16 |
+
# reload tokenizer
|
17 |
+
assert os.path.isfile(model_path), model_path
|
18 |
+
self.sp_model = SentencePieceProcessor(model_file=model_path)
|
19 |
+
|
20 |
+
# BOS / EOS token IDs
|
21 |
+
self.n_words: int = self.sp_model.vocab_size()
|
22 |
+
self.bos_id: int = self.sp_model.bos_id()
|
23 |
+
self.eos_id: int = self.sp_model.eos_id()
|
24 |
+
self.pad_id: int = self.sp_model.unk_id()
|
25 |
+
assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
|
26 |
+
|
27 |
+
role_special_tokens = ["<|system|>", "<|user|>", "<|assistant|>", "<|observation|>"]
|
28 |
+
special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop"] + role_special_tokens
|
29 |
+
self.special_tokens = {}
|
30 |
+
self.index_special_tokens = {}
|
31 |
+
for token in special_tokens:
|
32 |
+
self.special_tokens[token] = self.n_words
|
33 |
+
self.index_special_tokens[self.n_words] = token
|
34 |
+
self.n_words += 1
|
35 |
+
self.role_special_token_expression = "|".join([re.escape(token) for token in special_tokens]) # for apply_chat_template
|
36 |
+
|
37 |
+
def tokenize(self, s: str, encode_special_tokens=False):
|
38 |
+
if encode_special_tokens:
|
39 |
+
last_index = 0
|
40 |
+
t = []
|
41 |
+
for match in re.finditer(self.role_special_token_expression, s):
|
42 |
+
if last_index < match.start():
|
43 |
+
t.extend(self.sp_model.EncodeAsPieces(s[last_index:match.start()]))
|
44 |
+
t.append(s[match.start():match.end()])
|
45 |
+
last_index = match.end()
|
46 |
+
if last_index < len(s):
|
47 |
+
t.extend(self.sp_model.EncodeAsPieces(s[last_index:]))
|
48 |
+
return t
|
49 |
+
else:
|
50 |
+
return self.sp_model.EncodeAsPieces(s)
|
51 |
+
|
52 |
+
def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]:
|
53 |
+
assert type(s) is str
|
54 |
+
t = self.sp_model.encode(s)
|
55 |
+
if bos:
|
56 |
+
t = [self.bos_id] + t
|
57 |
+
if eos:
|
58 |
+
t = t + [self.eos_id]
|
59 |
+
return t
|
60 |
+
|
61 |
+
def decode(self, t: List[int]) -> str:
|
62 |
+
text, buffer = "", []
|
63 |
+
for token in t:
|
64 |
+
if token in self.index_special_tokens:
|
65 |
+
if buffer:
|
66 |
+
text += self.sp_model.decode(buffer)
|
67 |
+
buffer = []
|
68 |
+
text += self.index_special_tokens[token]
|
69 |
+
else:
|
70 |
+
buffer.append(token)
|
71 |
+
if buffer:
|
72 |
+
text += self.sp_model.decode(buffer)
|
73 |
+
return text
|
74 |
+
|
75 |
+
def decode_tokens(self, tokens: List[str]) -> str:
|
76 |
+
text = self.sp_model.DecodePieces(tokens)
|
77 |
+
return text
|
78 |
+
|
79 |
+
def convert_token_to_id(self, token):
|
80 |
+
""" Converts a token (str) in an id using the vocab. """
|
81 |
+
if token in self.special_tokens:
|
82 |
+
return self.special_tokens[token]
|
83 |
+
return self.sp_model.PieceToId(token)
|
84 |
+
|
85 |
+
def convert_id_to_token(self, index):
|
86 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
87 |
+
if index in self.index_special_tokens:
|
88 |
+
return self.index_special_tokens[index]
|
89 |
+
if index in [self.eos_id, self.bos_id, self.pad_id] or index < 0 or index > self.sp_model.vocab_size():
|
90 |
+
return ""
|
91 |
+
return self.sp_model.IdToPiece(index)
|
92 |
+
|
93 |
+
|
94 |
+
class ChatGLMTokenizer(PreTrainedTokenizer):
|
95 |
+
|
96 |
+
vocab_files_names = {"vocab_file": "tokenizer.model"}
|
97 |
+
model_input_names = ["input_ids", "attention_mask", "position_ids"]
|
98 |
+
|
99 |
+
def __init__(
|
100 |
+
self,
|
101 |
+
vocab_file,
|
102 |
+
padding_side="left",
|
103 |
+
clean_up_tokenization_spaces=False,
|
104 |
+
encode_special_tokens=False,
|
105 |
+
**kwargs
|
106 |
+
):
|
107 |
+
self.name = "GLMTokenizer"
|
108 |
+
self.vocab_file = vocab_file
|
109 |
+
self.tokenizer = SPTokenizer(vocab_file)
|
110 |
+
self.special_tokens = {
|
111 |
+
"<bos>": self.tokenizer.bos_id,
|
112 |
+
"<eos>": self.tokenizer.eos_id,
|
113 |
+
"<unk>": self.tokenizer.pad_id,
|
114 |
+
"<pad>": self.tokenizer.pad_id
|
115 |
+
}
|
116 |
+
self.encode_special_tokens = encode_special_tokens
|
117 |
+
|
118 |
+
super().__init__(
|
119 |
+
padding_side=padding_side,
|
120 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
121 |
+
**kwargs
|
122 |
+
)
|
123 |
+
|
124 |
+
def get_command(self, token):
|
125 |
+
if token in self.special_tokens:
|
126 |
+
return self.special_tokens[token]
|
127 |
+
assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
|
128 |
+
return self.tokenizer.special_tokens[token]
|
129 |
+
|
130 |
+
@property
|
131 |
+
def unk_token(self) -> str:
|
132 |
+
return self.tokenizer.sp_model.IdToPiece(self.get_command("<unk>"))
|
133 |
+
|
134 |
+
@property
|
135 |
+
def pad_token(self) -> str:
|
136 |
+
return self.tokenizer.sp_model.IdToPiece(self.get_command("<pad>"))
|
137 |
+
|
138 |
+
@property
|
139 |
+
def eos_token(self) -> str:
|
140 |
+
return self.tokenizer.sp_model.IdToPiece(self.get_command("<eos>"))
|
141 |
+
|
142 |
+
@property
|
143 |
+
def unk_token_id(self) -> int:
|
144 |
+
return self.get_command("<unk>")
|
145 |
+
|
146 |
+
@property
|
147 |
+
def pad_token_id(self) -> int:
|
148 |
+
return self.get_command("<pad>")
|
149 |
+
|
150 |
+
@property
|
151 |
+
def eos_token_id(self):
|
152 |
+
return self.get_command("<eos>")
|
153 |
+
|
154 |
+
@unk_token.setter
|
155 |
+
def unk_token(self, value):
|
156 |
+
logger.warning("Setting unk_token is not supported, use the default one.")
|
157 |
+
|
158 |
+
@pad_token.setter
|
159 |
+
def pad_token(self, value):
|
160 |
+
logger.warning("Setting pad_token is not supported, use the default one.")
|
161 |
+
|
162 |
+
@eos_token.setter
|
163 |
+
def eos_token(self, value):
|
164 |
+
logger.warning("Setting eos_token is not supported, use the default one.")
|
165 |
+
|
166 |
+
@property
|
167 |
+
def vocab_size(self):
|
168 |
+
return self.tokenizer.n_words
|
169 |
+
|
170 |
+
def get_vocab(self):
|
171 |
+
""" Returns vocab as a dict """
|
172 |
+
vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
|
173 |
+
vocab.update(self.added_tokens_encoder)
|
174 |
+
return vocab
|
175 |
+
|
176 |
+
def _tokenize(self, text, **kwargs):
|
177 |
+
return self.tokenizer.tokenize(text, encode_special_tokens=self.encode_special_tokens)
|
178 |
+
|
179 |
+
def _convert_token_to_id(self, token):
|
180 |
+
""" Converts a token (str) in an id using the vocab. """
|
181 |
+
return self.tokenizer.convert_token_to_id(token)
|
182 |
+
|
183 |
+
def _convert_id_to_token(self, index):
|
184 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
185 |
+
return self.tokenizer.convert_id_to_token(index)
|
186 |
+
|
187 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
188 |
+
return self.tokenizer.decode_tokens(tokens)
|
189 |
+
|
190 |
+
def save_vocabulary(self, save_directory, filename_prefix=None):
|
191 |
+
"""
|
192 |
+
Save the vocabulary and special tokens file to a directory.
|
193 |
+
|
194 |
+
Args:
|
195 |
+
save_directory (`str`):
|
196 |
+
The directory in which to save the vocabulary.
|
197 |
+
filename_prefix (`str`, *optional*):
|
198 |
+
An optional prefix to add to the named of the saved files.
|
199 |
+
|
200 |
+
Returns:
|
201 |
+
`Tuple(str)`: Paths to the files saved.
|
202 |
+
"""
|
203 |
+
if os.path.isdir(save_directory):
|
204 |
+
vocab_file = os.path.join(
|
205 |
+
save_directory, self.vocab_files_names["vocab_file"]
|
206 |
+
)
|
207 |
+
else:
|
208 |
+
vocab_file = save_directory
|
209 |
+
|
210 |
+
with open(self.vocab_file, 'rb') as fin:
|
211 |
+
proto_str = fin.read()
|
212 |
+
|
213 |
+
with open(vocab_file, "wb") as writer:
|
214 |
+
writer.write(proto_str)
|
215 |
+
|
216 |
+
return (vocab_file,)
|
217 |
+
|
218 |
+
def get_prefix_tokens(self):
|
219 |
+
prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]
|
220 |
+
return prefix_tokens
|
221 |
+
|
222 |
+
def build_single_message(self, role, metadata, message):
|
223 |
+
assert role in ["system", "user", "assistant", "observation"], role
|
224 |
+
role_tokens = [self.get_command(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n")
|
225 |
+
message_tokens = self.tokenizer.encode(message)
|
226 |
+
tokens = role_tokens + message_tokens
|
227 |
+
return tokens
|
228 |
+
|
229 |
+
def build_chat_input(self, query, history=None, role="user"):
|
230 |
+
if history is None:
|
231 |
+
history = []
|
232 |
+
input_ids = []
|
233 |
+
for item in history:
|
234 |
+
content = item["content"]
|
235 |
+
if item["role"] == "system" and "tools" in item:
|
236 |
+
content = content + "\n" + json.dumps(item["tools"], indent=4, ensure_ascii=False)
|
237 |
+
input_ids.extend(self.build_single_message(item["role"], item.get("metadata", ""), content))
|
238 |
+
input_ids.extend(self.build_single_message(role, "", query))
|
239 |
+
input_ids.extend([self.get_command("<|assistant|>")])
|
240 |
+
return self.batch_encode_plus([input_ids], return_tensors="pt", is_split_into_words=True)
|
241 |
+
|
242 |
+
def build_inputs_with_special_tokens(
|
243 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
244 |
+
) -> List[int]:
|
245 |
+
"""
|
246 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
247 |
+
adding special tokens. A BERT sequence has the following format:
|
248 |
+
|
249 |
+
- single sequence: `[CLS] X [SEP]`
|
250 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
251 |
+
|
252 |
+
Args:
|
253 |
+
token_ids_0 (`List[int]`):
|
254 |
+
List of IDs to which the special tokens will be added.
|
255 |
+
token_ids_1 (`List[int]`, *optional*):
|
256 |
+
Optional second list of IDs for sequence pairs.
|
257 |
+
|
258 |
+
Returns:
|
259 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
260 |
+
"""
|
261 |
+
prefix_tokens = self.get_prefix_tokens()
|
262 |
+
token_ids_0 = prefix_tokens + token_ids_0
|
263 |
+
if token_ids_1 is not None:
|
264 |
+
token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("<eos>")]
|
265 |
+
return token_ids_0
|
266 |
+
|
267 |
+
def _pad(
|
268 |
+
self,
|
269 |
+
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
|
270 |
+
max_length: Optional[int] = None,
|
271 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
272 |
+
pad_to_multiple_of: Optional[int] = None,
|
273 |
+
return_attention_mask: Optional[bool] = None,
|
274 |
+
) -> dict:
|
275 |
+
"""
|
276 |
+
Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
|
277 |
+
|
278 |
+
Args:
|
279 |
+
encoded_inputs:
|
280 |
+
Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
|
281 |
+
max_length: maximum length of the returned list and optionally padding length (see below).
|
282 |
+
Will truncate by taking into account the special tokens.
|
283 |
+
padding_strategy: PaddingStrategy to use for padding.
|
284 |
+
|
285 |
+
- PaddingStrategy.LONGEST Pad to the longest sequence in the batch
|
286 |
+
- PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
|
287 |
+
- PaddingStrategy.DO_NOT_PAD: Do not pad
|
288 |
+
The tokenizer padding sides are defined in self.padding_side:
|
289 |
+
|
290 |
+
- 'left': pads on the left of the sequences
|
291 |
+
- 'right': pads on the right of the sequences
|
292 |
+
pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
|
293 |
+
This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
|
294 |
+
`>= 7.5` (Volta).
|
295 |
+
return_attention_mask:
|
296 |
+
(optional) Set to False to avoid returning attention mask (default: set to model specifics)
|
297 |
+
"""
|
298 |
+
# Load from model defaults
|
299 |
+
assert self.padding_side == "left"
|
300 |
+
|
301 |
+
required_input = encoded_inputs[self.model_input_names[0]]
|
302 |
+
seq_length = len(required_input)
|
303 |
+
|
304 |
+
if padding_strategy == PaddingStrategy.LONGEST:
|
305 |
+
max_length = len(required_input)
|
306 |
+
|
307 |
+
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
|
308 |
+
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
|
309 |
+
|
310 |
+
needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
|
311 |
+
|
312 |
+
# Initialize attention mask if not present.
|
313 |
+
if "attention_mask" not in encoded_inputs:
|
314 |
+
encoded_inputs["attention_mask"] = [1] * seq_length
|
315 |
+
|
316 |
+
if "position_ids" not in encoded_inputs:
|
317 |
+
encoded_inputs["position_ids"] = list(range(seq_length))
|
318 |
+
|
319 |
+
if needs_to_be_padded:
|
320 |
+
difference = max_length - len(required_input)
|
321 |
+
|
322 |
+
if "attention_mask" in encoded_inputs:
|
323 |
+
encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
|
324 |
+
if "position_ids" in encoded_inputs:
|
325 |
+
encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
|
326 |
+
encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
|
327 |
+
|
328 |
+
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,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {
|
3 |
+
"64795": {
|
4 |
+
"content": "<|user|>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": true
|
10 |
+
},
|
11 |
+
"64797": {
|
12 |
+
"content": "<|observation|>",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": false,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false,
|
17 |
+
"special": true
|
18 |
+
}
|
19 |
+
},
|
20 |
+
"additional_special_tokens": [
|
21 |
+
"<|user|>",
|
22 |
+
"<|observation|>"
|
23 |
+
],
|
24 |
+
"auto_map": {
|
25 |
+
"AutoTokenizer": [
|
26 |
+
"tokenization_chatglm.ChatGLMTokenizer",
|
27 |
+
null
|
28 |
+
]
|
29 |
+
},
|
30 |
+
"chat_template": "{% for message in messages %}{% if loop.first %}[gMASK]sop<|{{ message['role'] }}|> \n {{ message['content'] }}{% else %}<|{{ message['role'] }}|> \n {{ message['content'] }}{% endif %}{% endfor %}{% if add_generation_prompt %}<|assistant|>{% endif %}",
|
31 |
+
"clean_up_tokenization_spaces": false,
|
32 |
+
"do_lower_case": false,
|
33 |
+
"eos_token": "</s>",
|
34 |
+
"model_max_length": 1000000000000000019884624838656,
|
35 |
+
"pad_token": "<unk>",
|
36 |
+
"padding_side": "left",
|
37 |
+
"remove_space": false,
|
38 |
+
"tokenizer_class": "ChatGLMTokenizer",
|
39 |
+
"unk_token": "<unk>"
|
40 |
+
}
|