cognitivess
commited on
Commit
•
35f8f0c
1
Parent(s):
97f6008
Update cognitivess_model/tokenization_cognitivess.py
Browse files
cognitivess_model/tokenization_cognitivess.py
CHANGED
@@ -1,48 +1,462 @@
|
|
1 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
from transformers import PreTrainedTokenizer
|
4 |
-
import json
|
5 |
|
6 |
class CognitivessTokenizer(PreTrainedTokenizer):
|
7 |
-
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
self.vocab_file = vocab_file
|
10 |
-
self.
|
11 |
-
self.
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
return tokens
|
28 |
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 Cognitivess and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
"""Tokenization classes for Cognitivess."""
|
17 |
+
|
18 |
+
import os
|
19 |
+
from shutil import copyfile
|
20 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
|
21 |
+
|
22 |
+
import sentencepiece as spm
|
23 |
+
|
24 |
+
from ...convert_slow_tokenizer import import_protobuf
|
25 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
26 |
+
from ...utils import logging
|
27 |
+
|
28 |
+
|
29 |
+
if TYPE_CHECKING:
|
30 |
+
from ...tokenization_utils_base import TextInput
|
31 |
+
|
32 |
+
logger = logging.get_logger(__name__)
|
33 |
+
|
34 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
|
35 |
+
|
36 |
+
SPIECE_UNDERLINE = "▁"
|
37 |
+
|
38 |
+
B_INST, E_INST = "[INST]", "[/INST]"
|
39 |
+
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
|
40 |
+
|
41 |
+
# fmt: off
|
42 |
+
DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
|
43 |
+
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
|
44 |
+
that your responses are socially unbiased and positive in nature.
|
45 |
+
|
46 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
|
47 |
+
correct. If you don't know the answer to a question, please don't share false information."""
|
48 |
+
# fmt: on
|
49 |
|
|
|
|
|
50 |
|
51 |
class CognitivessTokenizer(PreTrainedTokenizer):
|
52 |
+
"""
|
53 |
+
Construct a Cognitivess tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
|
54 |
+
no padding token in the original model.
|
55 |
+
|
56 |
+
Args:
|
57 |
+
vocab_file (`str`):
|
58 |
+
Path to the vocabulary file.
|
59 |
+
unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
|
60 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
61 |
+
token instead.
|
62 |
+
bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
|
63 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
64 |
+
eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
|
65 |
+
The end of sequence token.
|
66 |
+
pad_token (`str` or `tokenizers.AddedToken`, *optional*):
|
67 |
+
A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
|
68 |
+
attention mechanisms or loss computation.
|
69 |
+
sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
|
70 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
71 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
72 |
+
to set:
|
73 |
+
|
74 |
+
- `enable_sampling`: Enable subword regularization.
|
75 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
76 |
+
|
77 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
78 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
79 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
80 |
+
using forward-filtering-and-backward-sampling algorithm.
|
81 |
+
|
82 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
83 |
+
BPE-dropout.
|
84 |
+
|
85 |
+
add_bos_token (`bool`, *optional*, defaults to `True`):
|
86 |
+
Whether or not to add an `bos_token` at the start of sequences.
|
87 |
+
add_eos_token (`bool`, *optional*, defaults to `False`):
|
88 |
+
Whether or not to add an `eos_token` at the end of sequences.
|
89 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
90 |
+
Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
|
91 |
+
extra spaces.
|
92 |
+
use_default_system_prompt (`bool`, *optional*, defaults to `False`):
|
93 |
+
Whether or not the default system prompt for Cognitivess should be used.
|
94 |
+
spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
|
95 |
+
Whether or not to add spaces between special tokens.
|
96 |
+
legacy (`bool`, *optional*):
|
97 |
+
Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
|
98 |
+
and #25224 which includes fixes to properly handle tokens that appear after special tokens.
|
99 |
+
Make sure to also set `from_slow` to `True`.
|
100 |
+
A simple example:
|
101 |
+
|
102 |
+
- `legacy=True`:
|
103 |
+
```python
|
104 |
+
>>> from transformers import CognitivessTokenizerFast
|
105 |
+
|
106 |
+
>>> tokenizer = CognitivessTokenizerFast.from_pretrained("CognitivessAI/cognitivess", legacy=True, from_slow=True)
|
107 |
+
>>> tokenizer.encode("Hello <s>.") # 869 is '▁.'
|
108 |
+
[1, 15043, 29871, 1, 869]
|
109 |
+
```
|
110 |
+
- `legacy=False`:
|
111 |
+
```python
|
112 |
+
>>> from transformers import CognitivessTokenizerFast
|
113 |
+
|
114 |
+
>>> tokenizer = CognitivessTokenizerFast.from_pretrained("CognitivessAI/cognitivess", legacy=False, from_slow=True)
|
115 |
+
>>> tokenizer.encode("Hello <s>.") # 29889 is '.'
|
116 |
+
[1, 15043, 29871, 1, 29889]
|
117 |
+
```
|
118 |
+
Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
|
119 |
+
add_prefix_space (`bool`, *optional*, defaults to `True`):
|
120 |
+
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
|
121 |
+
other word. Again, this should be set with `from_slow=True` to make sure it's taken into account.
|
122 |
+
"""
|
123 |
+
|
124 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
125 |
+
model_input_names = ["input_ids", "attention_mask"]
|
126 |
+
|
127 |
+
def __init__(
|
128 |
+
self,
|
129 |
+
vocab_file,
|
130 |
+
unk_token="<unk>",
|
131 |
+
bos_token="<s>",
|
132 |
+
eos_token="</s>",
|
133 |
+
pad_token=None,
|
134 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
135 |
+
add_bos_token=True,
|
136 |
+
add_eos_token=False,
|
137 |
+
clean_up_tokenization_spaces=False,
|
138 |
+
use_default_system_prompt=False,
|
139 |
+
spaces_between_special_tokens=False,
|
140 |
+
legacy=None,
|
141 |
+
add_prefix_space=True,
|
142 |
+
**kwargs,
|
143 |
+
):
|
144 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
145 |
+
bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
|
146 |
+
eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
|
147 |
+
unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
|
148 |
+
pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
|
149 |
+
|
150 |
+
if legacy is None:
|
151 |
+
logger.warning_once(
|
152 |
+
f"You are using the default legacy behaviour of the {self.__class__}. This is"
|
153 |
+
" expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
|
154 |
+
" If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
|
155 |
+
" means, and thoroughly read the reason why this was added as explained in"
|
156 |
+
" https://github.com/huggingface/transformers/pull/24565 - if you loaded a Cognitivess tokenizer from a GGUF file"
|
157 |
+
" you can ignore this message"
|
158 |
+
)
|
159 |
+
legacy = True
|
160 |
+
|
161 |
+
self.legacy = legacy
|
162 |
self.vocab_file = vocab_file
|
163 |
+
self.add_bos_token = add_bos_token
|
164 |
+
self.add_eos_token = add_eos_token
|
165 |
+
self.use_default_system_prompt = use_default_system_prompt
|
166 |
+
self.sp_model = self.get_spm_processor(kwargs.pop("from_slow", False))
|
167 |
+
self.add_prefix_space = add_prefix_space
|
168 |
+
|
169 |
+
super().__init__(
|
170 |
+
bos_token=bos_token,
|
171 |
+
eos_token=eos_token,
|
172 |
+
unk_token=unk_token,
|
173 |
+
pad_token=pad_token,
|
174 |
+
add_bos_token=add_bos_token,
|
175 |
+
add_eos_token=add_eos_token,
|
176 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
177 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
178 |
+
use_default_system_prompt=use_default_system_prompt,
|
179 |
+
spaces_between_special_tokens=spaces_between_special_tokens,
|
180 |
+
legacy=legacy,
|
181 |
+
add_prefix_space=add_prefix_space,
|
182 |
+
**kwargs,
|
183 |
+
)
|
184 |
+
|
185 |
+
@property
|
186 |
+
def unk_token_length(self):
|
187 |
+
return len(self.sp_model.encode(str(self.unk_token)))
|
188 |
+
|
189 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor
|
190 |
+
def get_spm_processor(self, from_slow=False):
|
191 |
+
tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
192 |
+
if self.legacy or from_slow: # no dependency on protobuf
|
193 |
+
tokenizer.Load(self.vocab_file)
|
194 |
+
return tokenizer
|
195 |
+
|
196 |
+
with open(self.vocab_file, "rb") as f:
|
197 |
+
sp_model = f.read()
|
198 |
+
model_pb2 = import_protobuf(f"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)")
|
199 |
+
model = model_pb2.ModelProto.FromString(sp_model)
|
200 |
+
normalizer_spec = model_pb2.NormalizerSpec()
|
201 |
+
normalizer_spec.add_dummy_prefix = False
|
202 |
+
model.normalizer_spec.MergeFrom(normalizer_spec)
|
203 |
+
sp_model = model.SerializeToString()
|
204 |
+
tokenizer.LoadFromSerializedProto(sp_model)
|
205 |
+
return tokenizer
|
206 |
+
|
207 |
+
def __getstate__(self):
|
208 |
+
state = self.__dict__.copy()
|
209 |
+
state["sp_model"] = None
|
210 |
+
state["sp_model_proto"] = self.sp_model.serialized_model_proto()
|
211 |
+
return state
|
212 |
+
|
213 |
+
def __setstate__(self, d):
|
214 |
+
self.__dict__ = d
|
215 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
216 |
+
self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
|
217 |
+
|
218 |
+
@property
|
219 |
+
def vocab_size(self):
|
220 |
+
"""Returns vocab size"""
|
221 |
+
return self.sp_model.get_piece_size()
|
222 |
+
|
223 |
+
def get_vocab(self):
|
224 |
+
"""Returns vocab as a dict"""
|
225 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
226 |
+
vocab.update(self.added_tokens_encoder)
|
227 |
+
return vocab
|
228 |
+
|
229 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
|
230 |
+
def tokenize(self, text: "TextInput", **kwargs) -> List[str]:
|
231 |
+
"""
|
232 |
+
Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
|
233 |
+
first token is special.
|
234 |
+
"""
|
235 |
+
if self.legacy or len(text) == 0:
|
236 |
+
return super().tokenize(text, **kwargs)
|
237 |
+
|
238 |
+
text = text.replace(SPIECE_UNDERLINE, " ")
|
239 |
+
if self.add_prefix_space:
|
240 |
+
text = SPIECE_UNDERLINE + text
|
241 |
+
|
242 |
+
tokens = super().tokenize(text, **kwargs)
|
243 |
+
|
244 |
+
if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
|
245 |
+
tokens = tokens[1:]
|
246 |
return tokens
|
247 |
|
248 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
|
249 |
+
def _tokenize(self, text, **kwargs):
|
250 |
+
"""
|
251 |
+
Returns a tokenized string.
|
252 |
+
|
253 |
+
We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
|
254 |
+
SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
|
255 |
+
`['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
|
256 |
+
`unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
|
257 |
+
`self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
|
258 |
+
"""
|
259 |
+
tokens = self.sp_model.encode(text, out_type=str)
|
260 |
+
if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
|
261 |
+
return tokens
|
262 |
+
|
263 |
+
# 1. Encode string + prefix ex: "<unk> Hey"
|
264 |
+
tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
|
265 |
+
# 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
|
266 |
+
return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
|
267 |
+
|
268 |
+
def _convert_token_to_id(self, token):
|
269 |
+
"""Converts a token (str) in an id using the vocab."""
|
270 |
+
return self.sp_model.piece_to_id(token)
|
271 |
+
|
272 |
+
def _convert_id_to_token(self, index):
|
273 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
274 |
+
token = self.sp_model.IdToPiece(index)
|
275 |
+
return token
|
276 |
+
|
277 |
+
def convert_tokens_to_string(self, tokens):
|
278 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
279 |
+
# since we manually add the prefix space, we have to remove it when decoding
|
280 |
+
if tokens[0].startswith(SPIECE_UNDERLINE) and self.add_prefix_space:
|
281 |
+
tokens[0] = tokens[0][1:]
|
282 |
+
|
283 |
+
current_sub_tokens = []
|
284 |
+
out_string = ""
|
285 |
+
prev_is_special = False
|
286 |
+
for i, token in enumerate(tokens):
|
287 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
288 |
+
if token in self.all_special_tokens:
|
289 |
+
if not prev_is_special and i != 0 and self.legacy:
|
290 |
+
out_string += " "
|
291 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
292 |
+
prev_is_special = True
|
293 |
+
current_sub_tokens = []
|
294 |
+
else:
|
295 |
+
if prev_is_special and i == 1 and self.add_prefix_space and not token.startswith(SPIECE_UNDERLINE):
|
296 |
+
out_string += " "
|
297 |
+
current_sub_tokens.append(token)
|
298 |
+
prev_is_special = False
|
299 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
300 |
+
return out_string
|
301 |
+
|
302 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
303 |
+
"""
|
304 |
+
Save the vocabulary and special tokens file to a directory.
|
305 |
+
|
306 |
+
Args:
|
307 |
+
save_directory (`str`):
|
308 |
+
The directory in which to save the vocabulary.
|
309 |
+
|
310 |
+
Returns:
|
311 |
+
`Tuple(str)`: Paths to the files saved.
|
312 |
+
"""
|
313 |
+
if not os.path.isdir(save_directory):
|
314 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
315 |
+
return
|
316 |
+
out_vocab_file = os.path.join(
|
317 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
318 |
+
)
|
319 |
+
|
320 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
321 |
+
copyfile(self.vocab_file, out_vocab_file)
|
322 |
+
elif not os.path.isfile(self.vocab_file):
|
323 |
+
with open(out_vocab_file, "wb") as fi:
|
324 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
325 |
+
fi.write(content_spiece_model)
|
326 |
+
|
327 |
+
return (out_vocab_file,)
|
328 |
+
|
329 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
330 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
331 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
332 |
+
|
333 |
+
output = bos_token_id + token_ids_0 + eos_token_id
|
334 |
+
|
335 |
+
if token_ids_1 is not None:
|
336 |
+
output = output + bos_token_id + token_ids_1 + eos_token_id
|
337 |
+
|
338 |
+
return output
|
339 |
+
|
340 |
+
def get_special_tokens_mask(
|
341 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
342 |
+
) -> List[int]:
|
343 |
+
"""
|
344 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
345 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
346 |
+
|
347 |
+
Args:
|
348 |
+
token_ids_0 (`List[int]`):
|
349 |
+
List of IDs.
|
350 |
+
token_ids_1 (`List[int]`, *optional*):
|
351 |
+
Optional second list of IDs for sequence pairs.
|
352 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
353 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
354 |
+
|
355 |
+
Returns:
|
356 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
357 |
+
"""
|
358 |
+
if already_has_special_tokens:
|
359 |
+
return super().get_special_tokens_mask(
|
360 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
361 |
+
)
|
362 |
+
|
363 |
+
bos_token_id = [1] if self.add_bos_token else []
|
364 |
+
eos_token_id = [1] if self.add_eos_token else []
|
365 |
+
|
366 |
+
if token_ids_1 is None:
|
367 |
+
return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
|
368 |
+
return (
|
369 |
+
bos_token_id
|
370 |
+
+ ([0] * len(token_ids_0))
|
371 |
+
+ eos_token_id
|
372 |
+
+ bos_token_id
|
373 |
+
+ ([0] * len(token_ids_1))
|
374 |
+
+ eos_token_id
|
375 |
+
)
|
376 |
+
|
377 |
+
def create_token_type_ids_from_sequences(
|
378 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
379 |
+
) -> List[int]:
|
380 |
+
"""
|
381 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
382 |
+
sequence pair mask has the following format:
|
383 |
+
|
384 |
+
```
|
385 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
386 |
+
| first sequence | second sequence |
|
387 |
+
```
|
388 |
+
|
389 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
390 |
+
|
391 |
+
Args:
|
392 |
+
token_ids_0 (`List[int]`):
|
393 |
+
List of ids.
|
394 |
+
token_ids_1 (`List[int]`, *optional*):
|
395 |
+
Optional second list of IDs for sequence pairs.
|
396 |
+
|
397 |
+
Returns:
|
398 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
399 |
+
"""
|
400 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
401 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
402 |
+
|
403 |
+
output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
|
404 |
+
|
405 |
+
if token_ids_1 is not None:
|
406 |
+
output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
|
407 |
+
|
408 |
+
return output
|
409 |
+
|
410 |
+
@property
|
411 |
+
def default_chat_template(self):
|
412 |
+
"""
|
413 |
+
Cognitivess uses [INST] and [/INST] to indicate user messages, and <<SYS>> and <</SYS>> to indicate system messages.
|
414 |
+
Assistant messages do not have special tokens, because Cognitivess chat models are generally trained with strict
|
415 |
+
user/assistant/user/assistant message ordering, and so assistant messages can be identified from the ordering
|
416 |
+
rather than needing special tokens. The system message is partly 'embedded' in the first user message, which
|
417 |
+
results in an unusual token ordering when it is present. This template should definitely be changed if you wish
|
418 |
+
to fine-tune a model with more flexible role ordering!
|
419 |
+
|
420 |
+
The output should look something like:
|
421 |
+
|
422 |
+
<bos>[INST] B_SYS SystemPrompt E_SYS Prompt [/INST] Answer <eos><bos>[INST] Prompt [/INST] Answer <eos>
|
423 |
+
<bos>[INST] Prompt [/INST]
|
424 |
+
|
425 |
+
The reference for this chat template is [this code
|
426 |
+
snippet](https://github.com/facebookresearch/Cognitivess/blob/556949fdfb72da27c2f4a40b7f0e4cf0b8153a28/Cognitivess/generation.py#L320-L362)
|
427 |
+
in the original repository.
|
428 |
+
"""
|
429 |
+
template = (
|
430 |
+
"{% if messages[0]['role'] == 'system' %}"
|
431 |
+
"{% set loop_messages = messages[1:] %}" # Extract system message if it's present
|
432 |
+
"{% set system_message = messages[0]['content'] %}"
|
433 |
+
"{% elif USE_DEFAULT_PROMPT == true and not '<<SYS>>' in messages[0]['content'] %}"
|
434 |
+
"{% set loop_messages = messages %}" # Or use the default system message if the flag is set
|
435 |
+
"{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}"
|
436 |
+
"{% else %}"
|
437 |
+
"{% set loop_messages = messages %}"
|
438 |
+
"{% set system_message = false %}"
|
439 |
+
"{% endif %}"
|
440 |
+
"{% for message in loop_messages %}" # Loop over all non-system messages
|
441 |
+
"{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}"
|
442 |
+
"{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}"
|
443 |
+
"{% endif %}"
|
444 |
+
"{% if loop.index0 == 0 and system_message != false %}" # Embed system message in first message
|
445 |
+
"{% set content = '<<SYS>>\\n' + system_message + '\\n<</SYS>>\\n\\n' + message['content'] %}"
|
446 |
+
"{% else %}"
|
447 |
+
"{% set content = message['content'] %}"
|
448 |
+
"{% endif %}"
|
449 |
+
"{% if message['role'] == 'user' %}" # After all of that, handle messages/roles in a fairly normal way
|
450 |
+
"{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}"
|
451 |
+
"{% elif message['role'] == 'system' %}"
|
452 |
+
"{{ '<<SYS>>\\n' + content.strip() + '\\n<</SYS>>\\n\\n' }}"
|
453 |
+
"{% elif message['role'] == 'assistant' %}"
|
454 |
+
"{{ ' ' + content.strip() + ' ' + eos_token }}"
|
455 |
+
"{% endif %}"
|
456 |
+
"{% endfor %}"
|
457 |
+
)
|
458 |
+
template = template.replace("USE_DEFAULT_PROMPT", "true" if self.use_default_system_prompt else "false")
|
459 |
+
default_message = DEFAULT_SYSTEM_PROMPT.replace("\n", "\\n").replace("'", "\\'")
|
460 |
+
template = template.replace("DEFAULT_SYSTEM_MESSAGE", default_message)
|
461 |
+
|
462 |
+
return template
|