CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
tokenization_convbert_fast.py148 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."""16 17import json18from typing import Optional19 20from tokenizers import normalizers21 22from ...tokenization_utils_fast import PreTrainedTokenizerFast23from ...utils import logging24from .tokenization_convbert import ConvBertTokenizer25 26 27logger = logging.get_logger(__name__)28 29VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}30 31 32# Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast with bert-base-cased->YituTech/conv-bert-base, Bert->ConvBert, BERT->ConvBERT33class ConvBertTokenizerFast(PreTrainedTokenizerFast):34    r"""35    Construct a "fast" ConvBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.36 37    This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should38    refer to this superclass for more information regarding those methods.39 40    Args:41        vocab_file (`str`):42            File containing the vocabulary.43        do_lower_case (`bool`, *optional*, defaults to `True`):44            Whether or not to lowercase the input when tokenizing.45        unk_token (`str`, *optional*, defaults to `"[UNK]"`):46            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this47            token instead.48        sep_token (`str`, *optional*, defaults to `"[SEP]"`):49            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for50            sequence classification or for a text and a question for question answering. It is also used as the last51            token of a sequence built with special tokens.52        pad_token (`str`, *optional*, defaults to `"[PAD]"`):53            The token used for padding, for example when batching sequences of different lengths.54        cls_token (`str`, *optional*, defaults to `"[CLS]"`):55            The classifier token which is used when doing sequence classification (classification of the whole sequence56            instead of per-token classification). It is the first token of the sequence when built with special tokens.57        mask_token (`str`, *optional*, defaults to `"[MASK]"`):58            The token used for masking values. This is the token used when training this model with masked language59            modeling. This is the token which the model will try to predict.60        clean_text (`bool`, *optional*, defaults to `True`):61            Whether or not to clean the text before tokenization by removing any control characters and replacing all62            whitespaces by the classic one.63        tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):64            Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this65            issue](https://github.com/huggingface/transformers/issues/328)).66        strip_accents (`bool`, *optional*):67            Whether or not to strip all accents. If this option is not specified, then it will be determined by the68            value for `lowercase` (as in the original ConvBERT).69        wordpieces_prefix (`str`, *optional*, defaults to `"##"`):70            The prefix for subwords.71    """72 73    vocab_files_names = VOCAB_FILES_NAMES74    slow_tokenizer_class = ConvBertTokenizer75 76    def __init__(77        self,78        vocab_file=None,79        tokenizer_file=None,80        do_lower_case=True,81        unk_token="[UNK]",82        sep_token="[SEP]",83        pad_token="[PAD]",84        cls_token="[CLS]",85        mask_token="[MASK]",86        tokenize_chinese_chars=True,87        strip_accents=None,88        **kwargs,89    ):90        super().__init__(91            vocab_file,92            tokenizer_file=tokenizer_file,93            do_lower_case=do_lower_case,94            unk_token=unk_token,95            sep_token=sep_token,96            pad_token=pad_token,97            cls_token=cls_token,98            mask_token=mask_token,99            tokenize_chinese_chars=tokenize_chinese_chars,100            strip_accents=strip_accents,101            **kwargs,102        )103 104        normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())105        if (106            normalizer_state.get("lowercase", do_lower_case) != do_lower_case107            or normalizer_state.get("strip_accents", strip_accents) != strip_accents108            or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars109        ):110            normalizer_class = getattr(normalizers, normalizer_state.pop("type"))111            normalizer_state["lowercase"] = do_lower_case112            normalizer_state["strip_accents"] = strip_accents113            normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars114            self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)115 116        self.do_lower_case = do_lower_case117 118    def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):119        """120        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and121        adding special tokens. A ConvBERT sequence has the following format:122 123        - single sequence: `[CLS] X [SEP]`124        - pair of sequences: `[CLS] A [SEP] B [SEP]`125 126        Args:127            token_ids_0 (`List[int]`):128                List of IDs to which the special tokens will be added.129            token_ids_1 (`List[int]`, *optional*):130                Optional second list of IDs for sequence pairs.131 132        Returns:133            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.134        """135        output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]136 137        if token_ids_1 is not None:138            output += token_ids_1 + [self.sep_token_id]139 140        return output141 142    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:143        files = self._tokenizer.model.save(save_directory, name=filename_prefix)144        return tuple(files)145 146 147__all__ = ["ConvBertTokenizerFast"]148 
Aluode/PerceptionLabPortable · CoolFace