






'''simple docstring'''





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




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




					def 		A      (  self  :		int      )    ->							Any:
								UpperCAmelCase_      :       str          =       ids_tensor([self.batch_size, self.seq_length]				, self.vocab_size      )

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

								UpperCAmelCase_      :       Union[str, Any]          =       None
								if self.use_token_type_ids:
											UpperCAmelCase_      :       Optional[int]          =       ids_tensor([self.batch_size, self.seq_length]				, self.type_vocab_size      )

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

								UpperCAmelCase_      :       Any          =       self.get_config()

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




					def 		A      (  self  :		str      )    ->							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 		A      (  self  :		Dict				, _A  :		List[str]				, _A  :		Any				, _A  :		Dict				, _A  :		Optional[int]				, _A  :		int				, _A  :		Union[str, Any]				, _A  :		List[Any]      )    ->							Optional[Any]:
								UpperCAmelCase_      :       Optional[Any]          =       MobileBertModel(config=_A      )
								model.to(_A      )
								model.eval()
								UpperCAmelCase_      :       List[str]          =       model(_A				, attention_mask=_A				, token_type_ids=_A      )
								UpperCAmelCase_      :       int          =       model(_A				, token_type_ids=_A      )
								UpperCAmelCase_      :       Optional[int]          =       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 		A      (  self  :		int				, _A  :		Union[str, Any]				, _A  :		Optional[Any]				, _A  :		Union[str, Any]				, _A  :		Union[str, Any]				, _A  :		List[str]				, _A  :		List[Any]				, _A  :		str      )    ->							int:
								UpperCAmelCase_      :       str          =       MobileBertForMaskedLM(config=_A      )
								model.to(_A      )
								model.eval()
								UpperCAmelCase_      :       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 		A      (  self  :		str				, _A  :		int				, _A  :		Any				, _A  :		Any				, _A  :		List[str]				, _A  :		str				, _A  :		Optional[int]				, _A  :		Optional[int]      )    ->							Union[str, Any]:
								UpperCAmelCase_      :       Optional[Any]          =       MobileBertForNextSentencePrediction(config=_A      )
								model.to(_A      )
								model.eval()
								UpperCAmelCase_      :       Any          =       model(
								    _A				, attention_mask=_A				, token_type_ids=_A				, labels=_A				, )
								self.parent.assertEqual(result.logits.shape				, (self.batch_size, 2)      )




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




					def 		A      (  self  :		List[Any]				, _A  :		Optional[int]				, _A  :		List[Any]				, _A  :		List[str]				, _A  :		Any				, _A  :		List[str]				, _A  :		List[Any]				, _A  :		Optional[int]      )    ->							Union[str, Any]:
								UpperCAmelCase_      :       Optional[int]          =       self.num_labels
								UpperCAmelCase_      :       Tuple          =       MobileBertForTokenClassification(config=_A      )
								model.to(_A      )
								model.eval()
								UpperCAmelCase_      :       Tuple          =       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 		A      (  self  :		str				, _A  :		List[str]				, _A  :		Optional[Any]				, _A  :		Optional[int]				, _A  :		List[Any]				, _A  :		List[str]				, _A  :		int				, _A  :		List[Any]      )    ->							Dict:
								UpperCAmelCase_      :       List[Any]          =       self.num_choices
								UpperCAmelCase_      :       List[Any]          =       MobileBertForMultipleChoice(config=_A      )
								model.to(_A      )
								model.eval()
								UpperCAmelCase_      :       Optional[Any]          =       input_ids.unsqueeze(1      ).expand(-1				, self.num_choices				, -1      ).contiguous()
								UpperCAmelCase_      :       Optional[Any]          =       token_type_ids.unsqueeze(1      ).expand(-1				, self.num_choices				, -1      ).contiguous()
								UpperCAmelCase_      :       int          =       input_mask.unsqueeze(1      ).expand(-1				, self.num_choices				, -1      ).contiguous()
								UpperCAmelCase_      :       List[str]          =       model(
								    _A				, attention_mask=_A				, token_type_ids=_A				, labels=_A				, )
								self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.num_choices)      )





					def 		A      (  self  :		List[Any]      )    ->							List[Any]:
								UpperCAmelCase_      :       Tuple          =       self.prepare_config_and_inputs()
								(
								    (
								    UpperCAmelCase_
								)    ,      (
								    UpperCAmelCase_
								)    ,      (
								    UpperCAmelCase_
								)    ,      (
								    UpperCAmelCase_
								)    ,      (
								    UpperCAmelCase_
								)    ,      (
								    UpperCAmelCase_
								)    ,      (
								    UpperCAmelCase_
								)    ,      
								)      :       List[str]          =       config_and_inputs
								UpperCAmelCase_      :       List[str]          =       {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
								return config, inputs_dict






@require_torch
class  snake_case__      (					UpperCamelCase     ,				UpperCamelCase     ,				unittest.TestCase):
					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 		A      (  self  :		Optional[int]				, _A  :		Optional[Any]				, _A  :		Tuple				, _A  :		Union[str, Any]=False      )    ->							Dict:
								UpperCAmelCase_      :       Union[str, Any]          =       super()._prepare_for_class(_A				, _A				, return_labels=_A      )

								if return_labels:
											if model_class in get_values(_A      ):
														UpperCAmelCase_      :       Optional[Any]          =       torch.zeros(
														    (self.model_tester.batch_size, self.model_tester.seq_length)				, dtype=torch.long				, device=_A      )
														UpperCAmelCase_      :       List[Any]          =       torch.zeros(
														    self.model_tester.batch_size				, dtype=torch.long				, device=_A      )
								return inputs_dict




					def 		A      (  self  :		int      )    ->							Any:
								UpperCAmelCase_      :       int          =       MobileBertModelTester(self      )
								UpperCAmelCase_      :       Optional[Any]          =       ConfigTester(self				, config_class=_A				, hidden_size=37      )




					def 		A      (  self  :		List[str]      )    ->							Optional[int]:
								self.config_tester.run_common_tests()




					def 		A      (  self  :		int      )    ->							List[Any]:
								UpperCAmelCase_      :       Tuple          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_model(*_A      )




					def 		A      (  self  :		List[Any]      )    ->							Any:
								UpperCAmelCase_      :       Union[str, Any]          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_masked_lm(*_A      )




					def 		A      (  self  :		Optional[int]      )    ->							Any:
								UpperCAmelCase_      :       str          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_multiple_choice(*_A      )




					def 		A      (  self  :		List[Any]      )    ->							Tuple:
								UpperCAmelCase_      :       List[str]          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*_A      )




					def 		A      (  self  :		Tuple      )    ->							Dict:
								UpperCAmelCase_      :       Optional[int]          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_pretraining(*_A      )




					def 		A      (  self  :		Union[str, Any]      )    ->							str:
								UpperCAmelCase_      :       Union[str, Any]          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_question_answering(*_A      )




					def 		A      (  self  :		Dict      )    ->							List[str]:
								UpperCAmelCase_      :       Optional[Any]          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_sequence_classification(*_A      )





					def 		A      (  self  :		Optional[int]      )    ->							Optional[int]:
								UpperCAmelCase_      :       Optional[int]          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_token_classification(*_A      )






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


_UpperCamelCase						:						List[str]  =					1e-3







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




					@slow
					def 		A      (  self  :		int      )    ->							Any:
								UpperCAmelCase_      :       Any          =       MobileBertModel.from_pretrained('''google/mobilebert-uncased'''      ).to(_A      )
								UpperCAmelCase_      :       Optional[int]          =       _long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]]      )
								with torch.no_grad():
											UpperCAmelCase_      :       Optional[Any]          =       model(_A      )[0]
								UpperCAmelCase_      :       Optional[int]          =       torch.Size((1, 9, 5_12)      )
								self.assertEqual(output.shape				, _A      )
								UpperCAmelCase_      :       List[Any]          =       torch.tensor(
								    [
								        [
								            [-2.473_6526e07, 8.269_1656e04, 1.652_1838e05],
								            [-5.754_1704e-01, 3.905_6022e00, 4.401_1507e00],
								            [2.604_7359e00, 1.567_7652e00, -1.732_4188e-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
								UpperCAmelCase_      :       Any          =       torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE      )
								UpperCAmelCase_      :       str          =       torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE      )

								self.assertTrue(lower_bound and upper_bound      )










'''simple docstring'''





import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType


class  snake_case__      (					UpperCamelCase):
					a_        =					["image_processor", "tokenizer"]
					a_        =					"LayoutLMv2ImageProcessor"
					a_        =					("LayoutXLMTokenizer", "LayoutXLMTokenizerFast")




					def __init__(  self  :		Optional[int]				, _A  :		str=None				, _A  :		Optional[Any]=None				, **_A  :		Any      )    ->							Tuple:
								if "feature_extractor" in kwargs:
											warnings.warn(
											    '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
											    ''' instead.'''				, _A				, )
											UpperCAmelCase_      :       int          =       kwargs.pop('''feature_extractor'''      )

								UpperCAmelCase_      :       str          =       image_processor if image_processor is not None else feature_extractor
								if image_processor is None:
											raise ValueError('''You need to specify an `image_processor`.'''      )
								if tokenizer is None:
											raise ValueError('''You need to specify a `tokenizer`.'''      )

								super().__init__(_A				, _A      )




					def __call__(  self  :		str				, _A  :		Optional[int]				, _A  :		Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None				, _A  :		Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None				, _A  :		Union[List[List[int]], List[List[List[int]]]] = None				, _A  :		Optional[Union[List[int], List[List[int]]]] = None				, _A  :		bool = True				, _A  :		Union[bool, str, PaddingStrategy] = False				, _A  :		Union[bool, str, TruncationStrategy] = None				, _A  :		Optional[int] = None				, _A  :		int = 0				, _A  :		Optional[int] = None				, _A  :		Optional[bool] = None				, _A  :		Optional[bool] = None				, _A  :		bool = False				, _A  :		bool = False				, _A  :		bool = False				, _A  :		bool = False				, _A  :		bool = True				, _A  :		Optional[Union[str, TensorType]] = None				, **_A  :		Dict				, )    ->							BatchEncoding:
								# verify input
								if self.image_processor.apply_ocr and (boxes is not None):
											raise ValueError(
											    '''You cannot provide bounding boxes '''
											    '''if you initialized the image processor with apply_ocr set to True.'''      )

								if self.image_processor.apply_ocr and (word_labels is not None):
											raise ValueError(
											    '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.'''      )

								if return_overflowing_tokens is True and return_offsets_mapping is False:
											raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.'''      )

								# first, apply the image processor
								UpperCAmelCase_      :       int          =       self.image_processor(images=_A				, return_tensors=_A      )

								# second, apply the tokenizer
								if text is not None and self.image_processor.apply_ocr and text_pair is None:
											if isinstance(_A				, _A      ):
														UpperCAmelCase_      :       int          =       [text]  # add batch dimension (as the image processor always adds a batch dimension)
											UpperCAmelCase_      :       int          =       features['''words''']

								UpperCAmelCase_      :       str          =       self.tokenizer(
								    text=text if text is not None else features['''words''']				, text_pair=text_pair if text_pair is not None else None				, boxes=boxes if boxes is not None else features['''boxes''']				, word_labels=_A				, add_special_tokens=_A				, padding=_A				, truncation=_A				, max_length=_A				, stride=_A				, pad_to_multiple_of=_A				, return_token_type_ids=_A				, return_attention_mask=_A				, return_overflowing_tokens=_A				, return_special_tokens_mask=_A				, return_offsets_mapping=_A				, return_length=_A				, verbose=_A				, return_tensors=_A				, **_A				, )

								# add pixel values
								UpperCAmelCase_      :       int          =       features.pop('''pixel_values'''      )
								if return_overflowing_tokens is True:
											UpperCAmelCase_      :       List[Any]          =       self.get_overflowing_images(_A				, encoded_inputs['''overflow_to_sample_mapping''']      )
								UpperCAmelCase_      :       Optional[int]          =       images

								return encoded_inputs




					def 		A      (  self  :		Union[str, Any]				, _A  :		int				, _A  :		Tuple      )    ->							Dict:
								# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
								UpperCAmelCase_      :       Tuple          =       []
								for sample_idx in overflow_to_sample_mapping:
											images_with_overflow.append(images[sample_idx]      )

								if len(_A      ) != len(_A      ):
											raise ValueError(
											    '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'''
											    F" {len(_A      )} and {len(_A      )}"      )

								return images_with_overflow




					def 		A      (  self  :		Optional[Any]				, *_A  :		Union[str, Any]				, **_A  :		Union[str, Any]      )    ->							Tuple:
								return self.tokenizer.batch_decode(*_A				, **_A      )




					def 		A      (  self  :		Any				, *_A  :		Optional[Any]				, **_A  :		Tuple      )    ->							Tuple:
								return self.tokenizer.decode(*_A				, **_A      )




					@property
					def 		A      (  self  :		Union[str, Any]      )    ->							List[Any]:
								return ["input_ids", "bbox", "attention_mask", "image"]




					@property
					def 		A      (  self  :		Tuple      )    ->							Optional[int]:
								warnings.warn(
								    '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''				, _A				, )
								return self.image_processor_class





					@property
					def 		A      (  self  :		Tuple      )    ->							str:
								warnings.warn(
								    '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''				, _A				, )
								return self.image_processor


