



from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers import TFCvtForImageClassification, TFCvtModel
      from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor





class      lowercase__    (							__A  ):







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Any    =		self.config_class(**self.inputs_dict						)
       self.parent.assertTrue(hasattr(A__    ,						"""embed_dim"""						)						)
       self.parent.assertTrue(hasattr(A__    ,						"""num_heads"""						)						)





class      lowercase__    :







  def __init__(	self    ,						_lowercase    ,						_lowercase=13    ,						_lowercase=64    ,						_lowercase=3    ,						_lowercase=[16, 48, 96]    ,						_lowercase=[1, 3, 6]    ,						_lowercase=[1, 2, 10]    ,						_lowercase=[7, 3, 3]    ,						_lowercase=[4, 2, 2]    ,						_lowercase=[2, 1, 1]    ,						_lowercase=[2, 2, 2]    ,						_lowercase=[False, False, True]    ,						_lowercase=[0.0, 0.0, 0.0]    ,						_lowercase=0.02    ,						_lowercase=1e-12    ,						_lowercase=True    ,						_lowercase=True    ,						_lowercase=2    ,						):
       lowerCAmelCase_					:       List[Any]    =		parent
       lowerCAmelCase_					:       str    =		batch_size
       lowerCAmelCase_					:       Dict    =		image_size
       lowerCAmelCase_					:       int    =		patch_sizes
       lowerCAmelCase_					:       Optional[int]    =		patch_stride
       lowerCAmelCase_					:       int    =		patch_padding
       lowerCAmelCase_					:       str    =		is_training
       lowerCAmelCase_					:       Dict    =		use_labels
       lowerCAmelCase_					:       str    =		num_labels
       lowerCAmelCase_					:       Any    =		num_channels
       lowerCAmelCase_					:       Dict    =		embed_dim
       lowerCAmelCase_					:       int    =		num_heads
       lowerCAmelCase_					:       Tuple    =		stride_kv
       lowerCAmelCase_					:       List[Any]    =		depth
       lowerCAmelCase_					:       Dict    =		cls_token
       lowerCAmelCase_					:       Optional[Any]    =		attention_drop_rate
       lowerCAmelCase_					:       Tuple    =		initializer_range
       lowerCAmelCase_					:       List[str]    =		layer_norm_eps







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Tuple    =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       lowerCAmelCase_					:       List[Any]    =		None
       if self.use_labels:
            # create a random int32 tensor of given shape
            lowerCAmelCase_					:       List[Any]    =		ids_tensor([self.batch_size]    ,						self.num_labels						)

       lowerCAmelCase_					:       Tuple    =		self.get_config()
       return config, pixel_values, labels







  def 	UpperCAmelCase__		(	self						):
       return CvtConfig(
           image_size=self.image_size    ,						num_labels=self.num_labels    ,						num_channels=self.num_channels    ,						embed_dim=self.embed_dim    ,						num_heads=self.num_heads    ,						patch_sizes=self.patch_sizes    ,						patch_padding=self.patch_padding    ,						patch_stride=self.patch_stride    ,						stride_kv=self.stride_kv    ,						depth=self.depth    ,						cls_token=self.cls_token    ,						attention_drop_rate=self.attention_drop_rate    ,						initializer_range=self.initializer_range    ,						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       Tuple    =		TFCvtModel(config=A__						)
       lowerCAmelCase_					:       Tuple    =		model(A__    ,						training=A__						)
       lowerCAmelCase_					:       Dict    =		(self.image_size, self.image_size)
       lowerCAmelCase_					:       int    =		image_size[0], image_size[1]
       for i in range(len(self.depth						)						):
            lowerCAmelCase_					:       List[Any]    =		floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1						)
            lowerCAmelCase_					:       Any    =		floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1						)
       self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.embed_dim[-1], height, width)						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       Optional[Any]    =		self.num_labels
       lowerCAmelCase_					:       Optional[Any]    =		TFCvtForImageClassification(A__						)
       lowerCAmelCase_					:       str    =		model(A__    ,						labels=A__    ,						training=A__						)
       self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.num_labels)						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Union[str, Any]    =		self.prepare_config_and_inputs()
       lowerCAmelCase_					:       Optional[int]    =		config_and_inputs
       lowerCAmelCase_					:       Union[str, Any]    =		{"""pixel_values""": pixel_values}
       return config, inputs_dict





@require_tf
class      lowercase__    (							__A     ,					__A     ,					unittest.TestCase  ):
  __UpperCamelCase	     =  (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
  __UpperCamelCase	     =  (
      {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
      if is_tf_available()
      else {}
  )
  __UpperCamelCase	     =  False
  __UpperCamelCase	     =  False
  __UpperCamelCase	     =  False
  __UpperCamelCase	     =  False
  __UpperCamelCase	     =  False







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       List[str]    =		TFCvtModelTester(self						)
       lowerCAmelCase_					:       Any    =		TFCvtConfigTester(self    ,						config_class=A__    ,						has_text_modality=A__    ,						hidden_size=37						)







  def 	UpperCAmelCase__		(	self						):
       self.config_tester.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()







  @unittest.skip(reason="""Cvt does not output attentions"""						)
  def 	UpperCAmelCase__		(	self						):
       pass







  @unittest.skip(reason="""Cvt does not use inputs_embeds"""						)
  def 	UpperCAmelCase__		(	self						):
       pass







  @unittest.skip(reason="""Cvt does not support input and output embeddings"""						)
  def 	UpperCAmelCase__		(	self						):
       pass







  @unittest.skipIf(
      not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""						)						) == 0    ,						reason="""TF does not support backprop for grouped convolutions on CPU."""    ,						)
  def 	UpperCAmelCase__		(	self						):
       super().test_dataset_conversion()







  @unittest.skipIf(
      not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""						)						) == 0    ,						reason="""TF does not support backprop for grouped convolutions on CPU."""    ,						)
  @slow
  def 	UpperCAmelCase__		(	self						):
       super().test_keras_fit()







  @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8"""						)
  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Any    =		tf.keras.mixed_precision.Policy("""mixed_float16"""						)
       tf.keras.mixed_precision.set_global_policy(A__						)
       super().test_keras_fit()
       tf.keras.mixed_precision.set_global_policy("""float32"""						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       str    =		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            lowerCAmelCase_					:       Any    =		model_class(A__						)
            lowerCAmelCase_					:       Optional[Any]    =		inspect.signature(model.call						)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            lowerCAmelCase_					:       Dict    =		[*signature.parameters.keys()]

            lowerCAmelCase_					:       Tuple    =		["""pixel_values"""]
            self.assertListEqual(arg_names[:1]    ,						A__						)







  def 	UpperCAmelCase__		(	self						):
       def check_hidden_states_output(_lowercase    ,						_lowercase    ,						_lowercase						):
            lowerCAmelCase_					:       Optional[int]    =		model_class(A__						)

            lowerCAmelCase_					:       Optional[Any]    =		model(**self._prepare_for_class(A__    ,						A__						)						)
            lowerCAmelCase_					:       Dict    =		outputs.hidden_states

            lowerCAmelCase_					:       Any    =		len(self.model_tester.depth						)
            self.assertEqual(len(A__						)    ,						A__						)

            # verify the first hidden states (first block)
            self.assertListEqual(
                list(hidden_states[0].shape[-3:]						)    ,						[
                    self.model_tester.embed_dim[0],
                    self.model_tester.image_size // 4,
                    self.model_tester.image_size // 4,
                ]    ,						)

       lowerCAmelCase_					:       Optional[Any]    =		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            lowerCAmelCase_					:       Optional[Any]    =		True
            check_hidden_states_output(A__    ,						A__    ,						A__						)

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

            check_hidden_states_output(A__    ,						A__    ,						A__						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Tuple    =		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A__						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Optional[Any]    =		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*A__						)







  @slow
  def 	UpperCAmelCase__		(	self						):
       for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            lowerCAmelCase_					:       List[Any]    =		TFCvtModel.from_pretrained(A__						)
            self.assertIsNotNone(A__						)






def 							_lowerCAmelCase (  )	->			Union[str, Any]:
     lowerCAmelCase_					:       Dict    =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
     return image







@require_tf
@require_vision
class      lowercase__    (							unittest.TestCase  ):







  @cached_property
  def 	UpperCAmelCase__		(	self						):
       return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)







  @slow
  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Any    =		TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

       lowerCAmelCase_					:       str    =		self.default_image_processor
       lowerCAmelCase_					:       Union[str, Any]    =		prepare_img()
       lowerCAmelCase_					:       Tuple    =		image_processor(images=A__    ,						return_tensors="""tf"""						)

       # forward pass
       lowerCAmelCase_					:       Tuple    =		model(**A__						)

       # verify the logits
       lowerCAmelCase_					:       Optional[Any]    =		tf.TensorShape((1, 1_000)						)
       self.assertEqual(outputs.logits.shape    ,						A__						)

       lowerCAmelCase_					:       Any    =		tf.constant([0.9285, 0.9015, -0.3150]						)
       self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()    ,						A__    ,						atol=1e-4						)						)







from collections.abc import Generator
from math import sin






def 							_lowerCAmelCase (  _a   :					bytes			)	->			bytes:
     if len(_a			) != 32:
          raise ValueError("""Input must be of length 32"""			)

     lowerCAmelCase_					:       Any    =		B""""""
     for i in [3, 2, 1, 0]:
          little_endian += string_aa[8 * i : 8 * i + 8]
     return little_endian






def 							_lowerCAmelCase (  _a   :					int			)	->			bytes:
     if i < 0:
          raise ValueError("""Input must be non-negative"""			)

     lowerCAmelCase_					:       Tuple    =		format(_a					,   """08x"""			)[-8:]
     lowerCAmelCase_					:       Any    =		B""""""
     for i in [3, 2, 1, 0]:
          little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8"""			)
     return little_endian_hex






def 							_lowerCAmelCase (  _a   :					bytes			)	->			bytes:
     lowerCAmelCase_					:       Tuple    =		B""""""
     for char in message:
          bit_string += format(_a					,   """08b"""			).encode("""utf-8"""			)
     lowerCAmelCase_					:       Dict    =		format(len(_a			)					,   """064b"""			).encode("""utf-8"""			)

     # Pad bit_string to a multiple of 512 chars
     bit_string += b"1"
     while len(_a			) % 5_12 != 4_48:
          bit_string += b"0"
     bit_string += to_little_endian(start_len[32:]			) + to_little_endian(start_len[:32]			)

     return bit_string






def 							_lowerCAmelCase (  _a   :					bytes			)	->			Generator[list[int], None, None]:
     if len(_a			) % 5_12 != 0:
          raise ValueError("""Input must have length that's a multiple of 512"""			)

     for pos in range(0					,   len(_a			)					,   5_12			):
          lowerCAmelCase_					:       int    =		bit_string[pos : pos + 5_12]
          lowerCAmelCase_					:       Any    =		[]
          for i in range(0					,   5_12					,   32			):
               block_words.append(int(to_little_endian(block[i : i + 32]			)					,   2			)			)
          yield block_words






def 							_lowerCAmelCase (  _a   :					int			)	->			int:
     if i < 0:
          raise ValueError("""Input must be non-negative"""			)

     lowerCAmelCase_					:       List[str]    =		format(_a					,   """032b"""			)
     lowerCAmelCase_					:       Optional[int]    =		""""""
     for c in i_str:
          new_str += "1" if c == "0" else "0"
     return int(_a					,   2			)






def 							_lowerCAmelCase (  _a   :					int					,   _a   :					int			)	->			int:
     return (a + b) % 2**32






def 							_lowerCAmelCase (  _a   :					int					,   _a   :					int			)	->			int:
     if i < 0:
          raise ValueError("""Input must be non-negative"""			)
     if shift < 0:
          raise ValueError("""Shift must be non-negative"""			)
     return ((i << shift) ^ (i >> (32 - shift))) % 2**32






def 							_lowerCAmelCase (  _a   :					bytes			)	->			bytes:
     lowerCAmelCase_					:       Union[str, Any]    =		preprocess(_a			)

     lowerCAmelCase_					:       Optional[int]    =		[int(2**32 * abs(sin(i + 1			)			)			) for i in range(64			)]

     # Starting states
     lowerCAmelCase_					:       Tuple    =		0X67452301
     lowerCAmelCase_					:       Optional[int]    =		0XEFCDAB89
     lowerCAmelCase_					:       Tuple    =		0X98BADCFE
     lowerCAmelCase_					:       Tuple    =		0X10325476

     lowerCAmelCase_					:       Dict    =		[
         7,
         12,
         17,
         22,
         7,
         12,
         17,
         22,
         7,
         12,
         17,
         22,
         7,
         12,
         17,
         22,
         5,
         9,
         14,
         20,
         5,
         9,
         14,
         20,
         5,
         9,
         14,
         20,
         5,
         9,
         14,
         20,
         4,
         11,
         16,
         23,
         4,
         11,
         16,
         23,
         4,
         11,
         16,
         23,
         4,
         11,
         16,
         23,
         6,
         10,
         15,
         21,
         6,
         10,
         15,
         21,
         6,
         10,
         15,
         21,
         6,
         10,
         15,
         21,
     ]

     # Process bit string in chunks, each with 16 32-char words
     for block_words in get_block_words(_a			):
          lowerCAmelCase_					:       int    =		aa
          lowerCAmelCase_					:       Any    =		ba
          lowerCAmelCase_					:       List[str]    =		ca
          lowerCAmelCase_					:       Optional[Any]    =		da

          # Hash current chunk
          for i in range(64			):
               if i <= 15:
                    # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
                    lowerCAmelCase_					:       int    =		d ^ (b & (c ^ d))
                    lowerCAmelCase_					:       List[Any]    =		i
               elif i <= 31:
                    # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
                    lowerCAmelCase_					:       List[Any]    =		c ^ (d & (b ^ c))
                    lowerCAmelCase_					:       Optional[Any]    =		(5 * i + 1) % 16
               elif i <= 47:
                    lowerCAmelCase_					:       Union[str, Any]    =		b ^ c ^ d
                    lowerCAmelCase_					:       Optional[Any]    =		(3 * i + 5) % 16
               else:
                    lowerCAmelCase_					:       Any    =		c ^ (b | not_aa(_a			))
                    lowerCAmelCase_					:       List[str]    =		(7 * i) % 16
               lowerCAmelCase_					:       Tuple    =		(f + a + added_consts[i] + block_words[g]) % 2**32
               lowerCAmelCase_					:       Tuple    =		d
               lowerCAmelCase_					:       Optional[Any]    =		c
               lowerCAmelCase_					:       Dict    =		b
               lowerCAmelCase_					:       List[Any]    =		sum_aa(_a					,   left_rotate_aa(_a					,   shift_amounts[i]			)			)

          # Add hashed chunk to running total
          lowerCAmelCase_					:       Optional[int]    =		sum_aa(_a					,   _a			)
          lowerCAmelCase_					:       Optional[int]    =		sum_aa(_a					,   _a			)
          lowerCAmelCase_					:       Dict    =		sum_aa(_a					,   _a			)
          lowerCAmelCase_					:       Tuple    =		sum_aa(_a					,   _a			)

     lowerCAmelCase_					:       int    =		reformat_hex(_a			) + reformat_hex(_a			) + reformat_hex(_a			) + reformat_hex(_a			)
     return digest


if __name__ == "__main__":
      import doctest

      doctest.testmod()
