






import tensorflow as tf

from ...tf_utils import shape_list


class 						_a       (  tf.keras.layers.Layer    ):






  """simple docstring"""





  def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase=1		,		_UpperCAmelCase=False		,		**_UpperCAmelCase )			-> Dict:
     super().__init__(**_UpperCAmelCase )

     UpperCamelCase_									=     vocab_size
     UpperCamelCase_									=     d_embed
     UpperCamelCase_									=     d_proj

     UpperCamelCase_									=     cutoffs + [vocab_size]
     UpperCamelCase_									=     [0] + self.cutoffs
     UpperCamelCase_									=     div_val

     UpperCamelCase_									=     self.cutoffs[0]
     UpperCamelCase_									=     len(self.cutoffs ) - 1
     UpperCamelCase_									=     self.shortlist_size + self.n_clusters
     UpperCamelCase_									=     keep_order

     UpperCamelCase_									=     []
     UpperCamelCase_									=     []




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> str:
     if self.n_clusters > 0:
        UpperCamelCase_									=     self.add_weight(
            shape=(self.n_clusters, self.d_embed)		,		initializer='zeros'		,		trainable=_UpperCAmelCase		,		name='cluster_weight' )
        UpperCamelCase_									=     self.add_weight(
            shape=(self.n_clusters,)		,		initializer='zeros'		,		trainable=_UpperCAmelCase		,		name='cluster_bias' )

     if self.div_val == 1:
        for i in range(len(self.cutoffs ) ):
           if self.d_proj != self.d_embed:
              UpperCamelCase_									=     self.add_weight(
                  shape=(self.d_embed, self.d_proj)		,		initializer='zeros'		,		trainable=_UpperCAmelCase		,		name=f"""out_projs_._{i}"""		,		)
              self.out_projs.append(_UpperCAmelCase )
           else:
              self.out_projs.append(_UpperCAmelCase )
           UpperCamelCase_									=     self.add_weight(
               shape=(self.vocab_size, self.d_embed)		,		initializer='zeros'		,		trainable=_UpperCAmelCase		,		name=f"""out_layers_._{i}_._weight"""		,		)
           UpperCamelCase_									=     self.add_weight(
               shape=(self.vocab_size,)		,		initializer='zeros'		,		trainable=_UpperCAmelCase		,		name=f"""out_layers_._{i}_._bias"""		,		)
           self.out_layers.append((weight, bias) )
     else:
        for i in range(len(self.cutoffs ) ):
           UpperCamelCase_		,      UpperCamelCase_									=     self.cutoff_ends[i], self.cutoff_ends[i + 1]
           UpperCamelCase_									=     self.d_embed // (self.div_val**i)

           UpperCamelCase_									=     self.add_weight(
               shape=(d_emb_i, self.d_proj)		,		initializer='zeros'		,		trainable=_UpperCAmelCase		,		name=f"""out_projs_._{i}""" )
           self.out_projs.append(_UpperCAmelCase )
           UpperCamelCase_									=     self.add_weight(
               shape=(r_idx - l_idx, d_emb_i)		,		initializer='zeros'		,		trainable=_UpperCAmelCase		,		name=f"""out_layers_._{i}_._weight"""		,		)
           UpperCamelCase_									=     self.add_weight(
               shape=(r_idx - l_idx,)		,		initializer='zeros'		,		trainable=_UpperCAmelCase		,		name=f"""out_layers_._{i}_._bias"""		,		)
           self.out_layers.append((weight, bias) )
     super().build(_UpperCAmelCase )




  @staticmethod
  def    _UpperCAmelCase     (     _UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase=None )			-> Optional[Any]:
     UpperCamelCase_									=     x
     if proj is not None:
        UpperCamelCase_									=     tf.einsum('ibd,ed->ibe'		,		_UpperCAmelCase		,		_UpperCAmelCase )
     return tf.einsum('ibd,nd->ibn'		,		_UpperCAmelCase		,		_UpperCAmelCase ) + b




  @staticmethod
  def    _UpperCAmelCase     (     _UpperCAmelCase		,		_UpperCAmelCase )			-> List[Any]:
     UpperCamelCase_									=     shape_list(_UpperCAmelCase )
     UpperCamelCase_									=     tf.range(lp_size[0]		,		dtype=target.dtype )
     UpperCamelCase_									=     tf.stack([r, target]		,		1 )
     return tf.gather_nd(_UpperCAmelCase		,		_UpperCAmelCase )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase=True		,		_UpperCAmelCase=False )			-> Optional[Any]:
     UpperCamelCase_									=     0
     if self.n_clusters == 0:
        UpperCamelCase_									=     self._logit(_UpperCAmelCase		,		self.out_layers[0][0]		,		self.out_layers[0][1]		,		self.out_projs[0] )
        if target is not None:
           UpperCamelCase_									=     tf.nn.sparse_softmax_cross_entropy_with_logits(labels=_UpperCAmelCase		,		logits=_UpperCAmelCase )
        UpperCamelCase_									=     tf.nn.log_softmax(_UpperCAmelCase		,		axis=-1 )
     else:
        UpperCamelCase_									=     shape_list(_UpperCAmelCase )
        UpperCamelCase_									=     []
        UpperCamelCase_									=     tf.zeros(hidden_sizes[:2] )
        for i in range(len(self.cutoffs ) ):
           UpperCamelCase_		,      UpperCamelCase_									=     self.cutoff_ends[i], self.cutoff_ends[i + 1]
           if target is not None:
              UpperCamelCase_									=     (target >= l_idx) & (target < r_idx)
              UpperCamelCase_									=     tf.where(_UpperCAmelCase )
              UpperCamelCase_									=     tf.boolean_mask(_UpperCAmelCase		,		_UpperCAmelCase ) - l_idx

           if self.div_val == 1:
              UpperCamelCase_									=     self.out_layers[0][0][l_idx:r_idx]
              UpperCamelCase_									=     self.out_layers[0][1][l_idx:r_idx]
           else:
              UpperCamelCase_									=     self.out_layers[i][0]
              UpperCamelCase_									=     self.out_layers[i][1]

           if i == 0:
              UpperCamelCase_									=     tf.concat([cur_W, self.cluster_weight]		,		0 )
              UpperCamelCase_									=     tf.concat([cur_b, self.cluster_bias]		,		0 )

              UpperCamelCase_									=     self._logit(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		self.out_projs[0] )
              UpperCamelCase_									=     tf.nn.log_softmax(_UpperCAmelCase )
              out.append(head_logprob[..., : self.cutoffs[0]] )
              if target is not None:
                 UpperCamelCase_									=     tf.boolean_mask(_UpperCAmelCase		,		_UpperCAmelCase )
                 UpperCamelCase_									=     self._gather_logprob(_UpperCAmelCase		,		_UpperCAmelCase )
           else:
              UpperCamelCase_									=     self._logit(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		self.out_projs[i] )
              UpperCamelCase_									=     tf.nn.log_softmax(_UpperCAmelCase )
              UpperCamelCase_									=     self.cutoffs[0] + i - 1  # No probability for the head cluster
              UpperCamelCase_									=     head_logprob[..., cluster_prob_idx, None] + tail_logprob
              out.append(_UpperCAmelCase )
              if target is not None:
                 UpperCamelCase_									=     tf.boolean_mask(_UpperCAmelCase		,		_UpperCAmelCase )
                 UpperCamelCase_									=     tf.boolean_mask(_UpperCAmelCase		,		_UpperCAmelCase )
                 UpperCamelCase_									=     self._gather_logprob(_UpperCAmelCase		,		_UpperCAmelCase )
                 cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
           if target is not None:
              loss += tf.scatter_nd(_UpperCAmelCase		,		-cur_logprob		,		shape_list(_UpperCAmelCase ) )
        UpperCamelCase_									=     tf.concat(_UpperCAmelCase		,		axis=-1 )

     if target is not None:
        if return_mean:
           UpperCamelCase_									=     tf.reduce_mean(_UpperCAmelCase )
        # Add the training-time loss value to the layer using `self.add_loss()`.
        self.add_loss(_UpperCAmelCase )

        # Log the loss as a metric (we could log arbitrary metrics,
        # including different metrics for training and inference.
        self.add_metric(_UpperCAmelCase		,		name=self.name		,		aggregation='mean' if return_mean else '' )

     return out













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


snake_case__      :	List[str]       	=      logging.get_logger(__name__)

snake_case__      :	Optional[int]       	=      {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

snake_case__      :	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"""
        ),
    },
}

snake_case__      :	List[str]       	=      {
    """google/realm-cc-news-pretrained-embedder""": 5_1_2,
    """google/realm-cc-news-pretrained-encoder""": 5_1_2,
    """google/realm-cc-news-pretrained-scorer""": 5_1_2,
    """google/realm-cc-news-pretrained-openqa""": 5_1_2,
    """google/realm-orqa-nq-openqa""": 5_1_2,
    """google/realm-orqa-nq-reader""": 5_1_2,
    """google/realm-orqa-wq-openqa""": 5_1_2,
    """google/realm-orqa-wq-reader""": 5_1_2,
}

snake_case__      :	Tuple       	=      {
    """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 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   VOCAB_FILES_NAMES
  A_						=   PRETRAINED_VOCAB_FILES_MAP
  A_						=   PRETRAINED_INIT_CONFIGURATION
  A_						=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  A_						=   RealmTokenizer




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

     UpperCamelCase_									=     json.loads(self.backend_tokenizer.normalizer.__getstate__() )
     if (
         normalizer_state.get('lowercase'		,		_UpperCAmelCase ) != do_lower_case
         or normalizer_state.get('strip_accents'		,		_UpperCAmelCase ) != strip_accents
         or normalizer_state.get('handle_chinese_chars'		,		_UpperCAmelCase ) != tokenize_chinese_chars
     ):
        UpperCamelCase_									=     getattr(_UpperCAmelCase		,		normalizer_state.pop('type' ) )
        UpperCamelCase_									=     do_lower_case
        UpperCamelCase_									=     strip_accents
        UpperCamelCase_									=     tokenize_chinese_chars
        UpperCamelCase_									=     normalizer_class(**_UpperCAmelCase )

     UpperCamelCase_									=     do_lower_case




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		**_UpperCAmelCase )			-> List[Any]:
     UpperCamelCase_									=     PaddingStrategy.MAX_LENGTH

     UpperCamelCase_									=     text
     UpperCamelCase_									=     kwargs.pop('text_pair'		,		_UpperCAmelCase )
     UpperCamelCase_									=     kwargs.pop('return_tensors'		,		_UpperCAmelCase )

     UpperCamelCase_									=     {
         'input_ids': [],
         'attention_mask': [],
         'token_type_ids': [],
     }

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

        UpperCamelCase_									=     super().__call__(_UpperCAmelCase		,		_UpperCAmelCase		,		return_tensors=_UpperCAmelCase		,		**_UpperCAmelCase )

        UpperCamelCase_									=     encoded_candidates.get('input_ids' )
        UpperCamelCase_									=     encoded_candidates.get('attention_mask' )
        UpperCamelCase_									=     encoded_candidates.get('token_type_ids' )

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

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

     return BatchEncoding(_UpperCAmelCase		,		tensor_type=_UpperCAmelCase )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase=None )			-> Union[str, Any]:
     UpperCamelCase_									=     [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    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = None )			-> List[int]:
     UpperCamelCase_									=     [self.sep_token_id]
     UpperCamelCase_									=     [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    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = None )			-> Tuple[str]:
     UpperCamelCase_									=     self._tokenizer.model.save(_UpperCAmelCase		,		name=_UpperCAmelCase )
     return tuple(_UpperCAmelCase )





