



'''simple docstring'''
import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import RegNetForImageClassification, RegNetModel
					from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor






class 							lowercase__     :





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







							'''simple docstring'''
							_UpperCamelCase :		Any			    =       parent
							_UpperCamelCase :		Optional[int]			    =       batch_size
							_UpperCamelCase :		List[str]			    =       image_size
							_UpperCamelCase :		List[Any]			    =       num_channels
							_UpperCamelCase :		Optional[int]			    =       embeddings_size
							_UpperCamelCase :		Union[str, Any]			    =       hidden_sizes
							_UpperCamelCase :		List[Any]			    =       depths
							_UpperCamelCase :		Tuple			    =       is_training
							_UpperCamelCase :		Optional[Any]			    =       use_labels
							_UpperCamelCase :		Union[str, Any]			    =       hidden_act
							_UpperCamelCase :		int			    =       num_labels
							_UpperCamelCase :		Optional[Any]			    =       scope
							_UpperCamelCase :		List[str]			    =       len(lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    Any			):







							'''simple docstring'''
							_UpperCamelCase :		List[str]			    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

							_UpperCamelCase :		List[str]			    =       None
							if self.use_labels:
													_UpperCamelCase :		str			    =       ids_tensor([self.batch_size]			,self.num_labels			)

							_UpperCamelCase :		Optional[int]			    =       self.get_config()

							return config, pixel_values, labels





	def      UpperCamelCase_  (			self :    str			):







							'''simple docstring'''
							return RegNetConfig(
							    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			,)





	def      UpperCamelCase_  (			self :    List[Any]			,lowerCamelCase__ :    str			,lowerCamelCase__ :    List[str]			,lowerCamelCase__ :    str			):







							'''simple docstring'''
							_UpperCamelCase :		int			    =       RegNetModel(config=lowerCamelCase__			)
							model.to(lowerCamelCase__			)
							model.eval()
							_UpperCamelCase :		int			    =       model(lowerCamelCase__			)
							# 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      UpperCamelCase_  (			self :    Union[str, Any]			,lowerCamelCase__ :    Tuple			,lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    Dict			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[int]			    =       self.num_labels
							_UpperCamelCase :		str			    =       RegNetForImageClassification(lowerCamelCase__			)
							model.to(lowerCamelCase__			)
							model.eval()
							_UpperCamelCase :		int			    =       model(lowerCamelCase__			,labels=lowerCamelCase__			)
							self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.num_labels)			)





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[int]			    =       self.prepare_config_and_inputs()
							_UpperCamelCase    ,      _UpperCamelCase    ,      _UpperCamelCase :		int			    =       config_and_inputs
							_UpperCamelCase :		Union[str, Any]			    =       {'pixel_values': pixel_values}
							return config, inputs_dict






@require_torch
class 							lowercase__     (							lowercase						, lowercase						, unittest.TestCase       ):
	lowercase__      =      (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
	lowercase__      =      (
	    {"""feature-extraction""": RegNetModel, """image-classification""": RegNetForImageClassification}
	    if is_torch_available()
	    else {}
	)

	lowercase__      =      False
	lowercase__      =      False
	lowercase__      =      False
	lowercase__      =      False





	def      UpperCamelCase_  (			self :    Optional[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[Any]			    =       RegNetModelTester(self			)
							_UpperCamelCase :		Dict			    =       ConfigTester(self			,config_class=lowerCamelCase__			,has_text_modality=lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    Tuple			):







							'''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      UpperCamelCase_  (			self :    Dict			):







							'''simple docstring'''
							return





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







							'''simple docstring'''
							pass





	@unittest.skip(reason='RegNet does not support input and output embeddings'			)
	def      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''simple docstring'''
							pass





	def      UpperCamelCase_  (			self :    str			):







							'''simple docstring'''
							_UpperCamelCase    ,      _UpperCamelCase :		str			    =       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCamelCase :		List[str]			    =       model_class(lowerCamelCase__			)
													_UpperCamelCase :		Optional[int]			    =       inspect.signature(model.forward			)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													_UpperCamelCase :		Optional[int]			    =       [*signature.parameters.keys()]

													_UpperCamelCase :		Any			    =       ['pixel_values']
													self.assertListEqual(arg_names[:1]			,lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		str			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    Tuple			):







							'''simple docstring'''
							_UpperCamelCase    ,      _UpperCamelCase :		str			    =       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCamelCase :		Union[str, Any]			    =       model_class(config=lowerCamelCase__			)
													for name, module in model.named_modules():
																			if isinstance(lowerCamelCase__			,(nn.BatchNormad, nn.GroupNorm)			):
																									self.assertTrue(
																									    torch.all(module.weight == 1			)			,msg=F'Parameter {name} of model {model_class} seems not properly initialized'			,)
																									self.assertTrue(
																									    torch.all(module.bias == 0			)			,msg=F'Parameter {name} of model {model_class} seems not properly initialized'			,)





	def      UpperCamelCase_  (			self :    Tuple			):







							'''simple docstring'''
							def check_hidden_states_output(lowerCamelCase__ :    Dict			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    List[Any]			):
													_UpperCamelCase :		Union[str, Any]			    =       model_class(lowerCamelCase__			)
													model.to(lowerCamelCase__			)
													model.eval()

													with torch.no_grad():
																			_UpperCamelCase :		Dict			    =       model(**self._prepare_for_class(lowerCamelCase__			,lowerCamelCase__			)			)

													_UpperCamelCase :		List[Any]			    =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													_UpperCamelCase :		int			    =       self.model_tester.num_stages
													self.assertEqual(len(lowerCamelCase__			)			,expected_num_stages + 1			)

													# RegNet'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 // 2, self.model_tester.image_size // 2]			,)

							_UpperCamelCase    ,      _UpperCamelCase :		List[str]			    =       self.model_tester.prepare_config_and_inputs_for_common()
							_UpperCamelCase :		Any			    =       ['basic', 'bottleneck']
							for model_class in self.all_model_classes:
													for layer_type in layers_type:
																			_UpperCamelCase :		Dict			    =       layer_type
																			_UpperCamelCase :		Dict			    =       True
																			check_hidden_states_output(lowerCamelCase__			,lowerCamelCase__			,lowerCamelCase__			)

																			# check that output_hidden_states also work using config
																			del inputs_dict["output_hidden_states"]
																			_UpperCamelCase :		List[Any]			    =       True

																			check_hidden_states_output(lowerCamelCase__			,lowerCamelCase__			,lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		List[Any]			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__			)





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







							'''simple docstring'''
							for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_UpperCamelCase :		Union[str, Any]			    =       RegNetModel.from_pretrained(lowerCamelCase__			)
													self.assertIsNotNone(lowerCamelCase__			)






def A__   (					):
						_UpperCamelCase :		Union[str, Any]			    =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
						return image






@require_torch
@require_vision
class 							lowercase__     (							unittest.TestCase       ):





	@cached_property
	def      UpperCamelCase_  (			self :    Dict			):







							'''simple docstring'''
							return (
							    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)
							    if is_vision_available()
							    else None
							)





	@slow
	def      UpperCamelCase_  (			self :    str			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[int]			    =       RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			).to(lowerCamelCase__			)

							_UpperCamelCase :		Any			    =       self.default_image_processor
							_UpperCamelCase :		Union[str, Any]			    =       prepare_img()
							_UpperCamelCase :		Optional[int]			    =       image_processor(images=lowerCamelCase__			,return_tensors='pt'			).to(lowerCamelCase__			)

							# forward pass
							with torch.no_grad():
													_UpperCamelCase :		Tuple			    =       model(**lowerCamelCase__			)

							# verify the logits
							_UpperCamelCase :		Union[str, Any]			    =       torch.Size((1, 1000)			)
							self.assertEqual(outputs.logits.shape			,lowerCamelCase__			)

							_UpperCamelCase :		Tuple			    =       torch.tensor([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]			).to(lowerCamelCase__			)

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







'''simple docstring'''
import argparse

import torch

from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert
from transformers.utils import logging


logging.set_verbosity_info()






def A__   (					UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_							):
						# Initialise PyTorch model
						_UpperCamelCase :		Any			    =       LxmertConfig.from_json_file(UpperCAmelCase_							)
						print(f'Building PyTorch model from configuration: {config}'							)
						_UpperCamelCase :		int			    =       LxmertForPreTraining(UpperCAmelCase_							)

						# Load weights from tf checkpoint
						load_tf_weights_in_lxmert(UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_							)

						# Save pytorch-model
						print(f'Save PyTorch model to {pytorch_dump_path}'							)
						torch.save(model.state_dict()  ,  UpperCAmelCase_							)


if __name__ == "__main__":
					snake_case_			:     int  	=  argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.'
					)
					parser.add_argument(
					    '--config_file',
					    default=None,
					    type=str,
					    required=True,
					    help='The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.',
					)
					parser.add_argument(
					    '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
					)
					snake_case_			:     List[str]  	=  parser.parse_args()
					convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)


