

import argparse
import json
import logging
import os
import shutil
import sys
import tempfile
import unittest
from unittest import mock

import torch
from accelerate.utils import write_basic_config

from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device
from transformers.utils import is_apex_available


logging.basicConfig(level=logging.DEBUG)

__lowerCAmelCase			     =       logging.getLogger()



def    _lowercase			(	)							->					int:





	"""simple docstring"""


	_UpperCamelCase			=   argparse.ArgumentParser()
	parser.add_argument("-f"					)
	_UpperCamelCase			=   parser.parse_args()
	return args.f



def    _lowercase			(	a__						:			Union[str, Any]					)							->					Tuple:





	"""simple docstring"""


	_UpperCamelCase			=   {}
	_UpperCamelCase			=   os.path.join(A__							,  "all_results.json"					)
	if os.path.exists(A__					):
		with open(A__							,  "r"					) as f:
			_UpperCamelCase			=   json.load(A__					)
	else:
		raise ValueError(f'''can\'t find {path}'''					)
	return results



def    _lowercase			(	)							->					Tuple:





	"""simple docstring"""


	_UpperCamelCase			=   torch.cuda.is_available() and torch_device == """cuda"""
	return is_using_cuda and is_apex_available()


__lowerCAmelCase			     =       logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)




class 			lowerCamelCase_    (  a__		):


							@classmethod
							def  lowercase   ( cls						)							->   Union[str, Any]:



								"""simple docstring"""

								_UpperCamelCase			=   tempfile.mkdtemp()
								_UpperCamelCase			=   os.path.join(cls.tmpdir      ,				"default_config.yml"						)
								write_basic_config(save_location=cls.configPath						)
								_UpperCamelCase			=   ["""accelerate""", """launch""", """--config_file""", cls.configPath]


							@classmethod
							def  lowercase   ( cls						)							->   str:



								"""simple docstring"""

								shutil.rmtree(cls.tmpdir						)


							@mock.patch.dict(os.environ      ,				{"WANDB_MODE": "offline"}						)
							def  lowercase   ( self						)							->   Optional[Any]:



								"""simple docstring"""

								_UpperCamelCase			=   self.get_auto_remove_tmp_dir()
								_UpperCamelCase			=   f'''
            {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py
            --model_name_or_path distilbert-base-uncased
            --output_dir {tmp_dir}
            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --learning_rate=1e-4
            --seed=42
            --checkpointing_steps epoch
            --with_tracking
        '''.split()

								if is_cuda_and_apex_available():
									testargs.append("--fp16"						)

								run_command(self._launch_args + testargs						)
								_UpperCamelCase			=   get_results(__a						)
								self.assertGreaterEqual(result["eval_accuracy"]      ,				0.75						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"epoch_0"						)						)						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"glue_no_trainer"						)						)						)


							@mock.patch.dict(os.environ      ,				{"WANDB_MODE": "offline"}						)
							def  lowercase   ( self						)							->   str:



								"""simple docstring"""

								_UpperCamelCase			=   self.get_auto_remove_tmp_dir()
								_UpperCamelCase			=   f'''
            {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py
            --model_name_or_path distilgpt2
            --train_file ./tests/fixtures/sample_text.txt
            --validation_file ./tests/fixtures/sample_text.txt
            --block_size 128
            --per_device_train_batch_size 5
            --per_device_eval_batch_size 5
            --num_train_epochs 2
            --output_dir {tmp_dir}
            --checkpointing_steps epoch
            --with_tracking
        '''.split()

								if torch.cuda.device_count() > 1:
									# Skipping because there are not enough batches to train the model + would need a drop_last to work.
									return

								run_command(self._launch_args + testargs						)
								_UpperCamelCase			=   get_results(__a						)
								self.assertLess(result["perplexity"]      ,				1_00						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"epoch_0"						)						)						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"clm_no_trainer"						)						)						)


							@mock.patch.dict(os.environ      ,				{"WANDB_MODE": "offline"}						)
							def  lowercase   ( self						)							->   Optional[int]:



								"""simple docstring"""

								_UpperCamelCase			=   self.get_auto_remove_tmp_dir()
								_UpperCamelCase			=   f'''
            {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py
            --model_name_or_path distilroberta-base
            --train_file ./tests/fixtures/sample_text.txt
            --validation_file ./tests/fixtures/sample_text.txt
            --output_dir {tmp_dir}
            --num_train_epochs=1
            --checkpointing_steps epoch
            --with_tracking
        '''.split()

								run_command(self._launch_args + testargs						)
								_UpperCamelCase			=   get_results(__a						)
								self.assertLess(result["perplexity"]      ,				42						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"epoch_0"						)						)						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"mlm_no_trainer"						)						)						)


							@mock.patch.dict(os.environ      ,				{"WANDB_MODE": "offline"}						)
							def  lowercase   ( self						)							->   List[Any]:



								"""simple docstring"""

								_UpperCamelCase			=   7 if get_gpu_count() > 1 else 2

								_UpperCamelCase			=   self.get_auto_remove_tmp_dir()
								_UpperCamelCase			=   f'''
            {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py
            --model_name_or_path bert-base-uncased
            --train_file tests/fixtures/tests_samples/conll/sample.json
            --validation_file tests/fixtures/tests_samples/conll/sample.json
            --output_dir {tmp_dir}
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=2
            --num_train_epochs={epochs}
            --seed 7
            --checkpointing_steps epoch
            --with_tracking
        '''.split()

								run_command(self._launch_args + testargs						)
								_UpperCamelCase			=   get_results(__a						)
								self.assertGreaterEqual(result["eval_accuracy"]      ,				0.75						)
								self.assertLess(result["train_loss"]      ,				0.5						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"epoch_0"						)						)						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"ner_no_trainer"						)						)						)


							@unittest.skip(reason="Fix me @muellerzr"						)
							@mock.patch.dict(os.environ      ,				{"WANDB_MODE": "offline"}						)
							def  lowercase   ( self						)							->   Optional[Any]:



								"""simple docstring"""

								_UpperCamelCase			=   self.get_auto_remove_tmp_dir()
								_UpperCamelCase			=   f'''
            {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py
            --model_name_or_path bert-base-uncased
            --version_2_with_negative
            --train_file tests/fixtures/tests_samples/SQUAD/sample.json
            --validation_file tests/fixtures/tests_samples/SQUAD/sample.json
            --output_dir {tmp_dir}
            --seed=42
            --max_train_steps=10
            --num_warmup_steps=2
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --checkpointing_steps epoch
            --with_tracking
        '''.split()

								run_command(self._launch_args + testargs						)
								_UpperCamelCase			=   get_results(__a						)
								# Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics.
								self.assertGreaterEqual(result["eval_f1"]      ,				28						)
								self.assertGreaterEqual(result["eval_exact"]      ,				28						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"epoch_0"						)						)						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"qa_no_trainer"						)						)						)


							@mock.patch.dict(os.environ      ,				{"WANDB_MODE": "offline"}						)
							def  lowercase   ( self						)							->   List[str]:



								"""simple docstring"""

								_UpperCamelCase			=   self.get_auto_remove_tmp_dir()
								_UpperCamelCase			=   f'''
            {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py
            --model_name_or_path bert-base-uncased
            --train_file tests/fixtures/tests_samples/swag/sample.json
            --validation_file tests/fixtures/tests_samples/swag/sample.json
            --output_dir {tmp_dir}
            --max_train_steps=20
            --num_warmup_steps=2
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --with_tracking
        '''.split()

								run_command(self._launch_args + testargs						)
								_UpperCamelCase			=   get_results(__a						)
								self.assertGreaterEqual(result["eval_accuracy"]      ,				0.8						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"swag_no_trainer"						)						)						)


							@slow
							@mock.patch.dict(os.environ      ,				{"WANDB_MODE": "offline"}						)
							def  lowercase   ( self						)							->   Tuple:



								"""simple docstring"""

								_UpperCamelCase			=   self.get_auto_remove_tmp_dir()
								_UpperCamelCase			=   f'''
            {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py
            --model_name_or_path t5-small
            --train_file tests/fixtures/tests_samples/xsum/sample.json
            --validation_file tests/fixtures/tests_samples/xsum/sample.json
            --output_dir {tmp_dir}
            --max_train_steps=50
            --num_warmup_steps=8
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --checkpointing_steps epoch
            --with_tracking
        '''.split()

								run_command(self._launch_args + testargs						)
								_UpperCamelCase			=   get_results(__a						)
								self.assertGreaterEqual(result["eval_rouge1"]      ,				10						)
								self.assertGreaterEqual(result["eval_rouge2"]      ,				2						)
								self.assertGreaterEqual(result["eval_rougeL"]      ,				7						)
								self.assertGreaterEqual(result["eval_rougeLsum"]      ,				7						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"epoch_0"						)						)						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"summarization_no_trainer"						)						)						)


							@slow
							@mock.patch.dict(os.environ      ,				{"WANDB_MODE": "offline"}						)
							def  lowercase   ( self						)							->   Any:



								"""simple docstring"""

								_UpperCamelCase			=   self.get_auto_remove_tmp_dir()
								_UpperCamelCase			=   f'''
            {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py
            --model_name_or_path sshleifer/student_marian_en_ro_6_1
            --source_lang en
            --target_lang ro
            --train_file tests/fixtures/tests_samples/wmt16/sample.json
            --validation_file tests/fixtures/tests_samples/wmt16/sample.json
            --output_dir {tmp_dir}
            --max_train_steps=50
            --num_warmup_steps=8
            --num_beams=6
            --learning_rate=3e-3
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --source_lang en_XX
            --target_lang ro_RO
            --checkpointing_steps epoch
            --with_tracking
        '''.split()

								run_command(self._launch_args + testargs						)
								_UpperCamelCase			=   get_results(__a						)
								self.assertGreaterEqual(result["eval_bleu"]      ,				30						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"epoch_0"						)						)						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"translation_no_trainer"						)						)						)


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



								"""simple docstring"""

								_UpperCamelCase			=   logging.StreamHandler(sys.stdout						)
								logger.addHandler(__a						)

								_UpperCamelCase			=   self.get_auto_remove_tmp_dir()
								_UpperCamelCase			=   f'''
            {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py
            --dataset_name huggingface/semantic-segmentation-test-sample
            --output_dir {tmp_dir}
            --max_train_steps=10
            --num_warmup_steps=2
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --checkpointing_steps epoch
        '''.split()

								run_command(self._launch_args + testargs						)
								_UpperCamelCase			=   get_results(__a						)
								self.assertGreaterEqual(result["eval_overall_accuracy"]      ,				0.10						)







							@mock.patch.dict(os.environ      ,				{"WANDB_MODE": "offline"}						)
							def  lowercase   ( self						)							->   List[str]:



								"""simple docstring"""

								_UpperCamelCase			=   self.get_auto_remove_tmp_dir()
								_UpperCamelCase			=   f'''
            {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py
            --model_name_or_path google/vit-base-patch16-224-in21k
            --dataset_name hf-internal-testing/cats_vs_dogs_sample
            --learning_rate 1e-4
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 1
            --max_train_steps 2
            --train_val_split 0.1
            --seed 42
            --output_dir {tmp_dir}
            --with_tracking
            --checkpointing_steps 1
        '''.split()

								if is_cuda_and_apex_available():
									testargs.append("--fp16"						)

								run_command(self._launch_args + testargs						)
								_UpperCamelCase			=   get_results(__a						)
								# The base model scores a 25%
								self.assertGreaterEqual(result["eval_accuracy"]      ,				0.6						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"step_1"						)						)						)
								self.assertTrue(os.path.exists(os.path.join(__a      ,				"image_classification_no_trainer"						)						)						)








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   SCREAMING_SNAKE_CASE_			:




       '''simple docstring'''



       def __init__(						self				:				Optional[Any]		,				__a				:				int		,				__a				:				str=13		,				__a				:				Tuple=7		,				__a				:				int=True		,				__a				:				int=True		,				__a				:				Dict=True		,				__a				:				str=True		,				__a				:				List[str]=99		,				__a				:				Dict=64		,				__a				:				Optional[Any]=32		,				__a				:				List[Any]=5		,				__a				:				Optional[int]=4		,				__a				:				str=37		,				__a				:				str="gelu"		,				__a				:				Optional[Any]=0.1		,				__a				:				Union[str, Any]=0.1		,				__a				:				int=512		,				__a				:				Optional[Any]=16		,				__a				:				Any=2		,				__a				:				Dict=0.02		,				__a				:				str=3		,				__a				:				List[Any]=4		,				__a				:				List[str]=None		,				)					->Optional[int]:
          lowerCamelCase_						:   Dict		= parent
          lowerCamelCase_						:   Optional[Any]		= batch_size
          lowerCamelCase_						:   Any		= seq_length
          lowerCamelCase_						:   Union[str, Any]		= is_training
          lowerCamelCase_						:   int		= use_input_mask
          lowerCamelCase_						:   int		= use_token_type_ids
          lowerCamelCase_						:   int		= use_labels
          lowerCamelCase_						:   List[str]		= vocab_size
          lowerCamelCase_						:   Any		= hidden_size
          lowerCamelCase_						:   Any		= embedding_size
          lowerCamelCase_						:   int		= num_hidden_layers
          lowerCamelCase_						:   Union[str, Any]		= num_attention_heads
          lowerCamelCase_						:   Optional[Any]		= intermediate_size
          lowerCamelCase_						:   Optional[int]		= hidden_act
          lowerCamelCase_						:   Dict		= hidden_dropout_prob
          lowerCamelCase_						:   Any		= attention_probs_dropout_prob
          lowerCamelCase_						:   Optional[int]		= max_position_embeddings
          lowerCamelCase_						:   Dict		= type_vocab_size
          lowerCamelCase_						:   List[str]		= type_sequence_label_size
          lowerCamelCase_						:   Any		= initializer_range
          lowerCamelCase_						:   Union[str, Any]		= num_labels
          lowerCamelCase_						:   List[Any]		= num_choices
          lowerCamelCase_						:   Dict		= scope



       def 				_lowerCAmelCase							(						self				:				int							)					->str:
          lowerCamelCase_						:   Dict		= ids_tensor([self.batch_size, self.seq_length]		,				self.vocab_size							)

          lowerCamelCase_						:   Tuple		= None
          if self.use_input_mask:
             lowerCamelCase_						:   Any		= random_attention_mask([self.batch_size, self.seq_length]							)

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

          lowerCamelCase_						:   List[Any]		= None
          lowerCamelCase_						:   Tuple		= None
          lowerCamelCase_						:   Optional[int]		= None
          if self.use_labels:
             lowerCamelCase_						:   str		= ids_tensor([self.batch_size]		,				self.type_sequence_label_size							)
             lowerCamelCase_						:   Optional[int]		= ids_tensor([self.batch_size, self.seq_length]		,				self.num_labels							)
             lowerCamelCase_						:   Any		= ids_tensor([self.batch_size]		,				self.num_choices							)

          lowerCamelCase_						:   str		= self.get_config()

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



       def 				_lowerCAmelCase							(						self				:				Tuple							)					->Optional[Any]:
          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=__a		,				initializer_range=self.initializer_range		,				)



       def 				_lowerCAmelCase							(						self				:				Tuple		,				__a				:				int		,				__a				:				List[str]		,				__a				:				Tuple		,				__a				:				Any		,				__a				:				Union[str, Any]		,				__a				:				int		,				__a				:				Any							)					->Tuple:
          lowerCamelCase_						:   Tuple		= MobileBertModel(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Dict		= model(__a		,				attention_mask=__a		,				token_type_ids=__a							)
          lowerCamelCase_						:   Optional[int]		= model(__a		,				token_type_ids=__a							)
          lowerCamelCase_						:   Tuple		= model(__a							)

          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 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				str		,				__a				:				Union[str, Any]		,				__a				:				int		,				__a				:				List[Any]		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				List[str]							)					->Tuple:
          lowerCamelCase_						:   List[Any]		= MobileBertForMaskedLM(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Union[str, Any]		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.vocab_size)							)



       def 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				Tuple		,				__a				:				Tuple		,				__a				:				Dict		,				__a				:				Tuple		,				__a				:				Optional[Any]		,				__a				:				Union[str, Any]		,				__a				:				Dict							)					->int:
          lowerCamelCase_						:   Tuple		= MobileBertForNextSentencePrediction(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Any		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, 2)							)



       def 				_lowerCAmelCase							(						self				:				str		,				__a				:				Optional[Any]		,				__a				:				int		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Dict							)					->List[Any]:
          lowerCamelCase_						:   Optional[int]		= MobileBertForPreTraining(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   List[Any]		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				next_sentence_label=__a		,				)
          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 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				Tuple		,				__a				:				int		,				__a				:				Optional[Any]		,				__a				:				Optional[Any]		,				__a				:				Tuple		,				__a				:				Optional[Any]		,				__a				:				Any							)					->List[str]:
          lowerCamelCase_						:   Dict		= MobileBertForQuestionAnswering(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Tuple		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				start_positions=__a		,				end_positions=__a		,				)
          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 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				List[Any]		,				__a				:				str		,				__a				:				int		,				__a				:				Dict		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				str							)					->Tuple:
          lowerCamelCase_						:   Dict		= self.num_labels
          lowerCamelCase_						:   Optional[Any]		= MobileBertForSequenceClassification(__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   str		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)							)



       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				str		,				__a				:				List[str]		,				__a				:				Optional[int]		,				__a				:				int		,				__a				:				str		,				__a				:				str		,				__a				:				Optional[Any]							)					->Tuple:
          lowerCamelCase_						:   int		= self.num_labels
          lowerCamelCase_						:   List[str]		= MobileBertForTokenClassification(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Optional[Any]		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.num_labels)							)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]		,				__a				:				Any		,				__a				:				Tuple		,				__a				:				Dict		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				Optional[int]		,				__a				:				Optional[Any]							)					->List[str]:
          lowerCamelCase_						:   Any		= self.num_choices
          lowerCamelCase_						:   int		= MobileBertForMultipleChoice(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Tuple		= input_ids.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Tuple		= token_type_ids.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Any		= input_mask.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Tuple		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_choices)							)




       def 				_lowerCAmelCase							(						self				:				List[str]							)					->int:
          lowerCamelCase_						:   Optional[Any]		= self.prepare_config_and_inputs()
          (
              (
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	
          )						:   Optional[Any]		= config_and_inputs
          lowerCamelCase_						:   List[Any]		= {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
          return config, inputs_dict







@require_torch
class   SCREAMING_SNAKE_CASE_			(a__						,       a__						,       unittest.TestCase						):




       '''simple docstring'''



       _a   							=							(
           (
               MobileBertModel,
               MobileBertForMaskedLM,
               MobileBertForMultipleChoice,
               MobileBertForNextSentencePrediction,
               MobileBertForPreTraining,
               MobileBertForQuestionAnswering,
               MobileBertForSequenceClassification,
               MobileBertForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       _a   							=							(
           {
               "feature-extraction": MobileBertModel,
               "fill-mask": MobileBertForMaskedLM,
               "question-answering": MobileBertForQuestionAnswering,
               "text-classification": MobileBertForSequenceClassification,
               "token-classification": MobileBertForTokenClassification,
               "zero-shot": MobileBertForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       _a   							=							True



       def 				_lowerCAmelCase							(						self				:				Optional[int]		,				__a				:				Union[str, Any]		,				__a				:				Dict		,				__a				:				str=False							)					->Any:
          lowerCamelCase_						:   Optional[int]		= super()._prepare_for_class(__a		,				__a		,				return_labels=__a							)

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



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]							)					->Union[str, Any]:
          lowerCamelCase_						:   List[Any]		= MobileBertModelTester(self							)
          lowerCamelCase_						:   int		= ConfigTester(self		,				config_class=__a		,				hidden_size=37							)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]							)					->List[Any]:
          self.config_tester.run_common_tests()



       def 				_lowerCAmelCase							(						self				:				str							)					->Any:
          lowerCamelCase_						:   Union[str, Any]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_model(*__a							)



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->Tuple:
          lowerCamelCase_						:   List[str]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_masked_lm(*__a							)



       def 				_lowerCAmelCase							(						self				:				Optional[Any]							)					->Tuple:
          lowerCamelCase_						:   Union[str, Any]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__a							)



       def 				_lowerCAmelCase							(						self				:				Any							)					->List[Any]:
          lowerCamelCase_						:   Any		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__a							)



       def 				_lowerCAmelCase							(						self				:				Optional[int]							)					->str:
          lowerCamelCase_						:   List[str]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_pretraining(*__a							)



       def 				_lowerCAmelCase							(						self				:				str							)					->Optional[Any]:
          lowerCamelCase_						:   int		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_question_answering(*__a							)



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->int:
          lowerCamelCase_						:   Dict		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__a							)




       def 				_lowerCAmelCase							(						self				:				List[Any]							)					->Union[str, Any]:
          lowerCamelCase_						:   Dict		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_token_classification(*__a							)







def    __lowerCamelCase   (      A__						: List[str]					)     ->    Optional[int]:
   return torch.tensor(
       A__						,						dtype=torch.long						,						device=A__						,						)


snake_case__				:	List[str]					       =					1e-3





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




       '''simple docstring'''



       @slow
       def 				_lowerCAmelCase							(						self				:				List[Any]							)					->List[str]:
          lowerCamelCase_						:   Any		= MobileBertModel.from_pretrained("""google/mobilebert-uncased"""							).to(__a							)
          lowerCamelCase_						:   int		= _long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]]							)
          with torch.no_grad():
             lowerCamelCase_						:   Optional[Any]		= model(__a							)[0]
          lowerCamelCase_						:   Any		= torch.Size((1, 9, 512)							)
          self.assertEqual(output.shape		,				__a							)
          lowerCamelCase_						:   str		= 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=__a		,				)

          # 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
          lowerCamelCase_						:   str		= torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE							)
          lowerCamelCase_						:   Tuple		= torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE							)

          self.assertTrue(lower_bound and upper_bound							)





