


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




       """simple docstring"""



       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.0_2				,       _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"]				,       _SCREAMING_SNAKE_CASE=[2, 3, 4]				,       _SCREAMING_SNAKE_CASE=None				,       )->Optional[int]:




         '''simple docstring'''





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



       def        _snake_case       (      self		)->int:




         '''simple docstring'''





         A_      :				Optional[int]		     =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

         A_      :				List[Any]		     =					None
         if self.use_labels:
           A_      :				Optional[Any]		     =					ids_tensor([self.batch_size]				,       self.num_labels		)

         A_      :				str		     =					self.get_config()
         return config, pixel_values, labels



       def        _snake_case       (      self		)->int:




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




         '''simple docstring'''





         A_      :				Optional[int]		     =					ConvNextModel(config=_SCREAMING_SNAKE_CASE		)
         model.to(_SCREAMING_SNAKE_CASE		)
         model.eval()
         A_      :				Dict		     =					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        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)->List[Any]:




         '''simple docstring'''





         A_      :				Any		     =					ConvNextForImageClassification(_SCREAMING_SNAKE_CASE		)
         model.to(_SCREAMING_SNAKE_CASE		)
         model.eval()
         A_      :				Tuple		     =					model(_SCREAMING_SNAKE_CASE				,       labels=_SCREAMING_SNAKE_CASE		)
         self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.num_labels)		)



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)->Tuple:




         '''simple docstring'''





         A_      :				int		     =					ConvNextBackbone(config=_SCREAMING_SNAKE_CASE		)
         model.to(_SCREAMING_SNAKE_CASE		)
         model.eval()
         A_      :				Optional[int]		     =					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
         A_      :				Union[str, Any]		     =					None
         A_      :				List[Any]		     =					ConvNextBackbone(config=_SCREAMING_SNAKE_CASE		)
         model.to(_SCREAMING_SNAKE_CASE		)
         model.eval()
         A_      :				Union[str, Any]		     =					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        _snake_case       (      self		)->Union[str, Any]:




         '''simple docstring'''





         A_      :				Optional[Any]		     =					self.prepare_config_and_inputs()
         A_     ,       A_     ,       A_      :				Tuple		     =					config_and_inputs
         A_      :				Union[str, Any]		     =					{'''pixel_values''': pixel_values}
         return config, inputs_dict






@require_torch
class   _lowerCamelCase (					UpperCamelCase					,							UpperCamelCase					,							unittest.TestCase			):




       """simple docstring"""
       snake_case      =    (
           (
               ConvNextModel,
               ConvNextForImageClassification,
               ConvNextBackbone,
           )
           if is_torch_available()
           else ()
       )
       snake_case      =    (
           {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
           if is_torch_available()
           else {}
       )

       snake_case      =    True
       snake_case      =    False
       snake_case      =    False
       snake_case      =    False
       snake_case      =    False



       def        _snake_case       (      self		)->Dict:




         '''simple docstring'''





         A_      :				Optional[Any]		     =					ConvNextModelTester(self		)
         A_      :				List[str]		     =					ConfigTester(self				,       config_class=_SCREAMING_SNAKE_CASE				,       has_text_modality=_SCREAMING_SNAKE_CASE				,       hidden_size=37		)



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




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




         '''simple docstring'''





         return



       @unittest.skip(reason='''ConvNext does not use inputs_embeds'''		)
       def        _snake_case       (      self		)->str:




         '''simple docstring'''





         pass



       @unittest.skip(reason='''ConvNext does not support input and output embeddings'''		)
       def        _snake_case       (      self		)->List[Any]:




         '''simple docstring'''





         pass



       @unittest.skip(reason='''ConvNext does not use feedforward chunking'''		)
       def        _snake_case       (      self		)->Any:




         '''simple docstring'''





         pass



       def        _snake_case       (      self		)->str:




         '''simple docstring'''





         A_     ,       A_      :				Tuple		     =					self.model_tester.prepare_config_and_inputs_for_common()

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

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



       def        _snake_case       (      self		)->List[str]:




         '''simple docstring'''





         A_      :				Optional[int]		     =					self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE		)



       def        _snake_case       (      self		)->Any:




         '''simple docstring'''





         A_      :				Union[str, Any]		     =					self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE		)



       def        _snake_case       (      self		)->List[Any]:




         '''simple docstring'''





         def check_hidden_states_output(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		):
           A_      :				List[Any]		     =					model_class(_SCREAMING_SNAKE_CASE		)
           model.to(_SCREAMING_SNAKE_CASE		)
           model.eval()

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

           A_      :				int		     =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           A_      :				List[Any]		     =					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]				,       )

         A_     ,       A_      :				int		     =					self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           A_      :				Union[str, Any]		     =					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"]
           A_      :				Dict		     =					True

           check_hidden_states_output(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)



       def        _snake_case       (      self		)->Dict:




         '''simple docstring'''





         A_      :				Union[str, Any]		     =					self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE		)







       @slow
       def        _snake_case       (      self		)->str:




         '''simple docstring'''





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




def   _SCREAMING_SNAKE_CASE	( ):
  A_      :				Union[str, Any]		     =					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
  return image






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




       """simple docstring"""



       @cached_property
       def        _snake_case       (      self		)->int:




         '''simple docstring'''





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







       @slow
       def        _snake_case       (      self		)->Tuple:




         '''simple docstring'''





         A_      :				Union[str, Any]		     =					ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''		).to(_SCREAMING_SNAKE_CASE		)

         A_      :				Union[str, Any]		     =					self.default_image_processor
         A_      :				Union[str, Any]		     =					prepare_img()
         A_      :				Any		     =					image_processor(images=_SCREAMING_SNAKE_CASE				,       return_tensors='''pt'''		).to(_SCREAMING_SNAKE_CASE		)

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

         # verify the logits
         A_      :				Union[str, Any]		     =					torch.Size((1, 1000)		)
         self.assertEqual(outputs.logits.shape				,       _SCREAMING_SNAKE_CASE		)

         A_      :				int		     =					torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]		).to(_SCREAMING_SNAKE_CASE		)

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






@require_torch
class   _lowerCamelCase (					unittest.TestCase					,							UpperCamelCase			):




       """simple docstring"""
       snake_case      =    (ConvNextBackbone,) if is_torch_available() else ()
       snake_case      =    ConvNextConfig

       snake_case      =    False



       def        _snake_case       (      self		)->str:




         '''simple docstring'''





         A_      :				List[Any]		     =					ConvNextModelTester(self		)








import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test






class   _lowerCamelCase (					unittest.TestCase			):




       """simple docstring"""



       @parameterized.expand([(None,), ('''foo.json''',)]		)
       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE		)->Tuple:




         '''simple docstring'''





         A_      :				Dict		     =					GenerationConfig(
             do_sample=_SCREAMING_SNAKE_CASE				,       temperature=0.7				,       length_penalty=1.0				,       bad_words_ids=[[1, 2, 3], [4, 5]]				,       )
         with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(_SCREAMING_SNAKE_CASE				,       config_name=_SCREAMING_SNAKE_CASE		)
           A_      :				Tuple		     =					GenerationConfig.from_pretrained(_SCREAMING_SNAKE_CASE				,       config_name=_SCREAMING_SNAKE_CASE		)

         # Checks parameters that were specified
         self.assertEqual(loaded_config.do_sample				,       _SCREAMING_SNAKE_CASE		)
         self.assertEqual(loaded_config.temperature				,       0.7		)
         self.assertEqual(loaded_config.length_penalty				,       1.0		)
         self.assertEqual(loaded_config.bad_words_ids				,       [[1, 2, 3], [4, 5]]		)

         # Checks parameters that were not specified (defaults)
         self.assertEqual(loaded_config.top_k				,       50		)
         self.assertEqual(loaded_config.max_length				,       20		)
         self.assertEqual(loaded_config.max_time				,       _SCREAMING_SNAKE_CASE		)



       def        _snake_case       (      self		)->Dict:




         '''simple docstring'''





         A_      :				str		     =					AutoConfig.from_pretrained('''gpt2'''		)
         A_      :				int		     =					GenerationConfig.from_model_config(_SCREAMING_SNAKE_CASE		)
         A_      :				Dict		     =					GenerationConfig()

         # The generation config has loaded a few non-default parameters from the model config
         self.assertNotEqual(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)

         # One of those parameters is eos_token_id -- check if it matches
         self.assertNotEqual(generation_config_from_model.eos_token_id				,       default_generation_config.eos_token_id		)
         self.assertEqual(generation_config_from_model.eos_token_id				,       model_config.eos_token_id		)



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




         '''simple docstring'''





         A_      :				List[Any]		     =					GenerationConfig()
         A_      :				Optional[Any]		     =					{
             '''max_new_tokens''': 1024,
             '''foo''': '''bar''',
         }
         A_      :				Dict		     =					copy.deepcopy(_SCREAMING_SNAKE_CASE		)
         A_      :				Optional[int]		     =					generation_config.update(**_SCREAMING_SNAKE_CASE		)

         # update_kwargs was not modified (no side effects)
         self.assertEqual(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)

         # update_kwargs was used to update the config on valid attributes
         self.assertEqual(generation_config.max_new_tokens				,       1024		)

         # `.update()` returns a dictionary of unused kwargs
         self.assertEqual(_SCREAMING_SNAKE_CASE				,       {'''foo''': '''bar'''}		)



       def        _snake_case       (      self		)->str:




         '''simple docstring'''





         A_      :				List[str]		     =					GenerationConfig()
         A_      :				int		     =					'''bar'''

         with tempfile.TemporaryDirectory('''test-generation-config'''		) as tmp_dir:
           generation_config.save_pretrained(_SCREAMING_SNAKE_CASE		)

           A_      :				Optional[Any]		     =					GenerationConfig.from_pretrained(_SCREAMING_SNAKE_CASE		)
         # update_kwargs was used to update the config on valid attributes
         self.assertEqual(new_config.foo				,       '''bar'''		)

         A_      :				Optional[int]		     =					GenerationConfig.from_model_config(_SCREAMING_SNAKE_CASE		)
         assert not hasattr(_SCREAMING_SNAKE_CASE				,       '''foo'''		)  # no new kwargs should be initialized if from config







       def        _snake_case       (      self		)->List[Any]:




         '''simple docstring'''





         A_      :				str		     =					GenerationConfig()
         self.assertEqual(default_config.temperature				,       1.0		)
         self.assertEqual(default_config.do_sample				,       _SCREAMING_SNAKE_CASE		)
         self.assertEqual(default_config.num_beams				,       1		)

         A_      :				str		     =					GenerationConfig(
             do_sample=_SCREAMING_SNAKE_CASE				,       temperature=0.7				,       length_penalty=1.0				,       bad_words_ids=[[1, 2, 3], [4, 5]]				,       )
         self.assertEqual(config.temperature				,       0.7		)
         self.assertEqual(config.do_sample				,       _SCREAMING_SNAKE_CASE		)
         self.assertEqual(config.num_beams				,       1		)

         with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(_SCREAMING_SNAKE_CASE		)
           A_      :				Dict		     =					GenerationConfig.from_pretrained(_SCREAMING_SNAKE_CASE				,       temperature=1.0		)

         self.assertEqual(loaded_config.temperature				,       1.0		)
         self.assertEqual(loaded_config.do_sample				,       _SCREAMING_SNAKE_CASE		)
         self.assertEqual(loaded_config.num_beams				,       1		)  # default value






@is_staging_test
class   _lowerCamelCase (					unittest.TestCase			):




       """simple docstring"""



       @classmethod
       def        _snake_case       (      cls		)->Optional[int]:




         '''simple docstring'''





         A_      :				str		     =					TOKEN
         HfFolder.save_token(_SCREAMING_SNAKE_CASE		)



       @classmethod
       def        _snake_case       (      cls		)->List[Any]:




         '''simple docstring'''





         try:
           delete_repo(token=cls._token				,       repo_id='''test-generation-config'''		)
         except HTTPError:
           pass

         try:
           delete_repo(token=cls._token				,       repo_id='''valid_org/test-generation-config-org'''		)
         except HTTPError:
           pass



       def        _snake_case       (      self		)->List[Any]:




         '''simple docstring'''





         A_      :				List[Any]		     =					GenerationConfig(
             do_sample=_SCREAMING_SNAKE_CASE				,       temperature=0.7				,       length_penalty=1.0				,       )
         config.push_to_hub('''test-generation-config'''				,       use_auth_token=self._token		)

         A_      :				Optional[int]		     =					GenerationConfig.from_pretrained(F'''{USER}/test-generation-config'''		)
         for k, v in config.to_dict().items():
           if k != "transformers_version":
             self.assertEqual(_SCREAMING_SNAKE_CASE				,       getattr(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)		)

        # Reset repo
         delete_repo(token=self._token				,       repo_id='''test-generation-config'''		)

         # Push to hub via save_pretrained
         with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(
               _SCREAMING_SNAKE_CASE				,       repo_id='''test-generation-config'''				,       push_to_hub=_SCREAMING_SNAKE_CASE				,       use_auth_token=self._token		)

         A_      :				Optional[Any]		     =					GenerationConfig.from_pretrained(F'''{USER}/test-generation-config'''		)
         for k, v in config.to_dict().items():
           if k != "transformers_version":
             self.assertEqual(_SCREAMING_SNAKE_CASE				,       getattr(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)		)







       def        _snake_case       (      self		)->List[str]:




         '''simple docstring'''





         A_      :				Tuple		     =					GenerationConfig(
             do_sample=_SCREAMING_SNAKE_CASE				,       temperature=0.7				,       length_penalty=1.0				,       )
         config.push_to_hub('''valid_org/test-generation-config-org'''				,       use_auth_token=self._token		)

         A_      :				Union[str, Any]		     =					GenerationConfig.from_pretrained('''valid_org/test-generation-config-org'''		)
         for k, v in config.to_dict().items():
           if k != "transformers_version":
             self.assertEqual(_SCREAMING_SNAKE_CASE				,       getattr(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)		)

        # Reset repo
         delete_repo(token=self._token				,       repo_id='''valid_org/test-generation-config-org'''		)

         # Push to hub via save_pretrained
         with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(
               _SCREAMING_SNAKE_CASE				,       repo_id='''valid_org/test-generation-config-org'''				,       push_to_hub=_SCREAMING_SNAKE_CASE				,       use_auth_token=self._token		)

         A_      :				Dict		     =					GenerationConfig.from_pretrained('''valid_org/test-generation-config-org'''		)
         for k, v in config.to_dict().items():
           if k != "transformers_version":
             self.assertEqual(_SCREAMING_SNAKE_CASE				,       getattr(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)		)




