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

Class SpecialTokensMixin

bert/tokenization_utils_base.py:565–932  ·  view source on GitHub ↗

SpecialTokensMixin is derived by ``PreTrainedTokenizer`` and ``PreTrainedTokenizerFast`` and handles specific behaviors related to special tokens. In particular, this class hold the attributes which can be used to directly access to these special tokens in a model-independan

Source from the content-addressed store, hash-verified

563
564
565class SpecialTokensMixin:
566 """ SpecialTokensMixin is derived by ``PreTrainedTokenizer`` and ``PreTrainedTokenizerFast`` and
567 handles specific behaviors related to special tokens. In particular, this class hold the
568 attributes which can be used to directly access to these special tokens in a
569 model-independant manner and allow to set and update the special tokens.
570 """
571
572 SPECIAL_TOKENS_ATTRIBUTES = [
573 "bos_token",
574 "eos_token",
575 "unk_token",
576 "sep_token",
577 "pad_token",
578 "cls_token",
579 "mask_token",
580 "additional_special_tokens",
581 ]
582
583 def __init__(self, verbose=True, **kwargs):
584 self._bos_token = None
585 self._eos_token = None
586 self._unk_token = None
587 self._sep_token = None
588 self._pad_token = None
589 self._cls_token = None
590 self._mask_token = None
591 self._pad_token_type_id = 0
592 self._additional_special_tokens = []
593 self.verbose = verbose
594
595 # We directly set the hidden value to allow initialization with special tokens
596 # which are not yet in the vocabulary. Necesssary for serialization/de-serialization
597 # TODO clean this up at some point (probably by sitching to fast tokenizers)
598 for key, value in kwargs.items():
599 if key in self.SPECIAL_TOKENS_ATTRIBUTES:
600 if key == "additional_special_tokens":
601 assert isinstance(value, (list, tuple)) and all(isinstance(t, str) for t in value)
602 setattr(self, key, value)
603 elif isinstance(value, (str, AddedToken)):
604 setattr(self, key, value)
605 else:
606 raise TypeError(
607 "special token {} has to be either str or AddedToken but got: {}".format(key, type(value))
608 )
609
610 def sanitize_special_tokens(self) -> int:
611 """ Make sure that all the special tokens attributes of the tokenizer (tokenizer.mask_token, tokenizer.cls_token, ...)
612 are in the vocabulary. Add the missing ones to the vocabulary if needed.
613
614 Return:
615 Number of tokens added in the vocaulary during the operation.
616 """
617 return self.add_tokens(self.all_special_tokens_extended, special_tokens=True)
618
619 def add_special_tokens(self, special_tokens_dict: Dict[str, Union[str, AddedToken]]) -> int:
620 """
621 Add a dictionary of special tokens (eos, pad, cls...) to the encoder and link them
622 to class attributes. If special tokens are NOT in the vocabulary, they are added

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected