



import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
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 transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
 from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor




class 					snake_case__						:






     """simple docstring"""


     def __init__(       self  :  int, _snake_case  :  str, _snake_case  :  int=1_3, _snake_case  :  List[str]=3_2, _snake_case  :  Any=3, _snake_case  :  Optional[int]=4, _snake_case  :  List[Any]=[1_0, 2_0, 3_0, 4_0], _snake_case  :  Optional[int]=[2, 2, 3, 2], _snake_case  :  Any=True, _snake_case  :  Union[str, Any]=True, _snake_case  :  Any=3_7, _snake_case  :  str="gelu", _snake_case  :  List[Any]=1_0, _snake_case  :  Optional[Any]=0.0_2, _snake_case  :  str=["stage2", "stage3", "stage4"], _snake_case  :  Tuple=[2, 3, 4], _snake_case  :  Dict=None, )   ->Optional[Any]:
            snake_case__							:	int   	=	parent
            snake_case__							:	List[Any]   	=	batch_size
            snake_case__							:	Dict   	=	image_size
            snake_case__							:	Tuple   	=	num_channels
            snake_case__							:	str   	=	num_stages
            snake_case__							:	Any   	=	hidden_sizes
            snake_case__							:	Any   	=	depths
            snake_case__							:	int   	=	is_training
            snake_case__							:	Any   	=	use_labels
            snake_case__							:	Any   	=	intermediate_size
            snake_case__							:	int   	=	hidden_act
            snake_case__							:	List[Any]   	=	num_labels
            snake_case__							:	Dict   	=	initializer_range
            snake_case__							:	Dict   	=	out_features
            snake_case__							:	Optional[int]   	=	out_indices
            snake_case__							:	Optional[Any]   	=	scope






     def    lowercase_   (       self  :  int					)   ->int:
            snake_case__							:	Optional[Any]   	=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

            snake_case__							:	Tuple   	=	self.get_config()
            return config, pixel_values, labels






     def    lowercase_   (       self  :  Optional[int]					)   ->Union[str, Any]:
            return ConvNextConfig(
                num_channels=self.num_channels, hidden_sizes=self.hidden_sizes, depths=self.depths, num_stages=self.num_stages, hidden_act=self.hidden_act, is_decoder=_snake_case, initializer_range=self.initializer_range, out_features=self.out_features, out_indices=self.out_indices, num_labels=self.num_labels, )






     def    lowercase_   (       self  :  Any, _snake_case  :  Optional[Any], _snake_case  :  Optional[int], _snake_case  :  Optional[Any]					)   ->Dict:
            snake_case__							:	Union[str, Any]   	=	ConvNextModel(config=_snake_case					)
            model.to(_snake_case					)
            model.eval()
            snake_case__							:	List[Any]   	=	model(_snake_case					)
            # 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 // 3_2, self.image_size // 3_2), )






     def    lowercase_   (       self  :  Tuple, _snake_case  :  str, _snake_case  :  Dict, _snake_case  :  Optional[int]					)   ->List[Any]:
            snake_case__							:	Optional[int]   	=	ConvNextForImageClassification(_snake_case					)
            model.to(_snake_case					)
            model.eval()
            snake_case__							:	Tuple   	=	model(_snake_case, labels=_snake_case					)
            self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)					)






     def    lowercase_   (       self  :  Dict, _snake_case  :  Dict, _snake_case  :  Any, _snake_case  :  Dict					)   ->Optional[int]:
            snake_case__							:	Dict   	=	ConvNextBackbone(config=_snake_case					)
            model.to(_snake_case					)
            model.eval()
            snake_case__							:	Optional[int]   	=	model(_snake_case					)

            # verify hidden states
            self.parent.assertEqual(len(result.feature_maps					), len(config.out_features					)					)
            self.parent.assertListEqual(list(result.feature_maps[0].shape					), [self.batch_size, self.hidden_sizes[1], 4, 4]					)

            # verify channels
            self.parent.assertEqual(len(model.channels					), len(config.out_features					)					)
            self.parent.assertListEqual(model.channels, config.hidden_sizes[1:]					)

            # verify backbone works with out_features=None
            snake_case__							:	str   	=	None
            snake_case__							:	Optional[Any]   	=	ConvNextBackbone(config=_snake_case					)
            model.to(_snake_case					)
            model.eval()
            snake_case__							:	Dict   	=	model(_snake_case					)

            # verify feature maps
            self.parent.assertEqual(len(result.feature_maps					), 1					)
            self.parent.assertListEqual(list(result.feature_maps[0].shape					), [self.batch_size, self.hidden_sizes[-1], 1, 1]					)

            # verify channels
            self.parent.assertEqual(len(model.channels					), 1					)
            self.parent.assertListEqual(model.channels, [config.hidden_sizes[-1]]					)






     def    lowercase_   (       self  :  List[str]					)   ->Optional[Any]:
            snake_case__							:	str   	=	self.prepare_config_and_inputs()
            snake_case__	,				snake_case__	,				snake_case__							:	Union[str, Any]   	=	config_and_inputs
            snake_case__							:	Dict   	=	{'pixel_values': pixel_values}
            return config, inputs_dict




@require_torch
class 					snake_case__						(       lowerCAmelCase_				,     lowerCAmelCase_				,     unittest.TestCase     ):






     """simple docstring"""


     _SCREAMING_SNAKE_CASE						=	(
         (
             ConvNextModel,
             ConvNextForImageClassification,
             ConvNextBackbone,
         )
         if is_torch_available()
         else ()
     )
     _SCREAMING_SNAKE_CASE						=	(
         {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
         if is_torch_available()
         else {}
     )

     _SCREAMING_SNAKE_CASE						=	True
     _SCREAMING_SNAKE_CASE						=	False
     _SCREAMING_SNAKE_CASE						=	False
     _SCREAMING_SNAKE_CASE						=	False
     _SCREAMING_SNAKE_CASE						=	False






     def    lowercase_   (       self  :  Tuple					)   ->str:
            snake_case__							:	List[Any]   	=	ConvNextModelTester(self					)
            snake_case__							:	Union[str, Any]   	=	ConfigTester(self, config_class=_snake_case, has_text_modality=_snake_case, hidden_size=3_7					)






     def    lowercase_   (       self  :  Union[str, Any]					)   ->int:
            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    lowercase_   (       self  :  Any					)   ->Tuple:
            return






     @unittest.skip(reason='ConvNext does not use inputs_embeds'					)
     def    lowercase_   (       self  :  Optional[int]					)   ->Optional[Any]:
            pass






     @unittest.skip(reason='ConvNext does not support input and output embeddings'					)
     def    lowercase_   (       self  :  List[str]					)   ->Union[str, Any]:
            pass






     @unittest.skip(reason='ConvNext does not use feedforward chunking'					)
     def    lowercase_   (       self  :  Optional[Any]					)   ->Union[str, Any]:
            pass






     def    lowercase_   (       self  :  Union[str, Any]					)   ->Optional[int]:
            snake_case__	,				snake_case__							:	Union[str, Any]   	=	self.model_tester.prepare_config_and_inputs_for_common()

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

                   snake_case__							:	Optional[int]   	=	['pixel_values']
                   self.assertListEqual(arg_names[:1], _snake_case					)






     def    lowercase_   (       self  :  Tuple					)   ->Optional[Any]:
            snake_case__							:	List[str]   	=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*_snake_case					)






     def    lowercase_   (       self  :  Dict					)   ->str:
            snake_case__							:	Optional[int]   	=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_backbone(*_snake_case					)






     def    lowercase_   (       self  :  Dict					)   ->Any:
            def check_hidden_states_output(_snake_case  :  Optional[Any], _snake_case  :  int, _snake_case  :  Union[str, Any]					):
                   snake_case__							:	Union[str, Any]   	=	model_class(_snake_case					)
                   model.to(_snake_case					)
                   model.eval()

                   with torch.no_grad():
                          snake_case__							:	Tuple   	=	model(**self._prepare_for_class(_snake_case, _snake_case					)					)

                   snake_case__							:	List[str]   	=	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                   snake_case__							:	Tuple   	=	self.model_tester.num_stages
                   self.assertEqual(len(_snake_case					), expected_num_stages + 1					)

                   # ConvNext'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], )

            snake_case__	,				snake_case__							:	Tuple   	=	self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                   snake_case__							:	List[Any]   	=	True
                   check_hidden_states_output(_snake_case, _snake_case, _snake_case					)

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

                   check_hidden_states_output(_snake_case, _snake_case, _snake_case					)






     def    lowercase_   (       self  :  Any					)   ->Any:
            snake_case__							:	Union[str, Any]   	=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*_snake_case					)






     @slow
     def    lowercase_   (       self  :  Tuple					)   ->Tuple:
            for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   snake_case__							:	Dict   	=	ConvNextModel.from_pretrained(_snake_case					)
                   self.assertIsNotNone(_snake_case					)


def        lowercase_							():
       snake_case__							:	Tuple   	=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
       return image




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






     """simple docstring"""


     @cached_property
     def    lowercase_   (       self  :  Optional[int]					)   ->Any:
            return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'					) if is_vision_available() else None






     @slow
     def    lowercase_   (       self  :  Union[str, Any]					)   ->Any:
            snake_case__							:	Tuple   	=	ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'					).to(_snake_case					)

            snake_case__							:	Optional[int]   	=	self.default_image_processor
            snake_case__							:	Optional[Any]   	=	prepare_img()
            snake_case__							:	int   	=	image_processor(images=_snake_case, return_tensors='pt'					).to(_snake_case					)

            # forward pass
            with torch.no_grad():
                   snake_case__							:	Union[str, Any]   	=	model(**_snake_case					)

            # verify the logits
            snake_case__							:	Tuple   	=	torch.Size((1, 1_0_0_0)					)
            self.assertEqual(outputs.logits.shape, _snake_case					)

            snake_case__							:	Dict   	=	torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]					).to(_snake_case					)

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




@require_torch
class 					snake_case__						(       unittest.TestCase				,     lowerCAmelCase_     ):






     """simple docstring"""


     _SCREAMING_SNAKE_CASE						=	(ConvNextBackbone,) if is_torch_available() else ()
     _SCREAMING_SNAKE_CASE						=	ConvNextConfig

     _SCREAMING_SNAKE_CASE						=	False






     def    lowercase_   (       self  :  Tuple					)   ->Tuple:
            snake_case__							:	List[Any]   	=	ConvNextModelTester(self					)











import argparse

import torch

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


logging.set_verbosity_info()
def        lowercase_							(A : str		,					A : List[Any]		,					A : Any      ):
       # Initialise PyTorch model
       snake_case__							:	List[Any]   	=	LxmertConfig.from_json_file(A      )
       print(F'''Building PyTorch model from configuration: {config}'''      )
       snake_case__							:	List[str]   	=	LxmertForPreTraining(A      )

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

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


if __name__ == "__main__":
 a_   :Union[str, Any]        =      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."
 )
 a_   :Optional[int]        =      parser.parse_args()
 convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)






