





'''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     lowerCAmelCase__ :

       '''simple docstring'''

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

       def 			__snake_case      ( self					:				Dict						):
              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						):
              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=a__       ,     initializer_range=self.initializer_range       ,     out_features=self.out_features       ,     out_indices=self.out_indices       ,     num_labels=self.num_labels       ,     )

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

       def 			__snake_case      ( self					:				Any       ,     a__					:				Optional[Any]       ,     a__					:				List[Any]       ,     a__					:				Dict						):
              UpperCAmelCase  =						ConvNextVaBackbone(config=a__						)
              model.to(a__						)
              model.eval()
              UpperCAmelCase  =						model(a__						)

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

              # 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 			__snake_case      ( self					:				Any						):
              UpperCAmelCase  =						self.prepare_config_and_inputs()
              UpperCAmelCase,					UpperCAmelCase,					UpperCAmelCase  =						config_and_inputs
              UpperCAmelCase  =						{'''pixel_values''': pixel_values}
              return config, inputs_dict



       def 			__snake_case      ( self					:				List[str]						):
              UpperCAmelCase  =						self.prepare_config_and_inputs()
              UpperCAmelCase,					UpperCAmelCase,					UpperCAmelCase  =						config_and_inputs
              UpperCAmelCase  =						{'''pixel_values''': pixel_values, '''labels''': labels}
              return config, inputs_dict






@require_torch
class     lowerCAmelCase__ (				UpperCAmelCase_      , UpperCAmelCase_      , unittest.TestCase    ):

       '''simple docstring'''
       _lowerCamelCase								=(
           (
               ConvNextVaModel,
               ConvNextVaForImageClassification,
               ConvNextVaBackbone,
           )
           if is_torch_available()
           else ()
       )
       _lowerCamelCase								=(
           {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
           if is_torch_available()
           else {}
       )

       _lowerCamelCase								=False
       _lowerCamelCase								=False
       _lowerCamelCase								=False
       _lowerCamelCase								=False
       _lowerCamelCase								=False

       def 			__snake_case      ( self					:				List[Any]						):
              UpperCAmelCase  =						ConvNextVaModelTester(self						)
              UpperCAmelCase  =						ConfigTester(self       ,     config_class=a__       ,     has_text_modality=a__       ,     hidden_size=37						)

       def 			__snake_case      ( self					:				Tuple						):
              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					:				Optional[Any]						):
              return

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

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

       @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking'''						)
       def 			__snake_case      ( self					:				str						):
              pass

       def 			__snake_case      ( self					:				Optional[Any]						):
              if not self.model_tester.is_training:
                     return

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

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

                     UpperCAmelCase  =						model_class(a__						)
                     model.to(a__						)
                     model.train()
                     UpperCAmelCase  =						self._prepare_for_class(a__       ,     a__       ,     return_labels=a__						)
                     UpperCAmelCase  =						model(**a__						).loss
                     loss.backward()

       def 			__snake_case      ( self					:				Union[str, Any]						):
              if not self.model_tester.is_training:
                     return

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

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

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

       def 			__snake_case      ( self					:				str						):
              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.forward						)
                     # 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					:				Any						):
              UpperCAmelCase  =						self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*a__						)

       def 			__snake_case      ( self					:				Any						):
              def check_hidden_states_output(a__					:				Dict       ,     a__					:				str       ,     a__					:				Dict						):
                     UpperCAmelCase  =						model_class(a__						)
                     model.to(a__						)
                     model.eval()

                     with torch.no_grad():
                            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						)

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

              UpperCAmelCase,					UpperCAmelCase  =						self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     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					:				Union[str, Any]						):
              UpperCAmelCase  =						self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_image_classification(*a__						)



       @slow
       def 			__snake_case      ( self					:				Tuple						):
              for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     UpperCAmelCase  =						ConvNextVaModel.from_pretrained(a__						)
                     self.assertIsNotNone(a__						)


def       __snake_case		( )							->     int:

       """simple docstring"""


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






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

       '''simple docstring'''

       @cached_property
       def 			__snake_case      ( self					:				Dict						):
              return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224'''						) if is_vision_available() else None



       @slow
       def 			__snake_case      ( self					:				Dict						):
              UpperCAmelCase  =						ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224'''						).to(a__						)

              UpperCAmelCase  =						self.default_image_processor
              UpperCAmelCase  =						prepare_img()
              UpperCAmelCase  =						preprocessor(images=a__       ,     return_tensors='''pt'''						).to(a__						)

              # forward pass
              with torch.no_grad():
                     UpperCAmelCase  =						model(**a__						)

              # verify the logits
              UpperCAmelCase  =						torch.Size((1, 1000)						)
              self.assertEqual(outputs.logits.shape       ,     a__						)

              UpperCAmelCase  =						torch.tensor([0.9_996, 0.1_966, -0.4_386]						).to(a__						)
              self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,     a__       ,     atol=1e-4						)						)






import argparse
import json
from collections import OrderedDict
from functools import partial
from pathlib import Path

import timm
import torch
from huggingface_hub import hf_hub_download

from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
_lowerCAmelCase:						List[str]   				=       logging.get_logger()






def   _lowercase(					__a				:						int    ,     __a				:						str    ,     __a				:						LevitConfig    ,     __a				:						Path    ,     __a				:						bool = True     ):
							print(f"""Converting {name}..."""     )

							with torch.no_grad():
														if hidden_sizes == 128:
																					if name[-1] == "S":
																												a__      =timm.create_model('levit_128s'    ,     pretrained=__a     )
																					else:
																												a__      =timm.create_model('levit_128'    ,     pretrained=__a     )
														if hidden_sizes == 192:
																					a__      =timm.create_model('levit_192'    ,     pretrained=__a     )
														if hidden_sizes == 256:
																					a__      =timm.create_model('levit_256'    ,     pretrained=__a     )
														if hidden_sizes == 384:
																					a__      =timm.create_model('levit_384'    ,     pretrained=__a     )

														from_model.eval()
														a__      =LevitForImageClassificationWithTeacher(__a     ).eval()
														a__      =OrderedDict()

														a__      =from_model.state_dict()
														a__      =list(from_model.state_dict().keys()     )
														a__      =list(our_model.state_dict().keys()     )
														print(len(__a     )    ,     len(__a     )     )
														for i in range(len(__a     )     ):
																					a__      =weights[og_keys[i]]
														our_model.load_state_dict(__a     )

														a__      =torch.randn((2, 3, 224, 224)     )
														a__      =from_model(__a     )
														a__      =our_model(__a     ).logits

							assert torch.allclose(__a    ,     __a     ), "The model logits don't match the original one."

							a__      =name
							print(__a     )

							if push_to_hub:
														our_model.save_pretrained(save_directory / checkpoint_name     )
														a__      =LevitImageProcessor()
														image_processor.save_pretrained(save_directory / checkpoint_name     )

														print(f"""Pushed {checkpoint_name}"""     )






def   _lowercase(					__a				:						Path    ,     __a				:						str = None    ,     __a				:						bool = True     ):
							a__      ='imagenet-1k-id2label.json'
							a__      =1000
							a__      =(1, num_labels)

							a__      ='huggingface/label-files'
							a__      =num_labels
							a__      =json.load(open(hf_hub_download(__a    ,     __a    ,     repo_type='dataset'     )    ,     'r'     )     )
							a__      ={int(__a     ): v for k, v in idalabel.items()}

							a__      =idalabel
							a__      ={v: k for k, v in idalabel.items()}

							a__      =partial(__a    ,     num_labels=__a    ,     idalabel=__a    ,     labelaid=__a     )

							a__      ={
							    'levit-128S': 128,
							    'levit-128': 128,
							    'levit-192': 192,
							    'levit-256': 256,
							    'levit-384': 384,
							}

							a__      ={
							    'levit-128S': ImageNetPreTrainedConfig(
							        hidden_sizes=[128, 256, 384]    ,     num_attention_heads=[4, 6, 8]    ,     depths=[2, 3, 4]    ,     key_dim=[16, 16, 16]    ,     drop_path_rate=0    ,     ),
							    'levit-128': ImageNetPreTrainedConfig(
							        hidden_sizes=[128, 256, 384]    ,     num_attention_heads=[4, 8, 12]    ,     depths=[4, 4, 4]    ,     key_dim=[16, 16, 16]    ,     drop_path_rate=0    ,     ),
							    'levit-192': ImageNetPreTrainedConfig(
							        hidden_sizes=[192, 288, 384]    ,     num_attention_heads=[3, 5, 6]    ,     depths=[4, 4, 4]    ,     key_dim=[32, 32, 32]    ,     drop_path_rate=0    ,     ),
							    'levit-256': ImageNetPreTrainedConfig(
							        hidden_sizes=[256, 384, 512]    ,     num_attention_heads=[4, 6, 8]    ,     depths=[4, 4, 4]    ,     key_dim=[32, 32, 32]    ,     drop_path_rate=0    ,     ),
							    'levit-384': ImageNetPreTrainedConfig(
							        hidden_sizes=[384, 512, 768]    ,     num_attention_heads=[6, 9, 12]    ,     depths=[4, 4, 4]    ,     key_dim=[32, 32, 32]    ,     drop_path_rate=0.1    ,     ),
							}

							if model_name:
														convert_weight_and_push(
														    names_to_hidden_sizes[model_name]    ,     __a    ,     names_to_config[model_name]    ,     __a    ,     __a     )
							else:
														for model_name, config in names_to_config.items():
																					convert_weight_and_push(names_to_hidden_sizes[model_name]    ,     __a    ,     __a    ,     __a    ,     __a     )
							return config, expected_shape


if __name__ == "__main__":
	_lowerCAmelCase:						Any   				=       argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    '--model_name',
	    default=None,
	    type=str,
	    help='The name of the model you wish to convert, it must be one of the supported Levit* architecture,',
	)
	parser.add_argument(
	    '--pytorch_dump_folder_path',
	    default='levit-dump-folder/',
	    type=Path,
	    required=False,
	    help='Path to the output PyTorch model directory.',
	)
	parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub')
	parser.add_argument(
	    '--no-push_to_hub',
	    dest='push_to_hub',
	    action='store_false',
	    help='Do not push model and image processor to the hub',
	)

	_lowerCAmelCase:						Union[str, Any]   				=       parser.parse_args()
	_lowerCAmelCase:						Path   				=       args.pytorch_dump_folder_path
	pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
	convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)

