





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  A__    :




   """simple docstring"""



   def __init__(					self					,  lowercase					,  lowercase=13					,  lowercase=32					,  lowercase=3					,  lowercase=4					,  lowercase=[10, 20, 30, 40]					,  lowercase=[2, 2, 3, 2]					,  lowercase=True					,  lowercase=True					,  lowercase=37					,  lowercase="gelu"					,  lowercase=10					,  lowercase=0.02					,  lowercase=["stage2", "stage3", "stage4"]					,  lowercase=[2, 3, 4]					,  lowercase=None					,  )			->						Optional[Any]:







          '''simple docstring'''

          a__						:	str =				parent
          a__						:	int =				batch_size
          a__						:	Optional[int] =				image_size
          a__						:	Optional[Any] =				num_channels
          a__						:	str =				num_stages
          a__						:	Tuple =				hidden_sizes
          a__						:	Union[str, Any] =				depths
          a__						:	List[Any] =				is_training
          a__						:	List[Any] =				use_labels
          a__						:	List[str] =				intermediate_size
          a__						:	Optional[Any] =				hidden_act
          a__						:	Optional[Any] =				num_labels
          a__						:	List[Any] =				initializer_range
          a__						:	List[Any] =				out_features
          a__						:	str =				out_indices
          a__						:	Tuple =				scope

   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          a__						:	Any =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          a__						:	int =				None
          if self.use_labels:
                 a__						:	Union[str, Any] =				ids_tensor([self.batch_size]					,  self.num_labels)

          a__						:	Any =				self.get_config()

          return config, pixel_values, labels

   def 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

          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 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						Union[str, Any]:







          '''simple docstring'''

          a__						:	Optional[Any] =				ConvNextVaModel(config=_UpperCamelCase)
          model.to(_UpperCamelCase)
          model.eval()
          a__						:	Optional[int] =				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 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						int:







          '''simple docstring'''

          a__						:	Dict =				ConvNextVaForImageClassification(_UpperCamelCase)
          model.to(_UpperCamelCase)
          model.eval()
          a__						:	Dict =				model(_UpperCamelCase					,  labels=_UpperCamelCase)
          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.num_labels))

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						Any:







          '''simple docstring'''

          a__						:	Union[str, Any] =				ConvNextVaBackbone(config=_UpperCamelCase)
          model.to(_UpperCamelCase)
          model.eval()
          a__						:	Union[str, Any] =				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__						:	List[Any] =				None
          a__						:	List[Any] =				ConvNextVaBackbone(config=_UpperCamelCase)
          model.to(_UpperCamelCase)
          model.eval()
          a__						:	Tuple =				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 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

          a__						:	Any =				self.prepare_config_and_inputs()
          a__ ,							a__ ,							a__						:	List[Any] =				config_and_inputs
          a__						:	Optional[Any] =				{'pixel_values': pixel_values}
          return config, inputs_dict

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__						:	Dict =				self.prepare_config_and_inputs()
          a__ ,							a__ ,							a__						:	List[str] =				config_and_inputs
          a__						:	Union[str, Any] =				{'pixel_values': pixel_values, 'labels': labels}
          return config, inputs_dict





@require_torch
class  A__    (							_lowerCamelCase ,  _lowerCamelCase ,  unittest.TestCase	):




   """simple docstring"""



   __A   :				List[str]         =  (
       (
           ConvNextVaModel,
           ConvNextVaForImageClassification,
           ConvNextVaBackbone,
       )
       if is_torch_available()
       else ()
   )
   __A   :				Union[str, Any]         =  (
       {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
       if is_torch_available()
       else {}
   )

   __A   :				Tuple         =  False
   __A   :				Optional[int]         =  False
   __A   :				int         =  False
   __A   :				List[str]         =  False
   __A   :				Dict         =  False

   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          a__						:	Optional[Any] =				ConvNextVaModelTester(self)
          a__						:	Optional[Any] =				ConfigTester(self					,  config_class=_UpperCamelCase					,  has_text_modality=_UpperCamelCase					,  hidden_size=37)

   def 							__lowercase		(					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 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          return

   @unittest.skip(reason='ConvNextV2 does not use inputs_embeds')
   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          pass

   @unittest.skip(reason='ConvNextV2 does not support input and output embeddings')
   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          pass

   @unittest.skip(reason='ConvNextV2 does not use feedforward chunking')
   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          pass

   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          if not self.model_tester.is_training:
                 return

          for model_class in self.all_model_classes:
                 a__ ,							a__						:	str =				self.model_tester.prepare_config_and_inputs_with_labels()
                 a__						:	Optional[int] =				True

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

                 a__						:	Optional[int] =				model_class(_UpperCamelCase)
                 model.to(_UpperCamelCase)
                 model.train()
                 a__						:	List[str] =				self._prepare_for_class(_UpperCamelCase					,  _UpperCamelCase					,  return_labels=_UpperCamelCase)
                 a__						:	Any =				model(**_UpperCamelCase).loss
                 loss.backward()

   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          if not self.model_tester.is_training:
                 return

          for model_class in self.all_model_classes:
                 a__ ,							a__						:	Union[str, Any] =				self.model_tester.prepare_config_and_inputs_with_labels()
                 a__						:	int =				False
                 a__						:	Optional[Any] =				True

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

                 a__						:	List[str] =				model_class(_UpperCamelCase)
                 model.to(_UpperCamelCase)
                 model.gradient_checkpointing_enable()
                 model.train()
                 a__						:	Optional[Any] =				self._prepare_for_class(_UpperCamelCase					,  _UpperCamelCase					,  return_labels=_UpperCamelCase)
                 a__						:	str =				model(**_UpperCamelCase).loss
                 loss.backward()

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__ ,							a__						:	Optional[Any] =				self.model_tester.prepare_config_and_inputs_for_common()

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

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

   def 							__lowercase		(					self)			->						Optional[Any]:







          '''simple docstring'''

          a__						:	List[Any] =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_UpperCamelCase)

   def 							__lowercase		(					self)			->						Optional[Any]:







          '''simple docstring'''

          def check_hidden_states_output(lowercase					,  lowercase					,  lowercase):
                 a__						:	Tuple =				model_class(_UpperCamelCase)
                 model.to(_UpperCamelCase)
                 model.eval()

                 with torch.no_grad():
                        a__						:	List[Any] =				model(**self._prepare_for_class(_UpperCamelCase					,  _UpperCamelCase))

                 a__						:	Tuple =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 a__						:	Optional[Any] =				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__						:	List[str] =				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 a__						:	Tuple =				True
                 check_hidden_states_output(_UpperCamelCase					,  _UpperCamelCase					,  _UpperCamelCase)

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

                 check_hidden_states_output(_UpperCamelCase					,  _UpperCamelCase					,  _UpperCamelCase)

   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          a__						:	int =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase)

   @slow
   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a__						:	List[str] =				ConvNextVaModel.from_pretrained(_UpperCamelCase)
                 self.assertIsNotNone(_UpperCamelCase)



def A_	(		)  ->		int:
       a__						:	List[Any] =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
       return image





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




   """simple docstring"""



   @cached_property
   def 							__lowercase		(					self)			->						Union[str, Any]:







          '''simple docstring'''

          return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224') if is_vision_available() else None

   @slow
   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__						:	Optional[int] =				ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224').to(_UpperCamelCase)

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

          # forward pass
          with torch.no_grad():
                 a__						:	Optional[int] =				model(**_UpperCamelCase)

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

          a__						:	List[Any] =				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))









import argparse

import fairseq
import torch

from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging


logging.set_verbosity_info()
snake_case__					:							Dict													=     logging.get_logger(__name__)

snake_case__					:							Optional[Any]													=     {
    'post_extract_proj': 'feature_projection.projection',
    'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv',
    'self_attn.k_proj': 'encoder.layers.*.attention.k_proj',
    'self_attn.v_proj': 'encoder.layers.*.attention.v_proj',
    'self_attn.q_proj': 'encoder.layers.*.attention.q_proj',
    'self_attn.out_proj': 'encoder.layers.*.attention.out_proj',
    'self_attn_layer_norm': 'encoder.layers.*.layer_norm',
    'fc1': 'encoder.layers.*.feed_forward.intermediate_dense',
    'fc2': 'encoder.layers.*.feed_forward.output_dense',
    'final_layer_norm': 'encoder.layers.*.final_layer_norm',
    'encoder.layer_norm': 'encoder.layer_norm',
    'encoder.layer_norm_for_extract': 'layer_norm_for_extract',
    'w2v_model.layer_norm': 'feature_projection.layer_norm',
    'quantizer.weight_proj': 'quantizer.weight_proj',
    'quantizer.vars': 'quantizer.codevectors',
    'project_q': 'project_q',
    'final_proj': 'project_hid',
    'w2v_encoder.proj': 'lm_head',
    'label_embs_concat': 'label_embeddings_concat',
    'mask_emb': 'masked_spec_embed',
    'spk_proj': 'speaker_proj',
}
snake_case__					:							Optional[int]													=     [
    'lm_head',
    'quantizer.weight_proj',
    'quantizer.codevectors',
    'project_q',
    'project_hid',
    'label_embeddings_concat',
    'speaker_proj',
    'layer_norm_for_extract',
]



def _a				(	lowerCamelCase:   List[Any]					,				lowerCamelCase:   Any					,				lowerCamelCase:   Union[str, Any]					,				lowerCamelCase:   Any					,				lowerCamelCase:   int )	->						List[str]:







      '''simple docstring'''






      for attribute in key.split('''.''' ):
            __A          =				getattr(lowerCamelCase					,				lowerCamelCase )

      if weight_type is not None:
            __A          =				getattr(lowerCamelCase					,				lowerCamelCase ).shape
      else:
            __A          =				hf_pointer.shape

      if hf_shape != value.shape:
            raise ValueError(
                F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"""
                F""" {value.shape} for {full_name}""" )

      if weight_type == "weight":
            __A          =				value
      elif weight_type == "weight_g":
            __A          =				value
      elif weight_type == "weight_v":
            __A          =				value
      elif weight_type == "bias":
            __A          =				value
      else:
            __A          =				value

      logger.info(F"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" )



def _a				(	lowerCamelCase:   List[str]					,				lowerCamelCase:   Optional[int] )	->						Tuple:







      '''simple docstring'''






      __A          =				[]
      __A          =				fairseq_model.state_dict()

      __A          =				hf_model.unispeech_sat.feature_extractor

      for name, value in fairseq_dict.items():
            __A          =				False
            if "conv_layers" in name:
                  load_conv_layer(
                      lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase					,				hf_model.config.feat_extract_norm == '''group'''					,				)
                  __A          =				True
            else:
                  for key, mapped_key in MAPPING.items():
                        __A          =				'''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
                        if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]:
                              if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key):
                                    # special case since naming is very similar
                                    continue
                              __A          =				True
                              if "*" in mapped_key:
                                    __A          =				name.split(lowerCamelCase )[0].split('''.''' )[-2]
                                    __A          =				mapped_key.replace('''*'''					,				lowerCamelCase )
                              if "weight_g" in name:
                                    __A          =				'''weight_g'''
                              elif "weight_v" in name:
                                    __A          =				'''weight_v'''
                              elif "bias" in name:
                                    __A          =				'''bias'''
                              elif "weight" in name:
                                    # TODO: don't match quantizer.weight_proj
                                    __A          =				'''weight'''
                              else:
                                    __A          =				None
                              set_recursively(lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase )
                        continue
            if not is_used:
                  unused_weights.append(lowerCamelCase )

      logger.warning(F"""Unused weights: {unused_weights}""" )



def _a				(	lowerCamelCase:   int					,				lowerCamelCase:   Any					,				lowerCamelCase:   int					,				lowerCamelCase:   int					,				lowerCamelCase:   List[str] )	->						Union[str, Any]:







      '''simple docstring'''






      __A          =				full_name.split('''conv_layers.''' )[-1]
      __A          =				name.split('''.''' )
      __A          =				int(items[0] )
      __A          =				int(items[1] )

      if type_id == 0:
            if "bias" in name:
                  if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
                        raise ValueError(
                            F"""{full_name} has size {value.shape}, but"""
                            F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" )
                  __A          =				value
                  logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
            elif "weight" in name:
                  if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
                        raise ValueError(
                            F"""{full_name} has size {value.shape}, but"""
                            F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" )
                  __A          =				value
                  logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
      elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
            if "bias" in name:
                  if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
                        raise ValueError(
                            F"""{full_name} has size {value.shape}, but"""
                            F""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" )
                  __A          =				value
                  logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
            elif "weight" in name:
                  if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
                        raise ValueError(
                            F"""{full_name} has size {value.shape}, but"""
                            F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" )
                  __A          =				value
                  logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
      else:
            unused_weights.append(lowerCamelCase )



@torch.no_grad()
def _a				(	lowerCamelCase:   Tuple					,				lowerCamelCase:   int					,				lowerCamelCase:   Optional[Any]=None					,				lowerCamelCase:   Optional[Any]=None					,				lowerCamelCase:   Optional[int]=True )	->						List[Any]:







      '''simple docstring'''






      if config_path is not None:
            __A          =				UniSpeechSatConfig.from_pretrained(lowerCamelCase )
      else:
            __A          =				UniSpeechSatConfig()

      __A          =				''''''

      if is_finetuned:
            __A          =				UniSpeechSatForCTC(lowerCamelCase )
      else:
            __A          =				UniSpeechSatForPreTraining(lowerCamelCase )

      __A   ,						__A   ,						__A          =				fairseq.checkpoint_utils.load_model_ensemble_and_task(
          [checkpoint_path]					,				arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} )
      __A          =				model[0].eval()

      recursively_load_weights(lowerCamelCase					,				lowerCamelCase )

      hf_wavavec.save_pretrained(lowerCamelCase )


if __name__ == "__main__":
       snake_case__					:							Tuple													=     argparse.ArgumentParser()
       parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
       parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
       parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model')
       parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
       parser.add_argument(
           '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not'
       )
       snake_case__					:							Any													=     parser.parse_args()
       convert_unispeech_sat_checkpoint(
           args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
       )





