






from __future__ import annotations

import unittest

from transformers import MobileBertConfig, is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
							import tensorflow as tf

							from transformers import (
							    TF_MODEL_FOR_PRETRAINING_MAPPING,
							    TFMobileBertForMaskedLM,
							    TFMobileBertForMultipleChoice,
							    TFMobileBertForNextSentencePrediction,
							    TFMobileBertForPreTraining,
							    TFMobileBertForQuestionAnswering,
							    TFMobileBertForSequenceClassification,
							    TFMobileBertForTokenClassification,
							    TFMobileBertModel,
							)




@require_tf
class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					,  SCREAMING_SNAKE_CASE__					,  unittest.TestCase					):


						'''simple docstring'''




						A     :   str						=					(
						    (
						        TFMobileBertModel,
						        TFMobileBertForMaskedLM,
						        TFMobileBertForNextSentencePrediction,
						        TFMobileBertForPreTraining,
						        TFMobileBertForQuestionAnswering,
						        TFMobileBertForSequenceClassification,
						        TFMobileBertForTokenClassification,
						        TFMobileBertForMultipleChoice,
						    )
						    if is_tf_available()
						    else ()
						)
						A     :   int						=					(
						    {
						        'feature-extraction': TFMobileBertModel,
						        'fill-mask': TFMobileBertForMaskedLM,
						        'question-answering': TFMobileBertForQuestionAnswering,
						        'text-classification': TFMobileBertForSequenceClassification,
						        'token-classification': TFMobileBertForTokenClassification,
						        'zero-shot': TFMobileBertForSequenceClassification,
						    }
						    if is_tf_available()
						    else {}
						)
						A     :   Union[str, Any]						=					False
						A     :   Optional[Any]						=					False






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE=False				) ->				List[str]:
								snake_case_				:							Optional[int]						 =       super()._prepare_for_class(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				return_labels=_SCREAMING_SNAKE_CASE				)

								if return_labels:
										if model_class in get_values(_SCREAMING_SNAKE_CASE				):
												snake_case_				:							int						 =       tf.zeros(self.model_tester.batch_size		,				dtype=tf.intaa				)

								return inputs_dict




						class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


												'''simple docstring'''




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






												def       _lowerCAmelCase       (	self				) ->				Dict:
														snake_case_				:							Tuple						 =       ids_tensor([self.batch_size, self.seq_length]		,				self.vocab_size				)

														snake_case_				:							Union[str, Any]						 =       None
														if self.use_input_mask:
																snake_case_				:							Optional[int]						 =       random_attention_mask([self.batch_size, self.seq_length]				)

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

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

														snake_case_				:							Union[str, Any]						 =       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		,				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		,				initializer_range=self.initializer_range		,				embedding_size=self.embedding_size		,				)

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






												def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				List[str]:
														snake_case_				:							List[Any]						 =       TFMobileBertModel(config=_SCREAMING_SNAKE_CASE				)
														snake_case_				:							Any						 =       {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
														snake_case_				:							Any						 =       model(_SCREAMING_SNAKE_CASE				)

														snake_case_				:							int						 =       [input_ids, input_mask]
														snake_case_				:							Any						 =       model(_SCREAMING_SNAKE_CASE				)

														snake_case_				:							List[Any]						 =       model(_SCREAMING_SNAKE_CASE				)

														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		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				str:
														snake_case_				:							List[str]						 =       TFMobileBertForMaskedLM(config=_SCREAMING_SNAKE_CASE				)
														snake_case_				:							Union[str, Any]						 =       {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
														snake_case_				:							Optional[int]						 =       model(_SCREAMING_SNAKE_CASE				)
														self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.vocab_size)				)






												def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Optional[int]:
														snake_case_				:							Optional[int]						 =       TFMobileBertForNextSentencePrediction(config=_SCREAMING_SNAKE_CASE				)
														snake_case_				:							Union[str, Any]						 =       {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
														snake_case_				:							Any						 =       model(_SCREAMING_SNAKE_CASE				)
														self.parent.assertEqual(result.logits.shape		,				(self.batch_size, 2)				)






												def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Optional[Any]:
														snake_case_				:							List[Any]						 =       TFMobileBertForPreTraining(config=_SCREAMING_SNAKE_CASE				)
														snake_case_				:							str						 =       {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
														snake_case_				:							Union[str, Any]						 =       model(_SCREAMING_SNAKE_CASE				)
														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		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				str:
														snake_case_				:							Optional[Any]						 =       self.num_labels
														snake_case_				:							int						 =       TFMobileBertForSequenceClassification(config=_SCREAMING_SNAKE_CASE				)
														snake_case_				:							Tuple						 =       {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
														snake_case_				:							Optional[int]						 =       model(_SCREAMING_SNAKE_CASE				)
														self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)				)






												def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				str:
														snake_case_				:							List[Any]						 =       self.num_choices
														snake_case_				:							int						 =       TFMobileBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE				)
														snake_case_				:							Tuple						 =       tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE		,				1				)		,				(1, self.num_choices, 1)				)
														snake_case_				:							List[str]						 =       tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE		,				1				)		,				(1, self.num_choices, 1)				)
														snake_case_				:							List[str]						 =       tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE		,				1				)		,				(1, self.num_choices, 1)				)
														snake_case_				:							List[str]						 =       {
														    "input_ids": multiple_choice_inputs_ids,
														    "attention_mask": multiple_choice_input_mask,
														    "token_type_ids": multiple_choice_token_type_ids,
														}
														snake_case_				:							Optional[Any]						 =       model(_SCREAMING_SNAKE_CASE				)
														self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_choices)				)






												def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Union[str, Any]:
														snake_case_				:							List[Any]						 =       self.num_labels
														snake_case_				:							Tuple						 =       TFMobileBertForTokenClassification(config=_SCREAMING_SNAKE_CASE				)
														snake_case_				:							Optional[int]						 =       {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
														snake_case_				:							Any						 =       model(_SCREAMING_SNAKE_CASE				)
														self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.num_labels)				)






												def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				List[str]:
														snake_case_				:							Tuple						 =       TFMobileBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE				)
														snake_case_				:							List[str]						 =       {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
														snake_case_				:							List[str]						 =       model(_SCREAMING_SNAKE_CASE				)
														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]:
														snake_case_				:							Optional[Any]						 =       self.prepare_config_and_inputs()
														(
														    (
														    snake_case_
														) ,       (
														    snake_case_
														) ,       (
														    snake_case_
														) ,       (
														    snake_case_
														) ,       (
														    snake_case_
														) ,       (
														    snake_case_
														) ,       (
														    snake_case_
														) ,       
														)				:							Dict						 =       config_and_inputs
														snake_case_				:							Tuple						 =       {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
														return config, inputs_dict






						def       _lowerCAmelCase       (	self				) ->				Tuple:
								snake_case_				:							Union[str, Any]						 =       TFMobileBertModelTest.TFMobileBertModelTester(self				)
								snake_case_				:							Any						 =       ConfigTester(self		,				config_class=_SCREAMING_SNAKE_CASE		,				hidden_size=37				)






						def       _lowerCAmelCase       (	self				) ->				Optional[Any]:
								self.config_tester.run_common_tests()






						def       _lowerCAmelCase       (	self				) ->				Dict:
								snake_case_				:							Tuple						 =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_model(*_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				Any:
								snake_case_				:							int						 =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_masked_lm(*_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				int:
								snake_case_				:							Optional[Any]						 =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_multiple_choice(*_SCREAMING_SNAKE_CASE				)






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






						def       _lowerCAmelCase       (	self				) ->				int:
								snake_case_				:							Dict						 =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_pretraining(*_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				int:
								snake_case_				:							Optional[int]						 =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_question_answering(*_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				str:
								snake_case_				:							Any						 =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_sequence_classification(*_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				Tuple:
								snake_case_				:							int						 =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_mobilebert_for_token_classification(*_SCREAMING_SNAKE_CASE				)






						@slow
						def       _lowerCAmelCase       (	self				) ->				Optional[int]:
								# for model_name in TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								for model_name in ["google/mobilebert-uncased"]:
										snake_case_				:							List[Any]						 =       TFMobileBertModel.from_pretrained(_SCREAMING_SNAKE_CASE				)
										self.assertIsNotNone(_SCREAMING_SNAKE_CASE				)




@require_tf
class 		UpperCAmelCase_						(	unittest.TestCase					):


						'''simple docstring'''




						@slow
						def       _lowerCAmelCase       (	self				) ->				Union[str, Any]:
								snake_case_				:							List[str]						 =       TFMobileBertForPreTraining.from_pretrained("google/mobilebert-uncased"				)
								snake_case_				:							Dict						 =       tf.constant([[0, 1, 2, 3, 4, 5]]				)
								snake_case_				:							int						 =       model(_SCREAMING_SNAKE_CASE				)[0]

								snake_case_				:							Tuple						 =       [1, 6, 3_0522]
								self.assertEqual(output.shape		,				_SCREAMING_SNAKE_CASE				)

								snake_case_				:							List[str]						 =       tf.constant(
								    [
								        [
								            [-4.591_9547, -9.24_8295, -9.64_5256],
								            [-6.730_6175, -6.44_0284, -6.605_2837],
								            [-7.274_3506, -6.784_7915, -6.02_4673],
								        ]
								    ]				)
								tf.debugging.assert_near(output[:, :3, :3]		,				_SCREAMING_SNAKE_CASE		,				atol=1e-4				)








import argparse
import json
import os

from tensorflow.core.protobuf.saved_model_pba import SavedModel


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_copies.py
lowercase  :							Tuple			  =    '''.'''

# Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model)
lowercase  :							Union[str, Any]			  =    [
    '''Assert''',
    '''AssignVariableOp''',
    '''EmptyTensorList''',
    '''MergeV2Checkpoints''',
    '''ReadVariableOp''',
    '''ResourceGather''',
    '''RestoreV2''',
    '''SaveV2''',
    '''ShardedFilename''',
    '''StatefulPartitionedCall''',
    '''StaticRegexFullMatch''',
    '''VarHandleOp''',
]

def      lowerCAmelCase__	(    _a       :			Union[str, Any]  ,      _a       :			Dict  ,      _a       :			List[str]    ):
		snake_case_				:							Optional[int]						 =       SavedModel()
		snake_case_				:							Any						 =       []

		with open(os.path.join(_a  ,      "utils"  ,      "tf_ops"  ,      "onnx.json"    )    ) as f:
				snake_case_				:							int						 =       json.load(_a    )["opsets"]

		for i in range(1  ,      opset + 1    ):
				onnx_ops.extend(onnx_opsets[str(_a    )]    )

		with open(_a  ,      "rb"    ) as f:
				saved_model.ParseFromString(f.read()    )

		snake_case_				:							str						 =       set()

		# Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs)
		for meta_graph in saved_model.meta_graphs:
				# Add operations in the graph definition
				model_op_names.update(node.op for node in meta_graph.graph_def.node    )

				# Go through the functions in the graph definition
				for func in meta_graph.graph_def.library.function:
						# Add operations in each function
						model_op_names.update(node.op for node in func.node_def    )

    # Convert to list, sorted if you want
		snake_case_				:							int						 =       sorted(_a    )
		snake_case_				:							Optional[int]						 =       []

		for op in model_op_names:
				if op not in onnx_ops and op not in INTERNAL_OPS:
						incompatible_ops.append(_a    )

		if strict and len(_a    ) > 0:
				raise Exception(F'''Found the following incompatible ops for the opset {opset}:\n''' + incompatible_ops    )
		elif len(_a    ) > 0:
				print(F'''Found the following incompatible ops for the opset {opset}:'''    )
				print(*_a  ,      sep="\n"    )
		else:
				print(F'''The saved model {saved_model_path} can properly be converted with ONNX.'''    )


if __name__ == "__main__":
							lowercase  :							List[Any]			  =    argparse.ArgumentParser()
							parser.add_argument('''--saved_model_path''', help='''Path of the saved model to check (the .pb file).''')
							parser.add_argument(
							    '''--opset''', default=12, type=int, help='''The ONNX opset against which the model has to be tested.'''
							)
							parser.add_argument(
							    '''--framework''', choices=['''onnx'''], default='''onnx''', help='''Frameworks against which to test the saved model.'''
							)
							parser.add_argument(
							    '''--strict''', action='''store_true''', help='''Whether make the checking strict (raise errors) or not (raise warnings)'''
							)
							lowercase  :							int			  =    parser.parse_args()

							if args.framework == "onnx":
														onnx_compliancy(args.saved_model_path, args.strict, args.opset)
