


from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
    from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor



class 	__lowerCamelCase			:







       def __init__(			self: Dict,A_: List[str],A_: List[Any]=3,A_: Union[str, Any]=32,A_: List[str]=3,A_: List[str]=10,A_: Any=[10, 20, 30, 40],A_: List[str]=[1, 1, 2, 1],A_: Optional[int]=True,A_: Tuple=True,A_: str="relu",A_: Any=3,A_: Tuple=None,):






            '''simple docstring'''




            __UpperCamelCase =			parent
            __UpperCamelCase =			batch_size
            __UpperCamelCase =			image_size
            __UpperCamelCase =			num_channels
            __UpperCamelCase =			embeddings_size
            __UpperCamelCase =			hidden_sizes
            __UpperCamelCase =			depths
            __UpperCamelCase =			is_training
            __UpperCamelCase =			use_labels
            __UpperCamelCase =			hidden_act
            __UpperCamelCase =			num_labels
            __UpperCamelCase =			scope
            __UpperCamelCase =			len(A_					)







       def 		snake_case_	(			self: str					):






            '''simple docstring'''




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

            __UpperCamelCase =			None
            if self.use_labels:
                 __UpperCamelCase =			ids_tensor([self.batch_size],self.num_labels					)

            __UpperCamelCase =			self.get_config()

            return config, pixel_values, labels







       def 		snake_case_	(			self: Dict					):






            '''simple docstring'''




            return ResNetConfig(
                num_channels=self.num_channels,embeddings_size=self.embeddings_size,hidden_sizes=self.hidden_sizes,depths=self.depths,hidden_act=self.hidden_act,num_labels=self.num_labels,image_size=self.image_size,)







       def 		snake_case_	(			self: str,A_: Union[str, Any],A_: int,A_: str					):






            '''simple docstring'''




            __UpperCamelCase =			TFResNetModel(config=A_					)
            __UpperCamelCase =			model(A_					)
            # expected last hidden states: B, C, H // 32, W // 32
            self.parent.assertEqual(
                result.last_hidden_state.shape,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),)







       def 		snake_case_	(			self: Tuple,A_: Dict,A_: Union[str, Any],A_: Union[str, Any]					):






            '''simple docstring'''




            __UpperCamelCase =			self.num_labels
            __UpperCamelCase =			TFResNetForImageClassification(A_					)
            __UpperCamelCase =			model(A_,labels=A_					)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)					)







       def 		snake_case_	(			self: Union[str, Any]					):






            '''simple docstring'''




            __UpperCamelCase =			self.prepare_config_and_inputs()
            __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase =			config_and_inputs
            __UpperCamelCase =			{'pixel_values': pixel_values}
            return config, inputs_dict



@require_tf
class 	__lowerCamelCase			(_a				,      _a				,      unittest.TestCase						):
       _lowercase											=     (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
       _lowercase											=     (
           {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
           if is_tf_available()
           else {}
       )

       _lowercase											=     False
       _lowercase											=     False
       _lowercase											=     False
       _lowercase											=     False
       _lowercase											=     False







       def 		snake_case_	(			self: List[str]					):






            '''simple docstring'''




            __UpperCamelCase =			TFResNetModelTester(self					)
            __UpperCamelCase =			ConfigTester(self,config_class=A_,has_text_modality=A_					)







       def 		snake_case_	(			self: Dict					):






            '''simple docstring'''




            self.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()







       def 		snake_case_	(			self: Tuple					):






            '''simple docstring'''




            return







       @unittest.skip(reason='ResNet does not use inputs_embeds'					)
       def 		snake_case_	(			self: List[str]					):






            '''simple docstring'''




            pass







       @unittest.skip(reason='ResNet does not support input and output embeddings'					)
       def 		snake_case_	(			self: List[str]					):






            '''simple docstring'''




            pass







       def 		snake_case_	(			self: List[Any]					):






            '''simple docstring'''




            __UpperCamelCase,    __UpperCamelCase =			self.model_tester.prepare_config_and_inputs_for_common()

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

                 __UpperCamelCase =			['pixel_values']
                 self.assertListEqual(arg_names[:1],A_					)







       def 		snake_case_	(			self: str					):






            '''simple docstring'''




            __UpperCamelCase =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*A_					)







       def 		snake_case_	(			self: Dict					):






            '''simple docstring'''




            def check_hidden_states_output(A_: Union[str, Any],A_: Optional[Any],A_: Union[str, Any]					):
                 __UpperCamelCase =			model_class(A_					)
                 __UpperCamelCase =			model(**self._prepare_for_class(A_,A_					)					)

                 __UpperCamelCase =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 __UpperCamelCase =			self.model_tester.num_stages
                 self.assertEqual(len(A_					),expected_num_stages + 1					)

                 # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
                 self.assertListEqual(
                     list(hidden_states[0].shape[-2:]					),[self.model_tester.image_size // 4, self.model_tester.image_size // 4],)

            __UpperCamelCase,    __UpperCamelCase =			self.model_tester.prepare_config_and_inputs_for_common()
            __UpperCamelCase =			['basic', 'bottleneck']
            for model_class in self.all_model_classes:
                 for layer_type in layers_type:
                      __UpperCamelCase =			layer_type
                      __UpperCamelCase =			True
                      check_hidden_states_output(A_,A_,A_					)

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

                      check_hidden_states_output(A_,A_,A_					)







       def 		snake_case_	(			self: str					):






            '''simple docstring'''




            __UpperCamelCase =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*A_					)







       @slow
       def 		snake_case_	(			self: List[str]					):






            '''simple docstring'''




            for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __UpperCamelCase =			TFResNetModel.from_pretrained(A_					)
                 self.assertIsNotNone(A_					)






def 		_A		(		)					-> List[Any]:


     """simple docstring"""


     __UpperCamelCase =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
     return image



@require_tf
@require_vision
class 	__lowerCamelCase			(unittest.TestCase						):







       @cached_property
       def 		snake_case_	(			self: List[str]					):






            '''simple docstring'''




            return (
                AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)
                if is_vision_available()
                else None
            )







       @slow
       def 		snake_case_	(			self: Optional[Any]					):






            '''simple docstring'''




            __UpperCamelCase =			TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)

            __UpperCamelCase =			self.default_image_processor
            __UpperCamelCase =			prepare_img()
            __UpperCamelCase =			image_processor(images=A_,return_tensors='tf'					)

            # forward pass
            __UpperCamelCase =			model(**A_					)

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

            __UpperCamelCase =			tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]					)

            self.assertTrue(np.allclose(outputs.logits[0, :3].numpy(),A_,atol=1E-4					)					)



'''simple docstring'''


import argparse
import os

import numpy as np
import tensorflow as tf
import torch

from transformers import BertModel





def    lowerCAmelCase       (		UpperCamelCase__					: BertModel     ,       UpperCamelCase__					: str     ,       UpperCamelCase__					: str							):


	"""simple docstring"""
	__UpperCAmelCase      					=      ('''dense.weight''', '''attention.self.query''', '''attention.self.key''', '''attention.self.value''')

	__UpperCAmelCase      					=      (
	    ('''layer.''', '''layer_'''),
	    ('''word_embeddings.weight''', '''word_embeddings'''),
	    ('''position_embeddings.weight''', '''position_embeddings'''),
	    ('''token_type_embeddings.weight''', '''token_type_embeddings'''),
	    ('''.''', '''/'''),
	    ('''LayerNorm/weight''', '''LayerNorm/gamma'''),
	    ('''LayerNorm/bias''', '''LayerNorm/beta'''),
	    ('''weight''', '''kernel'''),
	)

	if not os.path.isdir(UpperCamelCase__							):
		os.makedirs(UpperCamelCase__							)

	__UpperCAmelCase      					=      model.state_dict()

	def to_tf_var_name(UpperCamelCase__					: str							):
		for patt, repl in iter(UpperCamelCase__							):
			__UpperCAmelCase      					=      name.replace(UpperCamelCase__     ,       UpperCamelCase__							)
		return f"""bert/{name}"""

	def create_tf_var(UpperCamelCase__					: np.ndarray     ,       UpperCamelCase__					: str     ,       UpperCamelCase__					: tf.Session							):
		__UpperCAmelCase      					=      tf.dtypes.as_dtype(tensor.dtype							)
		__UpperCAmelCase      					=      tf.get_variable(dtype=UpperCamelCase__     ,       shape=tensor.shape     ,       name=UpperCamelCase__     ,       initializer=tf.zeros_initializer()							)
		session.run(tf.variables_initializer([tf_var]							)							)
		session.run(UpperCamelCase__							)
		return tf_var

	tf.reset_default_graph()
	with tf.Session() as session:
		for var_name in state_dict:
			__UpperCAmelCase      					=      to_tf_var_name(UpperCamelCase__							)
			__UpperCAmelCase      					=      state_dict[var_name].numpy()
			if any(x in var_name for x in tensors_to_transpose							):
				__UpperCAmelCase      					=      torch_tensor.T
			__UpperCAmelCase      					=      create_tf_var(tensor=UpperCamelCase__     ,       name=UpperCamelCase__     ,       session=UpperCamelCase__							)
			tf.keras.backend.set_value(UpperCamelCase__     ,       UpperCamelCase__							)
			__UpperCAmelCase      					=      session.run(UpperCamelCase__							)
			print(f"""Successfully created {tf_name}: {np.allclose(UpperCamelCase__     ,       UpperCamelCase__							)}"""							)

		__UpperCAmelCase      					=      tf.train.Saver(tf.trainable_variables()							)
		saver.save(UpperCamelCase__     ,       os.path.join(UpperCamelCase__     ,       model_name.replace('''-'''     ,       '''_'''							) + '''.ckpt'''							)							)





def    lowerCAmelCase       (		UpperCamelCase__					: List[str]=None							):


	"""simple docstring"""
	__UpperCAmelCase      					=      argparse.ArgumentParser()
	parser.add_argument('''--model_name'''     ,       type=UpperCamelCase__     ,       required=UpperCamelCase__     ,       help='''model name e.g. bert-base-uncased'''							)
	parser.add_argument(
	    '''--cache_dir'''     ,       type=UpperCamelCase__     ,       default=UpperCamelCase__     ,       required=UpperCamelCase__     ,       help='''Directory containing pytorch model'''							)
	parser.add_argument('''--pytorch_model_path'''     ,       type=UpperCamelCase__     ,       required=UpperCamelCase__     ,       help='''/path/to/<pytorch-model-name>.bin'''							)
	parser.add_argument('''--tf_cache_dir'''     ,       type=UpperCamelCase__     ,       required=UpperCamelCase__     ,       help='''Directory in which to save tensorflow model'''							)
	__UpperCAmelCase      					=      parser.parse_args(UpperCamelCase__							)

	__UpperCAmelCase      					=      BertModel.from_pretrained(
	    pretrained_model_name_or_path=args.model_name     ,       state_dict=torch.load(args.pytorch_model_path							)     ,       cache_dir=args.cache_dir     ,       )

	convert_pytorch_checkpoint_to_tf(model=UpperCamelCase__     ,       ckpt_dir=args.tf_cache_dir     ,       model_name=args.model_name							)


if __name__ == "__main__":
					main()
