




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





       '''simple docstring'''






       def __init__(      self,							A,							A=13,							A=32,							A=3,							A=4,							A=[10, 20, 30, 40],							A=[2, 2, 3, 2],							A=True,							A=True,							A=37,							A="gelu",							A=10,							A=0.02,							A=["stage2", "stage3", "stage4"],							A=[2, 3, 4],							A=None,							):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						None
             if self.use_labels:
                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						ids_tensor([self.batch_size],							self.num_labels  )

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.get_config()

             return config, pixel_values, labels







       def        UpperCamelCase_							(      self  ):







             '''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=A,							initializer_range=self.initializer_range,							out_features=self.out_features,							out_indices=self.out_indices,							num_labels=self.num_labels,							)







       def        UpperCamelCase_							(      self,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						ConvNextVaModel(config=A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      str    					=						model(A  )
             # 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,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Dict    					=						ConvNextVaForImageClassification(A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						model(A,							labels=A  )
             self.parent.assertEqual(result.logits.shape,							(self.batch_size, self.num_labels)  )







       def        UpperCamelCase_							(      self,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      int    					=						ConvNextVaBackbone(config=A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      int    					=						model(A  )

             # 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
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						None
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						ConvNextVaBackbone(config=A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      List[str]    					=						model(A  )

             # 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  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Dict    					=						self.prepare_config_and_inputs()
             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Dict    					=						config_and_inputs
             SCREAMING_SNAKE_CASE   :      List[str]    					=						{'pixel_values': pixel_values, 'labels': labels}
             return config, inputs_dict






@require_torch
class 							_a				(			SCREAMING_SNAKE_CASE ,      SCREAMING_SNAKE_CASE ,      unittest.TestCase ):





       '''simple docstring'''






       A						:				Any        =						(
           (
               ConvNextVaModel,
               ConvNextVaForImageClassification,
               ConvNextVaBackbone,
           )
           if is_torch_available()
           else ()
       )
       A						:				List[str]        =						(
           {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
           if is_torch_available()
           else {}
       )

       A						:				Any        =						False
       A						:				Tuple        =						False
       A						:				Union[str, Any]        =						False
       A						:				Any        =						False
       A						:				List[Any]        =						False







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      int    					=						ConvNextVaModelTester(self  )
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						ConfigTester(self,							config_class=A,							has_text_modality=A,							hidden_size=37  )







       def        UpperCamelCase_							(      self  ):







             '''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        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return







       @unittest.skip(reason='ConvNextV2 does not use inputs_embeds'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







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







             '''simple docstring'''







             pass







       @unittest.skip(reason='ConvNextV2 does not use feedforward chunking'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             if not self.model_tester.is_training:
                   return

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Any    					=						self.model_tester.prepare_config_and_inputs_with_labels()
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						True

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

                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						model_class(A  )
                   model.to(A  )
                   model.train()
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						self._prepare_for_class(A,							A,							return_labels=A  )
                   SCREAMING_SNAKE_CASE   :      int    					=						model(**A  ).loss
                   loss.backward()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             if not self.model_tester.is_training:
                   return

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

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

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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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

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

                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						['pixel_values']
                   self.assertListEqual(arg_names[:1],							A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             def check_hidden_states_output(A,							A,							A  ):
                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						model_class(A  )
                   model.to(A  )
                   model.eval()

                   with torch.no_grad():
                         SCREAMING_SNAKE_CASE   :      List[Any]    					=						model(**self._prepare_for_class(A,							A  )  )

                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE   :      Any    					=						True
                   check_hidden_states_output(A,							A,							A  )

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

                   check_hidden_states_output(A,							A,							A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*A  )







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						ConvNextVaModel.from_pretrained(A  )
                   self.assertIsNotNone(A  )




def   lowercase__(			):

      """simple docstring"""






      SCREAMING_SNAKE_CASE   :      Tuple    					=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
      return image






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





       '''simple docstring'''






       @cached_property
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'  ).to(A  )

             SCREAMING_SNAKE_CASE   :      int    					=						self.default_image_processor
             SCREAMING_SNAKE_CASE   :      Any    					=						prepare_img()
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						preprocessor(images=A,							return_tensors='pt'  ).to(A  )

             # forward pass
             with torch.no_grad():
                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						model(**A  )

             # verify the logits
             SCREAMING_SNAKE_CASE   :      int    					=						torch.Size((1, 1_000)  )
             self.assertEqual(outputs.logits.shape,							A  )

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








from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import MagicMock, patch

from transformers import AutoModel, TFAutoModel
from transformers.onnx import FeaturesManager
from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch


@require_torch
@require_tf
class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



	"""simple docstring"""


	def 					lowerCamelCase__     (					self		:						Dict	)	->       List[Any]:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[Any]             =      SMALL_MODEL_IDENTIFIER
						__UpperCamelCase					:	List[str]             =      """pt"""
						__UpperCamelCase					:	List[Any]             =      """tf"""






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







						"""simple docstring"""







						__UpperCamelCase					:	str             =      AutoModel.from_pretrained(self.test_model	)
						model_pt.save_pretrained(lowerCAmelCase	)






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







						"""simple docstring"""







						__UpperCamelCase					:	List[str]             =      TFAutoModel.from_pretrained(self.test_model					,     from_pt=lowerCAmelCase	)
						model_tf.save_pretrained(lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						str	)	->       Tuple:







						"""simple docstring"""







						__UpperCamelCase					:	Any             =      """mock_framework"""

						# Framework provided - return whatever the user provides
						__UpperCamelCase					:	List[Any]             =      FeaturesManager.determine_framework(self.test_model					,     lowerCAmelCase	)
						self.assertEqual(lowerCAmelCase					,     lowerCAmelCase	)

						# Local checkpoint and framework provided - return provided framework
						# PyTorch checkpoint
						with TemporaryDirectory() as local_pt_ckpt:
											self._setup_pt_ckpt(lowerCAmelCase	)
											__UpperCamelCase					:	Union[str, Any]             =      FeaturesManager.determine_framework(lowerCAmelCase					,     lowerCAmelCase	)
											self.assertEqual(lowerCAmelCase					,     lowerCAmelCase	)

						# TensorFlow checkpoint
						with TemporaryDirectory() as local_tf_ckpt:
											self._setup_tf_ckpt(lowerCAmelCase	)
											__UpperCamelCase					:	Any             =      FeaturesManager.determine_framework(lowerCAmelCase					,     lowerCAmelCase	)
											self.assertEqual(lowerCAmelCase					,     lowerCAmelCase	)






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







						"""simple docstring"""







						with TemporaryDirectory() as local_pt_ckpt:
											self._setup_pt_ckpt(lowerCAmelCase	)
											__UpperCamelCase					:	Optional[Any]             =      FeaturesManager.determine_framework(lowerCAmelCase	)
											self.assertEqual(lowerCAmelCase					,     self.framework_pt	)

						# TensorFlow checkpoint
						with TemporaryDirectory() as local_tf_ckpt:
											self._setup_tf_ckpt(lowerCAmelCase	)
											__UpperCamelCase					:	Union[str, Any]             =      FeaturesManager.determine_framework(lowerCAmelCase	)
											self.assertEqual(lowerCAmelCase					,     self.framework_tf	)

						# Invalid local checkpoint
						with TemporaryDirectory() as local_invalid_ckpt:
											with self.assertRaises(lowerCAmelCase	):
																__UpperCamelCase					:	int             =      FeaturesManager.determine_framework(lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						Dict	)	->       Tuple:







						"""simple docstring"""







						__UpperCamelCase					:	str             =      MagicMock(return_value=lowerCAmelCase	)
						with patch("""transformers.onnx.features.is_tf_available"""					,     lowerCAmelCase	):
											__UpperCamelCase					:	Any             =      FeaturesManager.determine_framework(self.test_model	)
											self.assertEqual(lowerCAmelCase					,     self.framework_pt	)

						# PyTorch not in environment -> use TensorFlow
						__UpperCamelCase					:	Optional[int]             =      MagicMock(return_value=lowerCAmelCase	)
						with patch("""transformers.onnx.features.is_torch_available"""					,     lowerCAmelCase	):
											__UpperCamelCase					:	Any             =      FeaturesManager.determine_framework(self.test_model	)
											self.assertEqual(lowerCAmelCase					,     self.framework_tf	)

						# Both in environment -> use PyTorch
						__UpperCamelCase					:	Dict             =      MagicMock(return_value=lowerCAmelCase	)
						__UpperCamelCase					:	Any             =      MagicMock(return_value=lowerCAmelCase	)
						with patch("""transformers.onnx.features.is_tf_available"""					,     lowerCAmelCase	), patch(
						    """transformers.onnx.features.is_torch_available"""					,     lowerCAmelCase	):
											__UpperCamelCase					:	int             =      FeaturesManager.determine_framework(self.test_model	)
											self.assertEqual(lowerCAmelCase					,     self.framework_pt	)

						# Both not in environment -> raise error
						__UpperCamelCase					:	Union[str, Any]             =      MagicMock(return_value=lowerCAmelCase	)
						__UpperCamelCase					:	Tuple             =      MagicMock(return_value=lowerCAmelCase	)
						with patch("""transformers.onnx.features.is_tf_available"""					,     lowerCAmelCase	), patch(
						    """transformers.onnx.features.is_torch_available"""					,     lowerCAmelCase	):
											with self.assertRaises(lowerCAmelCase	):
																__UpperCamelCase					:	str             =      FeaturesManager.determine_framework(self.test_model	)






