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




   def __init__(					self    :       Optional[Any] ,			_lowercase    :       str ,			_lowercase    :       Optional[Any]=13 ,			_lowercase    :       List[Any]=32 ,			_lowercase    :       int=3 ,			_lowercase    :       str=4 ,			_lowercase    :       Tuple=[10, 20, 30, 40] ,			_lowercase    :       int=[2, 2, 3, 2] ,			_lowercase    :       Optional[Any]=True ,			_lowercase    :       Dict=True ,			_lowercase    :       Tuple=37 ,			_lowercase    :       int="gelu" ,			_lowercase    :       Optional[Any]=10 ,			_lowercase    :       Optional[Any]=0.02 ,			_lowercase    :       Tuple=["stage2", "stage3", "stage4"] ,			_lowercase    :       Tuple=[2, 3, 4] ,			_lowercase    :       str=None ,			):



     """simple docstring"""






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




   def 			__a		(					self    :       int   ):



     """simple docstring"""






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

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

     SCREAMING_SNAKE_CASE__    							=   self.get_config()
     return config, pixel_values, labels




   def 			__a		(					self    :       Optional[int]   ):



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




   def 			__a		(					self    :       Tuple ,			_lowercase    :       Optional[int] ,			_lowercase    :       List[str] ,			_lowercase    :       Optional[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   ConvNextModel(config=_lowercase   )
     model.to(_lowercase   )
     model.eval()
     SCREAMING_SNAKE_CASE__    							=   model(_lowercase   )
     # 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 			__a		(					self    :       Union[str, Any] ,			_lowercase    :       int ,			_lowercase    :       Optional[int] ,			_lowercase    :       Dict   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   ConvNextForImageClassification(_lowercase   )
     model.to(_lowercase   )
     model.eval()
     SCREAMING_SNAKE_CASE__    							=   model(_lowercase ,			labels=_lowercase   )
     self.parent.assertEqual(result.logits.shape ,			(self.batch_size, self.num_labels)   )




   def 			__a		(					self    :       List[Any] ,			_lowercase    :       List[Any] ,			_lowercase    :       str ,			_lowercase    :       Tuple   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   ConvNextBackbone(config=_lowercase   )
     model.to(_lowercase   )
     model.eval()
     SCREAMING_SNAKE_CASE__    							=   model(_lowercase   )

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

     # 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    :       int   ):



     """simple docstring"""






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







@require_torch
class __snake_case       (		lowerCamelCase_     ,	lowerCamelCase_     ,	unittest.TestCase	):
   lowerCAmelCase_														=							(
       (
           ConvNextModel,
           ConvNextForImageClassification,
           ConvNextBackbone,
       )
       if is_torch_available()
       else ()
   )
   lowerCAmelCase_														=							(
       {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
       if is_torch_available()
       else {}
   )

   lowerCAmelCase_														=							True
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False




   def 			__a		(					self    :       Optional[int]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   ConvNextModelTester(self   )
     SCREAMING_SNAKE_CASE__    							=   ConfigTester(self ,			config_class=_lowercase ,			has_text_modality=_lowercase ,			hidden_size=37   )




   def 			__a		(					self    :       str   ):



     """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 			__a		(					self    :       int   ):



     """simple docstring"""






     return




   @unittest.skip(reason="""ConvNext does not use inputs_embeds"""   )
   def 			__a		(					self    :       Tuple   ):



     """simple docstring"""






     pass




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



     """simple docstring"""






     pass




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



     """simple docstring"""






     pass




   def 			__a		(					self    :       Any   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs_for_common()

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

       SCREAMING_SNAKE_CASE__    							=   ["""pixel_values"""]
       self.assertListEqual(arg_names[:1] ,			_lowercase   )




   def 			__a		(					self    :       Optional[int]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_lowercase   )




   def 			__a		(					self    :       int   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_backbone(*_lowercase   )




   def 			__a		(					self    :       Any   ):



     """simple docstring"""






     def check_hidden_states_output(_lowercase    :       Dict ,			_lowercase    :       List[str] ,			_lowercase    :       Tuple   ):
       SCREAMING_SNAKE_CASE__    							=   model_class(_lowercase   )
       model.to(_lowercase   )
       model.eval()

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

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

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

     SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs_for_common()

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

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

       check_hidden_states_output(_lowercase ,			_lowercase ,			_lowercase   )




   def 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_lowercase   )




   @slow
   def 			__a		(					self    :       Optional[int]   ):



     """simple docstring"""






     for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       SCREAMING_SNAKE_CASE__    							=   ConvNextModel.from_pretrained(_lowercase   )
       self.assertIsNotNone(_lowercase   )





def 			__SCREAMING_SNAKE_CASE						(      )							->      str:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
  return image







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




   @cached_property
   def 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






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




   @slow
   def 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""   ).to(_lowercase   )

     SCREAMING_SNAKE_CASE__    							=   self.default_image_processor
     SCREAMING_SNAKE_CASE__    							=   prepare_img()
     SCREAMING_SNAKE_CASE__    							=   image_processor(images=_lowercase ,			return_tensors="""pt"""   ).to(_lowercase   )

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

     # verify the logits
     SCREAMING_SNAKE_CASE__    							=   torch.Size((1, 10_00)   )
     self.assertEqual(outputs.logits.shape ,			_lowercase   )

     SCREAMING_SNAKE_CASE__    							=   torch.tensor([-0.02_60, -0.47_39, 0.19_11]   ).to(_lowercase   )

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







@require_torch
class __snake_case       (		unittest.TestCase     ,	lowerCamelCase_	):
   lowerCAmelCase_														=							(ConvNextBackbone,) if is_torch_available() else ()
   lowerCAmelCase_														=							ConvNextConfig

   lowerCAmelCase_														=							False




   def 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   ConvNextModelTester(self   )

from __future__ import annotations

from collections.abc import Iterator
from typing import Any







class __snake_case       :




   def __init__(					self    :       Union[str, Any] ,			_lowercase    :       Any   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   data
     SCREAMING_SNAKE_CASE__    							=   None







class __snake_case       :




   def __init__(					self    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   None
     SCREAMING_SNAKE_CASE__    							=   None




   def __iter__(					self    :       Tuple   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.head
     while self.head:
       yield node.data
       SCREAMING_SNAKE_CASE__    							=   node.next
       if node == self.head:
         break




   def __len__(					self    :       int   ):



     """simple docstring"""






     return sum(1 for _ in self   )




   def __repr__(					self    :       Optional[int]   ):



     """simple docstring"""






     return "->".join(str(_lowercase   ) for item in iter(self   )   )




   def 			__a		(					self    :       Optional[int] ,			_lowercase    :       Any   ):



     """simple docstring"""






     self.insert_nth(len(self   ) ,			_lowercase   )




   def 			__a		(					self    :       Tuple ,			_lowercase    :       Any   ):



     """simple docstring"""






     self.insert_nth(0 ,			_lowercase   )




   def 			__a		(					self    :       Tuple ,			_lowercase    :       int ,			_lowercase    :       Any   ):



     """simple docstring"""






     if index < 0 or index > len(self   ):
       raise IndexError("""list index out of range."""   )
     SCREAMING_SNAKE_CASE__    							=   Node(_lowercase   )
     if self.head is None:
       SCREAMING_SNAKE_CASE__    							=   new_node  # first node points itself
       SCREAMING_SNAKE_CASE__    							=   SCREAMING_SNAKE_CASE__    							=   new_node
     elif index == 0:  # insert at head
       SCREAMING_SNAKE_CASE__    							=   self.head
       SCREAMING_SNAKE_CASE__    							=   SCREAMING_SNAKE_CASE__    							=   new_node
     else:
       SCREAMING_SNAKE_CASE__    							=   self.head
       for _ in range(index - 1   ):
         SCREAMING_SNAKE_CASE__    							=   temp.next
       SCREAMING_SNAKE_CASE__    							=   temp.next
       SCREAMING_SNAKE_CASE__    							=   new_node
       if index == len(self   ) - 1:  # insert at tail
         SCREAMING_SNAKE_CASE__    							=   new_node




   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     return self.delete_nth(0   )




   def 			__a		(					self    :       str   ):



     """simple docstring"""






     return self.delete_nth(len(self   ) - 1   )




   def 			__a		(					self    :       str ,			_lowercase    :       int = 0   ):



     """simple docstring"""






     if not 0 <= index < len(self   ):
       raise IndexError("""list index out of range."""   )
     SCREAMING_SNAKE_CASE__    							=   self.head
     if self.head == self.tail:  # just one node
       SCREAMING_SNAKE_CASE__    							=   SCREAMING_SNAKE_CASE__    							=   None
     elif index == 0:  # delete head node
       SCREAMING_SNAKE_CASE__    							=   self.tail.next.next
       SCREAMING_SNAKE_CASE__    							=   self.head.next
     else:
       SCREAMING_SNAKE_CASE__    							=   self.head
       for _ in range(index - 1   ):
         SCREAMING_SNAKE_CASE__    							=   temp.next
       SCREAMING_SNAKE_CASE__    							=   temp.next
       SCREAMING_SNAKE_CASE__    							=   temp.next.next
       if index == len(self   ) - 1:  # delete at tail
         SCREAMING_SNAKE_CASE__    							=   temp
     return delete_node.data




   def 			__a		(					self    :       Optional[int]   ):



     """simple docstring"""






     return len(self   ) == 0





def 			__SCREAMING_SNAKE_CASE						(      )							->      None:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   CircularLinkedList()
  assert len(__UpperCamelCase			) == 0
  assert circular_linked_list.is_empty() is True
  assert str(__UpperCamelCase			) == ""

  try:
    circular_linked_list.delete_front()
    raise AssertionError  # This should not happen
  except IndexError:
    assert True  # This should happen

  try:
    circular_linked_list.delete_tail()
    raise AssertionError  # This should not happen
  except IndexError:
    assert True  # This should happen

  try:
    circular_linked_list.delete_nth(-1			)
    raise AssertionError
  except IndexError:
    assert True

  try:
    circular_linked_list.delete_nth(0			)
    raise AssertionError
  except IndexError:
    assert True

  assert circular_linked_list.is_empty() is True
  for i in range(5			):
    assert len(__UpperCamelCase			) == i
    circular_linked_list.insert_nth(__UpperCamelCase				,  i + 1			)
  assert str(__UpperCamelCase			) == "->".join(str(__UpperCamelCase			) for i in range(1				,  6			)			)

  circular_linked_list.insert_tail(6			)
  assert str(__UpperCamelCase			) == "->".join(str(__UpperCamelCase			) for i in range(1				,  7			)			)
  circular_linked_list.insert_head(0			)
  assert str(__UpperCamelCase			) == "->".join(str(__UpperCamelCase			) for i in range(0				,  7			)			)

  assert circular_linked_list.delete_front() == 0
  assert circular_linked_list.delete_tail() == 6
  assert str(__UpperCamelCase			) == "->".join(str(__UpperCamelCase			) for i in range(1				,  6			)			)
  assert circular_linked_list.delete_nth(2			) == 3

  circular_linked_list.insert_nth(2				,  3			)
  assert str(__UpperCamelCase			) == "->".join(str(__UpperCamelCase			) for i in range(1				,  6			)			)

  assert circular_linked_list.is_empty() is False


if __name__ == "__main__":
   import doctest

   doctest.testmod()
