



'''simple docstring'''





import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple

from transformers import AddedToken, BatchEncoding, ByTaTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


if is_torch_available():
     A_		:     Optional[int]        =     '''pt'''
elif is_tf_available():
     A_		:     Tuple        =     '''tf'''
else:
     A_		:     Optional[int]        =     '''jax'''



class 		_lowercase		(       __A,   unittest.TestCase	):
   _UpperCAmelCase     	=			ByTaTokenizer
   _UpperCAmelCase     	=			False

   def 		A							(      self			:       Union[str, Any]							)       ->				List[str]:


    """simple docstring"""






    super().setUp()
    a						=		ByTaTokenizer()
    tokenizer.save_pretrained(self.tmpdirname							)

   @cached_property
   def 		A							(      self			:       Optional[int]							)       ->				Union[str, Any]:


    """simple docstring"""






    return ByTaTokenizer.from_pretrained("google/byt5-small"							)

   def 		A							(      self			:       str							,   **__lowerCAmelCase			:       Any							)       ->				ByTaTokenizer:


    """simple docstring"""






    return self.tokenizer_class.from_pretrained(self.tmpdirname							,   **__lowerCAmelCase							)

   def 		A							(      self			:       str							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Tuple=False							,   __lowerCAmelCase			:       Optional[Any]=20							,   __lowerCAmelCase			:       Union[str, Any]=5							)       ->				Tuple[str, list]:


    """simple docstring"""






    a						=		[]
    for i in range(len(__lowerCAmelCase							)							):
     try:
      a						=		tokenizer.decode([i]							,   clean_up_tokenization_spaces=__lowerCAmelCase							)
     except UnicodeDecodeError:
      pass
     toks.append((i, tok)							)

    a						=		list(filter(lambda __lowerCAmelCase							: re.match(R"^[ a-zA-Z]+$"							,   t[1]							)							,   __lowerCAmelCase							)							)
    a						=		list(filter(lambda __lowerCAmelCase							: [t[0]] == tokenizer.encode(t[1]							,   add_special_tokens=__lowerCAmelCase							)							,   __lowerCAmelCase							)							)
    if max_length is not None and len(__lowerCAmelCase							) > max_length:
     a						=		toks[:max_length]
    if min_length is not None and len(__lowerCAmelCase							) < min_length and len(__lowerCAmelCase							) > 0:
     while len(__lowerCAmelCase							) < min_length:
      a						=		toks + toks
     # toks_str = [t[1] for t in toks]
    a						=		[t[0] for t in toks]

    # Ensure consistency
    a						=		tokenizer.decode(__lowerCAmelCase							,   clean_up_tokenization_spaces=__lowerCAmelCase							)
    if " " not in output_txt and len(__lowerCAmelCase							) > 1:
     a						=		(
         tokenizer.decode([toks_ids[0]]							,   clean_up_tokenization_spaces=__lowerCAmelCase							)
         + ''' '''
         + tokenizer.decode(toks_ids[1:]							,   clean_up_tokenization_spaces=__lowerCAmelCase							)
     )
    if with_prefix_space:
     a						=		''' ''' + output_txt
    a						=		tokenizer.encode(__lowerCAmelCase							,   add_special_tokens=__lowerCAmelCase							)
    return output_txt, output_ids

   def 		A							(      self			:       Optional[int]							)       ->				str:


    """simple docstring"""






    a						=		self.ta_base_tokenizer
    a						=		tokenizer(["hi</s>", "I went to the gym</s>", "</s>"]							)
    a						=		tokenizer(["hi", "I went to the gym", ""]							)
    self.assertListEqual(batch_with_eos_added["input_ids"]							,   batch_without_eos_added["input_ids"]							)

   def 		A							(      self			:       Dict							)       ->				List[Any]:


    """simple docstring"""






    a						=		self.ta_base_tokenizer
    a						=		'''Unicode €.'''
    a						=		tokenizer(__lowerCAmelCase							)
    a						=		[88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1]
    self.assertEqual(encoded["input_ids"]							,   __lowerCAmelCase							)

    # decoding
    a						=		tokenizer.decode(__lowerCAmelCase							)
    self.assertEqual(__lowerCAmelCase							,   "Unicode €.</s>"							)

    a						=		tokenizer("e è é ê ë"							)
    a						=		[104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1]
    self.assertEqual(encoded["input_ids"]							,   __lowerCAmelCase							)
    # decoding
    a						=		tokenizer.decode(__lowerCAmelCase							)
    self.assertEqual(__lowerCAmelCase							,   "e è é ê ë</s>"							)

    # encode/decode, but with `encode` instead of `__call__`
    self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë"							)							)							,   "e è é ê ë</s>"							)

   def 		A							(      self			:       Optional[int]							)       ->				str:


    """simple docstring"""






    a						=		self.ta_base_tokenizer
    a						=		['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
    # fmt: off
    a						=		[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0]
    # fmt: on
    a						=		tokenizer(__lowerCAmelCase							,   padding=__lowerCAmelCase							,   return_tensors=__lowerCAmelCase							)
    self.assertIsInstance(__lowerCAmelCase							,   __lowerCAmelCase							)

    if FRAMEWORK != "jax":
     a						=		list(batch.input_ids.numpy()[0]							)
    else:
     a						=		list(batch.input_ids.tolist()[0]							)

    self.assertListEqual(__lowerCAmelCase							,   __lowerCAmelCase							)

    self.assertEqual((2, 37)							,   batch.input_ids.shape							)
    self.assertEqual((2, 37)							,   batch.attention_mask.shape							)

   def 		A							(      self			:       Dict							)       ->				Union[str, Any]:


    """simple docstring"""






    a						=		self.ta_base_tokenizer
    a						=		['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
    a						=		tokenizer(__lowerCAmelCase							,   padding=__lowerCAmelCase							,   return_tensors=__lowerCAmelCase							)
    # check if input_ids are returned and no decoder_input_ids
    self.assertIn("input_ids"							,   __lowerCAmelCase							)
    self.assertIn("attention_mask"							,   __lowerCAmelCase							)
    self.assertNotIn("decoder_input_ids"							,   __lowerCAmelCase							)
    self.assertNotIn("decoder_attention_mask"							,   __lowerCAmelCase							)

   def 		A							(      self			:       List[Any]							)       ->				Optional[Any]:


    """simple docstring"""






    a						=		self.ta_base_tokenizer
    a						=		[
        '''Summary of the text.''',
        '''Another summary.''',
    ]
    a						=		tokenizer(
        text_target=__lowerCAmelCase							,   max_length=32							,   padding="max_length"							,   truncation=__lowerCAmelCase							,   return_tensors=__lowerCAmelCase							)
    self.assertEqual(32							,   targets["input_ids"].shape[1]							)

   def 		A							(      self			:       Union[str, Any]							)       ->				List[Any]:


    """simple docstring"""






    a						=		self.ta_base_tokenizer
    a						=		['''A long paragraph for summarization. </s>''']
    a						=		['''Summary of the text. </s>''']
    # fmt: off
    a						=		[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1]
    a						=		[86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1]
    # fmt: on

    a						=		tokenizer(__lowerCAmelCase							,   text_target=__lowerCAmelCase							)

    self.assertEqual(__lowerCAmelCase							,   batch["input_ids"][0]							)
    self.assertEqual(__lowerCAmelCase							,   batch["labels"][0]							)

   def 		A							(      self			:       List[str]							)       ->				List[str]:


    """simple docstring"""






    a						=		self.get_tokenizers()
    for tokenizer in tokenizers:
     with self.subTest(f"""{tokenizer.__class__.__name__}"""							):
      self.assertNotEqual(tokenizer.model_max_length							,   42							)

     # Now let's start the test
    a						=		self.get_tokenizers()
    for tokenizer in tokenizers:
     with self.subTest(f"""{tokenizer.__class__.__name__}"""							):
      # Isolate this from the other tests because we save additional tokens/etc
      a						=		tempfile.mkdtemp()

      a						=		''' He is very happy, UNwant\u00E9d,running'''
      a						=		tokenizer.encode(__lowerCAmelCase							,   add_special_tokens=__lowerCAmelCase							)
      tokenizer.save_pretrained(__lowerCAmelCase							)

      a						=		tokenizer.__class__.from_pretrained(__lowerCAmelCase							)
      a						=		after_tokenizer.encode(__lowerCAmelCase							,   add_special_tokens=__lowerCAmelCase							)
      self.assertListEqual(__lowerCAmelCase							,   __lowerCAmelCase							)

      shutil.rmtree(__lowerCAmelCase							)

    a						=		self.get_tokenizers(model_max_length=42							)
    for tokenizer in tokenizers:
     with self.subTest(f"""{tokenizer.__class__.__name__}"""							):
      # Isolate this from the other tests because we save additional tokens/etc
      a						=		tempfile.mkdtemp()

      a						=		''' He is very happy, UNwant\u00E9d,running'''
      tokenizer.add_tokens(["bim", "bambam"]							)
      a						=		tokenizer.additional_special_tokens
      additional_special_tokens.append("new_additional_special_token"							)
      tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens}							)
      a						=		tokenizer.encode(__lowerCAmelCase							,   add_special_tokens=__lowerCAmelCase							)
      tokenizer.save_pretrained(__lowerCAmelCase							)

      a						=		tokenizer.__class__.from_pretrained(__lowerCAmelCase							)
      a						=		after_tokenizer.encode(__lowerCAmelCase							,   add_special_tokens=__lowerCAmelCase							)
      self.assertListEqual(__lowerCAmelCase							,   __lowerCAmelCase							)
      self.assertIn("new_additional_special_token"							,   after_tokenizer.additional_special_tokens							)
      self.assertEqual(after_tokenizer.model_max_length							,   42							)

      a						=		tokenizer.__class__.from_pretrained(__lowerCAmelCase							,   model_max_length=43							)
      self.assertEqual(tokenizer.model_max_length							,   43							)

      shutil.rmtree(__lowerCAmelCase							)

   def 		A							(      self			:       Any							)       ->				int:


    """simple docstring"""






    a						=		[]
    if self.test_slow_tokenizer:
     tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())							)

    if self.test_rust_tokenizer:
     tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())							)

    for tokenizer_class, tokenizer_utils in tokenizer_list:
     with tempfile.TemporaryDirectory() as tmp_dir:
      tokenizer_utils.save_pretrained(__lowerCAmelCase							)

      with open(os.path.join(__lowerCAmelCase							,   "special_tokens_map.json"							)							,   encoding="utf-8"							) as json_file:
       a						=		json.load(__lowerCAmelCase							)

      with open(os.path.join(__lowerCAmelCase							,   "tokenizer_config.json"							)							,   encoding="utf-8"							) as json_file:
       a						=		json.load(__lowerCAmelCase							)

      a						=		[f"""<extra_id_{i}>""" for i in range(125							)]

      a						=		added_tokens_extra_ids + [
          '''an_additional_special_token'''
      ]
      a						=		added_tokens_extra_ids + [
          '''an_additional_special_token'''
      ]

      with open(os.path.join(__lowerCAmelCase							,   "special_tokens_map.json"							)							,   "w"							,   encoding="utf-8"							) as outfile:
       json.dump(__lowerCAmelCase							,   __lowerCAmelCase							)
      with open(os.path.join(__lowerCAmelCase							,   "tokenizer_config.json"							)							,   "w"							,   encoding="utf-8"							) as outfile:
       json.dump(__lowerCAmelCase							,   __lowerCAmelCase							)

      # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
      # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
      # "special_tokens_map.json" files
      a						=		tokenizer_class.from_pretrained(
          __lowerCAmelCase							,   )
      self.assertIn(
          "an_additional_special_token"							,   tokenizer_without_change_in_init.additional_special_tokens							)
      # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
      self.assertEqual(
          ["an_additional_special_token"]							,   tokenizer_without_change_in_init.convert_ids_to_tokens(
              tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"]							)							)							,   )

      # Now we test that we can change the value of additional_special_tokens in the from_pretrained
      a						=		added_tokens_extra_ids + [AddedToken("a_new_additional_special_token"							,   lstrip=__lowerCAmelCase							)]
      a						=		tokenizer_class.from_pretrained(
          __lowerCAmelCase							,   additional_special_tokens=__lowerCAmelCase							,   )

      self.assertIn("a_new_additional_special_token"							,   tokenizer.additional_special_tokens							)
      self.assertEqual(
          ["a_new_additional_special_token"]							,   tokenizer.convert_ids_to_tokens(
              tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"]							)							)							,   )

   def 		A							(      self			:       Tuple							)       ->				List[str]:


    """simple docstring"""






    a						=		[]
    if self.test_slow_tokenizer:
     tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())							)

    if self.test_rust_tokenizer:
     tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())							)

    for tokenizer_class, tokenizer_utils in tokenizer_list:
     with tempfile.TemporaryDirectory() as tmp_dir:
      tokenizer_utils.save_pretrained(__lowerCAmelCase							)

      a						=		tokenizer_class.from_pretrained(__lowerCAmelCase							)

      self.assertTrue(tokenizer.decode([255]							) == ""							)

   def 		A							(      self			:       Tuple							)       ->				Optional[Any]:


    """simple docstring"""






    pass

   def 		A							(      self			:       Any							)       ->				List[str]:


    """simple docstring"""






    pass

   def 		A							(      self			:       List[Any]							)       ->				Optional[int]:


    """simple docstring"""






    pass

   def 		A							(      self			:       List[Any]							)       ->				List[Any]:


    """simple docstring"""






    pass

   def 		A							(      self			:       Optional[Any]							)       ->				Any:


    """simple docstring"""






    a						=		self.get_tokenizers(fast=__lowerCAmelCase							,   do_lower_case=__lowerCAmelCase							)
    for tokenizer in tokenizers:
     with self.subTest(f"""{tokenizer.__class__.__name__}"""							):
      a						=		['''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''x''', '''t''', '''</s>''']
      a						=		tokenizer.convert_tokens_to_string(__lowerCAmelCase							)

      self.assertIsInstance(__lowerCAmelCase							,   __lowerCAmelCase							)




   def 		A							(      self			:       List[Any]							)       ->				Tuple:


    """simple docstring"""






    a						=		self.get_tokenizers()
    for tokenizer in tokenizers:
     with self.subTest(f"""{tokenizer.__class__.__name__}"""							):
      a						=		[
          '''bos_token''',
          '''eos_token''',
          '''unk_token''',
          '''sep_token''',
          '''pad_token''',
          '''cls_token''',
          '''mask_token''',
      ]

      a						=		0
      a						=		tokenizer.convert_ids_to_tokens(
          __lowerCAmelCase							,   skip_special_tokens=__lowerCAmelCase							)

      for attr in attributes_list:
       setattr(__lowerCAmelCase							,   attr + "_id"							,   __lowerCAmelCase							)
       self.assertEqual(getattr(__lowerCAmelCase							,   __lowerCAmelCase							)							,   __lowerCAmelCase							)
       self.assertEqual(getattr(__lowerCAmelCase							,   attr + "_id"							)							,   __lowerCAmelCase							)

       setattr(__lowerCAmelCase							,   attr + "_id"							,   __lowerCAmelCase							)
       self.assertEqual(getattr(__lowerCAmelCase							,   __lowerCAmelCase							)							,   __lowerCAmelCase							)
       self.assertEqual(getattr(__lowerCAmelCase							,   attr + "_id"							)							,   __lowerCAmelCase							)

      setattr(__lowerCAmelCase							,   "additional_special_tokens_ids"							,   []							)
      self.assertListEqual(getattr(__lowerCAmelCase							,   "additional_special_tokens"							)							,   []							)
      self.assertListEqual(getattr(__lowerCAmelCase							,   "additional_special_tokens_ids"							)							,   []							)

      setattr(__lowerCAmelCase							,   "additional_special_tokens_ids"							,   [token_id_to_test_setters]							)
      self.assertListEqual(getattr(__lowerCAmelCase							,   "additional_special_tokens"							)							,   [token_to_test_setters]							)
      self.assertListEqual(getattr(__lowerCAmelCase							,   "additional_special_tokens_ids"							)							,   [token_id_to_test_setters]							)






import unittest

from transformers import MobileBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         MODEL_FOR_PRETRAINING_MAPPING,
         MobileBertForMaskedLM,
         MobileBertForMultipleChoice,
         MobileBertForNextSentencePrediction,
         MobileBertForPreTraining,
         MobileBertForQuestionAnswering,
         MobileBertForSequenceClassification,
         MobileBertForTokenClassification,
         MobileBertModel,
     )



class 		_lowercase		:

   def __init__(      self			:       List[Any]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Any=13							,   __lowerCAmelCase			:       Any=7							,   __lowerCAmelCase			:       int=True							,   __lowerCAmelCase			:       Union[str, Any]=True							,   __lowerCAmelCase			:       Any=True							,   __lowerCAmelCase			:       Union[str, Any]=True							,   __lowerCAmelCase			:       str=99							,   __lowerCAmelCase			:       List[str]=64							,   __lowerCAmelCase			:       Optional[Any]=32							,   __lowerCAmelCase			:       Dict=5							,   __lowerCAmelCase			:       int=4							,   __lowerCAmelCase			:       Optional[Any]=37							,   __lowerCAmelCase			:       Union[str, Any]="gelu"							,   __lowerCAmelCase			:       Union[str, Any]=0.1							,   __lowerCAmelCase			:       List[str]=0.1							,   __lowerCAmelCase			:       List[str]=512							,   __lowerCAmelCase			:       List[Any]=16							,   __lowerCAmelCase			:       Union[str, Any]=2							,   __lowerCAmelCase			:       Optional[Any]=0.0_2							,   __lowerCAmelCase			:       Dict=3							,   __lowerCAmelCase			:       Optional[int]=4							,   __lowerCAmelCase			:       Union[str, Any]=None							,   )       ->				List[str]:


    """simple docstring"""






    a						=		parent
    a						=		batch_size
    a						=		seq_length
    a						=		is_training
    a						=		use_input_mask
    a						=		use_token_type_ids
    a						=		use_labels
    a						=		vocab_size
    a						=		hidden_size
    a						=		embedding_size
    a						=		num_hidden_layers
    a						=		num_attention_heads
    a						=		intermediate_size
    a						=		hidden_act
    a						=		hidden_dropout_prob
    a						=		attention_probs_dropout_prob
    a						=		max_position_embeddings
    a						=		type_vocab_size
    a						=		type_sequence_label_size
    a						=		initializer_range
    a						=		num_labels
    a						=		num_choices
    a						=		scope

   def 		A							(      self			:       Optional[int]							)       ->				Optional[int]:


    """simple docstring"""






    a						=		ids_tensor([self.batch_size, self.seq_length]							,   self.vocab_size							)

    a						=		None
    if self.use_input_mask:
     a						=		random_attention_mask([self.batch_size, self.seq_length]							)

    a						=		None
    if self.use_token_type_ids:
     a						=		ids_tensor([self.batch_size, self.seq_length]							,   self.type_vocab_size							)

    a						=		None
    a						=		None
    a						=		None
    if self.use_labels:
     a						=		ids_tensor([self.batch_size]							,   self.type_sequence_label_size							)
     a						=		ids_tensor([self.batch_size, self.seq_length]							,   self.num_labels							)
     a						=		ids_tensor([self.batch_size]							,   self.num_choices							)

    a						=		self.get_config()

    return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

   def 		A							(      self			:       int							)       ->				List[str]:


    """simple docstring"""






    return MobileBertConfig(
        vocab_size=self.vocab_size							,   hidden_size=self.hidden_size							,   num_hidden_layers=self.num_hidden_layers							,   num_attention_heads=self.num_attention_heads							,   intermediate_size=self.intermediate_size							,   embedding_size=self.embedding_size							,   hidden_act=self.hidden_act							,   hidden_dropout_prob=self.hidden_dropout_prob							,   attention_probs_dropout_prob=self.attention_probs_dropout_prob							,   max_position_embeddings=self.max_position_embeddings							,   type_vocab_size=self.type_vocab_size							,   is_decoder=__lowerCAmelCase							,   initializer_range=self.initializer_range							,   )

   def 		A							(      self			:       Optional[int]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Dict							)       ->				Union[str, Any]:


    """simple docstring"""






    a						=		MobileBertModel(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							)
    a						=		model(__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							)
    a						=		model(__lowerCAmelCase							)

    self.parent.assertEqual(result.last_hidden_state.shape							,   (self.batch_size, self.seq_length, self.hidden_size)							)
    self.parent.assertEqual(result.pooler_output.shape							,   (self.batch_size, self.hidden_size)							)

   def 		A							(      self			:       List[Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Any							)       ->				str:


    """simple docstring"""






    a						=		MobileBertForMaskedLM(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							)
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.seq_length, self.vocab_size)							)

   def 		A							(      self			:       List[Any]							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       List[str]							)       ->				List[str]:


    """simple docstring"""






    a						=		MobileBertForNextSentencePrediction(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(
        __lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							,   )
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, 2)							)

   def 		A							(      self			:       List[str]							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       List[str]							)       ->				List[Any]:


    """simple docstring"""






    a						=		MobileBertForPreTraining(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(
        __lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							,   next_sentence_label=__lowerCAmelCase							,   )
    self.parent.assertEqual(result.prediction_logits.shape							,   (self.batch_size, self.seq_length, self.vocab_size)							)
    self.parent.assertEqual(result.seq_relationship_logits.shape							,   (self.batch_size, 2)							)

   def 		A							(      self			:       Union[str, Any]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       List[str]							)       ->				Any:


    """simple docstring"""






    a						=		MobileBertForQuestionAnswering(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(
        __lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   start_positions=__lowerCAmelCase							,   end_positions=__lowerCAmelCase							,   )
    self.parent.assertEqual(result.start_logits.shape							,   (self.batch_size, self.seq_length)							)
    self.parent.assertEqual(result.end_logits.shape							,   (self.batch_size, self.seq_length)							)

   def 		A							(      self			:       List[Any]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       Optional[Any]							)       ->				Optional[int]:


    """simple docstring"""






    a						=		self.num_labels
    a						=		MobileBertForSequenceClassification(__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							)
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.num_labels)							)

   def 		A							(      self			:       Tuple							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Any							)       ->				Optional[Any]:


    """simple docstring"""






    a						=		self.num_labels
    a						=		MobileBertForTokenClassification(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							)
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.seq_length, self.num_labels)							)

   def 		A							(      self			:       Union[str, Any]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Optional[int]							)       ->				List[str]:


    """simple docstring"""






    a						=		self.num_choices
    a						=		MobileBertForMultipleChoice(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		input_ids.unsqueeze(1							).expand(-1							,   self.num_choices							,   -1							).contiguous()
    a						=		token_type_ids.unsqueeze(1							).expand(-1							,   self.num_choices							,   -1							).contiguous()
    a						=		input_mask.unsqueeze(1							).expand(-1							,   self.num_choices							,   -1							).contiguous()
    a						=		model(
        __lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							,   )
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.num_choices)							)




   def 		A							(      self			:       List[Any]							)       ->				Dict:


    """simple docstring"""






    a						=		self.prepare_config_and_inputs()
    (
        (
        a
    )		,  (
        a
    )		,  (
        a
    )		,  (
        a
    )		,  (
        a
    )		,  (
        a
    )		,  (
        a
    )		,  
    )						=		config_and_inputs
    a						=		{"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
    return config, inputs_dict



@require_torch
class 		_lowercase		(       UpperCAmelCase__,   UpperCAmelCase__,   unittest.TestCase	):
   _UpperCAmelCase     	=			(
       (
           MobileBertModel,
           MobileBertForMaskedLM,
           MobileBertForMultipleChoice,
           MobileBertForNextSentencePrediction,
           MobileBertForPreTraining,
           MobileBertForQuestionAnswering,
           MobileBertForSequenceClassification,
           MobileBertForTokenClassification,
       )
       if is_torch_available()
       else ()
   )
   _UpperCAmelCase     	=			(
       {
           '''feature-extraction''': MobileBertModel,
           '''fill-mask''': MobileBertForMaskedLM,
           '''question-answering''': MobileBertForQuestionAnswering,
           '''text-classification''': MobileBertForSequenceClassification,
           '''token-classification''': MobileBertForTokenClassification,
           '''zero-shot''': MobileBertForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   _UpperCAmelCase     	=			True

   def 		A							(      self			:       Optional[int]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Any=False							)       ->				Any:


    """simple docstring"""






    a						=		super()._prepare_for_class(__lowerCAmelCase							,   __lowerCAmelCase							,   return_labels=__lowerCAmelCase							)

    if return_labels:
     if model_class in get_values(__lowerCAmelCase							):
      a						=		torch.zeros(
          (self.model_tester.batch_size, self.model_tester.seq_length)							,   dtype=torch.long							,   device=__lowerCAmelCase							)
      a						=		torch.zeros(
          self.model_tester.batch_size							,   dtype=torch.long							,   device=__lowerCAmelCase							)
    return inputs_dict

   def 		A							(      self			:       Optional[int]							)       ->				List[Any]:


    """simple docstring"""






    a						=		MobileBertModelTester(self							)
    a						=		ConfigTester(self							,   config_class=__lowerCAmelCase							,   hidden_size=37							)

   def 		A							(      self			:       int							)       ->				Tuple:


    """simple docstring"""






    self.config_tester.run_common_tests()

   def 		A							(      self			:       str							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_model(*__lowerCAmelCase							)

   def 		A							(      self			:       str							)       ->				str:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_masked_lm(*__lowerCAmelCase							)

   def 		A							(      self			:       List[str]							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__lowerCAmelCase							)

   def 		A							(      self			:       int							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__lowerCAmelCase							)

   def 		A							(      self			:       List[Any]							)       ->				int:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_pretraining(*__lowerCAmelCase							)

   def 		A							(      self			:       List[Any]							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_question_answering(*__lowerCAmelCase							)

   def 		A							(      self			:       List[Any]							)       ->				Optional[int]:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__lowerCAmelCase							)




   def 		A							(      self			:       int							)       ->				Tuple:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_token_classification(*__lowerCAmelCase							)


def 	UpperCAmelCase__      (      UpperCAmelCase__ :Dict					):






 '''simple docstring'''

 return torch.tensor(
     UpperCAmelCase__ ,					dtype=torch.long ,					device=UpperCAmelCase__ ,					)


A_		:     Dict        =     1E-3




@require_torch
@require_sentencepiece
@require_tokenizers
class 		_lowercase		(       unittest.TestCase	):

   @slow
   def 		A							(      self			:       Optional[Any]							)       ->				Optional[Any]:


    """simple docstring"""






    a						=		MobileBertModel.from_pretrained("google/mobilebert-uncased"							).to(__lowerCAmelCase							)
    a						=		_long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]]							)
    with torch.no_grad():
     a						=		model(__lowerCAmelCase							)[0]
    a						=		torch.Size((1, 9, 512)							)
    self.assertEqual(output.shape							,   __lowerCAmelCase							)
    a						=		torch.tensor(
        [
            [
                [-2.4_73_65_26E07, 8.2_69_16_56E04, 1.6_52_18_38E05],
                [-5.7_54_17_04E-01, 3.9_05_60_22E00, 4.4_01_15_07E00],
                [2.6_04_73_59E00, 1.5_67_76_52E00, -1.7_32_41_88E-01],
            ]
        ]							,   device=__lowerCAmelCase							,   )

    # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a
    # ~1 difference, it's therefore not a good idea to measure using addition.
    # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the
    # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE
    a						=		torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE							)
    a						=		torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE							)

    self.assertTrue(lower_bound and upper_bound							)

