



"""simple docstring"""
from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
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 TFViTForImageClassification, TFViTModel


if is_vision_available():
    from PIL import Image

    from transformers import ViTImageProcessor


class    SCREAMING_SNAKE_CASE__ :

    def __init__(				self			:				Any ,  lowerCAmelCase_			:				List[Any] ,  lowerCAmelCase_			:				int=1_3 ,  lowerCAmelCase_			:				Optional[int]=3_0 ,  lowerCAmelCase_			:				str=2 ,  lowerCAmelCase_			:				Tuple=3 ,  lowerCAmelCase_			:				Tuple=True ,  lowerCAmelCase_			:				Any=True ,  lowerCAmelCase_			:				List[Any]=3_2 ,  lowerCAmelCase_			:				List[Any]=2 ,  lowerCAmelCase_			:				Optional[int]=4 ,  lowerCAmelCase_			:				Any=3_7 ,  lowerCAmelCase_			:				Union[str, Any]="gelu" ,  lowerCAmelCase_			:				Tuple=0.1 ,  lowerCAmelCase_			:				Dict=0.1 ,  lowerCAmelCase_			:				Union[str, Any]=1_0 ,  lowerCAmelCase_			:				List[Any]=0.02 ,  lowerCAmelCase_			:				str=3 ,  lowerCAmelCase_			:				str=None ,  ):







      """simple docstring"""







      lowercase_								= parent
      lowercase_								= batch_size
      lowercase_								= image_size
      lowercase_								= patch_size
      lowercase_								= num_channels
      lowercase_								= is_training
      lowercase_								= use_labels
      lowercase_								= hidden_size
      lowercase_								= num_hidden_layers
      lowercase_								= num_attention_heads
      lowercase_								= intermediate_size
      lowercase_								= hidden_act
      lowercase_								= hidden_dropout_prob
      lowercase_								= attention_probs_dropout_prob
      lowercase_								= type_sequence_label_size
      lowercase_								= initializer_range
      lowercase_								= scope

      # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
      lowercase_								= (image_size // patch_size) ** 2
      lowercase_								= num_patches + 1

    def 					_UpperCAmelCase	(				self			:				Tuple):







      """simple docstring"""







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

      lowercase_								= None
      if self.use_labels:
        lowercase_								= ids_tensor([self.batch_size] ,  self.type_sequence_label_size)

      lowercase_								= self.get_config()

      return config, pixel_values, labels

    def 					_UpperCAmelCase	(				self			:				Optional[Any]):







      """simple docstring"""







      return ViTConfig(
          image_size=self.image_size ,  patch_size=self.patch_size ,  num_channels=self.num_channels ,  hidden_size=self.hidden_size ,  num_hidden_layers=self.num_hidden_layers ,  num_attention_heads=self.num_attention_heads ,  intermediate_size=self.intermediate_size ,  hidden_act=self.hidden_act ,  hidden_dropout_prob=self.hidden_dropout_prob ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob ,  is_decoder=lowerCAmelCase_ ,  initializer_range=self.initializer_range ,  )

    def 					_UpperCAmelCase	(				self			:				Dict ,  lowerCAmelCase_			:				Optional[int] ,  lowerCAmelCase_			:				Tuple ,  lowerCAmelCase_			:				Dict):







      """simple docstring"""







      lowercase_								= TFViTModel(config=lowerCAmelCase_)
      lowercase_								= model(lowerCAmelCase_ ,  training=lowerCAmelCase_)
      self.parent.assertEqual(result.last_hidden_state.shape ,  (self.batch_size, self.seq_length, self.hidden_size))

      # Test with an image with different size than the one specified in config.
      lowercase_								= self.image_size // 2
      lowercase_								= pixel_values[:, :, :image_size, :image_size]
      lowercase_								= model(lowerCAmelCase_ ,  interpolate_pos_encoding=lowerCAmelCase_ ,  training=lowerCAmelCase_)
      lowercase_								= (image_size // self.patch_size) ** 2 + 1
      self.parent.assertEqual(result.last_hidden_state.shape ,  (self.batch_size, seq_length, self.hidden_size))

    def 					_UpperCAmelCase	(				self			:				List[Any] ,  lowerCAmelCase_			:				Union[str, Any] ,  lowerCAmelCase_			:				Any ,  lowerCAmelCase_			:				str):







      """simple docstring"""







      lowercase_								= self.type_sequence_label_size
      lowercase_								= TFViTForImageClassification(lowerCAmelCase_)
      lowercase_								= model(lowerCAmelCase_ ,  labels=lowerCAmelCase_ ,  training=lowerCAmelCase_)
      self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.type_sequence_label_size))

      # Test with an image with different size than the one specified in config.
      lowercase_								= self.image_size // 2
      lowercase_								= pixel_values[:, :, :image_size, :image_size]
      lowercase_								= model(lowerCAmelCase_ ,  interpolate_pos_encoding=lowerCAmelCase_ ,  training=lowerCAmelCase_)
      self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.type_sequence_label_size))

      # test greyscale images
      lowercase_								= 1
      lowercase_								= TFViTForImageClassification(lowerCAmelCase_)
      lowercase_								= floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
      lowercase_								= model(lowerCAmelCase_)
      self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.type_sequence_label_size))




    def 					_UpperCAmelCase	(				self			:				Optional[int]):







      """simple docstring"""







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







@require_tf
class    SCREAMING_SNAKE_CASE__ (							__UpperCAmelCase      ,  __UpperCAmelCase      ,  unittest.TestCase   ):
    lowercase__      =   (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
    lowercase__      =   (
        {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification}
        if is_tf_available()
        else {}
    )

    lowercase__      =   False
    lowercase__      =   False
    lowercase__      =   False

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







      """simple docstring"""







      lowercase_								= TFViTModelTester(self)
      lowercase_								= ConfigTester(self ,  config_class=lowerCAmelCase_ ,  has_text_modality=lowerCAmelCase_ ,  hidden_size=3_7)

    def 					_UpperCAmelCase	(				self			:				List[str]):







      """simple docstring"""







      self.config_tester.run_common_tests()

    @unittest.skip(reason="""ViT does not use inputs_embeds""")
    def 					_UpperCAmelCase	(				self			:				List[str]):







      """simple docstring"""







      pass

    @unittest.skip(reason="""ViT does not use inputs_embeds""")
    def 					_UpperCAmelCase	(				self			:				int):







      """simple docstring"""







      pass

    def 					_UpperCAmelCase	(				self			:				Tuple):







      """simple docstring"""







      lowercase_					,    lowercase_								= self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowercase_								= model_class(lowerCAmelCase_)
        self.assertIsInstance(model.get_input_embeddings() ,  (tf.keras.layers.Layer))
        lowercase_								= model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(lowerCAmelCase_ ,  tf.keras.layers.Layer))

    def 					_UpperCAmelCase	(				self			:				Dict):







      """simple docstring"""







      lowercase_					,    lowercase_								= self.model_tester.prepare_config_and_inputs_for_common()

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

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

    def 					_UpperCAmelCase	(				self			:				Optional[int]):







      """simple docstring"""







      lowercase_								= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCAmelCase_)

    def 					_UpperCAmelCase	(				self			:				Any):







      """simple docstring"""







      lowercase_								= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_)




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







      """simple docstring"""







      lowercase_								= TFViTModel.from_pretrained("""google/vit-base-patch16-224""")
      self.assertIsNotNone(lowerCAmelCase_)







def 			_SCREAMING_SNAKE_CASE						() ->						List[Any]:







  '''simple docstring'''


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


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

    @cached_property
    def 					_UpperCAmelCase	(				self			:				Dict):







      """simple docstring"""







      return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""") if is_vision_available() else None




    @slow
    def 					_UpperCAmelCase	(				self			:				Union[str, Any]):







      """simple docstring"""







      lowercase_								= TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""")

      lowercase_								= self.default_image_processor
      lowercase_								= prepare_img()
      lowercase_								= image_processor(images=lowerCAmelCase_ ,  return_tensors="""tf""")

      # forward pass
      lowercase_								= model(**lowerCAmelCase_)

      # verify the logits
      lowercase_								= tf.TensorShape((1, 1_0_0_0))
      self.assertEqual(outputs.logits.shape ,  lowerCAmelCase_)

      lowercase_								= tf.constant([-0.2_744, 0.8_215, -0.0_836])

      tf.debugging.assert_near(outputs.logits[0, :3] ,  lowerCAmelCase_ ,  atol=1E-4)






"""simple docstring"""
def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase							) ->						int:







  '''simple docstring'''


  while a != 0:
    lowercase_					,    lowercase_								= b % a, a
  return b


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase							) ->						int:







  '''simple docstring'''


  if gcd(__lowerCAmelCase ,  __lowerCAmelCase							) != 1:
    lowercase_								= F'''mod inverse of {a!r} and {m!r} does not exist'''
    raise ValueError(__lowerCAmelCase							)
  lowercase_					,    lowercase_					,    lowercase_								= 1, 0, a
  lowercase_					,    lowercase_					,    lowercase_								= 0, 1, m
  while va != 0:
    lowercase_								= ua // va
    lowercase_					,    lowercase_					,    lowercase_					,    lowercase_					,    lowercase_					,    lowercase_								= (ua - q * va), (ua - q * va), (ua - q * va), va, va, va
  return ua % m

