






"""simple docstring"""





import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
  from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor






class 	a		:






    def __init__(			self	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]=13			,		__SCREAMING_SNAKE_CASE	:				Tuple=32			,		__SCREAMING_SNAKE_CASE	:				Optional[int]=3			,		__SCREAMING_SNAKE_CASE	:				int=4			,		__SCREAMING_SNAKE_CASE	:				Optional[int]=[10, 20, 30, 40]			,		__SCREAMING_SNAKE_CASE	:				List[str]=[2, 2, 3, 2]			,		__SCREAMING_SNAKE_CASE	:				Tuple=True			,		__SCREAMING_SNAKE_CASE	:				Tuple=True			,		__SCREAMING_SNAKE_CASE	:				str=37			,		__SCREAMING_SNAKE_CASE	:				Tuple="gelu"			,		__SCREAMING_SNAKE_CASE	:				List[str]=10			,		__SCREAMING_SNAKE_CASE	:				Any=0.02			,		__SCREAMING_SNAKE_CASE	:				Tuple=["stage2", "stage3", "stage4"]			,		__SCREAMING_SNAKE_CASE	:				int=[2, 3, 4]			,		__SCREAMING_SNAKE_CASE	:				Optional[int]=None			,		)	->						int:
      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   UpperCamelCase			(			self	:				Optional[Any]   )	->						List[Any]:
      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   UpperCamelCase			(			self	:				Dict   )	->						Union[str, Any]:
      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=__SCREAMING_SNAKE_CASE			,		initializer_range=self.initializer_range			,		out_features=self.out_features			,		out_indices=self.out_indices			,		num_labels=self.num_labels			,		)






    def   UpperCamelCase			(			self	:				Optional[int]			,		__SCREAMING_SNAKE_CASE	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				Dict   )	->						Optional[Any]:
      lowerCamelCase_       	=		ConvNextVaModel(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   UpperCamelCase			(			self	:				Any			,		__SCREAMING_SNAKE_CASE	:				Dict			,		__SCREAMING_SNAKE_CASE	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				Any   )	->						Tuple:
      lowerCamelCase_       	=		ConvNextVaForImageClassification(__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   UpperCamelCase			(			self	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				List[str]			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				Any   )	->						List[str]:
      lowerCamelCase_       	=		ConvNextVaBackbone(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_       	=		ConvNextVaBackbone(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   UpperCamelCase			(			self	:				List[Any]   )	->						Union[str, Any]:
      lowerCamelCase_       	=		self.prepare_config_and_inputs()
      lowerCamelCase_	,      lowerCamelCase_	,      lowerCamelCase_       	=		config_and_inputs
      lowerCamelCase_       	=		{'pixel_values': pixel_values}
      return config, inputs_dict






    def   UpperCamelCase			(			self	:				Union[str, Any]   )	->						Any:
      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 	a		(   __snake_case    , __snake_case    , unittest.TestCase						):
    SCREAMING_SNAKE_CASE		:	Optional[Any]		=					(
        (
            ConvNextVaModel,
            ConvNextVaForImageClassification,
            ConvNextVaBackbone,
        )
        if is_torch_available()
        else ()
    )
    SCREAMING_SNAKE_CASE		:	int		=					(
        {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
        if is_torch_available()
        else {}
    )

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






    def   UpperCamelCase			(			self	:				Tuple   )	->						Dict:
      lowerCamelCase_       	=		ConvNextVaModelTester(self   )
      lowerCamelCase_       	=		ConfigTester(self			,		config_class=__SCREAMING_SNAKE_CASE			,		has_text_modality=__SCREAMING_SNAKE_CASE			,		hidden_size=37   )






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






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






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






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






    def   UpperCamelCase			(			self	:				Tuple   )	->						List[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(__SCREAMING_SNAKE_CASE   ),
            *get_values(__SCREAMING_SNAKE_CASE   ),
        ]:
          continue

        lowerCamelCase_       	=		model_class(__SCREAMING_SNAKE_CASE   )
        model.to(__SCREAMING_SNAKE_CASE   )
        model.train()
        lowerCamelCase_       	=		self._prepare_for_class(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE			,		return_labels=__SCREAMING_SNAKE_CASE   )
        lowerCamelCase_       	=		model(**__SCREAMING_SNAKE_CASE   ).loss
        loss.backward()






    def   UpperCamelCase			(			self	:				Any   )	->						int:
      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(__SCREAMING_SNAKE_CASE   ), *get_values(__SCREAMING_SNAKE_CASE   )]
            or not model_class.supports_gradient_checkpointing
        ):
          continue

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






    def   UpperCamelCase			(			self	:				Union[str, Any]   )	->						Optional[Any]:
      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   UpperCamelCase			(			self	:				Optional[Any]   )	->						Optional[Any]:
      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				str   )	->						int:
      def check_hidden_states_output(__SCREAMING_SNAKE_CASE	:				Any			,		__SCREAMING_SNAKE_CASE	:				str			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]   ):
        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   )

        # 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(__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   UpperCamelCase			(			self	:				List[str]   )	->						Dict:
      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE   )






    @slow
    def   UpperCamelCase			(			self	:				int   )	->						Any:
      for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCamelCase_       	=		ConvNextVaModel.from_pretrained(__SCREAMING_SNAKE_CASE   )
        self.assertIsNotNone(__SCREAMING_SNAKE_CASE   )







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






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






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






    @slow
    def   UpperCamelCase			(			self	:				Tuple   )	->						Tuple:
      lowerCamelCase_       	=		ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'   ).to(__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		self.default_image_processor
      lowerCamelCase_       	=		prepare_img()
      lowerCamelCase_       	=		preprocessor(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, 1000)   )
      self.assertEqual(outputs.logits.shape			,		__SCREAMING_SNAKE_CASE   )

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












"""simple docstring"""





import unittest

from datasets import load_dataset

from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow






@is_pipeline_test
@require_torch
class 	a		(   unittest.TestCase						):






    @require_torch
    def   UpperCamelCase			(			self	:				str   )	->						str:
      lowerCamelCase_       	=		pipeline(
          task='zero-shot-audio-classification'			,		model='hf-internal-testing/tiny-clap-htsat-unfused'   )
      lowerCamelCase_       	=		load_dataset('ashraq/esc50'   )
      lowerCamelCase_       	=		dataset['train']['audio'][-1]['array']
      lowerCamelCase_       	=		audio_classifier(__SCREAMING_SNAKE_CASE			,		candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']   )
      self.assertEqual(
          nested_simplify(__SCREAMING_SNAKE_CASE   )			,		[{'score': 0.501, 'label': 'Sound of a dog'}, {'score': 0.499, 'label': 'Sound of vaccum cleaner'}]			,		)






    @unittest.skip('No models are available in TF'   )
    def   UpperCamelCase			(			self	:				Tuple   )	->						Optional[Any]:
      pass






    @slow
    @require_torch
    def   UpperCamelCase			(			self	:				Optional[Any]   )	->						Optional[Any]:
      lowerCamelCase_       	=		pipeline(
          task='zero-shot-audio-classification'			,		model='laion/clap-htsat-unfused'			,		)
      # This is an audio of a dog
      lowerCamelCase_       	=		load_dataset('ashraq/esc50'   )
      lowerCamelCase_       	=		dataset['train']['audio'][-1]['array']
      lowerCamelCase_       	=		audio_classifier(__SCREAMING_SNAKE_CASE			,		candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']   )

      self.assertEqual(
          nested_simplify(__SCREAMING_SNAKE_CASE   )			,		[
              {'score': 0.999, 'label': 'Sound of a dog'},
              {'score': 0.001, 'label': 'Sound of vaccum cleaner'},
          ]			,		)

      lowerCamelCase_       	=		audio_classifier([audio] * 5			,		candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']   )
      self.assertEqual(
          nested_simplify(__SCREAMING_SNAKE_CASE   )			,		[
              [
                  {'score': 0.999, 'label': 'Sound of a dog'},
                  {'score': 0.001, 'label': 'Sound of vaccum cleaner'},
              ],
          ]
          * 5			,		)
      lowerCamelCase_       	=		audio_classifier(
          [audio] * 5			,		candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']			,		batch_size=5   )
      self.assertEqual(
          nested_simplify(__SCREAMING_SNAKE_CASE   )			,		[
              [
                  {'score': 0.999, 'label': 'Sound of a dog'},
                  {'score': 0.001, 'label': 'Sound of vaccum cleaner'},
              ],
          ]
          * 5			,		)






    @unittest.skip('No models are available in TF'   )
    def   UpperCamelCase			(			self	:				Optional[int]   )	->						int:
      pass




