




'''simple docstring'''







import pyarrow.parquet as pq
import pytest

from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config
from datasets.features.image import Image
from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases





def 		snake_case_							(_a			:							str					,     _a			:							int  ):
    assert isinstance(_a					,     _a  )
    assert dataset.num_rows == 4
    assert dataset.num_columns == 3
    assert dataset.column_names == ["col_1", "col_2", "col_3"]
    for feature, expected_dtype in expected_features.items():
        assert dataset.features[feature].dtype == expected_dtype





@pytest.mark.parametrize('''keep_in_memory'''					,     [False, True]  )
def 		snake_case_							(_a			:							List[str]					,     _a			:							Tuple					,     _a			:							Optional[Any]  ):
    UpperCAmelCase     =	tmp_path / '''cache'''
    UpperCAmelCase     =	{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
    with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
        UpperCAmelCase     =	ParquetDatasetReader(_a					,     cache_dir=_a					,     keep_in_memory=_a  ).read()
    _check_parquet_dataset(_a					,     _a  )





@pytest.mark.parametrize(
    '''features'''					,     [
        None,
        {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
        {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
        {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
        {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
    ]					,     )
def 		snake_case_							(_a			:							Tuple					,     _a			:							int					,     _a			:							Dict  ):
    UpperCAmelCase     =	tmp_path / '''cache'''
    UpperCAmelCase     =	{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
    UpperCAmelCase     =	features.copy() if features else default_expected_features
    UpperCAmelCase     =	(
        Features({feature: Value(_a  ) for feature, dtype in features.items()}  ) if features is not None else None
    )
    UpperCAmelCase     =	ParquetDatasetReader(_a					,     features=_a					,     cache_dir=_a  ).read()
    _check_parquet_dataset(_a					,     _a  )





@pytest.mark.parametrize('''split'''					,     [None, NamedSplit('''train'''  ), '''train''', '''test''']  )
def 		snake_case_							(_a			:							Any					,     _a			:							int					,     _a			:							Dict  ):
    UpperCAmelCase     =	tmp_path / '''cache'''
    UpperCAmelCase     =	{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
    UpperCAmelCase     =	ParquetDatasetReader(_a					,     cache_dir=_a					,     split=_a  ).read()
    _check_parquet_dataset(_a					,     _a  )
    assert dataset.split == split if split else "train"





@pytest.mark.parametrize('''path_type'''					,     [str, list]  )
def 		snake_case_							(_a			:							Dict					,     _a			:							Optional[Any]					,     _a			:							str  ):
    if issubclass(_a					,     _a  ):
        UpperCAmelCase     =	parquet_path
    elif issubclass(_a					,     _a  ):
        UpperCAmelCase     =	[parquet_path]
    UpperCAmelCase     =	tmp_path / '''cache'''
    UpperCAmelCase     =	{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
    UpperCAmelCase     =	ParquetDatasetReader(_a					,     cache_dir=_a  ).read()
    _check_parquet_dataset(_a					,     _a  )





def 		snake_case_							(_a			:							Any					,     _a			:							Union[str, Any]					,     _a			:							Tuple=("train",)  ):
    assert isinstance(_a					,     _a  )
    for split in splits:
        UpperCAmelCase     =	dataset_dict[split]
        assert dataset.num_rows == 4
        assert dataset.num_columns == 3
        assert dataset.column_names == ["col_1", "col_2", "col_3"]
        for feature, expected_dtype in expected_features.items():
            assert dataset.features[feature].dtype == expected_dtype





@pytest.mark.parametrize('''keep_in_memory'''					,     [False, True]  )
def 		snake_case_							(_a			:							Optional[Any]					,     _a			:							Optional[int]					,     _a			:							Dict  ):
    UpperCAmelCase     =	tmp_path / '''cache'''
    UpperCAmelCase     =	{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
    with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
        UpperCAmelCase     =	ParquetDatasetReader(
            {'''train''': parquet_path}					,     cache_dir=_a					,     keep_in_memory=_a  ).read()
    _check_parquet_datasetdict(_a					,     _a  )





@pytest.mark.parametrize(
    '''features'''					,     [
        None,
        {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
        {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
        {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
        {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
    ]					,     )
def 		snake_case_							(_a			:							Tuple					,     _a			:							List[str]					,     _a			:							Dict  ):
    UpperCAmelCase     =	tmp_path / '''cache'''
    UpperCAmelCase     =	{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
    UpperCAmelCase     =	features.copy() if features else default_expected_features
    UpperCAmelCase     =	(
        Features({feature: Value(_a  ) for feature, dtype in features.items()}  ) if features is not None else None
    )
    UpperCAmelCase     =	ParquetDatasetReader({'''train''': parquet_path}					,     features=_a					,     cache_dir=_a  ).read()
    _check_parquet_datasetdict(_a					,     _a  )





@pytest.mark.parametrize('''split'''					,     [None, NamedSplit('''train'''  ), '''train''', '''test''']  )
def 		snake_case_							(_a			:							List[Any]					,     _a			:							Dict					,     _a			:							List[str]  ):
    if split:
        UpperCAmelCase     =	{split: parquet_path}
    else:
        UpperCAmelCase     =	'''train'''
        UpperCAmelCase     =	{'''train''': parquet_path, '''test''': parquet_path}
    UpperCAmelCase     =	tmp_path / '''cache'''
    UpperCAmelCase     =	{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
    UpperCAmelCase     =	ParquetDatasetReader(_a					,     cache_dir=_a  ).read()
    _check_parquet_datasetdict(_a					,     _a					,     splits=list(path.keys()  )  )
    assert all(dataset[split].split == split for split in path.keys()  )





def 		snake_case_							(_a			:							Union[str, Any]					,     _a			:							int  ):
    UpperCAmelCase     =	ParquetDatasetWriter(_a					,     tmp_path / '''foo.parquet'''  )
    assert writer.write() > 0
    UpperCAmelCase     =	pq.ParquetFile(tmp_path / '''foo.parquet'''  )
    UpperCAmelCase     =	pf.read()
    assert dataset.data.table == output_table





def 		snake_case_							(_a			:							Any					,     _a			:							Optional[Any]  ):
    UpperCAmelCase     =	str(shared_datadir / '''test_image_rgb.jpg'''  )
    UpperCAmelCase     =	{'''image''': [image_path]}
    UpperCAmelCase     =	Features({'''image''': Image()}  )
    UpperCAmelCase     =	Dataset.from_dict(_a					,     features=_a  )
    UpperCAmelCase     =	ParquetDatasetWriter(_a					,     tmp_path / '''foo.parquet'''  )
    assert writer.write() > 0

    UpperCAmelCase     =	Dataset.from_parquet(str(tmp_path / '''foo.parquet'''  )  )
    assert dataset.features == reloaded_dataset.features

    UpperCAmelCase     =	ParquetDatasetReader(str(tmp_path / '''foo.parquet'''  )					,     streaming=_a  ).read()
    assert dataset.features == reloaded_iterable_dataset.features







@pytest.mark.parametrize(
    '''feature, expected'''					,     [
        (Features({'''foo''': Value('''int32'''  )}  ), None),
        (Features({'''image''': Image(), '''foo''': Value('''int32'''  )}  ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS),
        (Features({'''nested''': Sequence(Audio()  )}  ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS),
    ]					,     )
def 		snake_case_							(_a			:							str					,     _a			:							Optional[int]  ):
    assert get_writer_batch_size(_a  ) == expected










'''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     _a						:
       def __init__(			self		:			List[str]     ,       lowercase		:			Dict     ,       lowercase		:			List[Any]=13     ,       lowercase		:			Optional[Any]=7     ,       lowercase		:			Any=True     ,       lowercase		:			str=True     ,       lowercase		:			List[Any]=True     ,       lowercase		:			str=True     ,       lowercase		:			List[str]=99     ,       lowercase		:			int=64     ,       lowercase		:			List[Any]=32     ,       lowercase		:			str=5     ,       lowercase		:			Optional[int]=4     ,       lowercase		:			int=37     ,       lowercase		:			str="gelu"     ,       lowercase		:			Any=0.1     ,       lowercase		:			Optional[Any]=0.1     ,       lowercase		:			Optional[int]=512     ,       lowercase		:			Union[str, Any]=16     ,       lowercase		:			List[str]=2     ,       lowercase		:			Tuple=0.02     ,       lowercase		:			List[Any]=3     ,       lowercase		:			int=4     ,       lowercase		:			Optional[Any]=None     ,       ):



           '''simple docstring'''

           UpperCAmelCase     =	parent
           UpperCAmelCase     =	batch_size
           UpperCAmelCase     =	seq_length
           UpperCAmelCase     =	is_training
           UpperCAmelCase     =	use_input_mask
           UpperCAmelCase     =	use_token_type_ids
           UpperCAmelCase     =	use_labels
           UpperCAmelCase     =	vocab_size
           UpperCAmelCase     =	hidden_size
           UpperCAmelCase     =	embedding_size
           UpperCAmelCase     =	num_hidden_layers
           UpperCAmelCase     =	num_attention_heads
           UpperCAmelCase     =	intermediate_size
           UpperCAmelCase     =	hidden_act
           UpperCAmelCase     =	hidden_dropout_prob
           UpperCAmelCase     =	attention_probs_dropout_prob
           UpperCAmelCase     =	max_position_embeddings
           UpperCAmelCase     =	type_vocab_size
           UpperCAmelCase     =	type_sequence_label_size
           UpperCAmelCase     =	initializer_range
           UpperCAmelCase     =	num_labels
           UpperCAmelCase     =	num_choices
           UpperCAmelCase     =	scope
       def 					A   (			self		:			Union[str, Any]       ):



           '''simple docstring'''

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

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

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

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

           UpperCAmelCase     =	self.get_config()

           return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
       def 					A   (			self		:			Optional[Any]       ):



           '''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=lowercase     ,       initializer_range=self.initializer_range     ,       )
       def 					A   (			self		:			Tuple     ,       lowercase		:			Optional[Any]     ,       lowercase		:			List[Any]     ,       lowercase		:			Optional[int]     ,       lowercase		:			Union[str, Any]     ,       lowercase		:			List[Any]     ,       lowercase		:			str     ,       lowercase		:			Dict       ):



           '''simple docstring'''

           UpperCAmelCase     =	MobileBertModel(config=lowercase       )
           model.to(lowercase       )
           model.eval()
           UpperCAmelCase     =	model(lowercase     ,       attention_mask=lowercase     ,       token_type_ids=lowercase       )
           UpperCAmelCase     =	model(lowercase     ,       token_type_ids=lowercase       )
           UpperCAmelCase     =	model(lowercase       )

           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		:			Dict     ,       lowercase		:			Union[str, Any]     ,       lowercase		:			List[str]     ,       lowercase		:			List[str]     ,       lowercase		:			Dict     ,       lowercase		:			List[str]     ,       lowercase		:			Optional[int]     ,       lowercase		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase     =	MobileBertForMaskedLM(config=lowercase       )
           model.to(lowercase       )
           model.eval()
           UpperCAmelCase     =	model(lowercase     ,       attention_mask=lowercase     ,       token_type_ids=lowercase     ,       labels=lowercase       )
           self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.seq_length, self.vocab_size)       )
       def 					A   (			self		:			Dict     ,       lowercase		:			Any     ,       lowercase		:			Dict     ,       lowercase		:			Optional[Any]     ,       lowercase		:			Optional[Any]     ,       lowercase		:			List[Any]     ,       lowercase		:			List[Any]     ,       lowercase		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase     =	MobileBertForNextSentencePrediction(config=lowercase       )
           model.to(lowercase       )
           model.eval()
           UpperCAmelCase     =	model(
               lowercase     ,       attention_mask=lowercase     ,       token_type_ids=lowercase     ,       labels=lowercase     ,       )
           self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, 2)       )
       def 					A   (			self		:			Optional[int]     ,       lowercase		:			Tuple     ,       lowercase		:			Optional[Any]     ,       lowercase		:			int     ,       lowercase		:			Optional[Any]     ,       lowercase		:			Union[str, Any]     ,       lowercase		:			Union[str, Any]     ,       lowercase		:			Tuple       ):



           '''simple docstring'''

           UpperCAmelCase     =	MobileBertForPreTraining(config=lowercase       )
           model.to(lowercase       )
           model.eval()
           UpperCAmelCase     =	model(
               lowercase     ,       attention_mask=lowercase     ,       token_type_ids=lowercase     ,       labels=lowercase     ,       next_sentence_label=lowercase     ,       )
           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		:			Optional[int]     ,       lowercase		:			Any     ,       lowercase		:			Dict     ,       lowercase		:			str     ,       lowercase		:			Optional[Any]     ,       lowercase		:			List[str]     ,       lowercase		:			int     ,       lowercase		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	MobileBertForQuestionAnswering(config=lowercase       )
           model.to(lowercase       )
           model.eval()
           UpperCAmelCase     =	model(
               lowercase     ,       attention_mask=lowercase     ,       token_type_ids=lowercase     ,       start_positions=lowercase     ,       end_positions=lowercase     ,       )
           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		:			Optional[Any]     ,       lowercase		:			Tuple     ,       lowercase		:			Union[str, Any]     ,       lowercase		:			List[Any]     ,       lowercase		:			List[str]     ,       lowercase		:			List[str]     ,       lowercase		:			str     ,       lowercase		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.num_labels
           UpperCAmelCase     =	MobileBertForSequenceClassification(lowercase       )
           model.to(lowercase       )
           model.eval()
           UpperCAmelCase     =	model(lowercase     ,       attention_mask=lowercase     ,       token_type_ids=lowercase     ,       labels=lowercase       )
           self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.num_labels)       )
       def 					A   (			self		:			List[Any]     ,       lowercase		:			int     ,       lowercase		:			List[Any]     ,       lowercase		:			Tuple     ,       lowercase		:			Optional[int]     ,       lowercase		:			List[Any]     ,       lowercase		:			List[str]     ,       lowercase		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.num_labels
           UpperCAmelCase     =	MobileBertForTokenClassification(config=lowercase       )
           model.to(lowercase       )
           model.eval()
           UpperCAmelCase     =	model(lowercase     ,       attention_mask=lowercase     ,       token_type_ids=lowercase     ,       labels=lowercase       )
           self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.seq_length, self.num_labels)       )
       def 					A   (			self		:			int     ,       lowercase		:			Optional[int]     ,       lowercase		:			Tuple     ,       lowercase		:			List[Any]     ,       lowercase		:			Tuple     ,       lowercase		:			str     ,       lowercase		:			Tuple     ,       lowercase		:			Dict       ):



           '''simple docstring'''

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







       def 					A   (			self		:			int       ):



           '''simple docstring'''

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






@require_torch
class     _a						(			__a							,							__a							,							unittest.TestCase				):
       __a       :  Dict            =      (
           (
               MobileBertModel,
               MobileBertForMaskedLM,
               MobileBertForMultipleChoice,
               MobileBertForNextSentencePrediction,
               MobileBertForPreTraining,
               MobileBertForQuestionAnswering,
               MobileBertForSequenceClassification,
               MobileBertForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       __a       :  List[str]            =      (
           {
               """feature-extraction""": MobileBertModel,
               """fill-mask""": MobileBertForMaskedLM,
               """question-answering""": MobileBertForQuestionAnswering,
               """text-classification""": MobileBertForSequenceClassification,
               """token-classification""": MobileBertForTokenClassification,
               """zero-shot""": MobileBertForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       __a       :  Any            =      True
       def 					A   (			self		:			List[Any]     ,       lowercase		:			int     ,       lowercase		:			Any     ,       lowercase		:			Optional[Any]=False       ):



           '''simple docstring'''

           UpperCAmelCase     =	super()._prepare_for_class(lowercase     ,       lowercase     ,       return_labels=lowercase       )

           if return_labels:
               if model_class in get_values(lowercase       ):
                   UpperCAmelCase     =	torch.zeros(
                       (self.model_tester.batch_size, self.model_tester.seq_length)     ,       dtype=torch.long     ,       device=lowercase       )
                   UpperCAmelCase     =	torch.zeros(
                       self.model_tester.batch_size     ,       dtype=torch.long     ,       device=lowercase       )
           return inputs_dict
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	MobileBertModelTester(self       )
           UpperCAmelCase     =	ConfigTester(self     ,       config_class=lowercase     ,       hidden_size=37       )
       def 					A   (			self		:			Dict       ):



           '''simple docstring'''

           self.config_tester.run_common_tests()
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mobilebert_model(*lowercase       )
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mobilebert_for_masked_lm(*lowercase       )
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mobilebert_for_multiple_choice(*lowercase       )
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*lowercase       )
       def 					A   (			self		:			int       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mobilebert_for_pretraining(*lowercase       )
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mobilebert_for_question_answering(*lowercase       )
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mobilebert_for_sequence_classification(*lowercase       )







       def 					A   (			self		:			Tuple       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mobilebert_for_token_classification(*lowercase       )






def 		snake_case_							(_a			:							List[Any]  ):
    return torch.tensor(
        _a					,     dtype=torch.long					,     device=_a					,     )


A									=1E-3







@require_torch
@require_sentencepiece
@require_tokenizers
class     _a						(			unittest.TestCase				):
       @slow
       def 					A   (			self		:			Union[str, Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	MobileBertModel.from_pretrained('''google/mobilebert-uncased'''       ).to(lowercase       )
           UpperCAmelCase     =	_long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]]       )
           with torch.no_grad():
               UpperCAmelCase     =	model(lowercase       )[0]
           UpperCAmelCase     =	torch.Size((1, 9, 512)       )
           self.assertEqual(output.shape     ,       lowercase       )
           UpperCAmelCase     =	torch.tensor(
               [
                   [
                       [-2.4_736_526E07, 8.2_691_656E04, 1.6_521_838E05],
                       [-5.7_541_704E-01, 3.9_056_022E00, 4.4_011_507E00],
                       [2.6_047_359E00, 1.5_677_652E00, -1.7_324_188E-01],
                   ]
               ]     ,       device=lowercase     ,       )

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

           self.assertTrue(lower_bound and upper_bound       )




