CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
tokenization_splinter_fast.py194 linesDownload Raw Back to splinter
1# coding=utf-82# Copyright 2021 Tel AViv University, AllenAI and 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"""Fast Tokenization classes for Splinter."""16 17import json18from typing import Optional19 20from tokenizers import normalizers21 22from ...tokenization_utils_fast import PreTrainedTokenizerFast23from ...utils import logging24from .tokenization_splinter import SplinterTokenizer25 26 27logger = logging.get_logger(__name__)28 29VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}30 31 32class SplinterTokenizerFast(PreTrainedTokenizerFast):33    r"""34    Construct a "fast" Splinter tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.35 36    This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should37    refer to this superclass for more information regarding those methods.38 39    Args:40        vocab_file (`str`):41            File containing the vocabulary.42        do_lower_case (`bool`, *optional*, defaults to `True`):43            Whether or not to lowercase the input when tokenizing.44        unk_token (`str`, *optional*, defaults to `"[UNK]"`):45            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this46            token instead.47        sep_token (`str`, *optional*, defaults to `"[SEP]"`):48            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for49            sequence classification or for a text and a question for question answering. It is also used as the last50            token of a sequence built with special tokens.51        pad_token (`str`, *optional*, defaults to `"[PAD]"`):52            The token used for padding, for example when batching sequences of different lengths.53        cls_token (`str`, *optional*, defaults to `"[CLS]"`):54            The classifier token which is used when doing sequence classification (classification of the whole sequence55            instead of per-token classification). It is the first token of the sequence when built with special tokens.56        mask_token (`str`, *optional*, defaults to `"[MASK]"`):57            The token used for masking values. This is the token used when training this model with masked language58            modeling. This is the token which the model will try to predict.59        question_token (`str`, *optional*, defaults to `"[QUESTION]"`):60            The token used for constructing question representations.61        clean_text (`bool`, *optional*, defaults to `True`):62            Whether or not to clean the text before tokenization by removing any control characters and replacing all63            whitespaces by the classic one.64        tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):65            Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this66            issue](https://github.com/huggingface/transformers/issues/328)).67        strip_accents (`bool`, *optional*):68            Whether or not to strip all accents. If this option is not specified, then it will be determined by the69            value for `lowercase` (as in the original BERT).70        wordpieces_prefix (`str`, *optional*, defaults to `"##"`):71            The prefix for subwords.72    """73 74    vocab_files_names = VOCAB_FILES_NAMES75    slow_tokenizer_class = SplinterTokenizer76 77    def __init__(78        self,79        vocab_file=None,80        tokenizer_file=None,81        do_lower_case=True,82        unk_token="[UNK]",83        sep_token="[SEP]",84        pad_token="[PAD]",85        cls_token="[CLS]",86        mask_token="[MASK]",87        question_token="[QUESTION]",88        tokenize_chinese_chars=True,89        strip_accents=None,90        **kwargs,91    ):92        super().__init__(93            vocab_file,94            tokenizer_file=tokenizer_file,95            do_lower_case=do_lower_case,96            unk_token=unk_token,97            sep_token=sep_token,98            pad_token=pad_token,99            cls_token=cls_token,100            mask_token=mask_token,101            tokenize_chinese_chars=tokenize_chinese_chars,102            strip_accents=strip_accents,103            additional_special_tokens=(question_token,),104            **kwargs,105        )106 107        pre_tok_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())108        if (109            pre_tok_state.get("lowercase", do_lower_case) != do_lower_case110            or pre_tok_state.get("strip_accents", strip_accents) != strip_accents111        ):112            pre_tok_class = getattr(normalizers, pre_tok_state.pop("type"))113            pre_tok_state["lowercase"] = do_lower_case114            pre_tok_state["strip_accents"] = strip_accents115            self.backend_tokenizer.normalizer = pre_tok_class(**pre_tok_state)116 117        self.do_lower_case = do_lower_case118 119    @property120    def question_token_id(self):121        """122        `Optional[int]`: Id of the question token in the vocabulary, used to condition the answer on a question123        representation.124        """125        return self.convert_tokens_to_ids(self.question_token)126 127    def build_inputs_with_special_tokens(128        self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None129    ) -> list[int]:130        """131        Build model inputs from a pair of sequence for question answering tasks by concatenating and adding special132        tokens. A Splinter sequence has the following format:133 134        - single sequence: `[CLS] X [SEP]`135        - pair of sequences for question answering: `[CLS] question_tokens [QUESTION] . [SEP] context_tokens [SEP]`136 137        Args:138            token_ids_0 (`list[int]`):139                The question token IDs if pad_on_right, else context tokens IDs140            token_ids_1 (`list[int]`, *optional*):141                The context token IDs if pad_on_right, else question token IDs142 143        Returns:144            `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.145        """146        if token_ids_1 is None:147            return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]148 149        cls = [self.cls_token_id]150        sep = [self.sep_token_id]151        question_suffix = [self.question_token_id] + [self.convert_tokens_to_ids(".")]152        if self.padding_side == "right":153            # Input is question-then-context154            return cls + token_ids_0 + question_suffix + sep + token_ids_1 + sep155        else:156            # Input is context-then-question157            return cls + token_ids_0 + sep + token_ids_1 + question_suffix + sep158 159    def create_token_type_ids_from_sequences(160        self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None161    ) -> list[int]:162        """163        Create the token type IDs corresponding to the sequences passed. [What are token type164        IDs?](../glossary#token-type-ids)165 166        Should be overridden in a subclass if the model has a special way of building those.167 168        Args:169            token_ids_0 (`list[int]`): The first tokenized sequence.170            token_ids_1 (`list[int]`, *optional*): The second tokenized sequence.171 172        Returns:173            `list[int]`: The token type ids.174        """175        sep = [self.sep_token_id]176        cls = [self.cls_token_id]177        question_suffix = [self.question_token_id] + [self.convert_tokens_to_ids(".")]178        if token_ids_1 is None:179            return len(cls + token_ids_0 + sep) * [0]180 181        if self.padding_side == "right":182            # Input is question-then-context183            return len(cls + token_ids_0 + question_suffix + sep) * [0] + len(token_ids_1 + sep) * [1]184        else:185            # Input is context-then-question186            return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + question_suffix + sep) * [1]187 188    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:189        files = self._tokenizer.model.save(save_directory, name=filename_prefix)190        return tuple(files)191 192 193__all__ = ["SplinterTokenizerFast"]194 
Aluode/PerceptionLabPortable · CoolFace