CoolFace
Apppublic

DoruC/Grounded-Segment-Anything

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
tokenization_convbert_fast.py199 linesDownload Raw Back to convbert
1# coding=utf-82# Copyright The HuggingFace Inc. team. 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 classes for ConvBERT."""16import json17from typing import List, Optional, Tuple18 19from tokenizers import normalizers20 21from ...tokenization_utils_fast import PreTrainedTokenizerFast22from ...utils import logging23from .tokenization_convbert import ConvBertTokenizer24 25 26logger = logging.get_logger(__name__)27 28VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}29 30PRETRAINED_VOCAB_FILES_MAP = {31    "vocab_file": {32        "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt",33        "YituTech/conv-bert-medium-small": (34            "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt"35        ),36        "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt",37    }38}39 40PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {41    "YituTech/conv-bert-base": 512,42    "YituTech/conv-bert-medium-small": 512,43    "YituTech/conv-bert-small": 512,44}45 46 47PRETRAINED_INIT_CONFIGURATION = {48    "YituTech/conv-bert-base": {"do_lower_case": True},49    "YituTech/conv-bert-medium-small": {"do_lower_case": True},50    "YituTech/conv-bert-small": {"do_lower_case": True},51}52 53 54# Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast with bert-base-cased->YituTech/conv-bert-base, Bert->ConvBert, BERT->ConvBERT55class ConvBertTokenizerFast(PreTrainedTokenizerFast):56    r"""57    Construct a "fast" ConvBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.58 59    This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should60    refer to this superclass for more information regarding those methods.61 62    Args:63        vocab_file (`str`):64            File containing the vocabulary.65        do_lower_case (`bool`, *optional*, defaults to `True`):66            Whether or not to lowercase the input when tokenizing.67        unk_token (`str`, *optional*, defaults to `"[UNK]"`):68            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this69            token instead.70        sep_token (`str`, *optional*, defaults to `"[SEP]"`):71            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for72            sequence classification or for a text and a question for question answering. It is also used as the last73            token of a sequence built with special tokens.74        pad_token (`str`, *optional*, defaults to `"[PAD]"`):75            The token used for padding, for example when batching sequences of different lengths.76        cls_token (`str`, *optional*, defaults to `"[CLS]"`):77            The classifier token which is used when doing sequence classification (classification of the whole sequence78            instead of per-token classification). It is the first token of the sequence when built with special tokens.79        mask_token (`str`, *optional*, defaults to `"[MASK]"`):80            The token used for masking values. This is the token used when training this model with masked language81            modeling. This is the token which the model will try to predict.82        clean_text (`bool`, *optional*, defaults to `True`):83            Whether or not to clean the text before tokenization by removing any control characters and replacing all84            whitespaces by the classic one.85        tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):86            Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this87            issue](https://github.com/huggingface/transformers/issues/328)).88        strip_accents (`bool`, *optional*):89            Whether or not to strip all accents. If this option is not specified, then it will be determined by the90            value for `lowercase` (as in the original ConvBERT).91        wordpieces_prefix (`str`, *optional*, defaults to `"##"`):92            The prefix for subwords.93    """94 95    vocab_files_names = VOCAB_FILES_NAMES96    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP97    pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION98    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES99    slow_tokenizer_class = ConvBertTokenizer100 101    def __init__(102        self,103        vocab_file=None,104        tokenizer_file=None,105        do_lower_case=True,106        unk_token="[UNK]",107        sep_token="[SEP]",108        pad_token="[PAD]",109        cls_token="[CLS]",110        mask_token="[MASK]",111        tokenize_chinese_chars=True,112        strip_accents=None,113        **kwargs,114    ):115        super().__init__(116            vocab_file,117            tokenizer_file=tokenizer_file,118            do_lower_case=do_lower_case,119            unk_token=unk_token,120            sep_token=sep_token,121            pad_token=pad_token,122            cls_token=cls_token,123            mask_token=mask_token,124            tokenize_chinese_chars=tokenize_chinese_chars,125            strip_accents=strip_accents,126            **kwargs,127        )128 129        normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())130        if (131            normalizer_state.get("lowercase", do_lower_case) != do_lower_case132            or normalizer_state.get("strip_accents", strip_accents) != strip_accents133            or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars134        ):135            normalizer_class = getattr(normalizers, normalizer_state.pop("type"))136            normalizer_state["lowercase"] = do_lower_case137            normalizer_state["strip_accents"] = strip_accents138            normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars139            self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)140 141        self.do_lower_case = do_lower_case142 143    def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):144        """145        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and146        adding special tokens. A ConvBERT sequence has the following format:147 148        - single sequence: `[CLS] X [SEP]`149        - pair of sequences: `[CLS] A [SEP] B [SEP]`150 151        Args:152            token_ids_0 (`List[int]`):153                List of IDs to which the special tokens will be added.154            token_ids_1 (`List[int]`, *optional*):155                Optional second list of IDs for sequence pairs.156 157        Returns:158            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.159        """160        output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]161 162        if token_ids_1 is not None:163            output += token_ids_1 + [self.sep_token_id]164 165        return output166 167    def create_token_type_ids_from_sequences(168        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None169    ) -> List[int]:170        """171        Create a mask from the two sequences passed to be used in a sequence-pair classification task. A ConvBERT172        sequence pair mask has the following format:173 174        ```175        0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1176        | first sequence    | second sequence |177        ```178 179        If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).180 181        Args:182            token_ids_0 (`List[int]`):183                List of IDs.184            token_ids_1 (`List[int]`, *optional*):185                Optional second list of IDs for sequence pairs.186 187        Returns:188            `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).189        """190        sep = [self.sep_token_id]191        cls = [self.cls_token_id]192        if token_ids_1 is None:193            return len(cls + token_ids_0 + sep) * [0]194        return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]195 196    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:197        files = self._tokenizer.model.save(save_directory, name=filename_prefix)198        return tuple(files)199