


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





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





     def      __A					(self       )     ->   Union[str, Any]:
      _lowercase							      =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

      _lowercase							      =self.get_config()

      return config, pixel_values, labels





     def      __A					(self       )     ->   Optional[Any]:
      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=UpperCAmelCase		,     initializer_range=self.initializer_range		,     out_features=self.out_features		,     out_indices=self.out_indices		,     num_labels=self.num_labels		,     )





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase       )     ->   str:
      _lowercase							      =ConvNextVaModel(config=UpperCAmelCase       )
      model.to(UpperCAmelCase       )
      model.eval()
      _lowercase							      =model(UpperCAmelCase       )
      # 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      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase       )     ->   Dict:
      _lowercase							      =ConvNextVaForImageClassification(UpperCAmelCase       )
      model.to(UpperCAmelCase       )
      model.eval()
      _lowercase							      =model(UpperCAmelCase		,     labels=UpperCAmelCase       )
      self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_labels)       )





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase       )     ->   Optional[int]:
      _lowercase							      =ConvNextVaBackbone(config=UpperCAmelCase       )
      model.to(UpperCAmelCase       )
      model.eval()
      _lowercase							      =model(UpperCAmelCase       )

      # 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
      _lowercase							      =None
      _lowercase							      =ConvNextVaBackbone(config=UpperCAmelCase       )
      model.to(UpperCAmelCase       )
      model.eval()
      _lowercase							      =model(UpperCAmelCase       )

      # 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      __A					(self       )     ->   Optional[int]:
      _lowercase							      =self.prepare_config_and_inputs()
      _lowercase      ,    _lowercase      ,    _lowercase							      =config_and_inputs
      _lowercase							      ={'''pixel_values''': pixel_values}
      return config, inputs_dict





     def      __A					(self       )     ->   List[str]:
      _lowercase							      =self.prepare_config_and_inputs()
      _lowercase      ,    _lowercase      ,    _lowercase							      =config_and_inputs
      _lowercase							      ={'''pixel_values''': pixel_values, '''labels''': labels}
      return config, inputs_dict







@require_torch
class       lowerCamelCase__   (       lowerCAmelCase   ,							lowerCAmelCase   ,							unittest.TestCase):
     SCREAMING_SNAKE_CASE__      			=			(
         (
             ConvNextVaModel,
             ConvNextVaForImageClassification,
             ConvNextVaBackbone,
         )
         if is_torch_available()
         else ()
     )
     SCREAMING_SNAKE_CASE__      			=			(
         {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE__      			=			False
     SCREAMING_SNAKE_CASE__      			=			False
     SCREAMING_SNAKE_CASE__      			=			False
     SCREAMING_SNAKE_CASE__      			=			False
     SCREAMING_SNAKE_CASE__      			=			False





     def      __A					(self       )     ->   Optional[Any]:
      _lowercase							      =ConvNextVaModelTester(self       )
      _lowercase							      =ConfigTester(self		,     config_class=UpperCAmelCase		,     has_text_modality=UpperCAmelCase		,     hidden_size=3_7       )





     def      __A					(self       )     ->   str:
      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      __A					(self       )     ->   Tuple:
      return





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





     @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings'''       )
     def      __A					(self       )     ->   List[str]:
      pass





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





     def      __A					(self       )     ->   Dict:
      if not self.model_tester.is_training:
       return

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

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

       _lowercase							      =model_class(UpperCAmelCase       )
       model.to(UpperCAmelCase       )
       model.train()
       _lowercase							      =self._prepare_for_class(UpperCAmelCase		,     UpperCAmelCase		,     return_labels=UpperCAmelCase       )
       _lowercase							      =model(**UpperCAmelCase       ).loss
       loss.backward()





     def      __A					(self       )     ->   Union[str, Any]:
      if not self.model_tester.is_training:
       return

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

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

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





     def      __A					(self       )     ->   Tuple:
      _lowercase      ,    _lowercase							      =self.model_tester.prepare_config_and_inputs_for_common()

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

       _lowercase							      =['''pixel_values''']
       self.assertListEqual(arg_names[:1]		,     UpperCAmelCase       )





     def      __A					(self       )     ->   Tuple:
      _lowercase							      =self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*UpperCAmelCase       )





     def      __A					(self       )     ->   List[Any]:
      def check_hidden_states_output(UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase       ):
       _lowercase							      =model_class(UpperCAmelCase       )
       model.to(UpperCAmelCase       )
       model.eval()

       with torch.no_grad():
        _lowercase							      =model(**self._prepare_for_class(UpperCAmelCase		,     UpperCAmelCase       )       )

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

       _lowercase							      =self.model_tester.num_stages
       self.assertEqual(len(UpperCAmelCase       )		,     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]		,     )

      _lowercase      ,    _lowercase							      =self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       _lowercase							      =True
       check_hidden_states_output(UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase       )

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

       check_hidden_states_output(UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase       )





     def      __A					(self       )     ->   Union[str, Any]:
      _lowercase							      =self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase       )





     @slow
     def      __A					(self       )     ->   int:
      for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       _lowercase							      =ConvNextVaModel.from_pretrained(UpperCAmelCase       )
       self.assertIsNotNone(UpperCAmelCase       )



def 				UpperCAmelCase_					(							)     ->			Any:







 """simple docstring"""


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







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





     @cached_property
     def      __A					(self       )     ->   Optional[int]:
      return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224'''       ) if is_vision_available() else None





     @slow
     def      __A					(self       )     ->   Any:
      _lowercase							      =ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224'''       ).to(UpperCAmelCase       )

      _lowercase							      =self.default_image_processor
      _lowercase							      =prepare_img()
      _lowercase							      =preprocessor(images=UpperCAmelCase		,     return_tensors='''pt'''       ).to(UpperCAmelCase       )

      # forward pass
      with torch.no_grad():
       _lowercase							      =model(**UpperCAmelCase       )

      # verify the logits
      _lowercase							      =torch.Size((1, 1_0_0_0)       )
      self.assertEqual(outputs.logits.shape		,     UpperCAmelCase       )

      _lowercase							      =torch.tensor([0.9996, 0.1966, -0.4386]       ).to(UpperCAmelCase       )
      self.assertTrue(torch.allclose(outputs.logits[0, :3]		,     UpperCAmelCase		,     atol=1e-4       )       )





import heapq as hq
import math
from collections.abc import Iterator







class       lowerCamelCase__   :





     def __init__(self		,     UpperCAmelCase       )     ->   Any:
      _lowercase							      =str(id_       )
      _lowercase							      =None
      _lowercase							      =None
      _lowercase							      =[]
      _lowercase							      ={}  # {vertex:distance}





     def __lt__(self		,     UpperCAmelCase       )     ->   List[str]:
      return self.key < other.key





     def __repr__(self       )     ->   str:
      return self.id





     def      __A					(self		,     UpperCAmelCase       )     ->   Dict:
      self.neighbors.append(UpperCAmelCase       )





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase       )     ->   Optional[Any]:
      _lowercase							      =weight



def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case						)     ->			List[str]:







 """simple docstring"""


 graph[a - 1].add_neighbor(graph[b - 1]						)
 graph[b - 1].add_neighbor(graph[a - 1]						)
 # add the edges:
 graph[a - 1].add_edge(graph[b - 1]     ,						__snake_case						)
 graph[b - 1].add_edge(graph[a - 1]     ,						__snake_case						)
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case						)     ->			list:







 """simple docstring"""


 _lowercase							      =[]
 for u in graph:
  _lowercase							      =math.inf
  _lowercase							      =None
 _lowercase							      =0
 _lowercase							      =graph[:]
 while q:
  _lowercase							      =min(__snake_case						)
  q.remove(__snake_case						)
  for v in u.neighbors:
   if (v in q) and (u.edges[v.id] < v.key):
    _lowercase							      =u
    _lowercase							      =u.edges[v.id]
 for i in range(1     ,						len(__snake_case						)						):
  a.append((int(graph[i].id						) + 1, int(graph[i].pi.id						) + 1)						)
 return a
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case						)     ->			Iterator[tuple]:







 """simple docstring"""


 for u in graph:
  _lowercase							      =math.inf
  _lowercase							      =None
 _lowercase							      =0

 _lowercase							      =list(__snake_case						)
 hq.heapify(__snake_case						)

 while h:
  _lowercase							      =hq.heappop(__snake_case						)
  for v in u.neighbors:
   if (v in h) and (u.edges[v.id] < v.key):
    _lowercase							      =u
    _lowercase							      =u.edges[v.id]
    hq.heapify(__snake_case						)

 for i in range(1     ,						len(__snake_case						)						):
  yield (int(graph[i].id						) + 1, int(graph[i].pi.id						) + 1)
def 				UpperCAmelCase_					(							)     ->			None:







 """simple docstring"""




if __name__ == "__main__":
  import doctest

  doctest.testmod()

