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






    '''simple docstring'''






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







    def     UpperCamelCase__     (			self) ->			Tuple:
        __UpperCamelCase  :List[str]    						=	ids_tensor([self.batch_size, self.seq_length]				,				self.vocab_size)

        __UpperCamelCase  :List[str]    						=	None
        if self.use_input_mask:
            __UpperCamelCase  :Dict    						=	random_attention_mask([self.batch_size, self.seq_length])

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

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

        __UpperCamelCase  :List[str]    						=	self.get_config()

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







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







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







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







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


@require_torch
class 			lowerCamelCase_  (     UpperCAmelCase_		,			UpperCAmelCase_		,			unittest.TestCase				):






    '''simple docstring'''






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







    def     UpperCamelCase__     (			self				,				__lowercase				,				__lowercase				,				__lowercase=False) ->			int:
        __UpperCamelCase  :List[Any]    						=	super()._prepare_for_class(__lowercase				,				__lowercase				,				return_labels=__lowercase)

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







    def     UpperCamelCase__     (			self) ->			Any:
        __UpperCamelCase  :Optional[Any]    						=	MobileBertModelTester(self)
        __UpperCamelCase  :Optional[int]    						=	ConfigTester(self				,				config_class=__lowercase				,				hidden_size=37)







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







    def     UpperCamelCase__     (			self) ->			Any:
        __UpperCamelCase  :Any    						=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mobilebert_model(*__lowercase)







    def     UpperCamelCase__     (			self) ->			Dict:
        __UpperCamelCase  :int    						=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mobilebert_for_masked_lm(*__lowercase)







    def     UpperCamelCase__     (			self) ->			int:
        __UpperCamelCase  :Union[str, Any]    						=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__lowercase)







    def     UpperCamelCase__     (			self) ->			int:
        __UpperCamelCase  :Union[str, Any]    						=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__lowercase)







    def     UpperCamelCase__     (			self) ->			List[Any]:
        __UpperCamelCase  :Tuple    						=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mobilebert_for_pretraining(*__lowercase)







    def     UpperCamelCase__     (			self) ->			Tuple:
        __UpperCamelCase  :Tuple    						=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mobilebert_for_question_answering(*__lowercase)







    def     UpperCamelCase__     (			self) ->			str:
        __UpperCamelCase  :List[Any]    						=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__lowercase)







    def     UpperCamelCase__     (			self) ->			Tuple:
        __UpperCamelCase  :int    						=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mobilebert_for_token_classification(*__lowercase)



def lowerCamelCase						(     SCREAMING_SNAKE_CASE			):
    '''simple docstring'''







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


__lowercase											=      1e-3


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






    '''simple docstring'''






    @slow
    def     UpperCamelCase__     (			self) ->			Union[str, Any]:
        __UpperCamelCase  :Optional[int]    						=	MobileBertModel.from_pretrained('''google/mobilebert-uncased''').to(__lowercase)
        __UpperCamelCase  :Optional[int]    						=	_long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]])
        with torch.no_grad():
            __UpperCamelCase  :List[str]    						=	model(__lowercase)[0]
        __UpperCamelCase  :Optional[int]    						=	torch.Size((1, 9, 512))
        self.assertEqual(output.shape				,				__lowercase)
        __UpperCamelCase  :int    						=	torch.tensor(
            [
                [
                    [-2.4_7_3_6_5_2_6E0_7, 8.2_6_9_1_6_5_6E0_4, 1.6_5_2_1_8_3_8E0_5],
                    [-5.7_5_4_1_7_0_4E-0_1, 3.9_0_5_6_0_2_2E0_0, 4.4_0_1_1_5_0_7E0_0],
                    [2.6_0_4_7_3_5_9E0_0, 1.5_6_7_7_6_5_2E0_0, -1.7_3_2_4_1_8_8E-0_1],
                ]
            ]				,				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  :Tuple    						=	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)






import qiskit



def lowerCamelCase						(     SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE			):
    '''simple docstring'''







    __UpperCamelCase  :Dict    						=	qiskit.Aer.get_backend('''aer_simulator'''			)

    __UpperCamelCase  :Tuple    						=	qiskit.QuantumCircuit(4						,    2			)
    # encode inputs in qubits 0 and 1
    if bita == 1:
        qc_ha.x(0			)
    if bita == 1:
        qc_ha.x(1			)
    qc_ha.barrier()

    # use cnots to write XOR of the inputs on qubit2
    qc_ha.cx(0						,    2			)
    qc_ha.cx(1						,    2			)

    # use ccx / toffoli gate to write AND of the inputs on qubit3
    qc_ha.ccx(0						,    1						,    3			)
    qc_ha.barrier()

    # extract outputs
    qc_ha.measure(2						,    0			)  # extract XOR value
    qc_ha.measure(3						,    1			)  # extract AND value

    # Execute the circuit on the qasm simulator
    __UpperCamelCase  :Optional[Any]    						=	qiskit.execute(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    shots=1_000			)

    # Return the histogram data of the results of the experiment
    return job.result().get_counts(SCREAMING_SNAKE_CASE			)


if __name__ == "__main__":
    __lowercase											=      half_adder(1, 1)
    print(F'Half Adder Output Qubit Counts: {counts}')





