




import torch

from transformers import AutoModel




class    __lowerCAmelCase       (							torch.nn.Module):






       def __init__(   self:					Tuple       ,					_lowerCAmelCase:					List[Any]="sayef/fsner-bert-base-uncased"				):
         super(__a       ,					self				).__init__()

         lowercase    :Union[str, Any]      	=						AutoModel.from_pretrained(__a       ,					return_dict=__a				)
         lowercase    :Optional[Any]      	=						torch.nn.CosineSimilarity(3       ,					1e-0_8				)
         lowercase    :Optional[Any]      	=						torch.nn.Softmax(dim=1				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]       ,					**_lowerCAmelCase:					Optional[int]				):
         return self.bert(**__a				).last_hidden_state






       def 					SCREAMING_SNAKE_CASE    (   self:					Union[str, Any]       ,					_lowerCAmelCase:					Any				):
         return token_embeddings.sum(2       ,					keepdim=__a				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]       ,					_lowerCAmelCase:					List[Any]       ,					_lowerCAmelCase:					List[Any]       ,					_lowerCAmelCase:					int=1				):
         return self.softmax(T * self.cos(__a       ,					__a				)				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]       ,					_lowerCAmelCase:					Optional[int]       ,					_lowerCAmelCase:					Dict				):
         lowercase    :str      	=						W_supports["sizes"].tolist()
         lowercase    :Union[str, Any]      	=						W_supports["start_token_id"].item()
         lowercase    :Tuple      	=						W_supports["end_token_id"].item()

         del W_supports["sizes"]
         del W_supports["start_token_id"]
         del W_supports["end_token_id"]

         lowercase    :List[str]      	=						self.BERT(**__a				)
         lowercase    :int      	=						self.BERT(**__a				)

         lowercase    :Dict      	=						None
         lowercase    :int      	=						None

         lowercase    :Tuple      	=						W_supports["input_ids"] == start_token_id
         lowercase    :Optional[Any]      	=						W_supports["input_ids"] == end_token_id

         for i, size in enumerate(__a				):
           if i == 0:
             lowercase    :Dict      	=						0
           else:
             lowercase    :Tuple      	=						support_sizes[i - 1]

           lowercase    :Dict      	=						S[s : s + size][start_token_masks[s : s + size]]
           lowercase    :str      	=						S[s : s + size][end_token_masks[s : s + size]]

           lowercase    :Optional[int]      	=						torch.matmul(q[i]       ,					s_start.T				).sum(1				).softmax(0				)
           lowercase    :str      	=						torch.matmul(q[i]       ,					s_end.T				).sum(1				).softmax(0				)

           if p_starts is not None:
             lowercase    :Any      	=						torch.vstack((p_starts, p_start)				)
             lowercase    :Union[str, Any]      	=						torch.vstack((p_ends, p_end)				)
           else:
             lowercase    :List[str]      	=						p_start
             lowercase    :Dict      	=						p_end

         return p_starts, p_ends









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


_UpperCAmelCase	:						Optional[int]			=     logging.get_logger(__name__)

_UpperCAmelCase	:						Union[str, Any]			=     {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

_UpperCAmelCase	:						Optional[Any]			=     {
    "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"
        ),
    },
}

_UpperCAmelCase	:						Tuple			=     {
    "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,
}

_UpperCAmelCase	:						Dict			=     {
    "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    __lowerCAmelCase       (							lowerCAmelCase):
       _a 					=						VOCAB_FILES_NAMES
       _a 					=						PRETRAINED_VOCAB_FILES_MAP
       _a 					=						PRETRAINED_INIT_CONFIGURATION
       _a 					=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       _a 					=						RealmTokenizer






       def __init__(   self:					Tuple       ,					_lowerCAmelCase:					int=None       ,					_lowerCAmelCase:					List[Any]=None       ,					_lowerCAmelCase:					Optional[int]=True       ,					_lowerCAmelCase:					Optional[Any]="[UNK]"       ,					_lowerCAmelCase:					Dict="[SEP]"       ,					_lowerCAmelCase:					List[str]="[PAD]"       ,					_lowerCAmelCase:					Optional[int]="[CLS]"       ,					_lowerCAmelCase:					List[Any]="[MASK]"       ,					_lowerCAmelCase:					Tuple=True       ,					_lowerCAmelCase:					Tuple=None       ,					**_lowerCAmelCase:					Union[str, Any]       ,					):
         super().__init__(
             _lowerCAmelCase       ,					tokenizer_file=_lowerCAmelCase       ,					do_lower_case=_lowerCAmelCase       ,					unk_token=_lowerCAmelCase       ,					sep_token=_lowerCAmelCase       ,					pad_token=_lowerCAmelCase       ,					cls_token=_lowerCAmelCase       ,					mask_token=_lowerCAmelCase       ,					tokenize_chinese_chars=_lowerCAmelCase       ,					strip_accents=_lowerCAmelCase       ,					**_lowerCAmelCase       ,					)

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

         lowercase    :Any      	=						do_lower_case






       def 					SCREAMING_SNAKE_CASE    (   self:					Any       ,					_lowerCAmelCase:					Optional[Any]       ,					**_lowerCAmelCase:					Optional[int]				):
         lowercase    :List[str]      	=						PaddingStrategy.MAX_LENGTH

         lowercase    :Optional[Any]      	=						text
         lowercase    :str      	=						kwargs.pop("text_pair"       ,					_lowerCAmelCase				)
         lowercase    :Any      	=						kwargs.pop("return_tensors"       ,					_lowerCAmelCase				)

         lowercase    :List[str]      	=						{
             "input_ids": [],
             "attention_mask": [],
             "token_type_ids": [],
         }

         for idx, candidate_text in enumerate(_lowerCAmelCase				):
           if batch_text_pair is not None:
             lowercase    :Any      	=						batch_text_pair[idx]
           else:
             lowercase    :Optional[Any]      	=						None

           lowercase    :Optional[Any]      	=						super().__call__(_lowerCAmelCase       ,					_lowerCAmelCase       ,					return_tensors=_lowerCAmelCase       ,					**_lowerCAmelCase				)

           lowercase    :Tuple      	=						encoded_candidates.get("input_ids"				)
           lowercase    :Optional[Any]      	=						encoded_candidates.get("attention_mask"				)
           lowercase    :int      	=						encoded_candidates.get("token_type_ids"				)

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

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

         return BatchEncoding(_lowerCAmelCase       ,					tensor_type=_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Any       ,					_lowerCAmelCase:					Any       ,					_lowerCAmelCase:					Tuple=None				):
         lowercase    :Dict      	=						[self.cls_token_id] + token_ids_a + [self.sep_token_id]

         if token_ids_a:
           output += token_ids_a + [self.sep_token_id]

         return output






       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple       ,					_lowerCAmelCase:					List[int]       ,					_lowerCAmelCase:					Optional[List[int]] = None				):
         lowercase    :List[str]      	=						[self.sep_token_id]
         lowercase    :List[Any]      	=						[self.cls_token_id]
         if token_ids_a is None:
           return len(cls + token_ids_a + sep				) * [0]
         return len(cls + token_ids_a + sep				) * [0] + len(token_ids_a + sep				) * [1]






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]       ,					_lowerCAmelCase:					str       ,					_lowerCAmelCase:					Optional[str] = None				):
         lowercase    :Tuple      	=						self._tokenizer.model.save(_lowerCAmelCase       ,					name=_lowerCAmelCase				)
         return tuple(_lowerCAmelCase				)



