






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 :       Dict							,       SCREAMING_SNAKE_CASE :       int							,       SCREAMING_SNAKE_CASE :       Optional[Any]=13							,       SCREAMING_SNAKE_CASE :       Dict=32							,       SCREAMING_SNAKE_CASE :       Optional[Any]=3							,       SCREAMING_SNAKE_CASE :       Optional[Any]=4							,       SCREAMING_SNAKE_CASE :       Optional[int]=[10, 20, 30, 40]							,       SCREAMING_SNAKE_CASE :       Optional[Any]=[2, 2, 3, 2]							,       SCREAMING_SNAKE_CASE :       Optional[int]=True							,       SCREAMING_SNAKE_CASE :       int=True							,       SCREAMING_SNAKE_CASE :       Dict=37							,       SCREAMING_SNAKE_CASE :       List[str]="gelu"							,       SCREAMING_SNAKE_CASE :       Optional[int]=10							,       SCREAMING_SNAKE_CASE :       Union[str, Any]=0.0_2							,       SCREAMING_SNAKE_CASE :       List[str]=["stage2", "stage3", "stage4"]							,       SCREAMING_SNAKE_CASE :       Dict=[2, 3, 4]							,       SCREAMING_SNAKE_CASE :       Optional[int]=None							,       ):


      '''simple docstring'''






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







 def  __lowercase (		self :       Optional[Any]						):


      '''simple docstring'''






      UpperCamelCase__      :       List[Any]	    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

      UpperCamelCase__      :       str	    =  None
      if self.use_labels:
           UpperCamelCase__      :       Optional[Any]	    =  ids_tensor([self.batch_size]							,       self.num_labels						)

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







 def  __lowercase (		self :       Tuple						):


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







 def  __lowercase (		self :       Tuple							,       SCREAMING_SNAKE_CASE :       Optional[int]							,       SCREAMING_SNAKE_CASE :       Union[str, Any]							,       SCREAMING_SNAKE_CASE :       Any						):


      '''simple docstring'''






      UpperCamelCase__      :       Tuple	    =  ConvNextModel(config=__UpperCAmelCase						)
      model.to(__UpperCAmelCase						)
      model.eval()
      UpperCamelCase__      :       Tuple	    =  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 // 32, self.image_size // 32)							,       )







 def  __lowercase (		self :       List[Any]							,       SCREAMING_SNAKE_CASE :       Tuple							,       SCREAMING_SNAKE_CASE :       Tuple							,       SCREAMING_SNAKE_CASE :       Optional[int]						):


      '''simple docstring'''






      UpperCamelCase__      :       List[Any]	    =  ConvNextForImageClassification(__UpperCAmelCase						)
      model.to(__UpperCAmelCase						)
      model.eval()
      UpperCamelCase__      :       int	    =  model(__UpperCAmelCase							,       labels=__UpperCAmelCase						)
      self.parent.assertEqual(result.logits.shape							,       (self.batch_size, self.num_labels)						)







 def  __lowercase (		self :       List[Any]							,       SCREAMING_SNAKE_CASE :       Any							,       SCREAMING_SNAKE_CASE :       List[str]							,       SCREAMING_SNAKE_CASE :       int						):


      '''simple docstring'''






      UpperCamelCase__      :       Optional[int]	    =  ConvNextBackbone(config=__UpperCAmelCase						)
      model.to(__UpperCAmelCase						)
      model.eval()
      UpperCamelCase__      :       Union[str, Any]	    =  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
      UpperCamelCase__      :       Dict	    =  None
      UpperCamelCase__      :       Dict	    =  ConvNextBackbone(config=__UpperCAmelCase						)
      model.to(__UpperCAmelCase						)
      model.eval()
      UpperCamelCase__      :       List[Any]	    =  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  __lowercase (		self :       List[str]						):


      '''simple docstring'''






      UpperCamelCase__      :       str	    =  self.prepare_config_and_inputs()
      UpperCamelCase__      :       Any	    =  config_and_inputs
      UpperCamelCase__      :       Dict	    =  {"""pixel_values""": pixel_values}
      return config, inputs_dict







@require_torch
class       __a  (   __SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE	,       unittest.TestCase	):
 _lowerCAmelCase	:	str				=			(
     (
         ConvNextModel,
         ConvNextForImageClassification,
         ConvNextBackbone,
     )
     if is_torch_available()
     else ()
 )
 _lowerCAmelCase	:	int				=			(
     {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
     if is_torch_available()
     else {}
 )

 _lowerCAmelCase	:	Union[str, Any]				=			True
 _lowerCAmelCase	:	List[Any]				=			False
 _lowerCAmelCase	:	Any				=			False
 _lowerCAmelCase	:	Optional[Any]				=			False
 _lowerCAmelCase	:	str				=			False







 def  __lowercase (		self :       Any						):


      '''simple docstring'''






      UpperCamelCase__      :       str	    =  ConvNextModelTester(self						)
      UpperCamelCase__      :       Dict	    =  ConfigTester(self							,       config_class=__UpperCAmelCase							,       has_text_modality=__UpperCAmelCase							,       hidden_size=37						)







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


      '''simple docstring'''






      return







 @unittest.skip(reason="ConvNext does not use inputs_embeds"						)
 def  __lowercase (		self :       Optional[Any]						):


      '''simple docstring'''






      pass







 @unittest.skip(reason="ConvNext does not support input and output embeddings"						)
 def  __lowercase (		self :       Any						):


      '''simple docstring'''






      pass







 @unittest.skip(reason="ConvNext does not use feedforward chunking"						)
 def  __lowercase (		self :       List[Any]						):


      '''simple docstring'''






      pass







 def  __lowercase (		self :       List[str]						):


      '''simple docstring'''






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

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

           UpperCamelCase__      :       int	    =  ["""pixel_values"""]
           self.assertListEqual(arg_names[:1]							,       __UpperCAmelCase						)







 def  __lowercase (		self :       List[Any]						):


      '''simple docstring'''






      UpperCamelCase__      :       int	    =  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase						)







 def  __lowercase (		self :       List[Any]						):


      '''simple docstring'''






      UpperCamelCase__      :       List[Any]	    =  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_backbone(*__UpperCAmelCase						)







 def  __lowercase (		self :       Dict						):


      '''simple docstring'''






      def check_hidden_states_output(SCREAMING_SNAKE_CASE :       List[Any]							,       SCREAMING_SNAKE_CASE :       int							,       SCREAMING_SNAKE_CASE :       str						):
           UpperCamelCase__      :       str	    =  model_class(__UpperCAmelCase						)
           model.to(__UpperCAmelCase						)
           model.eval()

           with torch.no_grad():
                UpperCamelCase__      :       Any	    =  model(**self._prepare_for_class(__UpperCAmelCase							,       __UpperCAmelCase						)						)

           UpperCamelCase__      :       List[str]	    =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           UpperCamelCase__      :       List[str]	    =  self.model_tester.num_stages
           self.assertEqual(len(__UpperCAmelCase						)							,       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]							,       )

      UpperCamelCase__      :       Any	    =  self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           UpperCamelCase__      :       List[str]	    =  True
           check_hidden_states_output(__UpperCAmelCase							,       __UpperCAmelCase							,       __UpperCAmelCase						)

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

           check_hidden_states_output(__UpperCAmelCase							,       __UpperCAmelCase							,       __UpperCAmelCase						)







 def  __lowercase (		self :       Union[str, Any]						):


      '''simple docstring'''






      UpperCamelCase__      :       Any	    =  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase						)







 @slow
 def  __lowercase (		self :       Any						):


      '''simple docstring'''






      for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__      :       List[Any]	    =  ConvNextModel.from_pretrained(__UpperCAmelCase						)
           self.assertIsNotNone(__UpperCAmelCase						)







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





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







 @cached_property
 def  __lowercase (		self :       List[str]						):


      '''simple docstring'''






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







 @slow
 def  __lowercase (		self :       Optional[Any]						):


      '''simple docstring'''






      UpperCamelCase__      :       Dict	    =  ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"						).to(__UpperCAmelCase						)

      UpperCamelCase__      :       Union[str, Any]	    =  self.default_image_processor
      UpperCamelCase__      :       Tuple	    =  prepare_img()
      UpperCamelCase__      :       Optional[int]	    =  image_processor(images=__UpperCAmelCase							,       return_tensors="pt"						).to(__UpperCAmelCase						)

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

      # verify the logits
      UpperCamelCase__      :       Optional[Any]	    =  torch.Size((1, 10_00)						)
      self.assertEqual(outputs.logits.shape							,       __UpperCAmelCase						)

      UpperCamelCase__      :       Dict	    =  torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]						).to(__UpperCAmelCase						)

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







@require_torch
class       __a  (   unittest.TestCase	,       __SCREAMING_SNAKE_CASE	):
 _lowerCAmelCase	:	int				=			(ConvNextBackbone,) if is_torch_available() else ()
 _lowerCAmelCase	:	Optional[Any]				=			ConvNextConfig

 _lowerCAmelCase	:	str				=			False







 def  __lowercase (		self :       List[str]						):


      '''simple docstring'''






      UpperCamelCase__      :       Optional[int]	    =  ConvNextModelTester(self						)







lowerCamelCase     :							Optional[int]    ={
    '''A''': ['''B''', '''C''', '''E'''],
    '''B''': ['''A''', '''D''', '''E'''],
    '''C''': ['''A''', '''F''', '''G'''],
    '''D''': ['''B'''],
    '''E''': ['''A''', '''B''', '''D'''],
    '''F''': ['''C'''],
    '''G''': ['''C'''],
}







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase ,   __lowerCAmelCase ,   __lowerCAmelCase      )			->     list[str]:
     UpperCamelCase__      :       Optional[Any]	    =  set()
     # keep track of all the paths to be checked
     UpperCamelCase__      :       Optional[Any]	    =  [[start]]

     # return path if start is goal
     if start == goal:
          return [start]

     # keeps looping until all possible paths have been checked
     while queue:
          # pop the first path from the queue
          UpperCamelCase__      :       int	    =  queue.pop(0      )
          # get the last node from the path
          UpperCamelCase__      :       Dict	    =  path[-1]
          if node not in explored:
               UpperCamelCase__      :       Tuple	    =  graph[node]
               # go through all neighbour nodes, construct a new path and
               # push it into the queue
               for neighbour in neighbours:
                    UpperCamelCase__      :       List[str]	    =  list(__lowerCAmelCase      )
                    new_path.append(__lowerCAmelCase      )
                    queue.append(__lowerCAmelCase      )
                    # return path if neighbour is goal
                    if neighbour == goal:
                         return new_path

            # mark node as explored
               explored.add(__lowerCAmelCase      )

    # in case there's no path between the 2 nodes
     return []







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase ,   __lowerCAmelCase ,   __lowerCAmelCase      )			->     int:
     if not graph or start not in graph or target not in graph:
          return -1
     if start == target:
          return 0
     UpperCamelCase__      :       Tuple	    =  [start]
     UpperCamelCase__      :       Optional[int]	    =  set(__lowerCAmelCase      )
     # Keep tab on distances from `start` node.
     UpperCamelCase__      :       str	    =  {start: 0, target: -1}
     while queue:
          UpperCamelCase__      :       Any	    =  queue.pop(0      )
          if node == target:
               UpperCamelCase__      :       Union[str, Any]	    =  (
                   dist[node] if dist[target] == -1 else min(dist[target] ,   dist[node]      )
               )
          for adjacent in graph[node]:
               if adjacent not in visited:
                    visited.add(__lowerCAmelCase      )
                    queue.append(__lowerCAmelCase      )
                    UpperCamelCase__      :       List[Any]	    =  dist[node] + 1
     return dist[target]


if __name__ == "__main__":
 print(bfs_shortest_path(demo_graph, '''G''', '''D'''))  # returns ['G', 'C', 'A', 'B', 'D']
 print(bfs_shortest_path_distance(demo_graph, '''G''', '''D'''))  # returns 4