CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
tokenization_pegasus_fast.py216 linesDownload Raw Back to pegasus
1# coding=utf-82# Copyright 2020 Google and The HuggingFace Inc. team.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Tokenization class for model PEGASUS."""16 17import os18from shutil import copyfile19from typing import Optional20 21from ...tokenization_utils_fast import PreTrainedTokenizerFast22from ...utils import is_sentencepiece_available, logging23 24 25if is_sentencepiece_available():26    from .tokenization_pegasus import PegasusTokenizer27else:28    PegasusTokenizer = None29 30 31logger = logging.get_logger(__name__)32 33 34SPIECE_UNDERLINE = "▁"35 36VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}37 38 39class PegasusTokenizerFast(PreTrainedTokenizerFast):40    r"""41    Construct a "fast" PEGASUS tokenizer (backed by HuggingFace's *tokenizers* library). Based on42    [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).43 44    This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should45    refer to this superclass for more information regarding those methods.46 47    Args:48        vocab_file (`str`):49            [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that50            contains the vocabulary necessary to instantiate a tokenizer.51        pad_token (`str`, *optional*, defaults to `"<pad>"`):52            The token used for padding, for example when batching sequences of different lengths.53        eos_token (`str`, *optional*, defaults to `"</s>"`):54            The end of sequence token.55 56            <Tip>57 58            When building a sequence using special tokens, this is not the token that is used for the end of sequence.59            The token used is the `sep_token`.60 61            </Tip>62 63        unk_token (`str`, *optional*, defaults to `"<unk>"`):64            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this65            token instead.66        mask_token (`str`, *optional*, defaults to `"<mask_2>"`):67            The token used for masking single token values. This is the token used when training this model with masked68            language modeling (MLM). This is the token that the PEGASUS encoder will try to predict during pretraining.69            It corresponds to *[MASK2]* in [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive70            Summarization](https://huggingface.co/papers/1912.08777).71        mask_token_sent (`str`, *optional*, defaults to `"<mask_1>"`):72            The token used for masking whole target sentences. This is the token used when training this model with gap73            sentences generation (GSG). This is the sentence that the PEGASUS decoder will try to predict during74            pretraining. It corresponds to *[MASK1]* in [PEGASUS: Pre-training with Extracted Gap-sentences for75            Abstractive Summarization](https://huggingface.co/papers/1912.08777).76        additional_special_tokens (`List[str]`, *optional*):77            Additional special tokens used by the tokenizer. If no additional_special_tokens are provided <mask_2> and78            <unk_2, ..., unk_102> are used as additional special tokens corresponding to the [original PEGASUS79            tokenizer](https://github.com/google-research/pegasus/blob/939830367bcf411193d2b5eca2f2f90f3f9260ca/pegasus/ops/pretrain_parsing_ops.cc#L66)80            that uses the tokens 2 - 104 only for pretraining81    """82 83    vocab_files_names = VOCAB_FILES_NAMES84    slow_tokenizer_class = PegasusTokenizer85    model_input_names = ["input_ids", "attention_mask"]86 87    def __init__(88        self,89        vocab_file=None,90        tokenizer_file=None,91        pad_token="<pad>",92        eos_token="</s>",93        unk_token="<unk>",94        mask_token="<mask_2>",95        mask_token_sent="<mask_1>",96        additional_special_tokens=None,97        offset=103,  # entries 2 - 104 are only used for pretraining98        **kwargs,99    ):100        self.offset = offset101 102        if additional_special_tokens is not None:103            if not isinstance(additional_special_tokens, list):104                raise TypeError(105                    f"additional_special_tokens should be of type {type(list)}, but is"106                    f" {type(additional_special_tokens)}"107                )108 109            additional_special_tokens_extended = (110                ([mask_token_sent] + additional_special_tokens)111                if mask_token_sent not in additional_special_tokens and mask_token_sent is not None112                else additional_special_tokens113            )114            # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken115            additional_special_tokens_extended += [116                f"<unk_{i}>" for i in range(len(additional_special_tokens_extended), self.offset - 1)117            ]118 119            if len(set(additional_special_tokens_extended)) != len(additional_special_tokens_extended):120                raise ValueError(121                    "Please make sure that the provided additional_special_tokens do not contain an incorrectly"122                    f" shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}."123                )124            additional_special_tokens = additional_special_tokens_extended125        else:126            additional_special_tokens = [mask_token_sent] if mask_token_sent is not None else []127            additional_special_tokens += [f"<unk_{i}>" for i in range(2, self.offset)]128 129        # pegasus was design to support changing the index of the first tokens. If one of the padding/eos/unk/mask token130        # is different from default, we must rebuild the vocab131        from_slow = kwargs.pop("from_slow", None)132        from_slow = from_slow or str(pad_token) != "<pad>" or str(eos_token) != "</s>" or str(unk_token) != "<unk>"133 134        kwargs.pop("added_tokens_decoder", {})135 136        super().__init__(137            vocab_file,138            tokenizer_file=tokenizer_file,139            pad_token=pad_token,140            eos_token=eos_token,141            unk_token=unk_token,142            mask_token=mask_token,143            mask_token_sent=mask_token_sent,144            offset=offset,145            additional_special_tokens=additional_special_tokens,146            from_slow=from_slow,147            **kwargs,148        )149        self.vocab_file = vocab_file150 151    def _special_token_mask(self, seq):152        all_special_ids = set(self.all_special_ids)  # call it once instead of inside list comp153        all_special_ids.remove(self.unk_token_id)  # <unk> is only sometimes special154 155        if all_special_ids != set(range(len(self.additional_special_tokens) + 3)):156            raise ValueError(157                "There should be 3 special tokens: mask_token, pad_token, and eos_token +"158                f" {len(self.additional_special_tokens)} additional_special_tokens, but got {all_special_ids}"159            )160 161        return [1 if x in all_special_ids else 0 for x in seq]162 163    def get_special_tokens_mask(164        self, token_ids_0: list, token_ids_1: Optional[list] = None, already_has_special_tokens: bool = False165    ) -> list[int]:166        """Get list where entries are [1] if a token is [eos] or [pad] else 0."""167        if already_has_special_tokens:168            return self._special_token_mask(token_ids_0)169        elif token_ids_1 is None:170            return self._special_token_mask(token_ids_0) + [1]171        else:172            return self._special_token_mask(token_ids_0 + token_ids_1) + [1]173 174    def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> list[int]:175        """176        Build model inputs from a sequence by adding eos to the end. no bos token is added to the front.177 178        - single sequence: `X </s>`179        - pair of sequences: `A B </s>` (not intended use)180 181        Args:182            token_ids_0 (`List[int]`):183                List of IDs to which the special tokens will be added184            token_ids_1 (`List[int]`, *optional*):185                Optional second list of IDs for sequence pairs.186 187        Returns:188            `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.189        """190        if token_ids_1 is None:191            return token_ids_0 + [self.eos_token_id]192        # We don't expect to process pairs, but leave the pair logic for API consistency193        return token_ids_0 + token_ids_1 + [self.eos_token_id]194 195    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:196        if not self.can_save_slow_tokenizer:197            raise ValueError(198                "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "199                "tokenizer."200            )201 202        if not os.path.isdir(save_directory):203            logger.error(f"Vocabulary path ({save_directory}) should be a directory")204            return205        out_vocab_file = os.path.join(206            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]207        )208 209        if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):210            copyfile(self.vocab_file, out_vocab_file)211 212        return (out_vocab_file,)213 214 215__all__ = ["PegasusTokenizerFast"]216 
Aluode/PerceptionLabPortable · CoolFace