-
Notifications
You must be signed in to change notification settings - Fork 0
/
mytokenizers.py
540 lines (464 loc) · 19.4 KB
/
mytokenizers.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import random
from transformers import BertTokenizer
from tokenization.tokenize_1 import tokenize_with_dp_1
import numpy as np
import json
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens
def tokenize_plain(chars, vocab):
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
return ["[UNK]"]
sub_tokens.append(cur_substr)
start = end
return sub_tokens
def search_part_score(M, label_id, full2part, fullid):
if fullid in full2part:
return M[label_id, full2part[fullid]]
else:
return 1e-16
def tokenize_with_dp(chars, label, tag2idx, M, vocab, full2part):
dp_sub_tokens = {}
dp_scores = {}
start_mid = 0
# if chars[0] not in vocab:
# return ["[UNK]"]
for i in range(len(chars)):
substr = "".join(chars[0:i + 1])
if substr in vocab:
dp_sub_tokens[i] = [substr]
dp_scores[i] = search_part_score(M, tag2idx[label], full2part, vocab[substr])
start_mid = i
break
if dp_scores == {}:
return ["[UNK]"]
# print(dp_sub_tokens)
cur_score = -1e9
cur_mid = start_mid
for end in range(1, len(chars)):
full_substr = "".join(chars[0:end + 1])
# print(full_substr)
if full_substr in vocab:
cur_score = search_part_score(M, tag2idx[label], full2part, vocab[full_substr])
else:
cur_score = -1e9
# print(cur_score)
cur_mid = -1
for mid in range(start_mid, end):
if mid not in dp_scores:
continue
substr = "##" + "".join(chars[mid + 1:end + 1])
if substr in vocab and dp_scores[mid] * search_part_score(M, tag2idx[label], full2part,
vocab[substr]) > cur_score:
# print(cur_score, "-->", dp_scores[mid], "*", search_part_score(M, tag2idx[label], full2part, vocab[substr]))
# if cur_mid != -1:
# tmp_cur_mid = dp_sub_tokens[cur_mid]
# else:
# tmp_cur_mid = ""
# print(
# tmp_cur_mid,
# ", ##", "".join(chars[cur_mid + 1:end + 1]),
# "-->",
# dp_sub_tokens[mid], ", ##", "".join(chars[mid + 1:end + 1]))
cur_score = dp_scores[mid] * search_part_score(M, tag2idx[label], full2part, vocab[substr])
cur_mid = mid
if cur_score != -1e9:
dp_scores[end] = cur_score
if cur_mid != -1:
dp_sub_tokens[end] = [bpe for bpe in dp_sub_tokens[cur_mid]]
dp_sub_tokens[end].append("##" + "".join(chars[cur_mid + 1:end + 1]))
else:
dp_sub_tokens[end] = [full_substr]
# print(dp_sub_tokens)
if len(chars) - 1 not in dp_sub_tokens:
return ["[UNK]"]
return dp_sub_tokens[len(chars) - 1]
class RandomWordpieceTokenizer(object):
"""Runs WordPiece tokenization."""
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through `BasicTokenizer`.
Returns:
A list of wordpiece tokens.
"""
output_tokens = []
for token in whitespace_tokenize(text):
# print("Token: ", token)
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
ends = list(range(start + 1, len(chars) + 1))
random.shuffle(ends)
# print(ends)
# end = len(chars)
cur_substr = None
cur_end = start + 1
for end in ends:
# while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
# print("curstr: ", cur_substr)
cur_end = end
# print("curend: ", cur_end)
break
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = cur_end
if is_bad:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens
class ReverseWordpieceTokenizer(object):
"""Runs WordPiece tokenization."""
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through `BasicTokenizer`.
Returns:
A list of wordpiece tokens.
"""
output_tokens = []
for token in whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
is_bad = False
end = len(chars)
sub_tokens = []
while end > 0:
start = 0
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
start += 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
end = start
if is_bad:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(reversed(sub_tokens))
return output_tokens
class bpeOTTokenizer(object):
"""Runs WordPiece tokenization."""
def __init__(self,
vocab,
unk_token,
tag2idx,
full2part,
include_bi=True,
include_o=False,
M=None,
max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
self.M = M
self.tag2idx = tag2idx
self.include_bi = include_bi
self.include_o = include_o
self.full2part = full2part
if isinstance(self.tag2idx, tuple):
self.tag2idx = self.tag2idx[0]
def tokenize(self, text, label):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through `BasicTokenizer`.
Returns:
A list of wordpiece tokens.
"""
output_tokens = []
# print(label)
# print(text)
if self.include_bi == False and label != "O":
label = label.split("-")[-1]
for token in whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
if token in self.vocab or label not in self.tag2idx:
sub_tokens = tokenize_plain(chars, self.vocab)
else:
sub_tokens = tokenize_with_dp(chars, label, self.tag2idx, self.M, self.vocab, self.full2part)
# print(sub_tokens)
if sub_tokens == ["[UNK]"]:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens
class bpeOTTokenizer_global(object):
"""Runs WordPiece tokenization."""
def __init__(self,
vocab,
unk_token,
tag2idx,
full2part,
word_part2idx,
idx2label_part,
word_idxes,
include_bi=True,
include_o=False,
M=None,
max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
self.M = M
self.tag2idx = tag2idx
self.include_bi = include_bi
self.include_o = include_o
self.full2part = full2part
self.word_part2idx = word_part2idx
self.idx2label_part = idx2label_part
self.word_idxes = word_idxes
if isinstance(self.tag2idx, tuple):
self.tag2idx = self.tag2idx[0]
def tokenize(self, text, label):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through `BasicTokenizer`.
Returns:
A list of wordpiece tokens.
"""
output_tokens = []
# print(label)
# print(text)
if self.include_bi == False and label != "O":
label = label.split("-")[-1]
for token in whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
if token in self.vocab or label not in self.tag2idx:
sub_tokens = tokenize_plain(chars, self.vocab)
else:
sub_tokens = tokenize_with_dp_1(
chars,
label,
self.word_part2idx,
self.idx2label_part,
self.word_idxes,
self.M,
self.vocab,
self.full2part
)
# print(sub_tokens)
if sub_tokens == ["[UNK]"]:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens
class OTTokenizer(object):
"""Runs WordPiece tokenization."""
def __init__(self,
vocab,
unk_token,
word2subtokenlist,
word2subtokenlist_ratio,
max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
self.word2subtokenlist = word2subtokenlist
self.word2subtokenlist_ratio = word2subtokenlist_ratio
def tokenize(self, text, label):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through `BasicTokenizer`.
Returns:
A list of wordpiece tokens.
"""
output_tokens = []
# print(self.word2subtokenlist_ratio)
for token in whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
is_normal = False
label = label[2:]
if token in self.word2subtokenlist_ratio and label in self.word2subtokenlist_ratio[token]:
# print("get: ", token)
ratios = np.array(self.word2subtokenlist_ratio[token][label])
# lengths = np.array([len(i) for i in self.word2subtokenlist[token]])
# ratios = ratios/lengths
ratios = ratios / ratios.sum()
if abs(ratios.sum() - 0) > 1e-10:
token_list = self.word2subtokenlist[token]
idx = np.random.choice(len(self.word2subtokenlist[token]), p=ratios)
sub_tokens = list(reversed(token_list[idx]))
output_tokens.extend(sub_tokens)
else:
# print("stream1")
is_normal = True
else:
# print("stream2")
is_normal = True
# print("is normal: ", is_normal)
if is_normal:
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens
class MyBertTokenizer(BertTokenizer):
def __init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None,
unk_token="[UNK]", sep_token="[SEP]", pad_token="[PAD]", cls_token="[CLS]",
mask_token="[MASK]", tokenize_chinese_chars=True, word_tokenizer="ot",
word2subtokenlist=None, word2subtokenlist_ratio=None, **kwargs):
super(MyBertTokenizer, self).__init__(vocab_file=vocab_file,
do_lower_case=do_lower_case,
do_basic_tokenize=do_basic_tokenize,
never_split=never_split,
unk_token=unk_token,
sep_token=sep_token,
pad_token=pad_token,
cls_token=cls_token,
mask_token=mask_token,
tokenize_chinese_chars=tokenize_chinese_chars,
**kwargs)
self.mode = word_tokenizer
self.word2subtokenlist = word2subtokenlist
self.word2subtokenlist_ratio = word2subtokenlist_ratio
if not word_tokenizer == "":
if word_tokenizer.startswith('ran'):
self.wordpiece_tokenizer = RandomWordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token)
elif word_tokenizer.startswith('rev'):
self.wordpiece_tokenizer = ReverseWordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token)
elif word_tokenizer == 'ot':
self.wordpiece_tokenizer = OTTokenizer(
vocab=self.vocab,
unk_token=self.unk_token,
word2subtokenlist=self.word2subtokenlist,
word2subtokenlist_ratio=self.word2subtokenlist_ratio
)
def set_split_ratio(self, word2subtokenlist, word2subtokenlist_ratio):
self.word2subtokenlist = word2subtokenlist
self.word2subtokenlist_ratio = word2subtokenlist_ratio
# self.change_tokenizer(self.mode)
def load_split_ratio(self, data_dir=""):
with open(data_dir + "ot_list.json", "r") as f:
self.word2subtokenlist = json.load(f)
with open(data_dir + "ot_ratio.json", "r") as f:
self.word2subtokenlist_ratio = json.load(f)
self.wordpiece_tokenizer = OTTokenizer(
vocab=self.vocab,
unk_token=self.unk_token,
word2subtokenlist=self.word2subtokenlist,
word2subtokenlist_ratio=self.word2subtokenlist_ratio
)
def dump_split_ratio(self, data_dir=""):
import os
if not os.path.exists(data_dir):
os.mkdir(data_dir)
with open(data_dir + "ot_list.json", "w") as f:
json.dump(self.word2subtokenlist, f)
with open(data_dir + "ot_ratio.json", "w") as f:
json.dump(self.word2subtokenlist_ratio, f)
def ot_tokenize(self, text, label):
split_tokens = []
if self.do_basic_tokenize:
for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
for sub_token in self.wordpiece_tokenizer.tokenize(token, label):
split_tokens.append(sub_token)
else:
split_tokens = self.wordpiece_tokenizer.tokenize(text, label)
return split_tokens
if __name__ == '__main__':
tokenizer = MyBertTokenizer(vocab_file="vocab.txt")