


'''simple docstring'''

import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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_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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
   from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor





class 						__SCREAMING_SNAKE_CASE					:






     def __init__(			self     ,							__UpperCamelCase     ,							__UpperCamelCase=13     ,							__UpperCamelCase=32     ,							__UpperCamelCase=3     ,							__UpperCamelCase=4     ,							__UpperCamelCase=[10, 20, 30, 40]     ,							__UpperCamelCase=[2, 2, 3, 2]     ,							__UpperCamelCase=True     ,							__UpperCamelCase=True     ,							__UpperCamelCase=37     ,							__UpperCamelCase="gelu"     ,							__UpperCamelCase=10     ,							__UpperCamelCase=0.02     ,							__UpperCamelCase=["stage2", "stage3", "stage4"]     ,							__UpperCamelCase=[2, 3, 4]     ,							__UpperCamelCase=None     ,							)       ->    Optional[Any]:
          _a						=		parent
          _a						=		batch_size
          _a						=		image_size
          _a						=		num_channels
          _a						=		num_stages
          _a						=		hidden_sizes
          _a						=		depths
          _a						=		is_training
          _a						=		use_labels
          _a						=		intermediate_size
          _a						=		hidden_act
          _a						=		num_labels
          _a						=		initializer_range
          _a						=		out_features
          _a						=		out_indices
          _a						=		scope






     def  a_					(			self		)       ->    Tuple:
          _a						=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

          _a						=		self.get_config()

          return config, pixel_values, labels






     def  a_					(			self		)       ->    List[str]:
          return ConvNextVaConfig(
              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=__UpperCamelCase     ,							initializer_range=self.initializer_range     ,							out_features=self.out_features     ,							out_indices=self.out_indices     ,							num_labels=self.num_labels     ,							)






     def  a_					(			self     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)       ->    Tuple:
          _a						=		ConvNextVaModel(config=__UpperCamelCase		)
          model.to(__UpperCamelCase		)
          model.eval()
          _a						=		model(__UpperCamelCase		)
          # 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  a_					(			self     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)       ->    Union[str, Any]:
          _a						=		ConvNextVaForImageClassification(__UpperCamelCase		)
          model.to(__UpperCamelCase		)
          model.eval()
          _a						=		model(__UpperCamelCase     ,							labels=__UpperCamelCase		)
          self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.num_labels)		)






     def  a_					(			self     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)       ->    List[Any]:
          _a						=		ConvNextVaBackbone(config=__UpperCamelCase		)
          model.to(__UpperCamelCase		)
          model.eval()
          _a						=		model(__UpperCamelCase		)

          # 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
          _a						=		None
          _a						=		ConvNextVaBackbone(config=__UpperCamelCase		)
          model.to(__UpperCamelCase		)
          model.eval()
          _a						=		model(__UpperCamelCase		)

          # 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  a_					(			self		)       ->    Optional[int]:
          _a						=		self.prepare_config_and_inputs()
          _a			,			_a			,			_a						=		config_and_inputs
          _a						=		{"pixel_values": pixel_values}
          return config, inputs_dict






     def  a_					(			self		)       ->    int:
          _a						=		self.prepare_config_and_inputs()
          _a			,			_a			,			_a						=		config_and_inputs
          _a						=		{"pixel_values": pixel_values, "labels": labels}
          return config, inputs_dict







@require_torch
class 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ,			lowerCamelCase__ ,			unittest.TestCase ):
     UpperCAmelCase 					=				(
         (
             ConvNextVaModel,
             ConvNextVaForImageClassification,
             ConvNextVaBackbone,
         )
         if is_torch_available()
         else ()
     )
     UpperCAmelCase 					=				(
         {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
         if is_torch_available()
         else {}
     )

     UpperCAmelCase 					=				False
     UpperCAmelCase 					=				False
     UpperCAmelCase 					=				False
     UpperCAmelCase 					=				False
     UpperCAmelCase 					=				False






     def  a_					(			self		)       ->    Union[str, Any]:
          _a						=		ConvNextVaModelTester(self		)
          _a						=		ConfigTester(self     ,							config_class=__UpperCamelCase     ,							has_text_modality=__UpperCamelCase     ,							hidden_size=37		)






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






     @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"		)
     def  a_					(			self		)       ->    Optional[Any]:
          pass






     @unittest.skip(reason="ConvNextV2 does not support input and output embeddings"		)
     def  a_					(			self		)       ->    Optional[Any]:
          pass






     @unittest.skip(reason="ConvNextV2 does not use feedforward chunking"		)
     def  a_					(			self		)       ->    str:
          pass






     def  a_					(			self		)       ->    Optional[int]:
          if not self.model_tester.is_training:
               return

          for model_class in self.all_model_classes:
               _a			,			_a						=		self.model_tester.prepare_config_and_inputs_with_labels()
               _a						=		True

               if model_class.__name__ in [
                   *get_values(__UpperCamelCase		),
                   *get_values(__UpperCamelCase		),
               ]:
                    continue

               _a						=		model_class(__UpperCamelCase		)
               model.to(__UpperCamelCase		)
               model.train()
               _a						=		self._prepare_for_class(__UpperCamelCase     ,							__UpperCamelCase     ,							return_labels=__UpperCamelCase		)
               _a						=		model(**__UpperCamelCase		).loss
               loss.backward()






     def  a_					(			self		)       ->    Any:
          if not self.model_tester.is_training:
               return

          for model_class in self.all_model_classes:
               _a			,			_a						=		self.model_tester.prepare_config_and_inputs_with_labels()
               _a						=		False
               _a						=		True

               if (
                   model_class.__name__
                   in [*get_values(__UpperCamelCase		), *get_values(__UpperCamelCase		)]
                   or not model_class.supports_gradient_checkpointing
               ):
                    continue

               _a						=		model_class(__UpperCamelCase		)
               model.to(__UpperCamelCase		)
               model.gradient_checkpointing_enable()
               model.train()
               _a						=		self._prepare_for_class(__UpperCamelCase     ,							__UpperCamelCase     ,							return_labels=__UpperCamelCase		)
               _a						=		model(**__UpperCamelCase		).loss
               loss.backward()






     def  a_					(			self		)       ->    Tuple:
          _a			,			_a						=		self.model_tester.prepare_config_and_inputs_for_common()

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

               _a						=		["pixel_values"]
               self.assertListEqual(arg_names[:1]     ,							__UpperCamelCase		)






     def  a_					(			self		)       ->    str:
          _a						=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__UpperCamelCase		)






     def  a_					(			self		)       ->    Tuple:
          def check_hidden_states_output(__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		):
               _a						=		model_class(__UpperCamelCase		)
               model.to(__UpperCamelCase		)
               model.eval()

               with torch.no_grad():
                    _a						=		model(**self._prepare_for_class(__UpperCamelCase     ,							__UpperCamelCase		)		)

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

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

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

          _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(__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)

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

               check_hidden_states_output(__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)






     def  a_					(			self		)       ->    int:
          _a						=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase		)






     @slow
     def  a_					(			self		)       ->    Dict:
          for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _a						=		ConvNextVaModel.from_pretrained(__UpperCamelCase		)
               self.assertIsNotNone(__UpperCamelCase		)







def __UpperCamelCase   (			)      ->     List[Any]:







     '''simple docstring'''






     _a						=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
     return image






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






     @cached_property
     def  a_					(			self		)       ->    Optional[int]:
          return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224"		) if is_vision_available() else None






     @slow
     def  a_					(			self		)       ->    List[str]:
          _a						=		ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"		).to(__UpperCamelCase		)

          _a						=		self.default_image_processor
          _a						=		prepare_img()
          _a						=		preprocessor(images=__UpperCamelCase     ,							return_tensors="pt"		).to(__UpperCamelCase		)

          # forward pass
          with torch.no_grad():
               _a						=		model(**__UpperCamelCase		)

          # verify the logits
          _a						=		torch.Size((1, 1_000)		)
          self.assertEqual(outputs.logits.shape     ,							__UpperCamelCase		)

          _a						=		torch.tensor([0.99_96, 0.19_66, -0.43_86]		).to(__UpperCamelCase		)
          self.assertTrue(torch.allclose(outputs.logits[0, :3]     ,							__UpperCamelCase     ,							atol=1e-4		)		)





'''simple docstring'''

import argparse
import os

import numpy as np
import tensorflow as tf
import torch

from transformers import BertModel






def __UpperCamelCase   (			__lowerCamelCase		: BertModel      ,  __lowerCamelCase		: str      ,  __lowerCamelCase		: str				)      ->     List[str]:







     '''simple docstring'''






     _a						=		("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value")

     _a						=		(
         ("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(__lowerCamelCase				):
          os.makedirs(__lowerCamelCase				)

     _a						=		model.state_dict()

     def to_tf_var_name(__lowerCamelCase		: str				):
          for patt, repl in iter(__lowerCamelCase				):
               _a						=		name.replace(__lowerCamelCase      ,  __lowerCamelCase				)
          return F"bert/{name}"

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

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

          _a						=		tf.train.Saver(tf.trainable_variables()				)
          saver.save(__lowerCamelCase      ,  os.path.join(__lowerCamelCase      ,  model_name.replace("-"      ,  "_"				) + ".ckpt"				)				)






def __UpperCamelCase   (			__lowerCamelCase		: str=None				)      ->     Optional[int]:







     '''simple docstring'''






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

     _a						=		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=__lowerCamelCase      ,  ckpt_dir=args.tf_cache_dir      ,  model_name=args.model_name				)


if __name__ == "__main__":
   main()

