





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







       def __init__( self	:      int						,   A	:      Tuple						,   A	:      Dict=1_3						,   A	:      Optional[Any]=3_2						,   A	:      str=3						,   A	:      Optional[int]=4						,   A	:      Dict=[1_0, 2_0, 3_0, 4_0]						,   A	:      Dict=[2, 2, 3, 2]						,   A	:      Optional[Any]=True						,   A	:      Any=True						,   A	:      List[str]=3_7						,   A	:      Optional[Any]="gelu"						,   A	:      str=1_0						,   A	:      List[Any]=0.02						,   A	:      int=["stage2", "stage3", "stage4"]						,   A	:      Union[str, Any]=[2, 3, 4]						,   A	:      List[str]=None						,   )  ->Any:
          lowerCamelCase__  :		Optional[int]     =				parent
          lowerCamelCase__  :		int     =				batch_size
          lowerCamelCase__  :		int     =				image_size
          lowerCamelCase__  :		List[Any]     =				num_channels
          lowerCamelCase__  :		str     =				num_stages
          lowerCamelCase__  :		Optional[int]     =				hidden_sizes
          lowerCamelCase__  :		List[Any]     =				depths
          lowerCamelCase__  :		Optional[Any]     =				is_training
          lowerCamelCase__  :		Any     =				use_labels
          lowerCamelCase__  :		Any     =				intermediate_size
          lowerCamelCase__  :		List[str]     =				hidden_act
          lowerCamelCase__  :		Tuple     =				num_labels
          lowerCamelCase__  :		Union[str, Any]     =				initializer_range
          lowerCamelCase__  :		Union[str, Any]     =				out_features
          lowerCamelCase__  :		Dict     =				out_indices
          lowerCamelCase__  :		str     =				scope







       def 		__lowerCamelCase       ( self	:      List[str]     )  ->Optional[Any]:
          lowerCamelCase__  :		int     =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

          lowerCamelCase__  :		Tuple     =				None
          if self.use_labels:
             lowerCamelCase__  :		List[str]     =				ids_tensor([self.batch_size]						,   self.num_labels     )

          lowerCamelCase__  :		Optional[int]     =				self.get_config()
          return config, pixel_values, labels







       def 		__lowerCamelCase       ( self	:      List[Any]     )  ->Tuple:
          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=__lowerCAmelCase						,   initializer_range=self.initializer_range						,   out_features=self.out_features						,   out_indices=self.out_indices						,   num_labels=self.num_labels						,   )







       def 		__lowerCamelCase       ( self	:      str						,   A	:      Union[str, Any]						,   A	:      Optional[int]						,   A	:      Dict     )  ->Optional[int]:
          lowerCamelCase__  :		Optional[int]     =				ConvNextModel(config=__lowerCAmelCase     )
          model.to(__lowerCAmelCase     )
          model.eval()
          lowerCamelCase__  :		str     =				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 		__lowerCamelCase       ( self	:      str						,   A	:      List[str]						,   A	:      Optional[Any]						,   A	:      Dict     )  ->List[str]:
          lowerCamelCase__  :		Any     =				ConvNextForImageClassification(__lowerCAmelCase     )
          model.to(__lowerCAmelCase     )
          model.eval()
          lowerCamelCase__  :		str     =				model(__lowerCAmelCase						,   labels=__lowerCAmelCase     )
          self.parent.assertEqual(result.logits.shape						,   (self.batch_size, self.num_labels)     )







       def 		__lowerCamelCase       ( self	:      Dict						,   A	:      Dict						,   A	:      Tuple						,   A	:      Optional[int]     )  ->Optional[Any]:
          lowerCamelCase__  :		List[Any]     =				ConvNextBackbone(config=__lowerCAmelCase     )
          model.to(__lowerCAmelCase     )
          model.eval()
          lowerCamelCase__  :		int     =				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__  :		List[str]     =				None
          lowerCamelCase__  :		str     =				ConvNextBackbone(config=__lowerCAmelCase     )
          model.to(__lowerCAmelCase     )
          model.eval()
          lowerCamelCase__  :		Dict     =				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 		__lowerCamelCase       ( self	:      int     )  ->Any:
          lowerCamelCase__  :		Union[str, Any]     =				self.prepare_config_and_inputs()
          lowerCamelCase__  ,				lowerCamelCase__  ,				lowerCamelCase__  :		int     =				config_and_inputs
          lowerCamelCase__  :		Any     =				{'''pixel_values''': pixel_values}
          return config, inputs_dict


@require_torch
class   __SCREAMING_SNAKE_CASE     (					lowerCAmelCase_	,lowerCAmelCase_	,unittest.TestCase   ):
       _UpperCAmelCase :    str					       =       (
           (
               ConvNextModel,
               ConvNextForImageClassification,
               ConvNextBackbone,
           )
           if is_torch_available()
           else ()
       )
       _UpperCAmelCase :    Union[str, Any]					       =       (
           {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
           if is_torch_available()
           else {}
       )

       _UpperCAmelCase :    Optional[int]					       =       True
       _UpperCAmelCase :    Union[str, Any]					       =       False
       _UpperCAmelCase :    Tuple					       =       False
       _UpperCAmelCase :    Any					       =       False
       _UpperCAmelCase :    Optional[int]					       =       False







       def 		__lowerCamelCase       ( self	:      Dict     )  ->Dict:
          lowerCamelCase__  :		int     =				ConvNextModelTester(self     )
          lowerCamelCase__  :		List[Any]     =				ConfigTester(self						,   config_class=__lowerCAmelCase						,   has_text_modality=__lowerCAmelCase						,   hidden_size=3_7     )







       def 		__lowerCamelCase       ( self	:      int     )  ->Any:
          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	:      Any     )  ->str:
          return







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







       @unittest.skip(reason='''ConvNext does not support input and output embeddings'''     )
       def 		__lowerCamelCase       ( self	:      Any     )  ->Tuple:
          pass







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







       def 		__lowerCamelCase       ( self	:      int     )  ->int:
          lowerCamelCase__  ,				lowerCamelCase__  :		str     =				self.model_tester.prepare_config_and_inputs_for_common()

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

             lowerCamelCase__  :		str     =				['''pixel_values''']
             self.assertListEqual(arg_names[:1]						,   __lowerCAmelCase     )







       def 		__lowerCamelCase       ( self	:      List[Any]     )  ->Any:
          lowerCamelCase__  :		int     =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__lowerCAmelCase     )







       def 		__lowerCamelCase       ( self	:      Union[str, Any]     )  ->Any:
          lowerCamelCase__  :		int     =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*__lowerCAmelCase     )







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






          def check_hidden_states_output(A	:      int						,   A	:      Tuple						,   A	:      Any     ):
             lowerCamelCase__  :		Dict     =				model_class(__lowerCAmelCase     )
             model.to(__lowerCAmelCase     )
             model.eval()

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

             lowerCamelCase__  :		Optional[int]     =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             lowerCamelCase__  :		Union[str, Any]     =				self.model_tester.num_stages
             self.assertEqual(len(__lowerCAmelCase     )						,   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]						,   )

          lowerCamelCase__  ,				lowerCamelCase__  :		Optional[int]     =				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
             lowerCamelCase__  :		Dict     =				True
             check_hidden_states_output(__lowerCAmelCase						,   __lowerCAmelCase						,   __lowerCAmelCase     )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             lowerCamelCase__  :		Union[str, Any]     =				True

             check_hidden_states_output(__lowerCAmelCase						,   __lowerCAmelCase						,   __lowerCAmelCase     )







       def 		__lowerCamelCase       ( self	:      Dict     )  ->List[Any]:
          lowerCamelCase__  :		List[str]     =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase     )







       @slow
       def 		__lowerCamelCase       ( self	:      Optional[Any]     )  ->List[str]:






          for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowerCamelCase__  :		List[str]     =				ConvNextModel.from_pretrained(__lowerCAmelCase     )
             self.assertIsNotNone(__lowerCAmelCase     )



def 			_a		(       )							->							str:







   """simple docstring"""
   lowerCamelCase__  :		Union[str, Any]     =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
   return image


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







       @cached_property
       def 		__lowerCamelCase       ( self	:      Union[str, Any]     )  ->int:
          return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''     ) if is_vision_available() else None







       @slow
       def 		__lowerCamelCase       ( self	:      int     )  ->List[Any]:
          lowerCamelCase__  :		Tuple     =				ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''     ).to(__lowerCAmelCase     )

          lowerCamelCase__  :		str     =				self.default_image_processor
          lowerCamelCase__  :		List[str]     =				prepare_img()
          lowerCamelCase__  :		Tuple     =				image_processor(images=__lowerCAmelCase						,   return_tensors='''pt'''     ).to(__lowerCAmelCase     )

          # forward pass
          with torch.no_grad():
             lowerCamelCase__  :		Optional[Any]     =				model(**__lowerCAmelCase     )

          # verify the logits
          lowerCamelCase__  :		Union[str, Any]     =				torch.Size((1, 1_0_0_0)     )
          self.assertEqual(outputs.logits.shape						,   __lowerCAmelCase     )

          lowerCamelCase__  :		List[str]     =				torch.tensor([-0.02_60, -0.47_39, 0.19_11]     ).to(__lowerCAmelCase     )

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


@require_torch
class   __SCREAMING_SNAKE_CASE     (					unittest.TestCase	,lowerCAmelCase_   ):
       _UpperCAmelCase :    str					       =       (ConvNextBackbone,) if is_torch_available() else ()
       _UpperCAmelCase :    Optional[int]					       =       ConvNextConfig

       _UpperCAmelCase :    Optional[Any]					       =       False







       def 		__lowerCamelCase       ( self	:      Tuple     )  ->List[str]:
          lowerCamelCase__  :		str     =				ConvNextModelTester(self     )










class     A     :
			'''simple docstring'''




			def __init__(     self  :       Optional[int]  )      ->      Dict:







					"""simple docstring"""






					A__     =  {}






			def   a_			(     self  :       Any  )      ->      None:







					"""simple docstring"""






					print(self.vertex  )
					for i in self.vertex:
							print(__lowerCAmelCase				,      """ -> """				,      """ -> """.join([str(__lowerCAmelCase  ) for j in self.vertex[i]]  )  )






			def   a_			(     self  :       Optional[int]				,      __lowerCAmelCase  :       int				,      __lowerCAmelCase  :       int  )      ->      None:







					"""simple docstring"""






					if from_vertex in self.vertex:
							self.vertex[from_vertex].append(__lowerCAmelCase  )
					else:
							# else make a new vertex
							A__     =  [to_vertex]






			def   a_			(     self  :       List[str]  )      ->      None:







					"""simple docstring"""






					A__     =  [False] * len(self.vertex  )

					# call the recursive helper function
					for i in range(len(self.vertex  )  ):
							if not visited[i]:
									self.dfs_recursive(__lowerCAmelCase				,      __lowerCAmelCase  )







			def   a_			(     self  :       List[str]				,      __lowerCAmelCase  :       int				,      __lowerCAmelCase  :       list  )      ->      None:







					"""simple docstring"""






					A__     =  True

					print(__lowerCAmelCase				,      end=""" """  )

					# Recur for all the vertices that are adjacent to this node
					for i in self.vertex:
							if not visited[i]:
									self.dfs_recursive(__lowerCAmelCase				,      __lowerCAmelCase  )


if __name__ == "__main__":
					A       :   Tuple					= Graph()
					g.add_edge(0, 1)
					g.add_edge(0, 2)
					g.add_edge(1, 2)
					g.add_edge(2, 0)
					g.add_edge(2, 3)
					g.add_edge(3, 3)

					g.print_graph()
					print('''DFS:''')
					g.dfs()

					# OUTPUT:
					# 0  ->  1 -> 2
					# 1  ->  2
					# 2  ->  0 -> 3
					# 3  ->  3
					# DFS:
					#  0 1 2 3



