

import tempfile
import unittest

import transformers
from transformers import XGLMConfig, XGLMTokenizer, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, require_sentencepiece, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
       import jax
       import jax.numpy as jnp
       import numpy as np

       from transformers.modeling_flax_pytorch_utils import (
           convert_pytorch_state_dict_to_flax,
           load_flax_weights_in_pytorch_model,
       )
       from transformers.models.xglm.modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel


if is_torch_available():
       import torch







@require_flax
class     a__    :







  """simple docstring"""




  def __init__(     self      :	int			,			UpperCAmelCase__      :	Tuple			,			UpperCAmelCase__      :	Optional[Any]=1_4			,			UpperCAmelCase__      :	Optional[int]=7			,			UpperCAmelCase__      :	Optional[Any]=True			,			UpperCAmelCase__      :	Tuple=True			,			UpperCAmelCase__      :	str=True			,			UpperCAmelCase__      :	Optional[int]=9_9			,			UpperCAmelCase__      :	List[str]=3_2			,			UpperCAmelCase__      :	int=5			,			UpperCAmelCase__      :	List[Any]=4			,			UpperCAmelCase__      :	Optional[Any]=3_7			,			UpperCAmelCase__      :	str="gelu"			,			UpperCAmelCase__      :	List[str]=0.1			,			UpperCAmelCase__      :	int=0.1			,			UpperCAmelCase__      :	str=5_1_2			,			UpperCAmelCase__      :	Optional[Any]=0.02			,			UpperCAmelCase__      :	List[Any]=None			,			)   ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				parent
        SCREAMING_SNAKE_CASE	: str					       =				batch_size
        SCREAMING_SNAKE_CASE	: Any					       =				seq_length
        SCREAMING_SNAKE_CASE	: Any					       =				is_training
        SCREAMING_SNAKE_CASE	: Tuple					       =				use_input_mask
        SCREAMING_SNAKE_CASE	: List[Any]					       =				use_labels
        SCREAMING_SNAKE_CASE	: List[Any]					       =				vocab_size
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				d_model
        SCREAMING_SNAKE_CASE	: List[str]					       =				num_hidden_layers
        SCREAMING_SNAKE_CASE	: List[Any]					       =				num_attention_heads
        SCREAMING_SNAKE_CASE	: List[Any]					       =				ffn_dim
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				activation_function
        SCREAMING_SNAKE_CASE	: int					       =				activation_dropout
        SCREAMING_SNAKE_CASE	: List[str]					       =				attention_dropout
        SCREAMING_SNAKE_CASE	: str					       =				max_position_embeddings
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				initializer_range
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				None
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				0
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				2
        SCREAMING_SNAKE_CASE	: int					       =				1


  def 	_lowercase (     self      :	int						)   ->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: int					       =				np.clip(ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size						)			,			3			,			self.vocab_size						)

        SCREAMING_SNAKE_CASE	: Optional[int]					       =				None
        if self.use_input_mask:
              SCREAMING_SNAKE_CASE	: Any					       =				random_attention_mask([self.batch_size, self.seq_length]						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				XGLMConfig(
            vocab_size=self.vocab_size			,			d_model=self.hidden_size			,			num_layers=self.num_hidden_layers			,			attention_heads=self.num_attention_heads			,			ffn_dim=self.ffn_dim			,			activation_function=self.activation_function			,			activation_dropout=self.activation_dropout			,			attention_dropout=self.attention_dropout			,			max_position_embeddings=self.max_position_embeddings			,			initializer_range=self.initializer_range			,			use_cache=UpperCAmelCase__			,			bos_token_id=self.bos_token_id			,			eos_token_id=self.eos_token_id			,			pad_token_id=self.pad_token_id			,			)

        return (config, input_ids, input_mask)


  def 	_lowercase (     self      :	Optional[Any]						)   ->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Tuple					       =				self.prepare_config_and_inputs()
        SCREAMING_SNAKE_CASE	: List[Any]					       =				config_and_inputs
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				{"""input_ids""": input_ids, """attention_mask""": attention_mask}
        return config, inputs_dict


  def 	_lowercase (     self      :	Any						)   ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Dict					       =				self.prepare_config_and_inputs()

        SCREAMING_SNAKE_CASE	: Optional[int]					       =				floats_tensor([self.batch_size, self.seq_length, self.hidden_size]						)
        SCREAMING_SNAKE_CASE	: Dict					       =				ids_tensor([self.batch_size, self.seq_length]			,			vocab_size=2						)

        return (
            config,
            input_ids,
            attention_mask,
            encoder_hidden_states,
            encoder_attention_mask,
        )


  def 	_lowercase (     self      :	List[Any]			,			UpperCAmelCase__      :	Optional[int]			,			UpperCAmelCase__      :	int			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	Any						)   ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Tuple					       =				2_0
        SCREAMING_SNAKE_CASE	: List[Any]					       =				model_class_name(UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				model.init_cache(input_ids.shape[0]			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Tuple					       =				jnp.ones((input_ids.shape[0], max_decoder_length)			,			dtype="""i4"""						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				jnp.broadcast_to(
            jnp.arange(input_ids.shape[-1] - 1						)[None, :]			,			(input_ids.shape[0], input_ids.shape[-1] - 1)						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				model(
            input_ids[:, :-1]			,			attention_mask=UpperCAmelCase__			,			past_key_values=UpperCAmelCase__			,			position_ids=UpperCAmelCase__			,			)

        SCREAMING_SNAKE_CASE	: Tuple					       =				jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]			,			dtype="""i4"""						)
        SCREAMING_SNAKE_CASE	: Dict					       =				model(
            input_ids[:, -1:]			,			attention_mask=UpperCAmelCase__			,			past_key_values=outputs_cache.past_key_values			,			position_ids=UpperCAmelCase__			,			)

        SCREAMING_SNAKE_CASE	: Any					       =				model(UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: str					       =				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])						)						)
        self.parent.assertTrue(diff < 1e-3			,			msg=f"Max diff is {diff}"						)




  def 	_lowercase (     self      :	int			,			UpperCAmelCase__      :	int			,			UpperCAmelCase__      :	List[str]			,			UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	Optional[Any]						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Any					       =				2_0
        SCREAMING_SNAKE_CASE	: int					       =				model_class_name(UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: int					       =				jnp.concatenate(
            [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])						)]			,			axis=-1			,			)

        SCREAMING_SNAKE_CASE	: List[Any]					       =				model.init_cache(input_ids.shape[0]			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: str					       =				jnp.broadcast_to(
            jnp.arange(input_ids.shape[-1] - 1						)[None, :]			,			(input_ids.shape[0], input_ids.shape[-1] - 1)						)

        SCREAMING_SNAKE_CASE	: Any					       =				model(
            input_ids[:, :-1]			,			attention_mask=UpperCAmelCase__			,			past_key_values=UpperCAmelCase__			,			position_ids=UpperCAmelCase__			,			)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]			,			dtype="""i4"""						)
        SCREAMING_SNAKE_CASE	: str					       =				model(
            input_ids[:, -1:]			,			past_key_values=outputs_cache.past_key_values			,			attention_mask=UpperCAmelCase__			,			position_ids=UpperCAmelCase__			,			)

        SCREAMING_SNAKE_CASE	: List[Any]					       =				model(UpperCAmelCase__			,			attention_mask=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])						)						)
        self.parent.assertTrue(diff < 1e-3			,			msg=f"Max diff is {diff}"						)







@require_sentencepiece
@require_flax
class     a__    (				UpperCAmelCase		,     UpperCAmelCase		,     unittest.TestCase    ):







  """simple docstring"""




  UpperCAmelCase__ :	Union[str, Any]         =(FlaxXGLMModel, FlaxXGLMForCausalLM) if is_flax_available() else ()
  UpperCAmelCase__ :	List[str]         =(FlaxXGLMForCausalLM,) if is_flax_available() else ()


  def 	_lowercase (     self      :	Tuple						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Any					       =				FlaxXGLMModelTester(self						)


  def 	_lowercase (     self      :	List[str]						)   ->Optional[Any]:
        """simple docstring"""







        for model_class_name in self.all_model_classes:
              SCREAMING_SNAKE_CASE	: Dict					       =				self.model_tester.prepare_config_and_inputs()
              self.model_tester.check_use_cache_forward(UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						)


  def 	_lowercase (     self      :	str						)   ->Dict:
        """simple docstring"""







        for model_class_name in self.all_model_classes:
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				self.model_tester.prepare_config_and_inputs()
              self.model_tester.check_use_cache_forward_with_attn_mask(
                  UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						)


  @slow
  def 	_lowercase (     self      :	List[str]						)   ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[int]					       =				XGLMTokenizer.from_pretrained("""XGLM"""			,			padding_side="""left"""						)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				tokenizer(["""Hello this is a long string""", """Hey"""]			,			return_tensors="""np"""			,			padding=UpperCAmelCase__			,			truncation=UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: Dict					       =				FlaxXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""						)
        SCREAMING_SNAKE_CASE	: int					       =				1
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				False

        SCREAMING_SNAKE_CASE	: Any					       =				jax.jit(model.generate						)

        SCREAMING_SNAKE_CASE	: Any					       =				jit_generate(inputs["""input_ids"""]			,			attention_mask=inputs["""attention_mask"""]						).sequences

        SCREAMING_SNAKE_CASE	: Tuple					       =				tokenizer.batch_decode(UpperCAmelCase__			,			skip_special_tokens=UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: int					       =				[
            """Hello this is a long string of questions, but I'm not sure if I'm""",
            """Hey, I'm a newbie to the forum and I'""",
        ]

        self.assertListEqual(UpperCAmelCase__			,			UpperCAmelCase__						)


  @is_pt_flax_cross_test
  def 	_lowercase (     self      :	Optional[int]						)   ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: List[str]					       =				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__						):
                    # prepare inputs
                    SCREAMING_SNAKE_CASE	: Any					       =				self._prepare_for_class(UpperCAmelCase__			,			UpperCAmelCase__						)
                    SCREAMING_SNAKE_CASE	: List[str]					       =				{k: torch.tensor(v.tolist()						) for k, v in prepared_inputs_dict.items()}

                    # load corresponding PyTorch class
                    SCREAMING_SNAKE_CASE	: str					       =				model_class.__name__[4:]  # Skip the "Flax" at the beginning
                    SCREAMING_SNAKE_CASE	: Any					       =				getattr(UpperCAmelCase__			,			UpperCAmelCase__						)

                    SCREAMING_SNAKE_CASE	: str					       =				pt_inputs["""input_ids"""].shape
                    SCREAMING_SNAKE_CASE	: Dict					       =				np.random.randint(0			,			seq_length - 1			,			size=(batch_size,)						)
                    for batch_idx, start_index in enumerate(UpperCAmelCase__						):
                          SCREAMING_SNAKE_CASE	: int					       =				0
                          SCREAMING_SNAKE_CASE	: Optional[Any]					       =				1
                          SCREAMING_SNAKE_CASE	: Dict					       =				0
                          SCREAMING_SNAKE_CASE	: Tuple					       =				1
                    SCREAMING_SNAKE_CASE	: Tuple					       =				pt_model_class(UpperCAmelCase__						).eval()
                    # Flax models don't use the `use_cache` option and cache is not returned as a default.
                    # So we disable `use_cache` here for PyTorch model.
                    SCREAMING_SNAKE_CASE	: Optional[Any]					       =				False
                    SCREAMING_SNAKE_CASE	: List[str]					       =				model_class(UpperCAmelCase__			,			dtype=jnp.floataa						)
                    SCREAMING_SNAKE_CASE	: Optional[int]					       =				convert_pytorch_state_dict_to_flax(pt_model.state_dict()			,			UpperCAmelCase__						)
                    SCREAMING_SNAKE_CASE	: List[str]					       =				fx_state

                    with torch.no_grad():
                          SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				pt_model(**UpperCAmelCase__						).to_tuple()

                    SCREAMING_SNAKE_CASE	: str					       =				fx_model(**UpperCAmelCase__						).to_tuple()
                    self.assertEqual(len(UpperCAmelCase__						)			,			len(UpperCAmelCase__						)			,			"""Output lengths differ between Flax and PyTorch"""						)
                    for fx_output, pt_output in zip(UpperCAmelCase__			,			UpperCAmelCase__						):
                          self.assert_almost_equals(fx_output[:, -1]			,			pt_output[:, -1].numpy()			,			4e-2						)

                    with tempfile.TemporaryDirectory() as tmpdirname:
                          pt_model.save_pretrained(UpperCAmelCase__						)
                          SCREAMING_SNAKE_CASE	: Optional[Any]					       =				model_class.from_pretrained(UpperCAmelCase__			,			from_pt=UpperCAmelCase__						)

                    SCREAMING_SNAKE_CASE	: str					       =				fx_model_loaded(**UpperCAmelCase__						).to_tuple()
                    self.assertEqual(
                        len(UpperCAmelCase__						)			,			len(UpperCAmelCase__						)			,			"""Output lengths differ between Flax and PyTorch"""						)
                    for fx_output_loaded, pt_output in zip(UpperCAmelCase__			,			UpperCAmelCase__						):
                          self.assert_almost_equals(fx_output_loaded[:, -1]			,			pt_output[:, -1].numpy()			,			4e-2						)


  @is_pt_flax_cross_test
  def 	_lowercase (     self      :	Dict						)   ->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: int					       =				self.model_tester.prepare_config_and_inputs_for_common()
        for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__						):
                    # prepare inputs
                    SCREAMING_SNAKE_CASE	: Tuple					       =				self._prepare_for_class(UpperCAmelCase__			,			UpperCAmelCase__						)
                    SCREAMING_SNAKE_CASE	: str					       =				{k: torch.tensor(v.tolist()						) for k, v in prepared_inputs_dict.items()}

                    # load corresponding PyTorch class
                    SCREAMING_SNAKE_CASE	: int					       =				model_class.__name__[4:]  # Skip the "Flax" at the beginning
                    SCREAMING_SNAKE_CASE	: int					       =				getattr(UpperCAmelCase__			,			UpperCAmelCase__						)

                    SCREAMING_SNAKE_CASE	: Dict					       =				pt_model_class(UpperCAmelCase__						).eval()
                    SCREAMING_SNAKE_CASE	: Tuple					       =				False
                    SCREAMING_SNAKE_CASE	: Tuple					       =				model_class(UpperCAmelCase__			,			dtype=jnp.floataa						)

                    SCREAMING_SNAKE_CASE	: int					       =				load_flax_weights_in_pytorch_model(UpperCAmelCase__			,			fx_model.params						)
                    SCREAMING_SNAKE_CASE	: str					       =				pt_inputs["""input_ids"""].shape
                    SCREAMING_SNAKE_CASE	: List[str]					       =				np.random.randint(0			,			seq_length - 1			,			size=(batch_size,)						)
                    for batch_idx, start_index in enumerate(UpperCAmelCase__						):
                          SCREAMING_SNAKE_CASE	: Tuple					       =				0
                          SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				1
                          SCREAMING_SNAKE_CASE	: int					       =				0
                          SCREAMING_SNAKE_CASE	: Optional[Any]					       =				1

                    # make sure weights are tied in PyTorch
                    pt_model.tie_weights()

                    with torch.no_grad():
                          SCREAMING_SNAKE_CASE	: Dict					       =				pt_model(**UpperCAmelCase__						).to_tuple()

                    SCREAMING_SNAKE_CASE	: List[str]					       =				fx_model(**UpperCAmelCase__						).to_tuple()
                    self.assertEqual(len(UpperCAmelCase__						)			,			len(UpperCAmelCase__						)			,			"""Output lengths differ between Flax and PyTorch"""						)
                    for fx_output, pt_output in zip(UpperCAmelCase__			,			UpperCAmelCase__						):
                          self.assert_almost_equals(fx_output[:, -1]			,			pt_output[:, -1].numpy()			,			4e-2						)

                    with tempfile.TemporaryDirectory() as tmpdirname:
                          fx_model.save_pretrained(UpperCAmelCase__						)
                          SCREAMING_SNAKE_CASE	: List[str]					       =				pt_model_class.from_pretrained(UpperCAmelCase__			,			from_flax=UpperCAmelCase__						)

                    with torch.no_grad():
                          SCREAMING_SNAKE_CASE	: Optional[Any]					       =				pt_model_loaded(**UpperCAmelCase__						).to_tuple()

                    self.assertEqual(
                        len(UpperCAmelCase__						)			,			len(UpperCAmelCase__						)			,			"""Output lengths differ between Flax and PyTorch"""						)
                    for fx_output, pt_output in zip(UpperCAmelCase__			,			UpperCAmelCase__						):
                          self.assert_almost_equals(fx_output[:, -1]			,			pt_output[:, -1].numpy()			,			4e-2						)




  @slow
  def 	_lowercase (     self      :	Optional[int]						)   ->Optional[Any]:
        """simple docstring"""







        for model_class_name in self.all_model_classes:
              SCREAMING_SNAKE_CASE	: int					       =				model_class_name.from_pretrained("""facebook/xglm-564M"""						)
              SCREAMING_SNAKE_CASE	: List[Any]					       =				model(np.ones((1, 1)						)						)
              self.assertIsNotNone(UpperCAmelCase__						)







import os
from typing import List, Union

import tensorflow as tf
from tensorflow_text import BertTokenizer as BertTokenizerLayer
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utfa, combine_segments, pad_model_inputs

from .tokenization_bert import BertTokenizer







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







  """simple docstring"""




  def __init__(     self      :	str			,			UpperCAmelCase__      :	List			,			UpperCAmelCase__      :	bool			,			UpperCAmelCase__      :	int = None			,			UpperCAmelCase__      :	int = None			,			UpperCAmelCase__      :	int = None			,			UpperCAmelCase__      :	str = "longest"			,			UpperCAmelCase__      :	bool = True			,			UpperCAmelCase__      :	int = 5_1_2			,			UpperCAmelCase__      :	int = None			,			UpperCAmelCase__      :	bool = True			,			UpperCAmelCase__      :	bool = True			,			UpperCAmelCase__      :	bool = True			,			**UpperCAmelCase__      :	Optional[int]			,			)   ->Union[str, Any]:
        """simple docstring"""







        super().__init__()
        if use_fast_bert_tokenizer:
              SCREAMING_SNAKE_CASE	: Any					       =				FastBertTokenizer(
                  UpperCAmelCase__			,			token_out_type=tf.intaa			,			lower_case_nfd_strip_accents=UpperCAmelCase__			,			**UpperCAmelCase__						)
        else:
              SCREAMING_SNAKE_CASE	: Any					       =				tf.lookup.StaticVocabularyTable(
                  tf.lookup.KeyValueTensorInitializer(
                      keys=UpperCAmelCase__			,			key_dtype=tf.string			,			values=tf.range(tf.size(UpperCAmelCase__			,			out_type=tf.intaa						)			,			dtype=tf.intaa						)			,			value_dtype=tf.intaa			,			)			,			num_oov_buckets=1			,			)
              SCREAMING_SNAKE_CASE	: Dict					       =				BertTokenizerLayer(
                  UpperCAmelCase__			,			token_out_type=tf.intaa			,			lower_case=UpperCAmelCase__			,			**UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: Any					       =				vocab_list
        SCREAMING_SNAKE_CASE	: int					       =				do_lower_case
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				cls_token_id or vocab_list.index("""[CLS]"""						)
        SCREAMING_SNAKE_CASE	: int					       =				sep_token_id or vocab_list.index("""[SEP]"""						)
        SCREAMING_SNAKE_CASE	: int					       =				pad_token_id or vocab_list.index("""[PAD]"""						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				ShrinkLongestTrimmer(max_length - 3			,			axis=1						)  # Allow room for special tokens
        SCREAMING_SNAKE_CASE	: Tuple					       =				max_length
        SCREAMING_SNAKE_CASE	: List[str]					       =				padding
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				truncation
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				pad_to_multiple_of
        SCREAMING_SNAKE_CASE	: Dict					       =				return_token_type_ids
        SCREAMING_SNAKE_CASE	: str					       =				return_attention_mask


  @classmethod
  def 	_lowercase (     cls      :	Optional[int]			,			UpperCAmelCase__      :	"PreTrainedTokenizerBase"			,			**UpperCAmelCase__      :	Tuple						)   ->str:  # noqa: F821
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Any					       =				kwargs.pop("""do_lower_case"""			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				tokenizer.do_lower_case if do_lower_case is None else do_lower_case
        SCREAMING_SNAKE_CASE	: Any					       =				kwargs.pop("""cls_token_id"""			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Any					       =				tokenizer.cls_token_id if cls_token_id is None else cls_token_id
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				kwargs.pop("""sep_token_id"""			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				tokenizer.sep_token_id if sep_token_id is None else sep_token_id
        SCREAMING_SNAKE_CASE	: int					       =				kwargs.pop("""pad_token_id"""			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Any					       =				tokenizer.pad_token_id if pad_token_id is None else pad_token_id

        SCREAMING_SNAKE_CASE	: List[str]					       =				tokenizer.get_vocab()
        SCREAMING_SNAKE_CASE	: List[str]					       =				sorted([(wordpiece, idx) for wordpiece, idx in vocab.items()]			,			key=lambda UpperCAmelCase__						: x[1]						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				[entry[0] for entry in vocab]
        return cls(
            vocab_list=UpperCAmelCase__			,			do_lower_case=UpperCAmelCase__			,			cls_token_id=UpperCAmelCase__			,			sep_token_id=UpperCAmelCase__			,			pad_token_id=UpperCAmelCase__			,			**UpperCAmelCase__			,			)


  @classmethod
  def 	_lowercase (     cls      :	str			,			UpperCAmelCase__      :	Union[str, os.PathLike]			,			*UpperCAmelCase__      :	Dict			,			**UpperCAmelCase__      :	int						)   ->Any:
        """simple docstring"""







        try:
              SCREAMING_SNAKE_CASE	: List[str]					       =				BertTokenizer.from_pretrained(UpperCAmelCase__			,			*UpperCAmelCase__			,			**UpperCAmelCase__						)
        except:  # noqa: E722
              from .tokenization_bert_fast import BertTokenizerFast

              SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				BertTokenizerFast.from_pretrained(UpperCAmelCase__			,			*UpperCAmelCase__			,			**UpperCAmelCase__						)
        return cls.from_tokenizer(UpperCAmelCase__			,			**UpperCAmelCase__						)


  def 	_lowercase (     self      :	Tuple			,			UpperCAmelCase__      :	List[str]						)   ->List[str]:
        """simple docstring"""







        if self.do_lower_case:
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				case_fold_utfa(UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: int					       =				self.tf_tokenizer.tokenize(UpperCAmelCase__						)
        return tokens.merge_dims(1			,			-1						)


  def 	_lowercase (     self      :	Tuple			,			UpperCAmelCase__      :	Any			,			UpperCAmelCase__      :	Dict=None			,			UpperCAmelCase__      :	Optional[int]=None			,			UpperCAmelCase__      :	Optional[Any]=None			,			UpperCAmelCase__      :	Union[str, Any]=None			,			UpperCAmelCase__      :	Dict=None			,			UpperCAmelCase__      :	int=None			,			UpperCAmelCase__      :	Tuple=None			,			)   ->Any:
        """simple docstring"""







        if padding is None:
              SCREAMING_SNAKE_CASE	: int					       =				self.padding
        if padding not in ("longest", "max_length"):
              raise ValueError("""Padding must be either 'longest' or 'max_length'!"""						)
        if max_length is not None and text_pair is not None:
              # Because we have to instantiate a Trimmer to do it properly
              raise ValueError("""max_length cannot be overridden at call time when truncating paired texts!"""						)
        if max_length is None:
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				self.max_length
        if truncation is None:
              SCREAMING_SNAKE_CASE	: str					       =				self.truncation
        if pad_to_multiple_of is None:
              SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				self.pad_to_multiple_of
        if return_token_type_ids is None:
              SCREAMING_SNAKE_CASE	: Any					       =				self.return_token_type_ids
        if return_attention_mask is None:
              SCREAMING_SNAKE_CASE	: int					       =				self.return_attention_mask
        if not isinstance(UpperCAmelCase__			,			tf.Tensor						):
              SCREAMING_SNAKE_CASE	: str					       =				tf.convert_to_tensor(UpperCAmelCase__						)
        if text_pair is not None and not isinstance(UpperCAmelCase__			,			tf.Tensor						):
              SCREAMING_SNAKE_CASE	: int					       =				tf.convert_to_tensor(UpperCAmelCase__						)
        if text_pair is not None:
              if text.shape.rank > 1:
                    raise ValueError("""text argument should not be multidimensional when a text pair is supplied!"""						)
              if text_pair.shape.rank > 1:
                    raise ValueError("""text_pair should not be multidimensional!"""						)
        if text.shape.rank == 2:
              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Dict					       =				text[:, 0], text[:, 1]
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				self.unpaired_tokenize(UpperCAmelCase__						)
        if text_pair is None:  # Unpaired text
              if truncation:
                    SCREAMING_SNAKE_CASE	: int					       =				text[:, : max_length - 2]  # Allow room for special tokens
              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: List[str]					       =				combine_segments(
                  (text,)			,			start_of_sequence_id=self.cls_token_id			,			end_of_segment_id=self.sep_token_id						)
        else:  # Paired text
              SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				self.unpaired_tokenize(UpperCAmelCase__						)
              if truncation:
                    SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Any					       =				self.paired_trimmer.trim([text, text_pair]						)
              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: str					       =				combine_segments(
                  (text, text_pair)			,			start_of_sequence_id=self.cls_token_id			,			end_of_segment_id=self.sep_token_id						)
        if padding == "longest":
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				input_ids.bounding_shape(axis=1						)
              if pad_to_multiple_of is not None:
                    # No ceiling division in tensorflow, so we negate floordiv instead
                    SCREAMING_SNAKE_CASE	: Any					       =				pad_to_multiple_of * (-tf.math.floordiv(-pad_length			,			UpperCAmelCase__						))
        else:
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				max_length

        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Tuple					       =				pad_model_inputs(UpperCAmelCase__			,			max_seq_length=UpperCAmelCase__			,			pad_value=self.pad_token_id						)
        SCREAMING_SNAKE_CASE	: Any					       =				{"""input_ids""": input_ids}
        if return_attention_mask:
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				attention_mask
        if return_token_type_ids:
              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Optional[Any]					       =				pad_model_inputs(
                  UpperCAmelCase__			,			max_seq_length=UpperCAmelCase__			,			pad_value=self.pad_token_id						)
              SCREAMING_SNAKE_CASE	: List[str]					       =				token_type_ids
        return output




  def 	_lowercase (     self      :	Optional[int]						)   ->Tuple:
        """simple docstring"""







        return {
            "vocab_list": self.vocab_list,
            "do_lower_case": self.do_lower_case,
            "cls_token_id": self.cls_token_id,
            "sep_token_id": self.sep_token_id,
            "pad_token_id": self.pad_token_id,
        }




