




from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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


if is_tf_available():
		import tensorflow as tf

		from transformers import TFCvtForImageClassification, TFCvtModel
		from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor

class 						__lowerCAmelCase      (      __magic_name__					):
							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								a									=				self.config_class(**self.inputs_dict							)
								self.parent.assertTrue(hasattr(__magic_name__						, """embed_dim"""							)							)
								self.parent.assertTrue(hasattr(__magic_name__						, """num_heads"""							)							)







class 						__lowerCAmelCase      :
							def __init__(		self		:List[Any]						, __magic_name__		:int						, __magic_name__		:Dict=13						, __magic_name__		:Optional[int]=64						, __magic_name__		:str=3						, __magic_name__		:List[str]=[16, 48, 96]						, __magic_name__		:List[Any]=[1, 3, 6]						, __magic_name__		:Tuple=[1, 2, 10]						, __magic_name__		:Optional[int]=[7, 3, 3]						, __magic_name__		:Dict=[4, 2, 2]						, __magic_name__		:List[str]=[2, 1, 1]						, __magic_name__		:Optional[int]=[2, 2, 2]						, __magic_name__		:Tuple=[False, False, True]						, __magic_name__		:str=[0.0, 0.0, 0.0]						, __magic_name__		:int=0.02						, __magic_name__		:int=1E-1_2						, __magic_name__		:int=True						, __magic_name__		:List[str]=True						, __magic_name__		:Any=2						, ):







								'''simple docstring'''







								a									=				parent
								a									=				batch_size
								a									=				image_size
								a									=				patch_sizes
								a									=				patch_stride
								a									=				patch_padding
								a									=				is_training
								a									=				use_labels
								a									=				num_labels
								a									=				num_channels
								a									=				embed_dim
								a									=				num_heads
								a									=				stride_kv
								a									=				depth
								a									=				cls_token
								a									=				attention_drop_rate
								a									=				initializer_range
								a									=				layer_norm_eps
							def  lowerCamelCase__				(		self		:int							):







								'''simple docstring'''







								a									=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

								a									=				None
								if self.use_labels:
									# create a random int32 tensor of given shape
									a									=				ids_tensor([self.batch_size]						, self.num_labels							)

								a									=				self.get_config()
								return config, pixel_values, labels
							def  lowerCamelCase__				(		self		:List[Any]							):







								'''simple docstring'''







								return CvtConfig(
								    image_size=self.image_size						, num_labels=self.num_labels						, num_channels=self.num_channels						, embed_dim=self.embed_dim						, num_heads=self.num_heads						, patch_sizes=self.patch_sizes						, patch_padding=self.patch_padding						, patch_stride=self.patch_stride						, stride_kv=self.stride_kv						, depth=self.depth						, cls_token=self.cls_token						, attention_drop_rate=self.attention_drop_rate						, initializer_range=self.initializer_range						, )
							def  lowerCamelCase__				(		self		:Dict						, __magic_name__		:Optional[int]						, __magic_name__		:Optional[int]						, __magic_name__		:List[str]							):







								'''simple docstring'''







								a									=				TFCvtModel(config=__magic_name__							)
								a									=				model(__magic_name__						, training=__magic_name__							)
								a									=				(self.image_size, self.image_size)
								a							,					a									=				image_size[0], image_size[1]
								for i in range(len(self.depth							)							):
									a									=				floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1							)
									a									=				floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1							)
								self.parent.assertEqual(result.last_hidden_state.shape						, (self.batch_size, self.embed_dim[-1], height, width)							)
							def  lowerCamelCase__				(		self		:List[str]						, __magic_name__		:Any						, __magic_name__		:Any						, __magic_name__		:Optional[Any]							):







								'''simple docstring'''







								a									=				self.num_labels
								a									=				TFCvtForImageClassification(__magic_name__							)
								a									=				model(__magic_name__						, labels=__magic_name__						, training=__magic_name__							)
								self.parent.assertEqual(result.logits.shape						, (self.batch_size, self.num_labels)							)





							def  lowerCamelCase__				(		self		:Optional[Any]							):







								'''simple docstring'''







								a									=				self.prepare_config_and_inputs()
								a							,					a							,					a									=				config_and_inputs
								a									=				{"""pixel_values""": pixel_values}
								return config, inputs_dict







@require_tf
class 						__lowerCAmelCase      (      __magic_name__ ,			__magic_name__ ,			unittest.TestCase					):
							UpperCamelCase__   	=    (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
							UpperCamelCase__   	=    (
							    {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
							    if is_tf_available()
							    else {}
							)
							UpperCamelCase__   	=    False
							UpperCamelCase__   	=    False
							UpperCamelCase__   	=    False
							UpperCamelCase__   	=    False
							UpperCamelCase__   	=    False
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								a									=				TFCvtModelTester(self							)
								a									=				TFCvtConfigTester(self						, config_class=__magic_name__						, has_text_modality=__magic_name__						, hidden_size=37							)
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								self.config_tester.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()
							@unittest.skip(reason="""Cvt does not output attentions"""							)
							def  lowerCamelCase__				(		self		:List[Any]							):







								'''simple docstring'''







								pass
							@unittest.skip(reason="""Cvt does not use inputs_embeds"""							)
							def  lowerCamelCase__				(		self		:int							):







								'''simple docstring'''







								pass
							@unittest.skip(reason="""Cvt does not support input and output embeddings"""							)
							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







								pass
							@unittest.skipIf(
							    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""							)							) == 0						, reason="""TF does not support backprop for grouped convolutions on CPU."""						, )
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								super().test_dataset_conversion()
							@unittest.skipIf(
							    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""							)							) == 0						, reason="""TF does not support backprop for grouped convolutions on CPU."""						, )
							@slow
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								super().test_keras_fit()
							@unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8"""							)
							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								a									=				tf.keras.mixed_precision.Policy("""mixed_float16"""							)
								tf.keras.mixed_precision.set_global_policy(__magic_name__							)
								super().test_keras_fit()
								tf.keras.mixed_precision.set_global_policy("""float32"""							)
							def  lowerCamelCase__				(		self		:Optional[Any]							):







								'''simple docstring'''







								a							,					a									=				self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									a									=				model_class(__magic_name__							)
									a									=				inspect.signature(model.call							)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									a									=				[*signature.parameters.keys()]

									a									=				["""pixel_values"""]
									self.assertListEqual(arg_names[:1]						, __magic_name__							)
							def  lowerCamelCase__				(		self		:Any							):







								'''simple docstring'''







								def check_hidden_states_output(__magic_name__		:List[str]						, __magic_name__		:Optional[Any]						, __magic_name__		:int							):
									a									=				model_class(__magic_name__							)

									a									=				model(**self._prepare_for_class(__magic_name__						, __magic_name__							)							)
									a									=				outputs.hidden_states

									a									=				len(self.model_tester.depth							)
									self.assertEqual(len(__magic_name__							)						, __magic_name__							)

									# verify the first hidden states (first block)
									self.assertListEqual(
									    list(hidden_states[0].shape[-3:]							)						, [
									        self.model_tester.embed_dim[0],
									        self.model_tester.image_size // 4,
									        self.model_tester.image_size // 4,
									    ]						, )

								a							,					a									=				self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									a									=				True
									check_hidden_states_output(__magic_name__						, __magic_name__						, __magic_name__							)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									a									=				True

									check_hidden_states_output(__magic_name__						, __magic_name__						, __magic_name__							)
							def  lowerCamelCase__				(		self		:Optional[Any]							):







								'''simple docstring'''







								a									=				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__magic_name__							)
							def  lowerCamelCase__				(		self		:Optional[Any]							):







								'''simple docstring'''







								a									=				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*__magic_name__							)





							@slow
							def  lowerCamelCase__				(		self		:int							):







								'''simple docstring'''







								for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									a									=				TFCvtModel.from_pretrained(__magic_name__							)
									self.assertIsNotNone(__magic_name__							)







def 						__A						(      ) ->			Optional[int]:
	a									=				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""       )
	return image



@require_tf
@require_vision
class 						__lowerCAmelCase      (      unittest.TestCase					):
							@cached_property
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)





							@slow
							def  lowerCamelCase__				(		self		:List[Any]							):







								'''simple docstring'''







								a									=				TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)

								a									=				self.default_image_processor
								a									=				prepare_img()
								a									=				image_processor(images=__magic_name__						, return_tensors="""tf"""							)

								# forward pass
								a									=				model(**__magic_name__							)

								# verify the logits
								a									=				tf.TensorShape((1, 1000)							)
								self.assertEqual(outputs.logits.shape						, __magic_name__							)

								a									=				tf.constant([0.9285, 0.9015, -0.3150]							)
								self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()						, __magic_name__						, 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
__UpperCamelCase   :			Tuple          = "."

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





def 						__A						(      __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase       ) ->			Union[str, Any]:
	a									=				SavedModel()
	a									=				[]

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

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

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

	a									=				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
	a									=				sorted(__lowerCamelCase       )
	a									=				[]

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

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


if __name__ == "__main__":
		__UpperCamelCase   :			Optional[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)"
		)
		__UpperCamelCase   :			str          = parser.parse_args()

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

