





import argparse

import torch

from transformers import (
    EncodecConfig,
    EncodecFeatureExtractor,
    EncodecModel,
    logging,
)


# checkpoints downloaded from:
# https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th
# https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin
# https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th


logging.set_verbosity_info()
lowercase_					     =	logging.get_logger("""transformers.models.encodec""")

lowercase_					     =	{
    """quantizer.vq.layers.*._codebook.inited""": """quantizer.layers.*.codebook.inited""",
    """quantizer.vq.layers.*._codebook.cluster_size""": """quantizer.layers.*.codebook.cluster_size""",
    """quantizer.vq.layers.*._codebook.embed""": """quantizer.layers.*.codebook.embed""",
    """quantizer.vq.layers.*._codebook.embed_avg""": """quantizer.layers.*.codebook.embed_avg""",
}
lowercase_					     =	{
    """encoder.model.0.conv.conv""": """encoder.layers.0.conv""",
    """encoder.model.1.block.1.conv.conv""": """encoder.layers.1.block.1.conv""",
    """encoder.model.1.block.3.conv.conv""": """encoder.layers.1.block.3.conv""",
    """encoder.model.1.shortcut.conv.conv""": """encoder.layers.1.shortcut.conv""",
    """encoder.model.3.conv.conv""": """encoder.layers.3.conv""",
    """encoder.model.4.block.1.conv.conv""": """encoder.layers.4.block.1.conv""",
    """encoder.model.4.block.3.conv.conv""": """encoder.layers.4.block.3.conv""",
    """encoder.model.4.shortcut.conv.conv""": """encoder.layers.4.shortcut.conv""",
    """encoder.model.6.conv.conv""": """encoder.layers.6.conv""",
    """encoder.model.7.block.1.conv.conv""": """encoder.layers.7.block.1.conv""",
    """encoder.model.7.block.3.conv.conv""": """encoder.layers.7.block.3.conv""",
    """encoder.model.7.shortcut.conv.conv""": """encoder.layers.7.shortcut.conv""",
    """encoder.model.9.conv.conv""": """encoder.layers.9.conv""",
    """encoder.model.10.block.1.conv.conv""": """encoder.layers.10.block.1.conv""",
    """encoder.model.10.block.3.conv.conv""": """encoder.layers.10.block.3.conv""",
    """encoder.model.10.shortcut.conv.conv""": """encoder.layers.10.shortcut.conv""",
    """encoder.model.12.conv.conv""": """encoder.layers.12.conv""",
    """encoder.model.13.lstm""": """encoder.layers.13.lstm""",
    """encoder.model.15.conv.conv""": """encoder.layers.15.conv""",
}
lowercase_					     =	{
    """encoder.model.0.conv.norm""": """encoder.layers.0.norm""",
    """encoder.model.1.block.1.conv.norm""": """encoder.layers.1.block.1.norm""",
    """encoder.model.1.block.3.conv.norm""": """encoder.layers.1.block.3.norm""",
    """encoder.model.1.shortcut.conv.norm""": """encoder.layers.1.shortcut.norm""",
    """encoder.model.3.conv.norm""": """encoder.layers.3.norm""",
    """encoder.model.4.block.1.conv.norm""": """encoder.layers.4.block.1.norm""",
    """encoder.model.4.block.3.conv.norm""": """encoder.layers.4.block.3.norm""",
    """encoder.model.4.shortcut.conv.norm""": """encoder.layers.4.shortcut.norm""",
    """encoder.model.6.conv.norm""": """encoder.layers.6.norm""",
    """encoder.model.7.block.1.conv.norm""": """encoder.layers.7.block.1.norm""",
    """encoder.model.7.block.3.conv.norm""": """encoder.layers.7.block.3.norm""",
    """encoder.model.7.shortcut.conv.norm""": """encoder.layers.7.shortcut.norm""",
    """encoder.model.9.conv.norm""": """encoder.layers.9.norm""",
    """encoder.model.10.block.1.conv.norm""": """encoder.layers.10.block.1.norm""",
    """encoder.model.10.block.3.conv.norm""": """encoder.layers.10.block.3.norm""",
    """encoder.model.10.shortcut.conv.norm""": """encoder.layers.10.shortcut.norm""",
    """encoder.model.12.conv.norm""": """encoder.layers.12.norm""",
    """encoder.model.15.conv.norm""": """encoder.layers.15.norm""",
}
lowercase_					     =	{
    """decoder.model.0.conv.conv""": """decoder.layers.0.conv""",
    """decoder.model.1.lstm""": """decoder.layers.1.lstm""",
    """decoder.model.3.convtr.convtr""": """decoder.layers.3.conv""",
    """decoder.model.4.block.1.conv.conv""": """decoder.layers.4.block.1.conv""",
    """decoder.model.4.block.3.conv.conv""": """decoder.layers.4.block.3.conv""",
    """decoder.model.4.shortcut.conv.conv""": """decoder.layers.4.shortcut.conv""",
    """decoder.model.6.convtr.convtr""": """decoder.layers.6.conv""",
    """decoder.model.7.block.1.conv.conv""": """decoder.layers.7.block.1.conv""",
    """decoder.model.7.block.3.conv.conv""": """decoder.layers.7.block.3.conv""",
    """decoder.model.7.shortcut.conv.conv""": """decoder.layers.7.shortcut.conv""",
    """decoder.model.9.convtr.convtr""": """decoder.layers.9.conv""",
    """decoder.model.10.block.1.conv.conv""": """decoder.layers.10.block.1.conv""",
    """decoder.model.10.block.3.conv.conv""": """decoder.layers.10.block.3.conv""",
    """decoder.model.10.shortcut.conv.conv""": """decoder.layers.10.shortcut.conv""",
    """decoder.model.12.convtr.convtr""": """decoder.layers.12.conv""",
    """decoder.model.13.block.1.conv.conv""": """decoder.layers.13.block.1.conv""",
    """decoder.model.13.block.3.conv.conv""": """decoder.layers.13.block.3.conv""",
    """decoder.model.13.shortcut.conv.conv""": """decoder.layers.13.shortcut.conv""",
    """decoder.model.15.conv.conv""": """decoder.layers.15.conv""",
}
lowercase_					     =	{
    """decoder.model.0.conv.norm""": """decoder.layers.0.norm""",
    """decoder.model.3.convtr.norm""": """decoder.layers.3.norm""",
    """decoder.model.4.block.1.conv.norm""": """decoder.layers.4.block.1.norm""",
    """decoder.model.4.block.3.conv.norm""": """decoder.layers.4.block.3.norm""",
    """decoder.model.4.shortcut.conv.norm""": """decoder.layers.4.shortcut.norm""",
    """decoder.model.6.convtr.norm""": """decoder.layers.6.norm""",
    """decoder.model.7.block.1.conv.norm""": """decoder.layers.7.block.1.norm""",
    """decoder.model.7.block.3.conv.norm""": """decoder.layers.7.block.3.norm""",
    """decoder.model.7.shortcut.conv.norm""": """decoder.layers.7.shortcut.norm""",
    """decoder.model.9.convtr.norm""": """decoder.layers.9.norm""",
    """decoder.model.10.block.1.conv.norm""": """decoder.layers.10.block.1.norm""",
    """decoder.model.10.block.3.conv.norm""": """decoder.layers.10.block.3.norm""",
    """decoder.model.10.shortcut.conv.norm""": """decoder.layers.10.shortcut.norm""",
    """decoder.model.12.convtr.norm""": """decoder.layers.12.norm""",
    """decoder.model.13.block.1.conv.norm""": """decoder.layers.13.block.1.norm""",
    """decoder.model.13.block.3.conv.norm""": """decoder.layers.13.block.3.norm""",
    """decoder.model.13.shortcut.conv.norm""": """decoder.layers.13.shortcut.norm""",
    """decoder.model.15.conv.norm""": """decoder.layers.15.norm""",
}
lowercase_					     =	{
    **MAPPING_QUANTIZER,
    **MAPPING_ENCODER,
    **MAPPING_DECODER,
}
lowercase_					     =	{
    **MAPPING_QUANTIZER,
    **MAPPING_ENCODER,
    **MAPPING_ENCODER_48K,
    **MAPPING_DECODER,
    **MAPPING_DECODER_48K,
}
lowercase_					     =	[]
lowercase_					     =	[]




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     Dict:
  for attribute in key.split('.'	):
    lowercase__			    =						getattr(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)

  if weight_type is not None:
    lowercase__			    =						getattr(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	).shape
  else:
    lowercase__			    =						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":
    lowercase__			    =						value
  elif weight_type == "weight_g":
    lowercase__			    =						value
  elif weight_type == "weight_v":
    lowercase__			    =						value
  elif weight_type == "bias":
    lowercase__			    =						value
  elif weight_type == "running_mean":
    lowercase__			    =						value
  elif weight_type == "running_var":
    lowercase__			    =						value
  elif weight_type == "num_batches_tracked":
    lowercase__			    =						value
  elif weight_type == "weight_ih_l0":
    lowercase__			    =						value
  elif weight_type == "weight_hh_l0":
    lowercase__			    =						value
  elif weight_type == "bias_ih_l0":
    lowercase__			    =						value
  elif weight_type == "bias_hh_l0":
    lowercase__			    =						value
  elif weight_type == "weight_ih_l1":
    lowercase__			    =						value
  elif weight_type == "weight_hh_l1":
    lowercase__			    =						value
  elif weight_type == "bias_ih_l1":
    lowercase__			    =						value
  elif weight_type == "bias_hh_l1":
    lowercase__			    =						value
  else:
    lowercase__			    =						value

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




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     Optional[Any]:
  for key in ignore_keys:
    if key.endswith('.*'	):
      if name.startswith(key[:-1]	):
        return True
    elif ".*." in key:
      lowercase__			    =						key.split('.*.'	)
      if prefix in name and suffix in name:
        return True
    elif key in name:
      return True
  return False




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     Tuple:
  lowercase__			    =						[]

  if model_name == "encodec_24khz" or "encodec_32khz":
    lowercase__			    =						MAPPING_24K
  elif model_name == "encodec_48khz":
    lowercase__			    =						MAPPING_48K
  else:
    raise ValueError(F"""Unsupported model: {model_name}"""	)

  for name, value in orig_dict.items():
    if should_ignore(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	):
      logger.info(F"""{name} was ignored"""	)
      continue

    lowercase__			    =						False
    for key, mapped_key in MAPPING.items():
      if "*" in key:
        lowercase__			    =						key.split('.*.'	)
        if prefix in name and suffix in name:
          lowercase__			    =						suffix

      if key in name:
        # HACK otherwise .embed gets initialized with .embed_avg too
        if key.endswith('embed'	) and name.endswith('embed_avg'	):
          continue

        lowercase__			    =						True
        if "*" in mapped_key:
          lowercase__			    =						name.split(_SCREAMING_SNAKE_CASE	)[0].split('.'	)[-2]
          lowercase__			    =						mapped_key.replace('*'	,		_SCREAMING_SNAKE_CASE	)
        if "weight_g" in name:
          lowercase__			    =						'weight_g'
        elif "weight_v" in name:
          lowercase__			    =						'weight_v'
        elif "weight_ih_l0" in name:
          lowercase__			    =						'weight_ih_l0'
        elif "weight_hh_l0" in name:
          lowercase__			    =						'weight_hh_l0'
        elif "bias_ih_l0" in name:
          lowercase__			    =						'bias_ih_l0'
        elif "bias_hh_l0" in name:
          lowercase__			    =						'bias_hh_l0'
        elif "weight_ih_l1" in name:
          lowercase__			    =						'weight_ih_l1'
        elif "weight_hh_l1" in name:
          lowercase__			    =						'weight_hh_l1'
        elif "bias_ih_l1" in name:
          lowercase__			    =						'bias_ih_l1'
        elif "bias_hh_l1" in name:
          lowercase__			    =						'bias_hh_l1'
        elif "bias" in name:
          lowercase__			    =						'bias'
        elif "weight" in name:
          lowercase__			    =						'weight'
        elif "running_mean" in name:
          lowercase__			    =						'running_mean'
        elif "running_var" in name:
          lowercase__			    =						'running_var'
        elif "num_batches_tracked" in name:
          lowercase__			    =						'num_batches_tracked'
        else:
          lowercase__			    =						None
        set_recursively(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)
      continue
    if not is_used:
      unused_weights.append(_SCREAMING_SNAKE_CASE	)

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




@torch.no_grad()
def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=None	,		_SCREAMING_SNAKE_CASE=None	,		)       ->     List[Any]:
  if config_path is not None:
    lowercase__			    =						EncodecConfig.from_pretrained(_SCREAMING_SNAKE_CASE	)
  else:
    lowercase__			    =						EncodecConfig()

  if model_name == "encodec_24khz":
    pass  # config is already correct
  elif model_name == "encodec_32khz":
    lowercase__			    =						[8, 5, 4, 4]
    lowercase__			    =						[2.2]
    lowercase__			    =						64
    lowercase__			    =						32000
    lowercase__			    =						2048
    lowercase__			    =						False
    lowercase__			    =						False
    lowercase__			    =						False
  elif model_name == "encodec_48khz":
    lowercase__			    =						[8, 5, 4, 2]
    lowercase__			    =						[3.0, 6.0, 1_2.0, 2_4.0]
    lowercase__			    =						48000
    lowercase__			    =						2
    lowercase__			    =						False
    lowercase__			    =						'time_group_norm'
    lowercase__			    =						True
    lowercase__			    =						1.0
    lowercase__			    =						0.0_1
  else:
    raise ValueError(F"""Unknown model name: {model_name}"""	)

  lowercase__			    =						EncodecModel(_SCREAMING_SNAKE_CASE	)

  lowercase__			    =						EncodecFeatureExtractor(
      feature_size=config.audio_channels	,		sampling_rate=config.sampling_rate	,		chunk_length_s=config.chunk_length_s	,		overlap=config.overlap	,		)
  feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE	)

  lowercase__			    =						torch.load(_SCREAMING_SNAKE_CASE	)
  if "best_state" in original_checkpoint:
    # we might have a training state saved, in which case discard the yaml results and just retain the weights
    lowercase__			    =						original_checkpoint['best_state']
  recursively_load_weights(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)
  model.save_pretrained(_SCREAMING_SNAKE_CASE	)

  if repo_id:
    print('Pushing to the hub...'	)
    feature_extractor.push_to_hub(_SCREAMING_SNAKE_CASE	)
    model.push_to_hub(_SCREAMING_SNAKE_CASE	)


if __name__ == "__main__":
   lowercase_					     =	argparse.ArgumentParser()
   parser.add_argument(
       """--model""",
       default="""encodec_24khz""",
       type=str,
       help="""The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.""",
   )
   parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""")
   parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
   parser.add_argument(
       """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model."""
   )
   parser.add_argument(
       """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub."""
   )

   lowercase_					     =	parser.parse_args()
   convert_checkpoint(
       args.model,
       args.checkpoint_path,
       args.pytorch_dump_folder_path,
       args.config_path,
       args.push_to_hub,
   )









import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    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 torch import nn

      from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
      from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import ViTImageProcessor
class        SCREAMING_SNAKE_CASE     :


   def __init__(					self    :       List[Any]    ,  a    :       Any    ,  a    :       Optional[int]=13    ,  a    :       Tuple=30    ,  a    :       Union[str, Any]=2    ,  a    :       List[str]=3    ,  a    :       Dict=True    ,  a    :       List[str]=True    ,  a    :       List[Any]=32    ,  a    :       List[str]=5    ,  a    :       Optional[int]=4    ,  a    :       List[str]=37    ,  a    :       Dict="gelu"    ,  a    :       Dict=0.1    ,  a    :       List[str]=0.1    ,  a    :       int=10    ,  a    :       List[str]=0.02    ,  a    :       int=None    ,  a    :       List[str]=2    ,  )->     Dict:





     """simple docstring"""







     lowercase__			    =						parent
     lowercase__			    =						batch_size
     lowercase__			    =						image_size
     lowercase__			    =						patch_size
     lowercase__			    =						num_channels
     lowercase__			    =						is_training
     lowercase__			    =						use_labels
     lowercase__			    =						hidden_size
     lowercase__			    =						num_hidden_layers
     lowercase__			    =						num_attention_heads
     lowercase__			    =						intermediate_size
     lowercase__			    =						hidden_act
     lowercase__			    =						hidden_dropout_prob
     lowercase__			    =						attention_probs_dropout_prob
     lowercase__			    =						type_sequence_label_size
     lowercase__			    =						initializer_range
     lowercase__			    =						scope
     lowercase__			    =						encoder_stride

     # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
     lowercase__			    =						(image_size // patch_size) ** 2
     lowercase__			    =						num_patches + 1


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Any:





     """simple docstring"""







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

     lowercase__			    =						None
     if self.use_labels:
       lowercase__			    =						ids_tensor([self.batch_size]    ,  self.type_sequence_label_size )

     lowercase__			    =						self.get_config()

     return config, pixel_values, labels


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     List[Any]:





     """simple docstring"""







     return ViTConfig(
         image_size=self.image_size    ,  patch_size=self.patch_size    ,  num_channels=self.num_channels    ,  hidden_size=self.hidden_size    ,  num_hidden_layers=self.num_hidden_layers    ,  num_attention_heads=self.num_attention_heads    ,  intermediate_size=self.intermediate_size    ,  hidden_act=self.hidden_act    ,  hidden_dropout_prob=self.hidden_dropout_prob    ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,  is_decoder=a    ,  initializer_range=self.initializer_range    ,  encoder_stride=self.encoder_stride    ,  )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Union[str, Any]    ,  a    :       List[Any]    ,  a    :       List[str]    ,  a    :       Dict )->     Optional[Any]:





     """simple docstring"""







     lowercase__			    =						ViTModel(config=a )
     model.to(a )
     model.eval()
     lowercase__			    =						model(a )
     self.parent.assertEqual(result.last_hidden_state.shape    ,  (self.batch_size, self.seq_length, self.hidden_size) )


   def  SCREAMING_SNAKE_CASE_							(					self    :       int    ,  a    :       Optional[Any]    ,  a    :       int    ,  a    :       Tuple )->     Union[str, Any]:





     """simple docstring"""







     lowercase__			    =						ViTForMaskedImageModeling(config=a )
     model.to(a )
     model.eval()
     lowercase__			    =						model(a )
     self.parent.assertEqual(
         result.reconstruction.shape    ,  (self.batch_size, self.num_channels, self.image_size, self.image_size) )

     # test greyscale images
     lowercase__			    =						1
     lowercase__			    =						ViTForMaskedImageModeling(a )
     model.to(a )
     model.eval()

     lowercase__			    =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
     lowercase__			    =						model(a )
     self.parent.assertEqual(result.reconstruction.shape    ,  (self.batch_size, 1, self.image_size, self.image_size) )


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str]    ,  a    :       List[str]    ,  a    :       int    ,  a    :       List[Any] )->     str:





     """simple docstring"""







     lowercase__			    =						self.type_sequence_label_size
     lowercase__			    =						ViTForImageClassification(a )
     model.to(a )
     model.eval()
     lowercase__			    =						model(a    ,  labels=a )
     self.parent.assertEqual(result.logits.shape    ,  (self.batch_size, self.type_sequence_label_size) )

     # test greyscale images
     lowercase__			    =						1
     lowercase__			    =						ViTForImageClassification(a )
     model.to(a )
     model.eval()

     lowercase__			    =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
     lowercase__			    =						model(a )
     self.parent.assertEqual(result.logits.shape    ,  (self.batch_size, self.type_sequence_label_size) )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     List[str]:





     """simple docstring"""







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






@require_torch
class        SCREAMING_SNAKE_CASE     (UpperCAmelCase    ,			UpperCAmelCase    ,			unittest.TestCase   ):
   _UpperCamelCase					:	Any				      = (
       (
           ViTModel,
           ViTForImageClassification,
           ViTForMaskedImageModeling,
       )
       if is_torch_available()
       else ()
   )
   _UpperCamelCase					:	Union[str, Any]				      = (
       {'feature-extraction': ViTModel, 'image-classification': ViTForImageClassification}
       if is_torch_available()
       else {}
   )
   _UpperCamelCase					:	int				      = True

   _UpperCamelCase					:	int				      = False
   _UpperCamelCase					:	Union[str, Any]				      = False
   _UpperCamelCase					:	Dict				      = False


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     List[str]:





     """simple docstring"""







     lowercase__			    =						ViTModelTester(self )
     lowercase__			    =						ConfigTester(self    ,  config_class=a    ,  has_text_modality=a    ,  hidden_size=37 )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Union[str, Any]:





     """simple docstring"""







     self.config_tester.run_common_tests()


   @unittest.skip(reason='ViT does not use inputs_embeds' )
   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Optional[Any]:





     """simple docstring"""







     pass


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[Any] )->     Union[str, Any]:





     """simple docstring"""







     lowercase__    ,					lowercase__			    =						self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       lowercase__			    =						model_class(a )
       self.assertIsInstance(model.get_input_embeddings()    ,  (nn.Module) )
       lowercase__			    =						model.get_output_embeddings()
       self.assertTrue(x is None or isinstance(a    ,  nn.Linear ) )


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str] )->     Optional[int]:





     """simple docstring"""







     lowercase__    ,					lowercase__			    =						self.model_tester.prepare_config_and_inputs_for_common()

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

       lowercase__			    =						['pixel_values']
       self.assertListEqual(arg_names[:1]    ,  a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str] )->     Union[str, Any]:





     """simple docstring"""







     lowercase__			    =						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Tuple:





     """simple docstring"""







     lowercase__			    =						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_image_modeling(*a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     int:





     """simple docstring"""







     lowercase__			    =						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*a )


   @slow
   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict )->     List[Any]:





     """simple docstring"""







     for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       lowercase__			    =						ViTModel.from_pretrained(a )
       self.assertIsNotNone(a )






def     __UpperCamelCase						()       ->     str:
  lowercase__			    =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
  return image


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


   @cached_property
   def  SCREAMING_SNAKE_CASE_							(					self    :       List[Any] )->     List[Any]:





     """simple docstring"""







     return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224' ) if is_vision_available() else None


   @slow
   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Union[str, Any]:





     """simple docstring"""







     lowercase__			    =						ViTForImageClassification.from_pretrained('google/vit-base-patch16-224' ).to(a )

     lowercase__			    =						self.default_image_processor
     lowercase__			    =						prepare_img()
     lowercase__			    =						image_processor(images=a    ,  return_tensors='pt' ).to(a )

     # forward pass
     with torch.no_grad():
       lowercase__			    =						model(**a )

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

     lowercase__			    =						torch.tensor([-0.2744, 0.8215, -0.0836] ).to(a )

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


   @slow
   def  SCREAMING_SNAKE_CASE_							(					self    :       int )->     List[str]:





     """simple docstring"""







     lowercase__			    =						ViTModel.from_pretrained('facebook/dino-vits8' ).to(a )

     lowercase__			    =						ViTImageProcessor.from_pretrained('facebook/dino-vits8'    ,  size=480 )
     lowercase__			    =						prepare_img()
     lowercase__			    =						image_processor(images=a    ,  return_tensors='pt' )
     lowercase__			    =						inputs.pixel_values.to(a )

     # forward pass
     with torch.no_grad():
       lowercase__			    =						model(a    ,  interpolate_pos_encoding=a )

     # verify the logits
     lowercase__			    =						torch.Size((1, 3_601, 384) )
     self.assertEqual(outputs.last_hidden_state.shape    ,  a )

     lowercase__			    =						torch.tensor(
         [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(a )

     self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]    ,  a    ,  atol=1E-4 ) )


   @slow
   @require_accelerate
   @require_torch_gpu
   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     str:





     """simple docstring"""







     lowercase__			    =						ViTModel.from_pretrained('facebook/dino-vits8'    ,  torch_dtype=torch.floataa    ,  device_map='auto' )
     lowercase__			    =						self.default_image_processor

     lowercase__			    =						prepare_img()
     lowercase__			    =						image_processor(images=a    ,  return_tensors='pt' )
     lowercase__			    =						inputs.pixel_values.to(a )

     # forward pass to make sure inference works in fp16
     with torch.no_grad():
       lowercase__			    =						model(a )


