






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

  """simple docstring"""


  def __init__(    self			:		Optional[int] ,  lowerCAmelCase_			:		Union[str, Any] ,  lowerCAmelCase_			:		Dict=1_3 ,  lowerCAmelCase_			:		str=3_2 ,  lowerCAmelCase_			:		List[Any]=3 ,  lowerCAmelCase_			:		str=4 ,  lowerCAmelCase_			:		Dict=[1_0, 2_0, 3_0, 4_0] ,  lowerCAmelCase_			:		int=[2, 2, 3, 2] ,  lowerCAmelCase_			:		Dict=True ,  lowerCAmelCase_			:		Optional[Any]=True ,  lowerCAmelCase_			:		str=3_7 ,  lowerCAmelCase_			:		str="gelu" ,  lowerCAmelCase_			:		Dict=1_0 ,  lowerCAmelCase_			:		Union[str, Any]=0.02 ,  lowerCAmelCase_			:		List[str]=["stage2", "stage3", "stage4"] ,  lowerCAmelCase_			:		List[Any]=[2, 3, 4] ,  lowerCAmelCase_			:		List[Any]=None ,  )							->						Union[str, Any]:
     __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     lowercase		(    self			:		int					)							->						Optional[int]:
     __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     lowercase		(    self			:		int					)							->						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=lowerCAmelCase_ ,  initializer_range=self.initializer_range ,  out_features=self.out_features ,  out_indices=self.out_indices ,  num_labels=self.num_labels ,  )






  def     lowercase		(    self			:		Any ,  lowerCAmelCase_			:		Optional[int] ,  lowerCAmelCase_			:		Any ,  lowerCAmelCase_			:		int					)							->						List[Any]:
     __lowerCAmelCase							     =     ConvNextVaModel(config=lowerCAmelCase_					)
     model.to(lowerCAmelCase_					)
     model.eval()
     __lowerCAmelCase							     =     model(lowerCAmelCase_					)
     # 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 // 3_2, self.image_size // 3_2) ,  )






  def     lowercase		(    self			:		Optional[int] ,  lowerCAmelCase_			:		Optional[int] ,  lowerCAmelCase_			:		int ,  lowerCAmelCase_			:		List[str]					)							->						Tuple:
     __lowerCAmelCase							     =     ConvNextVaForImageClassification(lowerCAmelCase_					)
     model.to(lowerCAmelCase_					)
     model.eval()
     __lowerCAmelCase							     =     model(lowerCAmelCase_ ,  labels=lowerCAmelCase_					)
     self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.num_labels)					)






  def     lowercase		(    self			:		List[str] ,  lowerCAmelCase_			:		Any ,  lowerCAmelCase_			:		str ,  lowerCAmelCase_			:		int					)							->						Dict:
     __lowerCAmelCase							     =     ConvNextVaBackbone(config=lowerCAmelCase_					)
     model.to(lowerCAmelCase_					)
     model.eval()
     __lowerCAmelCase							     =     model(lowerCAmelCase_					)

     # 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							     =     ConvNextVaBackbone(config=lowerCAmelCase_					)
     model.to(lowerCAmelCase_					)
     model.eval()
     __lowerCAmelCase							     =     model(lowerCAmelCase_					)

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






  def     lowercase		(    self			:		Dict					)							->						str:
     __lowerCAmelCase							     =     self.prepare_config_and_inputs()
     __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase							     =     config_and_inputs
     __lowerCAmelCase							     =     {'pixel_values': pixel_values, 'labels': labels}
     return config, inputs_dict





@require_torch
class     _UpperCAmelCase   (   _UpperCamelCase		,   _UpperCamelCase		,   unittest.TestCase   ):

  """simple docstring"""


  a_      =			(
      (
          ConvNextVaModel,
          ConvNextVaForImageClassification,
          ConvNextVaBackbone,
      )
      if is_torch_available()
      else ()
  )
  a_      =			(
      {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
      if is_torch_available()
      else {}
  )

  a_      =			False
  a_      =			False
  a_      =			False
  a_      =			False
  a_      =			False






  def     lowercase		(    self			:		str					)							->						Optional[Any]:
     __lowerCAmelCase							     =     ConvNextVaModelTester(self					)
     __lowerCAmelCase							     =     ConfigTester(self ,  config_class=lowerCAmelCase_ ,  has_text_modality=lowerCAmelCase_ ,  hidden_size=3_7					)






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






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






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






  @unittest.skip(reason='ConvNextV2 does not use feedforward chunking'					)
  def     lowercase		(    self			:		Optional[Any]					)							->						Union[str, Any]:
     pass






  def     lowercase		(    self			:		List[Any]					)							->						str:
     if not self.model_tester.is_training:
        return

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

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

        __lowerCAmelCase							     =     model_class(lowerCAmelCase_					)
        model.to(lowerCAmelCase_					)
        model.train()
        __lowerCAmelCase							     =     self._prepare_for_class(lowerCAmelCase_ ,  lowerCAmelCase_ ,  return_labels=lowerCAmelCase_					)
        __lowerCAmelCase							     =     model(**lowerCAmelCase_					).loss
        loss.backward()






  def     lowercase		(    self			:		List[str]					)							->						Dict:
     if not self.model_tester.is_training:
        return

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

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

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






  def     lowercase		(    self			:		Optional[Any]					)							->						Union[str, Any]:
     __lowerCAmelCase     ,     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __lowerCAmelCase							     =     model_class(lowerCAmelCase_					)
        __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] ,  lowerCAmelCase_					)






  def     lowercase		(    self			:		Union[str, Any]					)							->						str:
     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase_					)






  def     lowercase		(    self			:		Union[str, Any]					)							->						Dict:
     def check_hidden_states_output(lowerCAmelCase_			:		Optional[int] ,  lowerCAmelCase_			:		List[str] ,  lowerCAmelCase_			:		Any					):
        __lowerCAmelCase							     =     model_class(lowerCAmelCase_					)
        model.to(lowerCAmelCase_					)
        model.eval()

        with torch.no_grad():
           __lowerCAmelCase							     =     model(**self._prepare_for_class(lowerCAmelCase_ ,  lowerCAmelCase_					)					)

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

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

     __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(lowerCAmelCase_ ,  lowerCAmelCase_ ,  lowerCAmelCase_					)

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

        check_hidden_states_output(lowerCAmelCase_ ,  lowerCAmelCase_ ,  lowerCAmelCase_					)






  def     lowercase		(    self			:		Dict					)							->						Union[str, Any]:
     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_					)






  @slow
  def     lowercase		(    self			:		int					)							->						Optional[Any]:
     for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCAmelCase							     =     ConvNextVaModel.from_pretrained(lowerCAmelCase_					)
        self.assertIsNotNone(lowerCAmelCase_					)





def   a_   (			):
   __lowerCAmelCase							     =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
   return image




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

  """simple docstring"""


  @cached_property
  def     lowercase		(    self			:		List[str]					)							->						int:
     return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224'					) if is_vision_available() else None






  @slow
  def     lowercase		(    self			:		Optional[Any]					)							->						Optional[int]:
     __lowerCAmelCase							     =     ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'					).to(lowerCAmelCase_					)

     __lowerCAmelCase							     =     self.default_image_processor
     __lowerCAmelCase							     =     prepare_img()
     __lowerCAmelCase							     =     preprocessor(images=lowerCAmelCase_ ,  return_tensors='pt'					).to(lowerCAmelCase_					)

     # forward pass
     with torch.no_grad():
        __lowerCAmelCase							     =     model(**lowerCAmelCase_					)

     # verify the logits
     __lowerCAmelCase							     =     torch.Size((1, 1_0_0_0)					)
     self.assertEqual(outputs.logits.shape ,  lowerCAmelCase_					)

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








import math
from typing import Optional

import numpy as np

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_snake_case  :   List[str]						   =  logging.get_logger(__name__)

_snake_case  :   Dict						   =  {
    'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json',
    'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json',
}



class     _UpperCAmelCase   (   _UpperCamelCase   ):

  """simple docstring"""


  a_      =			"""encodec"""






  def __init__(    self			:		Optional[Any] ,  lowerCAmelCase_			:		List[Any]=[1.5, 3.0, 6.0, 12.0, 24.0] ,  lowerCAmelCase_			:		Optional[Any]=2_4_0_0_0 ,  lowerCAmelCase_			:		int=1 ,  lowerCAmelCase_			:		Union[str, Any]=False ,  lowerCAmelCase_			:		Optional[Any]=None ,  lowerCAmelCase_			:		Union[str, Any]=None ,  lowerCAmelCase_			:		Optional[Any]=1_2_8 ,  lowerCAmelCase_			:		List[Any]=3_2 ,  lowerCAmelCase_			:		Optional[Any]=1 ,  lowerCAmelCase_			:		Optional[int]=[8, 5, 4, 2] ,  lowerCAmelCase_			:		Optional[Any]="weight_norm" ,  lowerCAmelCase_			:		Tuple=7 ,  lowerCAmelCase_			:		Optional[int]=7 ,  lowerCAmelCase_			:		Dict=3 ,  lowerCAmelCase_			:		Optional[Any]=2 ,  lowerCAmelCase_			:		List[Any]=True ,  lowerCAmelCase_			:		Dict="reflect" ,  lowerCAmelCase_			:		List[Any]=2 ,  lowerCAmelCase_			:		int=2 ,  lowerCAmelCase_			:		Dict=1.0 ,  lowerCAmelCase_			:		str=1_0_2_4 ,  lowerCAmelCase_			:		Dict=None ,  lowerCAmelCase_			:		List[Any]=True ,  **lowerCAmelCase_			:		Optional[Any] ,  )							->						Union[str, Any]:
     __lowerCAmelCase							     =     target_bandwidths
     __lowerCAmelCase							     =     sampling_rate
     __lowerCAmelCase							     =     audio_channels
     __lowerCAmelCase							     =     normalize
     __lowerCAmelCase							     =     chunk_length_s
     __lowerCAmelCase							     =     overlap
     __lowerCAmelCase							     =     hidden_size
     __lowerCAmelCase							     =     num_filters
     __lowerCAmelCase							     =     num_residual_layers
     __lowerCAmelCase							     =     upsampling_ratios
     __lowerCAmelCase							     =     norm_type
     __lowerCAmelCase							     =     kernel_size
     __lowerCAmelCase							     =     last_kernel_size
     __lowerCAmelCase							     =     residual_kernel_size
     __lowerCAmelCase							     =     dilation_growth_rate
     __lowerCAmelCase							     =     use_causal_conv
     __lowerCAmelCase							     =     pad_mode
     __lowerCAmelCase							     =     compress
     __lowerCAmelCase							     =     num_lstm_layers
     __lowerCAmelCase							     =     trim_right_ratio
     __lowerCAmelCase							     =     codebook_size
     __lowerCAmelCase							     =     codebook_dim if codebook_dim is not None else hidden_size
     __lowerCAmelCase							     =     use_conv_shortcut

     if self.norm_type not in ["weight_norm", "time_group_norm"]:
        raise ValueError(
            f"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}"""					)

     super().__init__(**lowerCAmelCase_					)






  @property
  def     lowercase		(    self			:		Union[str, Any]					)							->						Optional[int]:
     if self.chunk_length_s is None:
        return None
     else:
        return int(self.chunk_length_s * self.sampling_rate					)






  @property
  def     lowercase		(    self			:		Optional[Any]					)							->						Optional[int]:
     if self.chunk_length_s is None or self.overlap is None:
        return None
     else:
        return max(1 ,  int((1.0 - self.overlap) * self.chunk_length					)					)






  @property
  def     lowercase		(    self			:		Any					)							->						int:
     __lowerCAmelCase							     =     np.prod(self.upsampling_ratios					)
     return math.ceil(self.sampling_rate / hop_length					)






  @property
  def     lowercase		(    self			:		str					)							->						int:
     return int(1_0_0_0 * self.target_bandwidths[-1] // (self.frame_rate * 1_0)					)

