


'''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    __magic_name__				:






       def __init__(     self    ,				snake_case    ,				snake_case=1_3    ,				snake_case=3_2    ,				snake_case=3    ,				snake_case=4    ,				snake_case=[1_0, 2_0, 3_0, 4_0]    ,				snake_case=[2, 2, 3, 2]    ,				snake_case=True    ,				snake_case=True    ,				snake_case=3_7    ,				snake_case="gelu"    ,				snake_case=1_0    ,				snake_case=0.02    ,				snake_case=["stage2", "stage3", "stage4"]    ,				snake_case=[2, 3, 4]    ,				snake_case=None    ,				)		->    List[Any]:




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






       def      lowerCAmelCase						(     self)		->    Dict:




          '''simple docstring'''
          _UpperCAmelCase  :  Dict				       =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

          _UpperCAmelCase  :  Tuple				       =self.get_config()

          return config, pixel_values, labels






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




          '''simple docstring'''
          return ConvNextVaConfig(
              num_channels=self.num_channels    ,				hidden_sizes=self.hidden_sizes    ,				depths=self.depths    ,				num_stages=self.num_stages    ,				hidden_act=self.hidden_act    ,				is_decoder=snake_case    ,				initializer_range=self.initializer_range    ,				out_features=self.out_features    ,				out_indices=self.out_indices    ,				num_labels=self.num_labels    ,				)






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case    ,				snake_case)		->    List[Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  Optional[int]				       =ConvNextVaModel(config=snake_case)
          model.to(snake_case)
          model.eval()
          _UpperCAmelCase  :  Optional[Any]				       =model(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 // 3_2, self.image_size // 3_2)    ,				)






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case    ,				snake_case)		->    Union[str, Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  List[Any]				       =ConvNextVaForImageClassification(snake_case)
          model.to(snake_case)
          model.eval()
          _UpperCAmelCase  :  Union[str, Any]				       =model(snake_case    ,				labels=snake_case)
          self.parent.assertEqual(result.logits.shape    ,				(self.batch_size, self.num_labels))






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case    ,				snake_case)		->    Optional[Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  Optional[Any]				       =ConvNextVaBackbone(config=snake_case)
          model.to(snake_case)
          model.eval()
          _UpperCAmelCase  :  List[str]				       =model(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
          _UpperCAmelCase  :  Optional[Any]				       =None
          _UpperCAmelCase  :  List[Any]				       =ConvNextVaBackbone(config=snake_case)
          model.to(snake_case)
          model.eval()
          _UpperCAmelCase  :  Any				       =model(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      lowerCAmelCase						(     self)		->    Dict:




          '''simple docstring'''
          _UpperCAmelCase  :  List[str]				       =self.prepare_config_and_inputs()
          _UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase  :  Tuple				       =config_and_inputs
          _UpperCAmelCase  :  List[str]				       ={'pixel_values': pixel_values}
          return config, inputs_dict






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




          '''simple docstring'''
          _UpperCAmelCase  :  Optional[Any]				       =self.prepare_config_and_inputs()
          _UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase  :  int				       =config_and_inputs
          _UpperCAmelCase  :  Any				       ={'pixel_values': pixel_values, 'labels': labels}
          return config, inputs_dict






@require_torch
class    __magic_name__				(						lowerCAmelCase   ,lowerCAmelCase   ,unittest.TestCase							):
       UpperCAmelCase		 =(
           (
               ConvNextVaModel,
               ConvNextVaForImageClassification,
               ConvNextVaBackbone,
           )
           if is_torch_available()
           else ()
       )
       UpperCAmelCase		 =(
           {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
           if is_torch_available()
           else {}
       )

       UpperCAmelCase		 =False
       UpperCAmelCase		 =False
       UpperCAmelCase		 =False
       UpperCAmelCase		 =False
       UpperCAmelCase		 =False






       def      lowerCAmelCase						(     self)		->    str:




          '''simple docstring'''
          _UpperCAmelCase  :  str				       =ConvNextVaModelTester(self)
          _UpperCAmelCase  :  int				       =ConfigTester(self    ,				config_class=snake_case    ,				has_text_modality=snake_case    ,				hidden_size=3_7)






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




          '''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      lowerCAmelCase						(     self)		->    Optional[int]:




          '''simple docstring'''
          return






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




          '''simple docstring'''
          pass






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




          '''simple docstring'''
          pass






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




          '''simple docstring'''
          pass






       def      lowerCAmelCase						(     self)		->    int:




          '''simple docstring'''
          if not self.model_tester.is_training:
             return

          for model_class in self.all_model_classes:
             _UpperCAmelCase       ,			_UpperCAmelCase  :  Union[str, Any]				       =self.model_tester.prepare_config_and_inputs_with_labels()
             _UpperCAmelCase  :  Any				       =True

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

             _UpperCAmelCase  :  List[Any]				       =model_class(snake_case)
             model.to(snake_case)
             model.train()
             _UpperCAmelCase  :  Any				       =self._prepare_for_class(snake_case    ,				snake_case    ,				return_labels=snake_case)
             _UpperCAmelCase  :  List[str]				       =model(**snake_case).loss
             loss.backward()






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




          '''simple docstring'''
          if not self.model_tester.is_training:
             return

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

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

             _UpperCAmelCase  :  Union[str, Any]				       =model_class(snake_case)
             model.to(snake_case)
             model.gradient_checkpointing_enable()
             model.train()
             _UpperCAmelCase  :  List[str]				       =self._prepare_for_class(snake_case    ,				snake_case    ,				return_labels=snake_case)
             _UpperCAmelCase  :  List[Any]				       =model(**snake_case).loss
             loss.backward()






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




          '''simple docstring'''
          _UpperCAmelCase       ,			_UpperCAmelCase  :  int				       =self.model_tester.prepare_config_and_inputs_for_common()

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

             _UpperCAmelCase  :  Tuple				       =['pixel_values']
             self.assertListEqual(arg_names[:1]    ,				snake_case)






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




          '''simple docstring'''
          _UpperCAmelCase  :  Optional[Any]				       =self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case)






       def      lowerCAmelCase						(     self)		->    int:




          '''simple docstring'''
          def check_hidden_states_output(snake_case    ,				snake_case    ,				snake_case):
             _UpperCAmelCase  :  Any				       =model_class(snake_case)
             model.to(snake_case)
             model.eval()

             with torch.no_grad():
                _UpperCAmelCase  :  Dict				       =model(**self._prepare_for_class(snake_case    ,				snake_case))

             _UpperCAmelCase  :  List[str]				       =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             _UpperCAmelCase  :  List[Any]				       =self.model_tester.num_stages
             self.assertEqual(len(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]    ,				)

          _UpperCAmelCase       ,			_UpperCAmelCase  :  str				       =self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
             _UpperCAmelCase  :  Any				       =True
             check_hidden_states_output(snake_case    ,				snake_case    ,				snake_case)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             _UpperCAmelCase  :  Tuple				       =True

             check_hidden_states_output(snake_case    ,				snake_case    ,				snake_case)






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




          '''simple docstring'''
          _UpperCAmelCase  :  List[str]				       =self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case)






       @slow
       def      lowerCAmelCase						(     self)		->    Dict:




          '''simple docstring'''
          for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _UpperCAmelCase  :  List[str]				       =ConvNextVaModel.from_pretrained(snake_case)
             self.assertIsNotNone(snake_case)






def lowerCamelCase__     (		):







   '''simple docstring'''




   _UpperCAmelCase  :  List[Any]				       =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
   return image






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






       @cached_property
       def      lowerCAmelCase						(     self)		->    Dict:




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






       @slow
       def      lowerCAmelCase						(     self)		->    str:




          '''simple docstring'''
          _UpperCAmelCase  :  Optional[int]				       =ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224').to(snake_case)

          _UpperCAmelCase  :  List[Any]				       =self.default_image_processor
          _UpperCAmelCase  :  Union[str, Any]				       =prepare_img()
          _UpperCAmelCase  :  List[str]				       =preprocessor(images=snake_case    ,				return_tensors='pt').to(snake_case)

          # forward pass
          with torch.no_grad():
             _UpperCAmelCase  :  Any				       =model(**snake_case)

          # verify the logits
          _UpperCAmelCase  :  Tuple				       =torch.Size((1, 1_0_0_0))
          self.assertEqual(outputs.logits.shape    ,				snake_case)

          _UpperCAmelCase  :  Union[str, Any]				       =torch.tensor([0.99_96, 0.19_66, -0.43_86]).to(snake_case)
          self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,				snake_case    ,				atol=1E-4))





'''simple docstring'''






import os

import pytest

from datasets import (
    get_dataset_config_info,
    get_dataset_config_names,
    get_dataset_infos,
    get_dataset_split_names,
    inspect_dataset,
    inspect_metric,
)


lowercase				=pytest.mark.integration





@pytest.mark.parametrize('path'			,       ['paws', 'csv']				)
def lowerCamelCase__     (		__lowerCamelCase			:				List[Any]			,       __lowerCamelCase			:				Optional[Any]				):







   '''simple docstring'''




   inspect_dataset(__lowerCamelCase			,       __lowerCamelCase				)
   _UpperCAmelCase  :  List[str]				       =path + '.py'
   assert script_name in os.listdir(__lowerCamelCase				)
   assert "__pycache__" not in os.listdir(__lowerCamelCase				)





@pytest.mark.filterwarnings('ignore:inspect_metric is deprecated:FutureWarning'				)
@pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'				)
@pytest.mark.parametrize('path'			,       ['accuracy']				)
def lowerCamelCase__     (		__lowerCamelCase			:				Dict			,       __lowerCamelCase			:				str				):







   '''simple docstring'''




   inspect_metric(__lowerCamelCase			,       __lowerCamelCase				)
   _UpperCAmelCase  :  List[Any]				       =path + '.py'
   assert script_name in os.listdir(__lowerCamelCase				)
   assert "__pycache__" not in os.listdir(__lowerCamelCase				)





@pytest.mark.parametrize(
    'path, config_name, expected_splits'			,       [
        ('squad', 'plain_text', ['train', 'validation']),
        ('dalle-mini/wit', 'dalle-mini--wit', ['train']),
        ('paws', 'labeled_final', ['train', 'test', 'validation']),
    ]			,       )
def lowerCamelCase__     (		__lowerCamelCase			:				Any			,       __lowerCamelCase			:				Optional[int]			,       __lowerCamelCase			:				str				):







   '''simple docstring'''




   _UpperCAmelCase  :  str				       =get_dataset_config_info(__lowerCamelCase			,       config_name=__lowerCamelCase				)
   assert info.config_name == config_name
   assert list(info.splits.keys()				) == expected_splits





@pytest.mark.parametrize(
    'path, config_name, expected_exception'			,       [
        ('paws', None, ValueError),
    ]			,       )
def lowerCamelCase__     (		__lowerCamelCase			:				List[Any]			,       __lowerCamelCase			:				Optional[Any]			,       __lowerCamelCase			:				List[str]				):







   '''simple docstring'''




   with pytest.raises(__lowerCamelCase				):
      get_dataset_config_info(__lowerCamelCase			,       config_name=__lowerCamelCase				)





@pytest.mark.parametrize(
    'path, expected'			,       [
        ('squad', 'plain_text'),
        ('acronym_identification', 'default'),
        ('lhoestq/squad', 'plain_text'),
        ('lhoestq/test', 'default'),
        ('lhoestq/demo1', 'lhoestq--demo1'),
        ('dalle-mini/wit', 'dalle-mini--wit'),
    ]			,       )
def lowerCamelCase__     (		__lowerCamelCase			:				Tuple			,       __lowerCamelCase			:				List[str]				):







   '''simple docstring'''




   _UpperCAmelCase  :  Dict				       =get_dataset_config_names(__lowerCamelCase				)
   assert expected in config_names





@pytest.mark.parametrize(
    'path, expected_configs, expected_splits_in_first_config'			,       [
        ('squad', ['plain_text'], ['train', 'validation']),
        ('dalle-mini/wit', ['dalle-mini--wit'], ['train']),
        ('paws', ['labeled_final', 'labeled_swap', 'unlabeled_final'], ['train', 'test', 'validation']),
    ]			,       )
def lowerCamelCase__     (		__lowerCamelCase			:				Tuple			,       __lowerCamelCase			:				List[Any]			,       __lowerCamelCase			:				List[Any]				):







   '''simple docstring'''




   _UpperCAmelCase  :  Optional[int]				       =get_dataset_infos(__lowerCamelCase				)
   assert list(infos.keys()				) == expected_configs
   _UpperCAmelCase  :  Optional[int]				       =expected_configs[0]
   assert expected_config in infos
   _UpperCAmelCase  :  Optional[int]				       =infos[expected_config]
   assert info.config_name == expected_config
   assert list(info.splits.keys()				) == expected_splits_in_first_config





@pytest.mark.parametrize(
    'path, expected_config, expected_splits'			,       [
        ('squad', 'plain_text', ['train', 'validation']),
        ('dalle-mini/wit', 'dalle-mini--wit', ['train']),
        ('paws', 'labeled_final', ['train', 'test', 'validation']),
    ]			,       )
def lowerCamelCase__     (		__lowerCamelCase			:				Tuple			,       __lowerCamelCase			:				Tuple			,       __lowerCamelCase			:				int				):







   '''simple docstring'''




   _UpperCAmelCase  :  str				       =get_dataset_infos(__lowerCamelCase				)
   assert expected_config in infos
   _UpperCAmelCase  :  Dict				       =infos[expected_config]
   assert info.config_name == expected_config
   assert list(info.splits.keys()				) == expected_splits





@pytest.mark.parametrize(
    'path, config_name, expected_exception'			,       [
        ('paws', None, ValueError),
    ]			,       )
def lowerCamelCase__     (		__lowerCamelCase			:				Union[str, Any]			,       __lowerCamelCase			:				Optional[Any]			,       __lowerCamelCase			:				Any				):







   '''simple docstring'''




   with pytest.raises(__lowerCamelCase				):
      get_dataset_split_names(__lowerCamelCase			,       config_name=__lowerCamelCase				)

