aframson commited on
Commit
49f9afd
·
1 Parent(s): e048a1f
Files changed (1) hide show
  1. tokenizeConfig.py +248 -208
tokenizeConfig.py CHANGED
@@ -1,222 +1,262 @@
1
- """This is an educational implementation of the byte pair encoding algorithm."""
2
- import collections
3
- from typing import Optional
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- import regex
 
 
 
 
 
 
 
6
 
7
- import tiktoken
8
 
 
 
 
9
 
10
- class OBITokenizer:
11
- def __init__(self, *, pat_str: str, mergeable_ranks: dict[bytes, int]) -> None:
12
- """Creates an Encoding object."""
13
- # A regex pattern string that is used to split the input text
14
- self.pat_str = pat_str
15
- # A dictionary mapping token bytes to their ranks. The ranks correspond to merge priority
16
- self.mergeable_ranks = mergeable_ranks
17
 
18
- self._decoder = {token: token_bytes for token_bytes, token in mergeable_ranks.items()}
19
- self._pat = regex.compile(pat_str)
20
 
21
- def encode(self, text: str, visualise: Optional[str] = "colour") -> list[int]:
22
- """Encodes a string into tokens.
23
 
24
- >>> enc.encode("hello world")
25
- [388, 372]
 
 
 
 
26
  """
27
- # Use the regex to split the text into (approximately) words
28
- words = self._pat.findall(text)
29
- tokens = []
30
- for word in words:
31
- # Turn each word into tokens, using the byte pair encoding algorithm
32
- word_bytes = word.encode("utf-8")
33
- word_tokens = bpe_encode(self.mergeable_ranks, word_bytes, visualise=visualise)
34
- tokens.extend(word_tokens)
35
- return tokens
36
-
37
- def decode_bytes(self, tokens: list[int]) -> bytes:
38
- """Decodes a list of tokens into bytes.
39
-
40
- >>> enc.decode_bytes([388, 372])
41
- b'hello world'
42
  """
43
- return b"".join(self._decoder[token] for token in tokens)
44
-
45
- def decode(self, tokens: list[int]) -> str:
46
- """Decodes a list of tokens into a string.
47
-
48
- Decoded bytes are not guaranteed to be valid UTF-8. In that case, we replace
49
- the invalid bytes with the replacement character "�".
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
- >>> enc.decode([388, 372])
52
- 'hello world'
 
53
  """
54
- return self.decode_bytes(tokens).decode("utf-8", errors="replace")
55
-
56
- def decode_tokens_bytes(self, tokens: list[int]) -> list[bytes]:
57
- """Decodes a list of tokens into a list of bytes.
58
-
59
- Useful for visualising how a string is tokenised.
60
-
61
- >>> enc.decode_tokens_bytes([388, 372])
62
- [b'hello', b' world']
 
 
 
 
 
63
  """
64
- return [self._decoder[token] for token in tokens]
65
-
66
- @staticmethod
67
- def train(training_data: str, vocab_size: int, pat_str: str):
68
- """Train a BPE tokeniser on some data!"""
69
- mergeable_ranks = bpe_train(data=training_data, vocab_size=vocab_size, pat_str=pat_str)
70
- return OBITokenizer(pat_str=pat_str, mergeable_ranks=mergeable_ranks)
71
-
72
- @staticmethod
73
- def from_tiktoken(encoding):
74
- if isinstance(encoding, str):
75
- encoding = tiktoken.get_encoding(encoding)
76
- return OBITokenizer(
77
- pat_str=encoding._pat_str, mergeable_ranks=encoding._mergeable_ranks
78
- )
79
 
 
 
80
 
81
- def bpe_encode(
82
- mergeable_ranks: dict[bytes, int], input: bytes, visualise: Optional[str] = "colour"
83
- ) -> list[int]:
84
- parts = [bytes([b]) for b in input]
85
- while True:
86
- # See the intermediate merges play out!
87
- if visualise:
88
- if visualise in ["colour", "color"]:
89
- visualise_tokens(parts)
90
- elif visualise == "simple":
91
- print(parts)
92
-
93
- # Iterate over all pairs and find the pair we want to merge the most
94
- min_idx = None
95
- min_rank = None
96
- for i, pair in enumerate(zip(parts[:-1], parts[1:])):
97
- rank = mergeable_ranks.get(pair[0] + pair[1])
98
-
99
- if rank is not None and (min_rank is None or rank < min_rank):
100
- min_idx = i
101
- min_rank = rank
102
-
103
- # If there were no pairs we could merge, we're done!
104
- if min_rank is None:
105
- break
106
- assert min_idx is not None
107
-
108
- # Otherwise, merge that pair and leave the rest unchanged. Then repeat.
109
- parts = parts[:min_idx] + [parts[min_idx] + parts[min_idx + 1]] + parts[min_idx + 2 :]
110
-
111
- if visualise:
112
- print()
113
-
114
- tokens = [mergeable_ranks[part] for part in parts]
115
- return tokens
116
-
117
-
118
- def bpe_train(
119
- data: str, vocab_size: int, pat_str: str, visualise: Optional[str] = "colour"
120
- ) -> dict[bytes, int]:
121
- # First, add tokens for each individual byte value
122
- if vocab_size < 2**8:
123
- raise ValueError("vocab_size must be at least 256, so we can encode all bytes")
124
- ranks = {}
125
- for i in range(2**8):
126
- ranks[bytes([i])] = i
127
-
128
- # Splinter up our data into lists of bytes
129
- # data = "Hello world"
130
- # words = [
131
- # [b'H', b'e', b'l', b'l', b'o'],
132
- # [b' ', b'w', b'o', b'r', b'l', b'd']
133
- # ]
134
- words: list[list[bytes]] = [
135
- [bytes([b]) for b in word.encode("utf-8")] for word in regex.findall(pat_str, data)
136
- ]
137
-
138
- # Now, use our data to figure out which merges we should make
139
- while len(ranks) < vocab_size:
140
- # Find the most common pair. This will become our next token
141
- stats = collections.Counter()
142
- for piece in words:
143
- for pair in zip(piece[:-1], piece[1:]):
144
- stats[pair] += 1
145
-
146
- most_common_pair = max(stats, key=lambda x: stats[x])
147
- token_bytes = most_common_pair[0] + most_common_pair[1]
148
- token = len(ranks)
149
- # Add the new token!
150
- ranks[token_bytes] = token
151
-
152
- # Now merge that most common pair in all the words. That is, update our training data
153
- # to reflect our decision to make that pair into a new token.
154
- new_words = []
155
- for word in words:
156
- new_word = []
157
- i = 0
158
- while i < len(word) - 1:
159
- if (word[i], word[i + 1]) == most_common_pair:
160
- # We found our pair! Merge it
161
- new_word.append(token_bytes)
162
- i += 2
163
- else:
164
- new_word.append(word[i])
165
- i += 1
166
- if i == len(word) - 1:
167
- new_word.append(word[i])
168
- new_words.append(new_word)
169
- words = new_words
170
-
171
- # See the intermediate merges play out!
172
- if visualise:
173
- print(f"The current most common pair is {most_common_pair[0]} + {most_common_pair[1]}")
174
- print(f"So we made {token_bytes} our {len(ranks)}th token")
175
- if visualise in ["colour", "color"]:
176
- print("Now the first fifty words in our training data look like:")
177
- visualise_tokens([token for word in words[:50] for token in word])
178
- elif visualise == "simple":
179
- print("Now the first twenty words in our training data look like:")
180
- for word in words[:20]:
181
- print(word)
182
- print("\n")
183
-
184
- return ranks
185
-
186
-
187
- def visualise_tokens(token_values: list[bytes]) -> None:
188
- background = [f"\u001b[48;5;{i}m" for i in [167, 179, 185, 77, 80, 68, 134]]
189
- # If token boundaries do not occur at unicode character boundaries, it's unclear how best to
190
- # visualise the token. Here, we'll just use the unicode replacement character to represent some
191
- # fraction of a character.
192
- unicode_token_values = [x.decode("utf-8", errors="replace") for x in token_values]
193
-
194
- running_length = 0
195
- last_color = None
196
- for token in unicode_token_values:
197
- color = background[running_length % len(background)]
198
- if color == last_color:
199
- color = background[(running_length + 1) % len(background)]
200
- assert color != last_color
201
- last_color = color
202
- running_length += len(token)
203
- print(color + token, end="")
204
- print("\u001b[0m")
205
-
206
-
207
- def train_simple_encoding():
208
- gpt2_pattern = (
209
- r"""'s|'t|'re|'ve|'m|'ll|'d| ?[\p{L}]+| ?[\p{N}]+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""
210
- )
211
- with open(__file__, "r") as f:
212
- data = f.read()
213
-
214
- enc = OBITokenizer.train(data, vocab_size=600, pat_str=gpt2_pattern)
215
-
216
- print("This is the sequence of merges performed in order to encode 'hello world':")
217
- tokens = enc.encode("hello world")
218
- assert enc.decode(tokens) == "hello world"
219
- assert enc.decode_bytes(tokens) == b"hello world"
220
- assert enc.decode_tokens_bytes(tokens) == [b"hello", b" world"]
221
-
222
- return enc
 
1
+ # Copyright (c) 2023, Baichuan Intelligent Technology. All rights reserved.
2
+
3
+ import os
4
+ from shutil import copyfile
5
+ from typing import Any, Dict, List, Optional, Tuple
6
+
7
+ import sentencepiece as spm
8
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
9
+ from transformers.utils import logging
10
+
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
15
+
16
+ PRETRAINED_VOCAB_FILES_MAP = {
17
+ "vocab_file": {},
18
+ "tokenizer_file": {},
19
+ }
20
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
21
+
22
+
23
+ class BaichuanTokenizer(PreTrainedTokenizer):
24
+ """
25
+ Construct a Baichuan tokenizer. Based on byte-level Byte-Pair-Encoding.
26
+ Args:
27
+ vocab_file (`str`):
28
+ Path to the vocabulary file.
29
+ """
30
+
31
+ vocab_files_names = VOCAB_FILES_NAMES
32
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
33
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
34
+ model_input_names = ["input_ids", "attention_mask"]
35
+
36
+ def __init__(
37
+ self,
38
+ vocab_file,
39
+ unk_token="<unk>",
40
+ bos_token="<s>",
41
+ eos_token="</s>",
42
+ pad_token=None,
43
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
44
+ add_bos_token=True,
45
+ add_eos_token=False,
46
+ clean_up_tokenization_spaces=False,
47
+ **kwargs,
48
+ ):
49
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
50
+ bos_token = (
51
+ AddedToken(bos_token, lstrip=False, rstrip=False)
52
+ if isinstance(bos_token, str)
53
+ else bos_token
54
+ )
55
+ eos_token = (
56
+ AddedToken(eos_token, lstrip=False, rstrip=False)
57
+ if isinstance(eos_token, str)
58
+ else eos_token
59
+ )
60
+ unk_token = (
61
+ AddedToken(unk_token, lstrip=False, rstrip=False)
62
+ if isinstance(unk_token, str)
63
+ else unk_token
64
+ )
65
+ pad_token = (
66
+ AddedToken(pad_token, lstrip=False, rstrip=False)
67
+ if isinstance(pad_token, str)
68
+ else pad_token
69
+ )
70
+ super().__init__(
71
+ bos_token=bos_token,
72
+ eos_token=eos_token,
73
+ unk_token=unk_token,
74
+ pad_token=pad_token,
75
+ add_bos_token=add_bos_token,
76
+ add_eos_token=add_eos_token,
77
+ sp_model_kwargs=self.sp_model_kwargs,
78
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
79
+ **kwargs,
80
+ )
81
+ self.vocab_file = vocab_file
82
+ self.add_bos_token = add_bos_token
83
+ self.add_eos_token = add_eos_token
84
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
85
+ self.sp_model.Load(vocab_file)
86
+
87
+ def __getstate__(self):
88
+ state = self.__dict__.copy()
89
+ state["sp_model"] = None
90
+ return state
91
+
92
+ def __setstate__(self, d):
93
+ self.__dict__ = d
94
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
95
+ self.sp_model.Load(self.vocab_file)
96
+
97
+ @property
98
+ def vocab_size(self):
99
+ """Returns vocab size"""
100
+ return self.sp_model.get_piece_size()
101
+
102
+
103
+
104
+
105
+ def get_vocab(self):
106
+ """Returns vocab as a dict"""
107
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
108
+ vocab.update(self.added_tokens_encoder)
109
+ return vocab
110
+
111
+ def _tokenize(self, text):
112
+ """Returns a tokenized string."""
113
+ return self.sp_model.encode(text, out_type=str)
114
+
115
+ def _convert_token_to_id(self, token):
116
+ """Converts a token (str) in an id using the vocab."""
117
+ return self.sp_model.piece_to_id(token)
118
+
119
+ def _convert_id_to_token(self, index):
120
+ """Converts an index (integer) in a token (str) using the vocab."""
121
+ token = self.sp_model.IdToPiece(index)
122
+ return token
123
+
124
+ def convert_tokens_to_string(self, tokens):
125
+ """Converts a sequence of tokens (string) in a single string."""
126
+ current_sub_tokens = []
127
+ out_string = ""
128
+ prev_is_special = False
129
+ for i, token in enumerate(tokens):
130
+ # make sure that special tokens are not decoded using sentencepiece model
131
+ if token in self.all_special_tokens:
132
+ if not prev_is_special and i != 0:
133
+ out_string += " "
134
+ out_string += self.sp_model.decode(current_sub_tokens) + token
135
+ prev_is_special = True
136
+ current_sub_tokens = []
137
+ else:
138
+ current_sub_tokens.append(token)
139
+ prev_is_special = False
140
+ out_string += self.sp_model.decode(current_sub_tokens)
141
+ return out_string
142
+
143
+ def _encode(self,text):
144
+ tokens = self._tokenize(text)
145
+ ids = self._convert_token_to_id(tokens)
146
+ return ids
147
+
148
+ def _decode(self,ids):
149
+ tokens = self._convert_id_to_token(ids)
150
+ text = self.convert_tokens_to_string(tokens)
151
+ return text
152
+
153
+ def save_vocabulary(
154
+ self, save_directory, filename_prefix: Optional[str] = None
155
+ ) -> Tuple[str]:
156
+ """
157
+ Save the vocabulary and special tokens file to a directory.
158
+ Args:
159
+ save_directory (`str`):
160
+ The directory in which to save the vocabulary.
161
+ Returns:
162
+ `Tuple(str)`: Paths to the files saved.
163
+ """
164
+ if not os.path.isdir(save_directory):
165
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
166
+ return
167
+ out_vocab_file = os.path.join(
168
+ save_directory,
169
+ (filename_prefix + "-" if filename_prefix else "")
170
+ + VOCAB_FILES_NAMES["vocab_file"],
171
+ )
172
 
173
+ if os.path.abspath(self.vocab_file) != os.path.abspath(
174
+ out_vocab_file
175
+ ) and os.path.isfile(self.vocab_file):
176
+ copyfile(self.vocab_file, out_vocab_file)
177
+ elif not os.path.isfile(self.vocab_file):
178
+ with open(out_vocab_file, "wb") as fi:
179
+ content_spiece_model = self.sp_model.serialized_model_proto()
180
+ fi.write(content_spiece_model)
181
 
182
+ return (out_vocab_file,)
183
 
184
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
185
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
186
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
187
 
188
+ output = bos_token_id + token_ids_0 + eos_token_id
 
 
 
 
 
 
189
 
190
+ if token_ids_1 is not None:
191
+ output = output + bos_token_id + token_ids_1 + eos_token_id
192
 
193
+ return output
 
194
 
195
+ def get_special_tokens_mask(
196
+ self,
197
+ token_ids_0: List[int],
198
+ token_ids_1: Optional[List[int]] = None,
199
+ already_has_special_tokens: bool = False,
200
+ ) -> List[int]:
201
  """
202
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
203
+ special tokens using the tokenizer `prepare_for_model` method.
204
+ Args:
205
+ token_ids_0 (`List[int]`):
206
+ List of IDs.
207
+ token_ids_1 (`List[int]`, *optional*):
208
+ Optional second list of IDs for sequence pairs.
209
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
210
+ Whether or not the token list is already formatted with special tokens for the model.
211
+ Returns:
212
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
 
 
 
 
213
  """
214
+ if already_has_special_tokens:
215
+ return super().get_special_tokens_mask(
216
+ token_ids_0=token_ids_0,
217
+ token_ids_1=token_ids_1,
218
+ already_has_special_tokens=True,
219
+ )
220
+
221
+ bos_token_id = [1] if self.add_bos_token else []
222
+ eos_token_id = [1] if self.add_eos_token else []
223
+
224
+ if token_ids_1 is None:
225
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
226
+ return (
227
+ bos_token_id
228
+ + ([0] * len(token_ids_0))
229
+ + eos_token_id
230
+ + bos_token_id
231
+ + ([0] * len(token_ids_1))
232
+ + eos_token_id
233
+ )
234
 
235
+ def create_token_type_ids_from_sequences(
236
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
237
+ ) -> List[int]:
238
  """
239
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
240
+ sequence pair mask has the following format:
241
+ ```
242
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
243
+ | first sequence | second sequence |
244
+ ```
245
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
246
+ Args:
247
+ token_ids_0 (`List[int]`):
248
+ List of ids.
249
+ token_ids_1 (`List[int]`, *optional*):
250
+ Optional second list of IDs for sequence pairs.
251
+ Returns:
252
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
253
  """
254
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
255
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
256
+
257
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
 
 
 
 
 
 
 
 
 
 
 
258
 
259
+ if token_ids_1 is not None:
260
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
261
 
262
+ return output