


'''simple docstring'''







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






      def __init__(					self     :Optional[int]	,		SCREAMING_SNAKE_CASE     :List[str]	,		SCREAMING_SNAKE_CASE     :int=1_3	,		SCREAMING_SNAKE_CASE     :Optional[int]=3_2	,		SCREAMING_SNAKE_CASE     :Tuple=3	,		SCREAMING_SNAKE_CASE     :List[Any]=4	,		SCREAMING_SNAKE_CASE     :Optional[int]=[1_0, 2_0, 3_0, 4_0]	,		SCREAMING_SNAKE_CASE     :Optional[Any]=[2, 2, 3, 2]	,		SCREAMING_SNAKE_CASE     :Dict=True	,		SCREAMING_SNAKE_CASE     :List[str]=True	,		SCREAMING_SNAKE_CASE     :Optional[int]=3_7	,		SCREAMING_SNAKE_CASE     :Union[str, Any]="gelu"	,		SCREAMING_SNAKE_CASE     :Union[str, Any]=1_0	,		SCREAMING_SNAKE_CASE     :List[str]=0.02	,		SCREAMING_SNAKE_CASE     :List[Any]=["stage2", "stage3", "stage4"]	,		SCREAMING_SNAKE_CASE     :List[Any]=[2, 3, 4]	,		SCREAMING_SNAKE_CASE     :str=None	,		)			->   str:




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






      def __UpperCAmelCase			(					self     :Tuple      )			->   str:




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

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

             _a       :					Tuple	   =self.get_config()
             return config, pixel_values, labels






      def __UpperCAmelCase			(					self     :Optional[int]      )			->   Any:




             '''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 __UpperCAmelCase			(					self     :str	,		SCREAMING_SNAKE_CASE     :List[str]	,		SCREAMING_SNAKE_CASE     :Tuple	,		SCREAMING_SNAKE_CASE     :List[str]      )			->   int:




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






      def __UpperCAmelCase			(					self     :Any	,		SCREAMING_SNAKE_CASE     :str	,		SCREAMING_SNAKE_CASE     :Tuple	,		SCREAMING_SNAKE_CASE     :Any      )			->   Union[str, Any]:




             '''simple docstring'''
             _a       :					Optional[Any]	   =ConvNextForImageClassification(_SCREAMING_SNAKE_CASE      )
             model.to(_SCREAMING_SNAKE_CASE      )
             model.eval()
             _a       :					Union[str, Any]	   =model(_SCREAMING_SNAKE_CASE	,		labels=_SCREAMING_SNAKE_CASE      )
             self.parent.assertEqual(result.logits.shape	,		(self.batch_size, self.num_labels)      )






      def __UpperCAmelCase			(					self     :Any	,		SCREAMING_SNAKE_CASE     :Union[str, Any]	,		SCREAMING_SNAKE_CASE     :List[str]	,		SCREAMING_SNAKE_CASE     :Optional[int]      )			->   Union[str, Any]:




             '''simple docstring'''
             _a       :					str	   =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       :					int	   =ConvNextBackbone(config=_SCREAMING_SNAKE_CASE      )
             model.to(_SCREAMING_SNAKE_CASE      )
             model.eval()
             _a       :					int	   =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     :Optional[Any]      )			->   str:




             '''simple docstring'''
             _a       :					Tuple	   =self.prepare_config_and_inputs()
             _a   ,       _a   ,       _a       :					Optional[Any]	   =config_and_inputs
             _a       :					Optional[Any]	   ={"""pixel_values""": pixel_values}
             return config, inputs_dict







@require_torch
class A__			(		a_					,	a_					,	unittest.TestCase ):
      __UpperCamelCase			:    List[Any]      			=				(
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      __UpperCamelCase			:    int      			=				(
          {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

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






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




             '''simple docstring'''
             _a       :					str	   =ConvNextModelTester(self      )
             _a       :					str	   =ConfigTester(self	,		config_class=_SCREAMING_SNAKE_CASE	,		has_text_modality=_SCREAMING_SNAKE_CASE	,		hidden_size=3_7      )






      def __UpperCAmelCase			(					self     :List[Any]      )			->   List[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 __UpperCAmelCase			(					self     :Optional[int]      )			->   List[str]:




             '''simple docstring'''
             return






      @unittest.skip(reason="""ConvNext does not use inputs_embeds"""      )
      def __UpperCAmelCase			(					self     :Optional[int]      )			->   List[Any]:




             '''simple docstring'''
             pass






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




             '''simple docstring'''
             pass






      @unittest.skip(reason="""ConvNext does not use feedforward chunking"""      )
      def __UpperCAmelCase			(					self     :str      )			->   Dict:




             '''simple docstring'''
             pass






      def __UpperCAmelCase			(					self     :int      )			->   int:




             '''simple docstring'''
             _a   ,       _a       :					Tuple	   =self.model_tester.prepare_config_and_inputs_for_common()

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

                    _a       :					List[str]	   =["""pixel_values"""]
                    self.assertListEqual(arg_names[:1]	,		_SCREAMING_SNAKE_CASE      )






      def __UpperCAmelCase			(					self     :List[Any]      )			->   int:




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






      def __UpperCAmelCase			(					self     :Dict      )			->   str:




             '''simple docstring'''
             _a       :					Optional[int]	   =self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE      )






      def __UpperCAmelCase			(					self     :Dict      )			->   Tuple:




             '''simple docstring'''

             def check_hidden_states_output(SCREAMING_SNAKE_CASE     :Union[str, Any]	,		SCREAMING_SNAKE_CASE     :Dict	,		SCREAMING_SNAKE_CASE     :Optional[int]      ):
                    _a       :					Optional[int]	   =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       :					List[str]	   =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                    _a       :					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       :					List[str]	   =self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    _a       :					List[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       :					int	   =True

                    check_hidden_states_output(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE      )






      def __UpperCAmelCase			(					self     :int      )			->   Optional[Any]:




             '''simple docstring'''
             _a       :					Any	   =self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE      )






      @slow
      def __UpperCAmelCase			(					self     :Dict      )			->   Tuple:




             '''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_   (    )    ->     List[str]:
       _a       :					List[Any]	   =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
       return image







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






      @cached_property
      def __UpperCAmelCase			(					self     :Dict      )			->   Union[str, Any]:




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






      @slow
      def __UpperCAmelCase			(					self     :List[Any]      )			->   Optional[int]:




             '''simple docstring'''
             _a       :					Optional[Any]	   =ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""      ).to(_SCREAMING_SNAKE_CASE      )

             _a       :					List[Any]	   =self.default_image_processor
             _a       :					Tuple	   =prepare_img()
             _a       :					Union[str, Any]	   =image_processor(images=_SCREAMING_SNAKE_CASE	,		return_tensors="""pt"""      ).to(_SCREAMING_SNAKE_CASE      )

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

             # verify the logits
             _a       :					Dict	   =torch.Size((1, 1_0_0_0)      )
             self.assertEqual(outputs.logits.shape	,		_SCREAMING_SNAKE_CASE      )

             _a       :					Optional[Any]	   =torch.tensor([-0.0_260, -0.4_739, 0.1_911]      ).to(_SCREAMING_SNAKE_CASE      )

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







@require_torch
class A__			(		unittest.TestCase					,	a_ ):
      __UpperCamelCase			:    Dict      			=				(ConvNextBackbone,) if is_torch_available() else ()
      __UpperCamelCase			:    Tuple      			=				ConvNextConfig

      __UpperCamelCase			:    Dict      			=				False






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




             '''simple docstring'''
             _a       :					Tuple	   =ConvNextModelTester(self      )





'''simple docstring'''



def       snake_case   (	snake_case      : dict			) ->  set:


    """simple docstring"""


    lowerCAmelCase 						=							set()
    # edges = list of graph's edges
    lowerCAmelCase 						=							get_edges(snake_case			)

    # While there are still elements in edges list, take an arbitrary edge
    # (from_node, to_node) and add his extremity to chosen_vertices and then
    # remove all arcs adjacent to the from_node and to_node
    while edges:
        lowerCAmelCase						,   lowerCAmelCase 						=							edges.pop()
        chosen_vertices.add(snake_case			)
        chosen_vertices.add(snake_case			)
        for edge in edges.copy():
            if from_node in edge or to_node in edge:
                edges.discard(snake_case			)
    return chosen_vertices


def       snake_case   (	snake_case      : dict			) ->  set:


    """simple docstring"""


    lowerCAmelCase 						=							set()
    for from_node, to_nodes in graph.items():
        for to_node in to_nodes:
            edges.add((from_node, to_node)			)
    return edges


if __name__ == "__main__":
     import doctest

     doctest.testmod()

     # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}
     # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")





