-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokenization_rodimus_fast.py
225 lines (195 loc) · 6.67 KB
/
tokenization_rodimus_fast.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import json
import os
import re
import warnings
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from transformers.file_utils import to_py_obj
from transformers.tokenization_utils_base import (
AddedToken,
BatchEncoding,
EncodedInput,
PreTokenizedInput,
TextInput,
TruncationStrategy,
)
from transformers.utils import PaddingStrategy, TensorType, logging
from transformers import AutoTokenizer, PreTrainedTokenizerFast
from modules.chat_format import Chat
logger = logging.get_logger(__name__)
class RodimusTokenizer(PreTrainedTokenizerFast):
slow_tokenizer_class = None
padding_side = "left"
model_input_names = ["input_ids", "attention_mask"]
slow_tokenizer_class = None
SPECIAL_TOKENS_ATTRIBUTES = [
"bos_token",
"eos_token",
"unk_token",
"sep_token",
"pad_token",
"cls_token",
"mask_token",
"gmask_token",
"additional_special_tokens",
]
def __init__(
self,
vocab_file=None,
merges_file=None,
tokenizer_file=None,
clean_up_tokenization_spaces=False,
bos_token="<|startoftext|>",
eos_token="<|endoftext|>",
cls_token="[CLS]",
gmask_token="[gMASK]",
add_bos_token=False,
add_eos_token=False,
**kwargs,
):
self._gmask_token = (
AddedToken(gmask_token, lstrip=False,
rstrip=False, normalized=False)
if isinstance(gmask_token, str)
else gmask_token
)
self._sop_token = (
AddedToken(bos_token, lstrip=False, rstrip=False, normalized=False)
if isinstance(bos_token, str)
else bos_token
)
self._eop_token = (
AddedToken(eos_token, lstrip=False, rstrip=False, normalized=False)
if isinstance(eos_token, str)
else eos_token
)
super().__init__(
vocab_file=vocab_file,
merges_file=merges_file,
tokenizer_file=tokenizer_file,
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
bos_token=bos_token,
eos_token=eos_token,
cls_token=cls_token,
pad_token=eos_token,
gmask_token=gmask_token,
add_bos_token=add_bos_token,
add_eos_token=add_eos_token,
**kwargs,
)
self.check_special_tokens()
def check_special_tokens(self):
'''
eos_token, cls_token, mask_token
special tokens should init, check special token is not None
'''
for name, special_token in zip(
['eos', 'bos', 'cls', 'gmask'],
[self.eos_token, self.bos_token, self.cls_token, self.gmask_token],
):
assert special_token is not None, f'should init special token [{name}] in tokenizer_config.json'
@property
def gmask_token(self) -> Optional[str]:
if self._gmask_token is None:
if self.verbose:
logger.error("Using gmask_token, but it is not set yet.")
return None
return str(self._gmask_token)
@gmask_token.setter
def gmask_token(self, value):
if not isinstance(value, (str, AddedToken)) and value is not None:
raise ValueError(
"Cannot set a non-string value as the gmask token")
self._gmask_token = value
@property
def gmask_token_id(self) -> Optional[int]:
if self._gmask_token is None:
return None
return self.convert_tokens_to_ids(self.gmask_token)
@property
def sop_token(self) -> Optional[str]:
if self._sop_token is None:
if self.verbose:
logger.error("Using sop_token, but it is not set yet.")
return None
return str(self._sop_token)
@sop_token.setter
def sop_token(self, value):
if not isinstance(value, (str, AddedToken)) and value is not None:
raise ValueError("Cannot set a non-string value as the sop token")
self._sop_token = value
@property
def sop_token_id(self) -> Optional[int]:
if self._sop_token is None:
return None
return self.convert_tokens_to_ids(self.sop_token)
@property
def eop_token(self) -> Optional[str]:
if self._eop_token is None:
if self.verbose:
logger.error("Using eop_token, but it is not set yet.")
return None
return str(self._eop_token)
@eop_token.setter
def eop_token(self, value):
if not isinstance(value, (str, AddedToken)) and value is not None:
raise ValueError("Cannot set a non-string value as the eop token")
self._eop_token = value
@property
def eop_token_id(self) -> Optional[int]:
if self._eop_token is None:
return None
return self.convert_tokens_to_ids(self.eop_token)
@property
def vocab_size(self):
return len(self.get_vocab())
def apply_chat_template(
self,
conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]]],
system: str = None,
tokenize=False,
padding: bool = False,
truncation: bool = False,
max_length: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_dict: bool = False,
**kwargs,
):
chat_format = kwargs.get('chat_format', 'rodimus_chat')
is_batched = False
if isinstance(conversation, List) and (
isinstance(conversation[0], (list, tuple)
) or "messages" in conversation[0]
):
conversations = conversation
is_batched = True
if not is_batched:
conversations = [conversation]
rendered = []
for chat in conversations:
if "messages" not in chat:
# Indicates it's a Conversation object
chat = {'messages': chat}
if system:
chat['system_message'] = system
rendered_chat = Chat.from_json(chat, name=chat_format).prompt_str
rendered.append(rendered_chat)
if not is_batched:
rendered = rendered[0]
if tokenize:
out = self(
rendered,
padding=padding,
truncation=truncation,
max_length=max_length,
add_special_tokens=False,
return_tensors=return_tensors,
)
if return_dict:
return out
else:
return out["input_ids"]
else:
return rendered