MCPcopy Create free account
hub / github.com/SooLab/CGFormer / WordpieceTokenizer

Class WordpieceTokenizer

bert/tokenization_bert.py:487–544  ·  view source on GitHub ↗

Runs WordPiece tokenization.

Source from the content-addressed store, hash-verified

485
486
487class WordpieceTokenizer(object):
488 """Runs WordPiece tokenization."""
489
490 def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
491 self.vocab = vocab
492 self.unk_token = unk_token
493 self.max_input_chars_per_word = max_input_chars_per_word
494
495 def tokenize(self, text):
496 """Tokenizes a piece of text into its word pieces.
497
498 This uses a greedy longest-match-first algorithm to perform tokenization
499 using the given vocabulary.
500
501 For example:
502 input = "unaffable"
503 output = ["un", "##aff", "##able"]
504
505 Args:
506 text: A single token or whitespace separated tokens. This should have
507 already been passed through `BasicTokenizer`.
508
509 Returns:
510 A list of wordpiece tokens.
511 """
512
513 output_tokens = []
514 for token in whitespace_tokenize(text):
515 chars = list(token)
516 if len(chars) > self.max_input_chars_per_word:
517 output_tokens.append(self.unk_token)
518 continue
519
520 is_bad = False
521 start = 0
522 sub_tokens = []
523 while start < len(chars):
524 end = len(chars)
525 cur_substr = None
526 while start < end:
527 substr = "".join(chars[start:end])
528 if start > 0:
529 substr = "##" + substr
530 if substr in self.vocab:
531 cur_substr = substr
532 break
533 end -= 1
534 if cur_substr is None:
535 is_bad = True
536 break
537 sub_tokens.append(cur_substr)
538 start = end
539
540 if is_bad:
541 output_tokens.append(self.unk_token)
542 else:
543 output_tokens.extend(sub_tokens)
544 return output_tokens

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected