CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
tokenization_bert_generation.py178 linesDownload Raw Back to bert_generation
1# coding=utf-82# Copyright (c) 2020, NVIDIA CORPORATION.  All rights reserved.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 BertGeneration."""16 17import os18from shutil import copyfile19from typing import Any, Optional20 21import sentencepiece as spm22 23from ...tokenization_utils import PreTrainedTokenizer24from ...utils import logging25from ...utils.import_utils import requires26 27 28logger = logging.get_logger(__name__)29 30VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}31 32 33@requires(backends=("sentencepiece",))34class BertGenerationTokenizer(PreTrainedTokenizer):35    """36    Construct a BertGeneration tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).37 38    This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to39    this superclass for more information regarding those methods.40 41    Args:42        vocab_file (`str`):43            [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that44            contains the vocabulary necessary to instantiate a tokenizer.45        bos_token (`str`, *optional*, defaults to `"<s>"`):46            The begin of sequence token.47        eos_token (`str`, *optional*, defaults to `"</s>"`):48            The end of sequence token.49        unk_token (`str`, *optional*, defaults to `"<unk>"`):50            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this51            token instead.52        pad_token (`str`, *optional*, defaults to `"<pad>"`):53            The token used for padding, for example when batching sequences of different lengths.54        sep_token (`str`, *optional*, defaults to `"<::::>"`):55            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for56            sequence classification or for a text and a question for question answering. It is also used as the last57            token of a sequence built with special tokens.58        sp_model_kwargs (`dict`, *optional*):59            Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for60            SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,61            to set:62 63            - `enable_sampling`: Enable subword regularization.64            - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.65 66              - `nbest_size = {0,1}`: No sampling is performed.67              - `nbest_size > 1`: samples from the nbest_size results.68              - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)69                using forward-filtering-and-backward-sampling algorithm.70 71            - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for72              BPE-dropout.73    """74 75    vocab_files_names = VOCAB_FILES_NAMES76    prefix_tokens: list[int] = []77    model_input_names = ["input_ids", "attention_mask"]78 79    def __init__(80        self,81        vocab_file,82        bos_token="<s>",83        eos_token="</s>",84        unk_token="<unk>",85        pad_token="<pad>",86        sep_token="<::::>",87        sp_model_kwargs: Optional[dict[str, Any]] = None,88        **kwargs,89    ) -> None:90        self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs91 92        self.vocab_file = vocab_file93 94        self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)95        self.sp_model.Load(vocab_file)96 97        # Add extra_ids to the special token list98        super().__init__(99            bos_token=bos_token,100            eos_token=eos_token,101            unk_token=unk_token,102            pad_token=pad_token,103            sep_token=sep_token,104            sp_model_kwargs=self.sp_model_kwargs,105            **kwargs,106        )107 108    @property109    def vocab_size(self):110        return self.sp_model.get_piece_size()111 112    def get_vocab(self):113        vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}114        vocab.update(self.added_tokens_encoder)115        return vocab116 117    def __getstate__(self):118        state = self.__dict__.copy()119        state["sp_model"] = None120        return state121 122    def __setstate__(self, d):123        self.__dict__ = d124 125        # for backward compatibility126        if not hasattr(self, "sp_model_kwargs"):127            self.sp_model_kwargs = {}128 129        self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)130        self.sp_model.Load(self.vocab_file)131 132    def _tokenize(self, text: str) -> list[str]:133        """Take as input a string and return a list of strings (tokens) for words/sub-words"""134        return self.sp_model.encode(text, out_type=str)135 136    def _convert_token_to_id(self, token):137        """Converts a token (str) in an id using the vocab."""138        return self.sp_model.piece_to_id(token)139 140    def _convert_id_to_token(self, index):141        """Converts an index (integer) in a token (str) using the vocab."""142        token = self.sp_model.IdToPiece(index)143        return token144 145    def convert_tokens_to_string(self, tokens):146        """Converts a sequence of tokens (string) in a single string."""147        current_sub_tokens = []148        out_string = ""149        for token in tokens:150            # make sure that special tokens are not decoded using sentencepiece model151            if token in self.all_special_tokens:152                out_string += self.sp_model.decode(current_sub_tokens) + token153                current_sub_tokens = []154            else:155                current_sub_tokens.append(token)156        out_string += self.sp_model.decode(current_sub_tokens)157        return out_string.strip()158 159    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:160        if not os.path.isdir(save_directory):161            logger.error(f"Vocabulary path ({save_directory}) should be a directory")162            return163        out_vocab_file = os.path.join(164            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]165        )166 167        if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):168            copyfile(self.vocab_file, out_vocab_file)169        elif not os.path.isfile(self.vocab_file):170            with open(out_vocab_file, "wb") as fi:171                content_spiece_model = self.sp_model.serialized_model_proto()172                fi.write(content_spiece_model)173 174        return (out_vocab_file,)175 176 177__all__ = ["BertGenerationTokenizer"]178 
Aluode/PerceptionLabPortable · CoolFace