




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







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



          '''simple docstring'''



          a     =				parent
          a     =				batch_size
          a     =				image_size
          a     =				num_channels
          a     =				num_stages
          a     =				hidden_sizes
          a     =				depths
          a     =				is_training
          a     =				use_labels
          a     =				intermediate_size
          a     =				hidden_act
          a     =				num_labels
          a     =				initializer_range
          a     =				out_features
          a     =				out_indices
          a     =				scope







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



          '''simple docstring'''



          a     =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

          a     =				None
          if self.use_labels:
               a     =				ids_tensor([self.batch_size]  ,		self.num_labels			)

          a     =				self.get_config()

          return config, pixel_values, labels







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



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



          '''simple docstring'''



          a     =				ConvNextVaModel(config=A			)
          model.to(A			)
          model.eval()
          a     =				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       lowerCAmelCase_    (     self  ,		A  ,		A  ,		A			)  ->   Dict:



          '''simple docstring'''



          a     =				ConvNextVaForImageClassification(A			)
          model.to(A			)
          model.eval()
          a     =				model(A  ,		labels=A			)
          self.parent.assertEqual(result.logits.shape  ,		(self.batch_size, self.num_labels)			)







     def       lowerCAmelCase_    (     self  ,		A  ,		A  ,		A			)  ->   Dict:



          '''simple docstring'''



          a     =				ConvNextVaBackbone(config=A			)
          model.to(A			)
          model.eval()
          a     =				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
          a     =				None
          a     =				ConvNextVaBackbone(config=A			)
          model.to(A			)
          model.eval()
          a     =				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       lowerCAmelCase_    (     self			)  ->   Dict:



          '''simple docstring'''



          a     =				self.prepare_config_and_inputs()
          a  ,				a  ,				a     =				config_and_inputs
          a     =				{"pixel_values": pixel_values}
          return config, inputs_dict







     def       lowerCAmelCase_    (     self			)  ->   Dict:



          '''simple docstring'''



          a     =				self.prepare_config_and_inputs()
          a  ,				a  ,				a     =				config_and_inputs
          a     =				{"pixel_values": pixel_values, "labels": labels}
          return config, inputs_dict







@require_torch
class       a__	( UpperCamelCase__       , UpperCamelCase__       , unittest.TestCase				):
     a		:      List[Any]		 =     (
         (
             ConvNextVaModel,
             ConvNextVaForImageClassification,
             ConvNextVaBackbone,
         )
         if is_torch_available()
         else ()
     )
     a		:      Union[str, Any]		 =     (
         {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
         if is_torch_available()
         else {}
     )

     a		:      str		 =     False
     a		:      Any		 =     False
     a		:      Optional[int]		 =     False
     a		:      str		 =     False
     a		:      Tuple		 =     False







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



          '''simple docstring'''



          a     =				ConvNextVaModelTester(self			)
          a     =				ConfigTester(self  ,		config_class=A  ,		has_text_modality=A  ,		hidden_size=37			)







     def       lowerCAmelCase_    (     self			)  ->   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[Any]:



          '''simple docstring'''



          return







     @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"			)
     def       lowerCAmelCase_    (     self			)  ->   str:



          '''simple docstring'''



          pass







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



          '''simple docstring'''



          pass







     @unittest.skip(reason="ConvNextV2 does not use feedforward chunking"			)
     def       lowerCAmelCase_    (     self			)  ->   List[str]:



          '''simple docstring'''



          pass







     def       lowerCAmelCase_    (     self			)  ->   Any:



          '''simple docstring'''



          if not self.model_tester.is_training:
               return

          for model_class in self.all_model_classes:
               a  ,				a     =				self.model_tester.prepare_config_and_inputs_with_labels()
               a     =				True

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

               a     =				model_class(A			)
               model.to(A			)
               model.train()
               a     =				self._prepare_for_class(A  ,		A  ,		return_labels=A			)
               a     =				model(**A			).loss
               loss.backward()







     def       lowerCAmelCase_    (     self			)  ->   int:



          '''simple docstring'''



          if not self.model_tester.is_training:
               return

          for model_class in self.all_model_classes:
               a  ,				a     =				self.model_tester.prepare_config_and_inputs_with_labels()
               a     =				False
               a     =				True

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

               a     =				model_class(A			)
               model.to(A			)
               model.gradient_checkpointing_enable()
               model.train()
               a     =				self._prepare_for_class(A  ,		A  ,		return_labels=A			)
               a     =				model(**A			).loss
               loss.backward()







     def       lowerCAmelCase_    (     self			)  ->   int:



          '''simple docstring'''



          a  ,				a     =				self.model_tester.prepare_config_and_inputs_for_common()

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

               a     =				["pixel_values"]
               self.assertListEqual(arg_names[:1]  ,		A			)







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



          '''simple docstring'''



          a     =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*A			)







     def       lowerCAmelCase_    (     self			)  ->   int:



          '''simple docstring'''



          def check_hidden_states_output(A  ,		A  ,		A			):
               a     =				model_class(A			)
               model.to(A			)
               model.eval()

               with torch.no_grad():
                    a     =				model(**self._prepare_for_class(A  ,		A			)			)

               a     =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               a     =				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]  ,		)

          a  ,				a     =				self.model_tester.prepare_config_and_inputs_for_common()

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

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               a     =				True

               check_hidden_states_output(A  ,		A  ,		A			)







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



          '''simple docstring'''



          a     =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*A			)







     @slow
     def       lowerCAmelCase_    (     self			)  ->   Dict:



          '''simple docstring'''



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







def  SCREAMING_SNAKE_CASE							(       )      ->					Union[str, Any]:
     a     =				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
     return image





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







     @cached_property
     def       lowerCAmelCase_    (     self			)  ->   Any:



          '''simple docstring'''



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







     @slow
     def       lowerCAmelCase_    (     self			)  ->   int:



          '''simple docstring'''



          a     =				ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"			).to(A			)

          a     =				self.default_image_processor
          a     =				prepare_img()
          a     =				preprocessor(images=A  ,		return_tensors="pt"			).to(A			)

          # forward pass
          with torch.no_grad():
               a     =				model(**A			)

          # verify the logits
          a     =				torch.Size((1, 1000)			)
          self.assertEqual(outputs.logits.shape  ,		A			)

          a     =				torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6]			).to(A			)
          self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,		A  ,		atol=1e-4			)			)







# Author: OMKAR PATHAK, Nwachukwu Chidiebere

# Use a Python dictionary to construct the graph.
from __future__ import annotations

from pprint import pformat
from typing import Generic, TypeVar

lowercase__				:      str	   = TypeVar("T")




class       a__	( Generic[T]				):







     def __init__(     self  ,		A = True			)  ->   None:



          '''simple docstring'''



          a     =				{}  # dictionary of lists
          a     =				directed







     def       lowerCAmelCase_    (     self  ,		A  ,		A			)  ->   GraphAdjacencyList[T]:



          '''simple docstring'''



          if not self.directed:  # For undirected graphs
               # if both source vertex and destination vertex are both present in the
               # adjacency list, add destination vertex to source vertex list of adjacent
               # vertices and add source vertex to destination vertex list of adjacent
               # vertices.
               if source_vertex in self.adj_list and destination_vertex in self.adj_list:
                    self.adj_list[source_vertex].append(A			)
                    self.adj_list[destination_vertex].append(A			)
               # if only source vertex is present in adjacency list, add destination vertex
               # to source vertex list of adjacent vertices, then create a new vertex with
               # destination vertex as key and assign a list containing the source vertex
               # as it's first adjacent vertex.
               elif source_vertex in self.adj_list:
                    self.adj_list[source_vertex].append(A			)
                    a     =				[source_vertex]
               # if only destination vertex is present in adjacency list, add source vertex
               # to destination vertex list of adjacent vertices, then create a new vertex
               # with source vertex as key and assign a list containing the source vertex
               # as it's first adjacent vertex.
               elif destination_vertex in self.adj_list:
                    self.adj_list[destination_vertex].append(A			)
                    a     =				[destination_vertex]
               # if both source vertex and destination vertex are not present in adjacency
               # list, create a new vertex with source vertex as key and assign a list
               # containing the destination vertex as it's first adjacent vertex also
               # create a new vertex with destination vertex as key and assign a list
               # containing the source vertex as it's first adjacent vertex.
               else:
                    a     =				[destination_vertex]
                    a     =				[source_vertex]
          else:  # For directed graphs
               # if both source vertex and destination vertex are present in adjacency
               # list, add destination vertex to source vertex list of adjacent vertices.
               if source_vertex in self.adj_list and destination_vertex in self.adj_list:
                    self.adj_list[source_vertex].append(A			)
               # if only source vertex is present in adjacency list, add destination
               # vertex to source vertex list of adjacent vertices and create a new vertex
               # with destination vertex as key, which has no adjacent vertex
               elif source_vertex in self.adj_list:
                    self.adj_list[source_vertex].append(A			)
                    a     =				[]
               # if only destination vertex is present in adjacency list, create a new
               # vertex with source vertex as key and assign a list containing destination
               # vertex as first adjacent vertex
               elif destination_vertex in self.adj_list:
                    a     =				[destination_vertex]
               # if both source vertex and destination vertex are not present in adjacency
               # list, create a new vertex with source vertex as key and a list containing
               # destination vertex as it's first adjacent vertex. Then create a new vertex
               # with destination vertex as key, which has no adjacent vertex
               else:
                    a     =				[destination_vertex]
                    a     =				[]

          return self







     def __repr__(     self			)  ->   str:



          '''simple docstring'''



          return pformat(self.adj_list			)

