"""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     UpperCAmelCase						:



    """simple docstring"""

    def __init__(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase=13    ,			_UpperCAmelCase=32    ,			_UpperCAmelCase=3    ,			_UpperCAmelCase=4    ,			_UpperCAmelCase=[10, 20, 30, 40]    ,			_UpperCAmelCase=[2, 2, 3, 2]    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase=37    ,			_UpperCAmelCase="gelu"    ,			_UpperCAmelCase=10    ,			_UpperCAmelCase=0.02    ,			_UpperCAmelCase=["stage2", "stage3", "stage4"]    ,			_UpperCAmelCase=[2, 3, 4]    ,			_UpperCAmelCase=None    ,			):
       lowercase__:   str					=      parent
       lowercase__:   List[str]					=      batch_size
       lowercase__:   Optional[int]					=      image_size
       lowercase__:   str					=      num_channels
       lowercase__:   Dict					=      num_stages
       lowercase__:   List[str]					=      hidden_sizes
       lowercase__:   Tuple					=      depths
       lowercase__:   str					=      is_training
       lowercase__:   Tuple					=      use_labels
       lowercase__:   Optional[int]					=      intermediate_size
       lowercase__:   Dict					=      hidden_act
       lowercase__:   Any					=      num_labels
       lowercase__:   Optional[int]					=      initializer_range
       lowercase__:   List[str]					=      out_features
       lowercase__:   str					=      out_indices
       lowercase__:   Optional[int]					=      scope






    def _snake_case			(   self							):
       lowercase__:   List[str]					=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

       lowercase__:   List[str]					=      self.get_config()
       return config, pixel_values, labels






    def _snake_case			(   self							):
       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 _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       lowercase__:   Dict					=      ConvNextModel(config=_UpperCAmelCase							)
       model.to(_UpperCAmelCase							)
       model.eval()
       lowercase__:   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 _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       lowercase__:   Any					=      ConvNextForImageClassification(_UpperCAmelCase							)
       model.to(_UpperCAmelCase							)
       model.eval()
       lowercase__:   str					=      model(_UpperCAmelCase    ,			labels=_UpperCAmelCase							)
       self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels)							)






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       lowercase__:   Any					=      ConvNextBackbone(config=_UpperCAmelCase							)
       model.to(_UpperCAmelCase							)
       model.eval()
       lowercase__:   Dict					=      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__:   List[Any]					=      None
       lowercase__:   Any					=      ConvNextBackbone(config=_UpperCAmelCase							)
       model.to(_UpperCAmelCase							)
       model.eval()
       lowercase__:   Optional[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 _snake_case			(   self							):
       lowercase__:   int					=      self.prepare_config_and_inputs()
       lowercase__, lowercase__, lowercase__:   Optional[Any]					=      config_and_inputs
       lowercase__:   Union[str, Any]					=      {'''pixel_values''': pixel_values}
       return config, inputs_dict



@require_torch
class     UpperCAmelCase						(_UpperCAmelCase    ,_UpperCAmelCase    ,unittest.TestCase  ):



    """simple docstring"""

    _UpperCAmelCase	:int						    = (
        (
            ConvNextModel,
            ConvNextForImageClassification,
            ConvNextBackbone,
        )
        if is_torch_available()
        else ()
    )
    _UpperCAmelCase	:Tuple						    = (
        {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
        if is_torch_available()
        else {}
    )

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






    def _snake_case			(   self							):
       lowercase__:   Any					=      ConvNextModelTester(self							)
       lowercase__:   Dict					=      ConfigTester(self    ,			config_class=_UpperCAmelCase    ,			has_text_modality=_UpperCAmelCase    ,			hidden_size=37							)






    def _snake_case			(   self							):
       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 _snake_case			(   self							):
       return






    @unittest.skip(reason='''ConvNext does not use inputs_embeds'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip(reason='''ConvNext does not support input and output embeddings'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip(reason='''ConvNext does not use feedforward chunking'''							)
    def _snake_case			(   self							):
       pass






    def _snake_case			(   self							):
       lowercase__, lowercase__:   int					=      self.model_tester.prepare_config_and_inputs_for_common()

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

          lowercase__:   int					=      ['''pixel_values''']
          self.assertListEqual(arg_names[:1]    ,			_UpperCAmelCase							)






    def _snake_case			(   self							):
       lowercase__:   str					=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_UpperCAmelCase							)






    def _snake_case			(   self							):
       lowercase__:   List[str]					=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*_UpperCAmelCase							)






    def _snake_case			(   self							):
       def check_hidden_states_output(_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
          lowercase__:   Union[str, Any]					=      model_class(_UpperCAmelCase							)
          model.to(_UpperCAmelCase							)
          model.eval()

          with torch.no_grad():
             lowercase__:   Dict					=      model(**self._prepare_for_class(_UpperCAmelCase    ,			_UpperCAmelCase							)							)

          lowercase__:   str					=      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          lowercase__:   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]    ,			)

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

       for model_class in self.all_model_classes:
          lowercase__:   str					=      True
          check_hidden_states_output(_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							)

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          lowercase__:   Optional[Any]					=      True

          check_hidden_states_output(_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							)






    def _snake_case			(   self							):
       lowercase__:   Union[str, Any]					=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase							)






    @slow
    def _snake_case			(   self							):
       for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowercase__:   Dict					=      ConvNextModel.from_pretrained(_UpperCAmelCase							)
          self.assertIsNotNone(_UpperCAmelCase							)



def SCREAMING_SNAKE_CASE__			(   )  ->  int:
   lowercase__:   Tuple					=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
   return image


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



    """simple docstring"""

    @cached_property
    def _snake_case			(   self							):
       return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''							) if is_vision_available() else None






    @slow
    def _snake_case			(   self							):
       lowercase__:   str					=      ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''							).to(_UpperCAmelCase							)

       lowercase__:   Union[str, Any]					=      self.default_image_processor
       lowercase__:   Any					=      prepare_img()
       lowercase__:   Any					=      image_processor(images=_UpperCAmelCase    ,			return_tensors='''pt'''							).to(_UpperCAmelCase							)

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

       # verify the logits
       lowercase__:   Optional[Any]					=      torch.Size((1, 1000)							)
       self.assertEqual(outputs.logits.shape    ,			_UpperCAmelCase							)

       lowercase__:   Tuple					=      torch.tensor([-0.0_260, -0.4_739, 0.1_911]							).to(_UpperCAmelCase							)

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



@require_torch
class     UpperCAmelCase						(unittest.TestCase    ,_UpperCAmelCase  ):



    """simple docstring"""

    _UpperCAmelCase	:Tuple						    = (ConvNextBackbone,) if is_torch_available() else ()
    _UpperCAmelCase	:str						    = ConvNextConfig

    _UpperCAmelCase	:Tuple						    = False






    def _snake_case			(   self							):
       lowercase__:   Dict					=      ConvNextModelTester(self							)

"""simple docstring"""






def SCREAMING_SNAKE_CASE__			(   __UpperCAmelCase       ,    __UpperCAmelCase )  ->  List[str]:
   lowercase__:   Optional[Any]					=      0
   lowercase__:   List[Any]					=      len(__UpperCAmelCase ) - 1

   while left <= right:
      # avoid divided by 0 during interpolation
      if sorted_collection[left] == sorted_collection[right]:
         if sorted_collection[left] == item:
            return left
         else:
            return None

      lowercase__:   Tuple					=      left + ((item - sorted_collection[left]) * (right - left)) // (
          sorted_collection[right] - sorted_collection[left]
      )

      # out of range check
      if point < 0 or point >= len(__UpperCAmelCase ):
         return None

      lowercase__:   Optional[int]					=      sorted_collection[point]
      if current_item == item:
         return point
      else:
         if point < left:
            lowercase__:   List[Any]					=      left
            lowercase__:   int					=      point
         elif point > right:
            lowercase__:   Dict					=      right
            lowercase__:   List[str]					=      point
         else:
            if item < current_item:
               lowercase__:   int					=      point - 1
            else:
               lowercase__:   int					=      point + 1
   return None



def SCREAMING_SNAKE_CASE__			(   __UpperCAmelCase       ,    __UpperCAmelCase       ,    __UpperCAmelCase       ,    __UpperCAmelCase )  ->  List[str]:

   # avoid divided by 0 during interpolation
   if sorted_collection[left] == sorted_collection[right]:
      if sorted_collection[left] == item:
         return left
      else:
         return None

   lowercase__:   Optional[int]					=      left + ((item - sorted_collection[left]) * (right - left)) // (
       sorted_collection[right] - sorted_collection[left]
   )

   # out of range check
   if point < 0 or point >= len(__UpperCAmelCase ):
      return None

   if sorted_collection[point] == item:
      return point
   elif point < left:
      return interpolation_search_by_recursion(__UpperCAmelCase       ,    __UpperCAmelCase       ,    __UpperCAmelCase       ,    __UpperCAmelCase )
   elif point > right:
      return interpolation_search_by_recursion(__UpperCAmelCase       ,    __UpperCAmelCase       ,    __UpperCAmelCase       ,    __UpperCAmelCase )
   else:
      if sorted_collection[point] > item:
         return interpolation_search_by_recursion(
             __UpperCAmelCase       ,    __UpperCAmelCase       ,    __UpperCAmelCase       ,    point - 1 )
      else:
         return interpolation_search_by_recursion(
             __UpperCAmelCase       ,    __UpperCAmelCase       ,    point + 1       ,    __UpperCAmelCase )



def SCREAMING_SNAKE_CASE__			(   __UpperCAmelCase )  ->  List[Any]:
   if collection != sorted(__UpperCAmelCase ):
      raise ValueError('''Collection must be ascending sorted''' )
   return True


if __name__ == "__main__":
       import sys
       __A			   = 0
       if debug == 1:
              __A			   = [1_0, 3_0, 4_0, 4_5, 5_0, 6_6, 7_7, 9_3]
              try:
                     __assert_sorted(collection)
              except ValueError:
                     sys.exit("Sequence must be ascending sorted to apply interpolation search")
              __A			   = 6_7

       __A			   = interpolation_search(collection, target)
       if result is not None:
              print(f'''{target} found at positions: {result}''')
       else:
              print("Not found")
