codingutf8 2022 the realm s and the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license fast tokenization classes for realm import json from typing import list optional tuple from tokenizers import normalizers from tokenizationutilsbase import batchencoding from tokenizationutilsfast import pretrainedtokenizerfast from utils import paddingstrategy logging from tokenizationrealm import realmtokenizer logger logging getloggername vocabfilesnames vocabfile vocab txt tokenizerfile tokenizer json pretrainedvocabfilesmap vocabfile googlerealmccnewspretrainedembedder https huggingface cogooglerealmccnewspretrainedembedderresolvemainvocab txt googlerealmccnewspretrainedencoder https huggingface cogooglerealmccnewspretrainedencoderresolvemainvocab txt googlerealmccnewspretrainedscorer https huggingface cogooglerealmccnewspretrainedscorerresolvemainvocab txt googlerealmccnewspretrainedopenqa https huggingface cogooglerealmccnewspretrainedopenqaaresolvemainvocab txt googlerealmorqanqopenqa https huggingface cogooglerealmorqanqopenqaresolvemainvocab txt googlerealmorqanqreader https huggingface cogooglerealmorqanqreaderresolvemainvocab txt googlerealmorqawqopenqa https huggingface cogooglerealmorqawqopenqaresolvemainvocab txt googlerealmorqawqreader https huggingface cogooglerealmorqawqreaderresolvemainvocab txt tokenizerfile googlerealmccnewspretrainedembedder https huggingface cogooglerealmccnewspretrainedembedderresolvemaintokenizer jsont googlerealmccnewspretrainedencoder https huggingface cogooglerealmccnewspretrainedencoderresolvemaintokenizer json googlerealmccnewspretrainedscorer https huggingface cogooglerealmccnewspretrainedscorerresolvemaintokenizer json googlerealmccnewspretrainedopenqa https huggingface cogooglerealmccnewspretrainedopenqaaresolvemaintokenizer json googlerealmorqanqopenqa https huggingface cogooglerealmorqanqopenqaresolvemaintokenizer json googlerealmorqanqreader https huggingface cogooglerealmorqanqreaderresolvemaintokenizer json googlerealmorqawqopenqa https huggingface cogooglerealmorqawqopenqaresolvemaintokenizer json googlerealmorqawqreader https huggingface cogooglerealmorqawqreaderresolvemaintokenizer json pretrainedpositionalembeddingssizes googlerealmccnewspretrainedembedder 512 googlerealmccnewspretrainedencoder 512 googlerealmccnewspretrainedscorer 512 googlerealmccnewspretrainedopenqa 512 googlerealmorqanqopenqa 512 googlerealmorqanqreader 512 googlerealmorqawqopenqa 512 googlerealmorqawqreader 512 pretrainedinitconfiguration googlerealmccnewspretrainedembedder dolowercase true googlerealmccnewspretrainedencoder dolowercase true googlerealmccnewspretrainedscorer dolowercase true googlerealmccnewspretrainedopenqa dolowercase true googlerealmorqanqopenqa dolowercase true googlerealmorqanqreader dolowercase true googlerealmorqawqopenqa dolowercase true googlerealmorqawqreader dolowercase true class realmtokenizerfastpretrainedtokenizerfast r construct a fast realm tokenizer backed by huggingface s tokenizers library based on wordpiece realmtokenizerfast is identical to berttokenizerfast and runs endtoend tokenization punctuation splitting and wordpiece this tokenizer inherits from pretrainedtokenizerfast which contains most of the main methods users should refer to this superclass for more information regarding those methods args vocabfile str file containing the vocabulary dolowercase bool optional defaults to true whether or not to lowercase the input when tokenizing unktoken str optional defaults to unk the unknown token a token that is not in the vocabulary cannot be converted to an id and is set to be this token instead septoken str optional defaults to sep the separator token which is used when building a sequence from multiple sequences e g two sequences for sequence classification or for a text and a question for question answering it is also used as the last token of a sequence built with special tokens padtoken str optional defaults to pad the token used for padding for example when batching sequences of different lengths clstoken str optional defaults to cls the classifier token which is used when doing sequence classification classification of the whole sequence instead of pertoken classification it is the first token of the sequence when built with special tokens masktoken str optional defaults to mask the token used for masking values this is the token used when training this model with masked language modeling this is the token which the model will try to predict cleantext bool optional defaults to true whether or not to clean the text before tokenization by removing any control characters and replacing all whitespaces by the classic one tokenizechinesechars bool optional defaults to true whether or not to tokenize chinese characters this should likely be deactivated for japanese see this issuehttps github comhuggingfacetransformersissues328 stripaccents bool optional whether or not to strip all accents if this option is not specified then it will be determined by the value for lowercase as in the original bert wordpiecesprefix str optional defaults to the prefix for subwords always using a fixed sequence length to encode in order to stack candidates into a batch build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens a realm sequence has the following format single sequence cls x sep pair of sequences cls a sep b sep args tokenids0 listint list of ids to which the special tokens will be added tokenids1 listint optional optional second list of ids for sequence pairs returns listint list of input ids glossaryinputids with the appropriate special tokens create a mask from the two sequences passed to be used in a sequencepair classification task a realm sequence pair mask has the following format 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 first sequence second sequence if tokenids1 is none this method only returns the first portion of the mask 0s args tokenids0 listint list of ids tokenids1 listint optional optional second list of ids for sequence pairs returns listint list of token type ids glossarytokentypeids according to the given sequences coding utf 8 2022 the realm s and the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license fast tokenization classes for realm construct a fast realm tokenizer backed by huggingface s tokenizers library based on wordpiece realmtokenizerfast is identical to berttokenizerfast and runs end to end tokenization punctuation splitting and wordpiece this tokenizer inherits from pretrainedtokenizerfast which contains most of the main methods users should refer to this superclass for more information regarding those methods args vocab_file str file containing the vocabulary do_lower_case bool optional defaults to true whether or not to lowercase the input when tokenizing unk_token str optional defaults to unk the unknown token a token that is not in the vocabulary cannot be converted to an id and is set to be this token instead sep_token str optional defaults to sep the separator token which is used when building a sequence from multiple sequences e g two sequences for sequence classification or for a text and a question for question answering it is also used as the last token of a sequence built with special tokens pad_token str optional defaults to pad the token used for padding for example when batching sequences of different lengths cls_token str optional defaults to cls the classifier token which is used when doing sequence classification classification of the whole sequence instead of per token classification it is the first token of the sequence when built with special tokens mask_token str optional defaults to mask the token used for masking values this is the token used when training this model with masked language modeling this is the token which the model will try to predict clean_text bool optional defaults to true whether or not to clean the text before tokenization by removing any control characters and replacing all whitespaces by the classic one tokenize_chinese_chars bool optional defaults to true whether or not to tokenize chinese characters this should likely be deactivated for japanese see this issue https github com huggingface transformers issues 328 strip_accents bool optional whether or not to strip all accents if this option is not specified then it will be determined by the value for lowercase as in the original bert wordpieces_prefix str optional defaults to the prefix for subwords encode a batch of text or text pair this method is similar to regular __call__ method but has the following differences 1 handle additional num_candidate axis batch_size num_candidates text 2 always pad the sequences to max_length 3 must specify max_length in order to stack packs of candidates into a batch single sequence cls x sep pair of sequences cls a sep b sep args text list list str the batch of sequences to be encoded each sequence must be in this format batch_size num_candidates text text_pair list list str optional the batch of sequences to be encoded each sequence must be in this format batch_size num_candidates text kwargs keyword arguments of the __call__ method returns batchencoding encoded text or text pair example python from transformers import realmtokenizerfast batch_size 2 num_candidates 2 text hello world nice to meet you the cute cat the adorable dog tokenizer realmtokenizerfast from_pretrained google realm cc news pretrained encoder tokenized_text tokenizer batch_encode_candidates text max_length 10 return_tensors pt always using a fixed sequence length to encode in order to stack candidates into a batch build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens a realm sequence has the following format single sequence cls x sep pair of sequences cls a sep b sep args token_ids_0 list int list of ids to which the special tokens will be added token_ids_1 list int optional optional second list of ids for sequence pairs returns list int list of input ids glossary input ids with the appropriate special tokens create a mask from the two sequences passed to be used in a sequence pair classification task a realm sequence pair mask has the following format 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 first sequence second sequence if token_ids_1 is none this method only returns the first portion of the mask 0s args token_ids_0 list int list of ids token_ids_1 list int optional optional second list of ids for sequence pairs returns list int list of token type ids glossary token type ids according to the given sequence s
import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_realm import RealmTokenizer


logger = logging.get_logger(__name__)

VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

PRETRAINED_VOCAB_FILES_MAP = {
    "vocab_file": {
        "google/realm-cc-news-pretrained-embedder": (
            "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt"
        ),
        "google/realm-cc-news-pretrained-encoder": (
            "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt"
        ),
        "google/realm-cc-news-pretrained-scorer": (
            "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt"
        ),
        "google/realm-cc-news-pretrained-openqa": (
            "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt"
        ),
        "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt",
        "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt",
        "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt",
        "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt",
    },
    "tokenizer_file": {
        "google/realm-cc-news-pretrained-embedder": (
            "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont"
        ),
        "google/realm-cc-news-pretrained-encoder": (
            "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json"
        ),
        "google/realm-cc-news-pretrained-scorer": (
            "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json"
        ),
        "google/realm-cc-news-pretrained-openqa": (
            "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json"
        ),
        "google/realm-orqa-nq-openqa": (
            "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json"
        ),
        "google/realm-orqa-nq-reader": (
            "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json"
        ),
        "google/realm-orqa-wq-openqa": (
            "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json"
        ),
        "google/realm-orqa-wq-reader": (
            "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json"
        ),
    },
}

PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
    "google/realm-cc-news-pretrained-embedder": 512,
    "google/realm-cc-news-pretrained-encoder": 512,
    "google/realm-cc-news-pretrained-scorer": 512,
    "google/realm-cc-news-pretrained-openqa": 512,
    "google/realm-orqa-nq-openqa": 512,
    "google/realm-orqa-nq-reader": 512,
    "google/realm-orqa-wq-openqa": 512,
    "google/realm-orqa-wq-reader": 512,
}

PRETRAINED_INIT_CONFIGURATION = {
    "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True},
    "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True},
    "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True},
    "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True},
    "google/realm-orqa-nq-openqa": {"do_lower_case": True},
    "google/realm-orqa-nq-reader": {"do_lower_case": True},
    "google/realm-orqa-wq-openqa": {"do_lower_case": True},
    "google/realm-orqa-wq-reader": {"do_lower_case": True},
}


class RealmTokenizerFast(PreTrainedTokenizerFast):
    r

    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    slow_tokenizer_class = RealmTokenizer

    def __init__(
        self,
        vocab_file=None,
        tokenizer_file=None,
        do_lower_case=True,
        unk_token="[UNK]",
        sep_token="[SEP]",
        pad_token="[PAD]",
        cls_token="[CLS]",
        mask_token="[MASK]",
        tokenize_chinese_chars=True,
        strip_accents=None,
        **kwargs,
    ):
        super().__init__(
            vocab_file,
            tokenizer_file=tokenizer_file,
            do_lower_case=do_lower_case,
            unk_token=unk_token,
            sep_token=sep_token,
            pad_token=pad_token,
            cls_token=cls_token,
            mask_token=mask_token,
            tokenize_chinese_chars=tokenize_chinese_chars,
            strip_accents=strip_accents,
            **kwargs,
        )

        normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
        if (
            normalizer_state.get("lowercase", do_lower_case) != do_lower_case
            or normalizer_state.get("strip_accents", strip_accents) != strip_accents
            or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
        ):
            normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
            normalizer_state["lowercase"] = do_lower_case
            normalizer_state["strip_accents"] = strip_accents
            normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
            self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)

        self.do_lower_case = do_lower_case

    def batch_encode_candidates(self, text, **kwargs):
        r

        
        kwargs["padding"] = PaddingStrategy.MAX_LENGTH

        batch_text = text
        batch_text_pair = kwargs.pop("text_pair", None)
        return_tensors = kwargs.pop("return_tensors", None)

        output_data = {
            "input_ids": [],
            "attention_mask": [],
            "token_type_ids": [],
        }

        for idx, candidate_text in enumerate(batch_text):
            if batch_text_pair is not None:
                candidate_text_pair = batch_text_pair[idx]
            else:
                candidate_text_pair = None

            encoded_candidates = super().__call__(candidate_text, candidate_text_pair, return_tensors=None, **kwargs)

            encoded_input_ids = encoded_candidates.get("input_ids")
            encoded_attention_mask = encoded_candidates.get("attention_mask")
            encoded_token_type_ids = encoded_candidates.get("token_type_ids")

            if encoded_input_ids is not None:
                output_data["input_ids"].append(encoded_input_ids)
            if encoded_attention_mask is not None:
                output_data["attention_mask"].append(encoded_attention_mask)
            if encoded_token_type_ids is not None:
                output_data["token_type_ids"].append(encoded_token_type_ids)

        output_data = {key: item for key, item in output_data.items() if len(item) != 0}

        return BatchEncoding(output_data, tensor_type=return_tensors)

    def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
        
        output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]

        if token_ids_1 is not None:
            output += token_ids_1 + [self.sep_token_id]

        return output

    def create_token_type_ids_from_sequences(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        
        sep = [self.sep_token_id]
        cls = [self.cls_token_id]
        if token_ids_1 is None:
            return len(cls + token_ids_0 + sep) * [0]
        return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        files = self._tokenizer.model.save(save_directory, name=filename_prefix)
        return tuple(files)