





'''simple docstring'''




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


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

          '''simple docstring'''






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


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Optional[Any]						=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

          __A		:					List[str]						=			self.get_config()

          return config, pixel_values, labels


     def 				SCREAMING_SNAKE_CASE    (		self):

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


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase):

          '''simple docstring'''






          __A		:					List[Any]						=			ConvNextVaModel(config=__lowerCAmelCase)
          model.to(__lowerCAmelCase)
          model.eval()
          __A		:					Dict						=			model(__lowerCAmelCase)
          # 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 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase):

          '''simple docstring'''






          __A		:					Optional[int]						=			ConvNextVaForImageClassification(__lowerCAmelCase)
          model.to(__lowerCAmelCase)
          model.eval()
          __A		:					Any						=			model(__lowerCAmelCase		,      labels=__lowerCAmelCase)
          self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels))


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase):

          '''simple docstring'''






          __A		:					List[str]						=			ConvNextVaBackbone(config=__lowerCAmelCase)
          model.to(__lowerCAmelCase)
          model.eval()
          __A		:					Union[str, Any]						=			model(__lowerCAmelCase)

          # 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		:					List[str]						=			None
          __A		:					Tuple						=			ConvNextVaBackbone(config=__lowerCAmelCase)
          model.to(__lowerCAmelCase)
          model.eval()
          __A		:					List[str]						=			model(__lowerCAmelCase)

          # 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 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					str						=			self.prepare_config_and_inputs()
          __A					,__A					,__A		:					Tuple						=			config_and_inputs
          __A		:					str						=			{'pixel_values': pixel_values}
          return config, inputs_dict


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






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




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

     lowerCAmelCase						     =			False
     lowerCAmelCase						     =			False
     lowerCAmelCase						     =			False
     lowerCAmelCase						     =			False
     lowerCAmelCase						     =			False


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					List[Any]						=			ConvNextVaModelTester(self)
          __A		:					List[Any]						=			ConfigTester(self		,      config_class=__lowerCAmelCase		,      has_text_modality=__lowerCAmelCase		,      hidden_size=37)


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''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 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          return


     @unittest.skip(reason='ConvNextV2 does not use inputs_embeds')
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          pass


     @unittest.skip(reason='ConvNextV2 does not support input and output embeddings')
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          pass


     @unittest.skip(reason='ConvNextV2 does not use feedforward chunking')
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          pass


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          if not self.model_tester.is_training:
               return

          for model_class in self.all_model_classes:
               __A					,__A		:					Any						=			self.model_tester.prepare_config_and_inputs_with_labels()
               __A		:					List[str]						=			True

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

               __A		:					Any						=			model_class(__lowerCAmelCase)
               model.to(__lowerCAmelCase)
               model.train()
               __A		:					str						=			self._prepare_for_class(__lowerCAmelCase		,      __lowerCAmelCase		,      return_labels=__lowerCAmelCase)
               __A		:					Any						=			model(**__lowerCAmelCase).loss
               loss.backward()


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          if not self.model_tester.is_training:
               return

          for model_class in self.all_model_classes:
               __A					,__A		:					List[Any]						=			self.model_tester.prepare_config_and_inputs_with_labels()
               __A		:					List[Any]						=			False
               __A		:					str						=			True

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

               __A		:					str						=			model_class(__lowerCAmelCase)
               model.to(__lowerCAmelCase)
               model.gradient_checkpointing_enable()
               model.train()
               __A		:					Optional[int]						=			self._prepare_for_class(__lowerCAmelCase		,      __lowerCAmelCase		,      return_labels=__lowerCAmelCase)
               __A		:					Any						=			model(**__lowerCAmelCase).loss
               loss.backward()


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A					,__A		:					List[str]						=			self.model_tester.prepare_config_and_inputs_for_common()

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

               __A		:					int						=			['pixel_values']
               self.assertListEqual(arg_names[:1]		,      __lowerCAmelCase)


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					str						=			self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__lowerCAmelCase)


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          def check_hidden_states_output(_UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase):
               __A		:					Optional[int]						=			model_class(__lowerCAmelCase)
               model.to(__lowerCAmelCase)
               model.eval()

               with torch.no_grad():
                    __A		:					int						=			model(**self._prepare_for_class(__lowerCAmelCase		,      __lowerCAmelCase))

               __A		:					Dict						=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               __A		:					Union[str, Any]						=			self.model_tester.num_stages
               self.assertEqual(len(__lowerCAmelCase)		,      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		:					Tuple						=			self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __A		:					Optional[int]						=			True
               check_hidden_states_output(__lowerCAmelCase		,      __lowerCAmelCase		,      __lowerCAmelCase)

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __A		:					Union[str, Any]						=			True

               check_hidden_states_output(__lowerCAmelCase		,      __lowerCAmelCase		,      __lowerCAmelCase)


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Optional[int]						=			self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase)


     @slow
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __A		:					List[Any]						=			ConvNextVaModel.from_pretrained(__lowerCAmelCase)
               self.assertIsNotNone(__lowerCAmelCase)






def 			_lowerCAmelCase     (    )	->	Tuple:
     __A		:					Any						=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
     return image







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


     @cached_property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






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


     @slow
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					str						=			ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224').to(__lowerCAmelCase)

          __A		:					Optional[int]						=			self.default_image_processor
          __A		:					Union[str, Any]						=			prepare_img()
          __A		:					Union[str, Any]						=			preprocessor(images=__lowerCAmelCase		,      return_tensors='pt').to(__lowerCAmelCase)

          # forward pass
          with torch.no_grad():
               __A		:					Union[str, Any]						=			model(**__lowerCAmelCase)

          # verify the logits
          __A		:					List[str]						=			torch.Size((1, 1000))
          self.assertEqual(outputs.logits.shape		,      __lowerCAmelCase)

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




UpperCAmelCase_		 =					2_5_6
# Modulus to hash a string
UpperCAmelCase_		 =					1_0_0_0_0_0_3

def 	SCREAMING_SNAKE_CASE_							(	_snake_case	:str	,   _snake_case	:str				)  ->     bool:
   _A      =       len(_snake_case				)
   _A      =       len(_snake_case				)
   if p_len > t_len:
      return False

   _A      =       0
   _A      =       0
   _A      =       1

   # Calculating the hash of pattern and substring of text
   for i in range(_snake_case				):
      _A      =       (ord(pattern[i]				) + p_hash * alphabet_size) % modulus
      _A      =       (ord(text[i]				) + text_hash * alphabet_size) % modulus
      if i == p_len - 1:
         continue
      _A      =       (modulus_power * alphabet_size) % modulus

   for i in range(0	,   t_len - p_len + 1				):
      if text_hash == p_hash and text[i : i + p_len] == pattern:
         return True
      if i == t_len - p_len:
         continue
      # Calculate the https://en.wikipedia.org/wiki/Rolling_hash
      _A      =       (
          (text_hash - ord(text[i]				) * modulus_power) * alphabet_size
          + ord(text[i + p_len]				)
      ) % modulus
   return False

def 	SCREAMING_SNAKE_CASE_							(	)  ->     None:
   _A      =       '''abc1abc12'''
   _A      =       '''alskfjaldsabc1abc1abc12k23adsfabcabc'''
   _A      =       '''alskfjaldsk23adsfabcabc'''
   assert rabin_karp(_snake_case	,   _snake_case				) and not rabin_karp(_snake_case	,   _snake_case				)

   # Test 2)
   _A      =       '''ABABX'''
   _A      =       '''ABABZABABYABABX'''
   assert rabin_karp(_snake_case	,   _snake_case				)

   # Test 3)
   _A      =       '''AAAB'''
   _A      =       '''ABAAAAAB'''
   assert rabin_karp(_snake_case	,   _snake_case				)

   # Test 4)
   _A      =       '''abcdabcy'''
   _A      =       '''abcxabcdabxabcdabcdabcy'''
   assert rabin_karp(_snake_case	,   _snake_case				)

   # Test 5)
   _A      =       '''Lü'''
   _A      =       '''Lüsai'''
   assert rabin_karp(_snake_case	,   _snake_case				)
   _A      =       '''Lue'''
   assert not rabin_karp(_snake_case	,   _snake_case				)
   print('''Success.'''				)


if __name__ == "__main__":
   test_rabin_karp()



