

'''simple docstring'''



import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

from transformers import (
    WavaVecaConfig,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaForPreTraining,
    WavaVecaProcessor,
    logging,
)
from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification


logging.set_verbosity_info()
_UpperCamelCase						:  Tuple							       =				logging.get_logger(__name__)

_UpperCamelCase						:  str							       =				{
    "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",
    "adapter_layer": "encoder.layers.*.adapter_layer",
    "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",
    "mask_emb": "masked_spec_embed",
    "pooling_layer.linear": "projector",
    "pooling_layer.projection": "classifier",
}
_UpperCamelCase						:  Optional[int]							       =				[
    "lm_head",
    "quantizer.weight_proj",
    "quantizer.codevectors",
    "project_q",
    "project_hid",
    "projector",
    "classifier",
]


def       snake_case   (	snake_case      : List[str]			) ->  List[str]:


    """simple docstring"""


    lowerCAmelCase 						=							{}
    with open(snake_case					,		'r'			) as file:
        for line_number, line in enumerate(snake_case			):
            lowerCAmelCase 						=							line.strip()
            if line:
                lowerCAmelCase 						=							line.split()
                lowerCAmelCase 						=							line_number
                lowerCAmelCase 						=							words[0]
                lowerCAmelCase 						=							value
    return result


def       snake_case   (	snake_case      : Dict					,		snake_case      : Tuple					,		snake_case      : str					,		snake_case      : Dict					,		snake_case      : List[Any]			) ->  int:


    """simple docstring"""


    for attribute in key.split('.'			):
        lowerCAmelCase 						=							getattr(snake_case					,		snake_case			)

    lowerCAmelCase 						=							None
    for param_key in PARAM_MAPPING.keys():
        if full_name.endswith(snake_case			):
            lowerCAmelCase 						=							PARAM_MAPPING[full_name.split('.'			)[-1]]
            lowerCAmelCase 						=							'param'

    if weight_type is not None and weight_type != "param":
        lowerCAmelCase 						=							getattr(snake_case					,		snake_case			).shape
    elif weight_type is not None and weight_type == "param":
        lowerCAmelCase 						=							hf_pointer
        for attribute in hf_param_name.split('.'			):
            lowerCAmelCase 						=							getattr(snake_case					,		snake_case			)
        lowerCAmelCase 						=							shape_pointer.shape

        # let's reduce dimension
        lowerCAmelCase 						=							value[0]
    else:
        lowerCAmelCase 						=							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":
        lowerCAmelCase 						=							value
    elif weight_type == "weight_g":
        lowerCAmelCase 						=							value
    elif weight_type == "weight_v":
        lowerCAmelCase 						=							value
    elif weight_type == "bias":
        lowerCAmelCase 						=							value
    elif weight_type == "param":
        for attribute in hf_param_name.split('.'			):
            lowerCAmelCase 						=							getattr(snake_case					,		snake_case			)
        lowerCAmelCase 						=							value
    else:
        lowerCAmelCase 						=							value

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


def       snake_case   (	snake_case      : List[str]					,		snake_case      : Union[str, Any]					,		snake_case      : Dict					,		snake_case      : List[Any]					,		snake_case      : Dict			) ->  int:


    """simple docstring"""


    lowerCAmelCase 						=							None
    for param_key in PARAM_MAPPING.keys():
        if full_name.endswith(snake_case			):
            lowerCAmelCase 						=							PARAM_MAPPING[full_name.split('.'			)[-1]]
            lowerCAmelCase 						=							'param'

    if weight_type is not None and weight_type != "param":
        lowerCAmelCase 						=							'.'.join([key, weight_type]			)
    elif weight_type is not None and weight_type == "param":
        lowerCAmelCase 						=							'.'.join([key, hf_param_name]			)
    else:
        lowerCAmelCase 						=							key

    lowerCAmelCase 						=							value if 'lm_head' in full_key else value[0]


_UpperCamelCase						:  Optional[Any]							       =				{
    "W_a": "linear_1.weight",
    "W_b": "linear_2.weight",
    "b_a": "linear_1.bias",
    "b_b": "linear_2.bias",
    "ln_W": "norm.weight",
    "ln_b": "norm.bias",
}


def       snake_case   (	snake_case      : Dict					,		snake_case      : str					,		snake_case      : int=None					,		snake_case      : List[Any]=None			) ->  int:


    """simple docstring"""


    lowerCAmelCase 						=							False
    for key, mapped_key in MAPPING.items():
        lowerCAmelCase 						=							'wav2vec2.' + 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]:
            lowerCAmelCase 						=							True
            if "*" in mapped_key:
                lowerCAmelCase 						=							name.split(snake_case			)[0].split('.'			)[-2]
                lowerCAmelCase 						=							mapped_key.replace('*'					,		snake_case			)
            if "weight_g" in name:
                lowerCAmelCase 						=							'weight_g'
            elif "weight_v" in name:
                lowerCAmelCase 						=							'weight_v'
            elif "bias" in name:
                lowerCAmelCase 						=							'bias'
            elif "weight" in name:
                # TODO: don't match quantizer.weight_proj
                lowerCAmelCase 						=							'weight'
            else:
                lowerCAmelCase 						=							None
            if hf_dict is not None:
                rename_dict(snake_case					,		snake_case					,		snake_case					,		snake_case					,		snake_case			)
            else:
                set_recursively(snake_case					,		snake_case					,		snake_case					,		snake_case					,		snake_case			)
            return is_used
    return is_used


def       snake_case   (	snake_case      : Dict					,		snake_case      : List[str]					,		snake_case      : int			) ->  Optional[int]:


    """simple docstring"""


    lowerCAmelCase 						=							[]
    lowerCAmelCase 						=							fairseq_model.state_dict()

    lowerCAmelCase 						=							hf_model.wavaveca.feature_extractor

    for name, value in fairseq_dict.items():
        lowerCAmelCase 						=							False
        if "conv_layers" in name:
            load_conv_layer(
                snake_case					,		snake_case					,		snake_case					,		snake_case					,		hf_model.config.feat_extract_norm == 'group'					,		)
            lowerCAmelCase 						=							True
        else:
            lowerCAmelCase 						=							load_wavaveca_layer(snake_case					,		snake_case					,		snake_case			)
        if not is_used:
            unused_weights.append(snake_case			)

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


def       snake_case   (	snake_case      : Union[str, Any]					,		snake_case      : Union[str, Any]					,		snake_case      : Optional[int]					,		snake_case      : int					,		snake_case      : List[Any]			) ->  Optional[int]:


    """simple docstring"""


    lowerCAmelCase 						=							full_name.split('conv_layers.'			)[-1]
    lowerCAmelCase 						=							name.split('.'			)
    lowerCAmelCase 						=							int(items[0]			)
    lowerCAmelCase 						=							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.'			)
            lowerCAmelCase 						=							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.'			)
            lowerCAmelCase 						=							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.conv_layers[layer_id].layer_norm.bias.data.shape} was found.'			)
            lowerCAmelCase 						=							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.conv_layers[layer_id].layer_norm.weight.data.shape} was found.'			)
            lowerCAmelCase 						=							value
            logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'			)
    else:
        unused_weights.append(snake_case			)


@torch.no_grad()
def       snake_case   (	snake_case      : Optional[int]					,		snake_case      : Optional[int]					,		snake_case      : Any=None					,		snake_case      : Any=None					,		snake_case      : Optional[Any]=True					,		snake_case      : Optional[int]=False			) ->  Any:


    """simple docstring"""


    if config_path is not None:
        lowerCAmelCase 						=							WavaVecaConfig.from_pretrained(snake_case			)
    else:
        lowerCAmelCase 						=							WavaVecaConfig()

    if is_seq_class:
        lowerCAmelCase 						=							read_txt_into_dict(snake_case			)
        lowerCAmelCase 						=							idalabel
        lowerCAmelCase 						=							WavaVecaForSequenceClassification(snake_case			)
        lowerCAmelCase 						=							WavaVecaFeatureExtractor(
            feature_size=1					,		sampling_rate=16000					,		padding_value=0					,		do_normalize=snake_case					,		return_attention_mask=snake_case					,		)
        feature_extractor.save_pretrained(snake_case			)

    elif is_finetuned:
        if dict_path:
            lowerCAmelCase 						=							Dictionary.load(snake_case			)

            # important change bos & pad token id since CTC symbol is <pad> and
            # not <s> as in fairseq
            lowerCAmelCase 						=							target_dict.pad_index
            lowerCAmelCase 						=							target_dict.bos_index
            lowerCAmelCase 						=							target_dict.eos_index
            lowerCAmelCase 						=							len(target_dict.symbols			)
            lowerCAmelCase 						=							os.path.join(snake_case					,		'vocab.json'			)
            if not os.path.isdir(snake_case			):
                logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(snake_case			)			)
                return
            os.makedirs(snake_case					,		exist_ok=snake_case			)
            lowerCAmelCase 						=							target_dict.indices

            # fairseq has the <pad> and <s> switched
            lowerCAmelCase 						=							0
            lowerCAmelCase 						=							1
            with open(snake_case					,		'w'					,		encoding='utf-8'			) as vocab_handle:
                json.dump(snake_case					,		snake_case			)
            lowerCAmelCase 						=							WavaVecaCTCTokenizer(
                snake_case					,		unk_token=target_dict.unk_word					,		pad_token=target_dict.pad_word					,		bos_token=target_dict.bos_word					,		eos_token=target_dict.eos_word					,		word_delimiter_token='|'					,		do_lower_case=snake_case					,		)
            lowerCAmelCase 						=							True if config.feat_extract_norm == 'layer' else False
            lowerCAmelCase 						=							WavaVecaFeatureExtractor(
                feature_size=1					,		sampling_rate=16000					,		padding_value=0					,		do_normalize=snake_case					,		return_attention_mask=snake_case					,		)
            lowerCAmelCase 						=							WavaVecaProcessor(feature_extractor=snake_case					,		tokenizer=snake_case			)
            processor.save_pretrained(snake_case			)

        lowerCAmelCase 						=							WavaVecaForCTC(snake_case			)
    else:
        lowerCAmelCase 						=							WavaVecaForPreTraining(snake_case			)

    if is_finetuned or is_seq_class:
        lowerCAmelCase						,   lowerCAmelCase						,   lowerCAmelCase 						=							fairseq.checkpoint_utils.load_model_ensemble_and_task(
            [checkpoint_path]					,		arg_overrides={'data': '/'.join(dict_path.split('/'			)[:-1]			)}			)
    else:
        lowerCAmelCase 						=							argparse.Namespace(task='audio_pretraining'			)
        lowerCAmelCase 						=							fairseq.tasks.setup_task(snake_case			)

        lowerCAmelCase						,   lowerCAmelCase						,   lowerCAmelCase 						=							fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]					,		task=snake_case			)

    lowerCAmelCase 						=							model[0].eval()

    recursively_load_weights(snake_case					,		snake_case					,		not is_finetuned			)

    hf_wavavec.save_pretrained(snake_case			)


if __name__ == "__main__":
     _UpperCamelCase						:  Union[str, Any]							       =				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"
     )
     parser.add_argument(
         "--is_seq_class",
         action="store_true",
         help="Whether the model to convert is a fine-tuned sequence classification model or not",
     )
     _UpperCamelCase						:  Optional[int]							       =				parser.parse_args()

     _UpperCamelCase						:  Tuple							       =				not args.not_finetuned and not args.is_seq_class
     convert_wavaveca_checkpoint(
         args.checkpoint_path,
         args.pytorch_dump_folder_path,
         args.config_path,
         args.dict_path,
         is_finetuned,
         args.is_seq_class,
     )








'''simple docstring'''



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					:

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





      '''simple docstring'''

      lowerCAmelCase 						=							parent
      lowerCAmelCase 						=							batch_size
      lowerCAmelCase 						=							image_size
      lowerCAmelCase 						=							num_channels
      lowerCAmelCase 						=							num_stages
      lowerCAmelCase 						=							hidden_sizes
      lowerCAmelCase 						=							depths
      lowerCAmelCase 						=							is_training
      lowerCAmelCase 						=							use_labels
      lowerCAmelCase 						=							intermediate_size
      lowerCAmelCase 						=							hidden_act
      lowerCAmelCase 						=							num_labels
      lowerCAmelCase 						=							initializer_range
      lowerCAmelCase 						=							out_features
      lowerCAmelCase 						=							out_indices
      lowerCAmelCase 						=							scope

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

      lowerCAmelCase 						=							self.get_config()
      return config, pixel_values, labels

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      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=_SCREAMING_SNAKE_CASE      , initializer_range=self.initializer_range      , out_features=self.out_features      , out_indices=self.out_indices      , num_labels=self.num_labels      , )

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextModel(config=_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_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 // 32, self.image_size // 32)      , )

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextForImageClassification(_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_SNAKE_CASE      , labels=_SCREAMING_SNAKE_CASE	)
      self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.num_labels)	)

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextBackbone(config=_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_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
      lowerCAmelCase 						=							None
      lowerCAmelCase 						=							ConvNextBackbone(config=_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_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   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.prepare_config_and_inputs()
      lowerCAmelCase						,   lowerCAmelCase						,   lowerCAmelCase 						=							config_and_inputs
      lowerCAmelCase 						=							{'pixel_values': pixel_values}
      return config, inputs_dict



@require_torch
class 				_snake_case					(   a_     , a_     , unittest.TestCase			):
  SCREAMING_SNAKE_CASE			:       List[Any]				=     (
      (
          ConvNextModel,
          ConvNextForImageClassification,
          ConvNextBackbone,
      )
      if is_torch_available()
      else ()
  )
  SCREAMING_SNAKE_CASE			:       int				=     (
      {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
      if is_torch_available()
      else {}
  )

  SCREAMING_SNAKE_CASE			:       Tuple				=     True
  SCREAMING_SNAKE_CASE			:       Union[str, Any]				=     False
  SCREAMING_SNAKE_CASE			:       Tuple				=     False
  SCREAMING_SNAKE_CASE			:       List[str]				=     False
  SCREAMING_SNAKE_CASE			:       Optional[int]				=     False

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextModelTester(self	)
      lowerCAmelCase 						=							ConfigTester(self      , config_class=_SCREAMING_SNAKE_CASE      , has_text_modality=_SCREAMING_SNAKE_CASE      , hidden_size=37	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





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





      '''simple docstring'''

      return

  @unittest.skip(reason='ConvNext does not use inputs_embeds'	)
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      pass

  @unittest.skip(reason='ConvNext does not support input and output embeddings'	)
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      pass

  @unittest.skip(reason='ConvNext does not use feedforward chunking'	)
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      pass

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase						,   lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs_for_common()

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

          lowerCAmelCase 						=							['pixel_values']
          self.assertListEqual(arg_names[:1]      , _SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      def check_hidden_states_output(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):
          lowerCAmelCase 						=							model_class(_SCREAMING_SNAKE_CASE	)
          model.to(_SCREAMING_SNAKE_CASE	)
          model.eval()

          with torch.no_grad():
              lowerCAmelCase 						=							model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)	)

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

          lowerCAmelCase 						=							self.model_tester.num_stages
          self.assertEqual(len(_SCREAMING_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]      , )

      lowerCAmelCase						,   lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          lowerCAmelCase 						=							True
          check_hidden_states_output(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)

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

          check_hidden_states_output(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE	)


  @slow
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase 						=							ConvNextModel.from_pretrained(_SCREAMING_SNAKE_CASE	)
          self.assertIsNotNone(_SCREAMING_SNAKE_CASE	)



def       snake_case   (	) ->  List[str]:


    """simple docstring"""


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



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

  @cached_property
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

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


  @slow
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'	).to(_SCREAMING_SNAKE_CASE	)

      lowerCAmelCase 						=							self.default_image_processor
      lowerCAmelCase 						=							prepare_img()
      lowerCAmelCase 						=							image_processor(images=_SCREAMING_SNAKE_CASE      , return_tensors='pt'	).to(_SCREAMING_SNAKE_CASE	)

      # forward pass
      with torch.no_grad():
          lowerCAmelCase 						=							model(**_SCREAMING_SNAKE_CASE	)

      # verify the logits
      lowerCAmelCase 						=							torch.Size((1, 10_00)	)
      self.assertEqual(outputs.logits.shape      , _SCREAMING_SNAKE_CASE	)

      lowerCAmelCase 						=							torch.tensor([-0.0_260, -0.4_739, 0.1_911]	).to(_SCREAMING_SNAKE_CASE	)

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



@require_torch
class 				_snake_case					(   unittest.TestCase     , a_			):
  SCREAMING_SNAKE_CASE			:       Dict				=     (ConvNextBackbone,) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE			:       Tuple				=     ConvNextConfig

  SCREAMING_SNAKE_CASE			:       Dict				=     False

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextModelTester(self	)





