
'''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 							UpperCAmelCase_							:

 '''simple docstring'''







 def __init__(					self		:  Optional[int]			,				snake_case__		:  int			,				snake_case__		:  Tuple=13			,				snake_case__		:  Tuple=30			,				snake_case__		:  Optional[Any]=2			,				snake_case__		:  Optional[Any]=3			,				snake_case__		:  Optional[int]=True			,				snake_case__		:  Union[str, Any]=True			,				snake_case__		:  Union[str, Any]=32			,				snake_case__		:  List[Any]=2			,				snake_case__		:  Optional[Any]=4			,				snake_case__		:  Dict=37			,				snake_case__		:  List[str]="gelu"			,				snake_case__		:  Dict=0.1			,				snake_case__		:  Tuple=0.1			,				snake_case__		:  Optional[Any]=10			,				snake_case__		:  List[Any]=0.02			,				snake_case__		:  Tuple=3			,				snake_case__		:  Optional[Any]=None			,				):



   '''simple docstring'''




   UpperCAmelCase__      :					Tuple				       =							parent
   UpperCAmelCase__      :					Union[str, Any]				       =							batch_size
   UpperCAmelCase__      :					Dict				       =							image_size
   UpperCAmelCase__      :					Dict				       =							patch_size
   UpperCAmelCase__      :					Dict				       =							num_channels
   UpperCAmelCase__      :					Dict				       =							is_training
   UpperCAmelCase__      :					List[Any]				       =							use_labels
   UpperCAmelCase__      :					Optional[Any]				       =							hidden_size
   UpperCAmelCase__      :					Optional[int]				       =							num_hidden_layers
   UpperCAmelCase__      :					Any				       =							num_attention_heads
   UpperCAmelCase__      :					Union[str, Any]				       =							intermediate_size
   UpperCAmelCase__      :					Optional[int]				       =							hidden_act
   UpperCAmelCase__      :					Optional[Any]				       =							hidden_dropout_prob
   UpperCAmelCase__      :					Optional[Any]				       =							attention_probs_dropout_prob
   UpperCAmelCase__      :					Tuple				       =							type_sequence_label_size
   UpperCAmelCase__      :					List[Any]				       =							initializer_range
   UpperCAmelCase__      :					Optional[Any]				       =							scope

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







 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					str				       =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

   UpperCAmelCase__      :					str				       =							None
   if self.use_labels:
     UpperCAmelCase__      :					Tuple				       =							ids_tensor([self.batch_size]			,				self.type_sequence_label_size )

   UpperCAmelCase__      :					str				       =							self.get_config()

   return config, pixel_values, labels







 def 							UpperCamelCase  (					self		:  List[str] ):



   '''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=snake_case__			,				initializer_range=self.initializer_range			,				)







 def 							UpperCamelCase  (					self		:  int			,				snake_case__		:  Tuple			,				snake_case__		:  Tuple			,				snake_case__		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					str				       =							TFViTModel(config=snake_case__ )
   UpperCAmelCase__      :					str				       =							model(snake_case__			,				training=snake_case__ )
   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.
   UpperCAmelCase__      :					Union[str, Any]				       =							self.image_size // 2
   UpperCAmelCase__      :					List[Any]				       =							pixel_values[:, :, :image_size, :image_size]
   UpperCAmelCase__      :					Optional[Any]				       =							model(snake_case__			,				interpolate_pos_encoding=snake_case__			,				training=snake_case__ )
   UpperCAmelCase__      :					List[Any]				       =							(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		:  Tuple			,				snake_case__		:  Union[str, Any]			,				snake_case__		:  Optional[int]			,				snake_case__		:  Any ):



   '''simple docstring'''




   UpperCAmelCase__      :					Any				       =							self.type_sequence_label_size
   UpperCAmelCase__      :					List[Any]				       =							TFViTForImageClassification(snake_case__ )
   UpperCAmelCase__      :					List[str]				       =							model(snake_case__			,				labels=snake_case__			,				training=snake_case__ )
   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.
   UpperCAmelCase__      :					Dict				       =							self.image_size // 2
   UpperCAmelCase__      :					List[Any]				       =							pixel_values[:, :, :image_size, :image_size]
   UpperCAmelCase__      :					Tuple				       =							model(snake_case__			,				interpolate_pos_encoding=snake_case__			,				training=snake_case__ )
   self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.type_sequence_label_size) )

   # test greyscale images
   UpperCAmelCase__      :					Tuple				       =							1
   UpperCAmelCase__      :					Optional[int]				       =							TFViTForImageClassification(snake_case__ )
   UpperCAmelCase__      :					Dict				       =							floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
   UpperCAmelCase__      :					List[Any]				       =							model(snake_case__ )
   self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.type_sequence_label_size) )







 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[Any]				       =							self.prepare_config_and_inputs()
   UpperCAmelCase__       ,			UpperCAmelCase__       ,			UpperCAmelCase__      :					Optional[Any]				       =							config_and_inputs
   UpperCAmelCase__      :					Tuple				       =							{"pixel_values": pixel_values}
   return config, inputs_dict






@require_tf
class 							UpperCAmelCase_							(    A					,				A					,				unittest.TestCase				):

 '''simple docstring'''
 lowercase_					:    Optional[Any]				=							(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
 lowercase_					:    Tuple				=							(
     {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification}
     if is_tf_available()
     else {}
 )

 lowercase_					:    List[Any]				=							False
 lowercase_					:    Optional[int]				=							False
 lowercase_					:    Any				=							False







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					Dict				       =							TFViTModelTester(self )
   UpperCAmelCase__      :					Any				       =							ConfigTester(self			,				config_class=snake_case__			,				has_text_modality=snake_case__			,				hidden_size=37 )







 def 							UpperCamelCase  (					self		:  Optional[Any] ):



   '''simple docstring'''




   self.config_tester.run_common_tests()







 @unittest.skip(reason="ViT does not use inputs_embeds" )
 def 							UpperCamelCase  (					self		:  Optional[Any] ):



   '''simple docstring'''




   pass







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



   '''simple docstring'''




   pass







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




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

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







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__       ,			UpperCAmelCase__      :					int				       =							self.model_tester.prepare_config_and_inputs_for_common()

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

     UpperCAmelCase__      :					Dict				       =							["pixel_values"]
     self.assertListEqual(arg_names[:1]			,				snake_case__ )







 def 							UpperCamelCase  (					self		:  Optional[Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[Any]				       =							self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*snake_case__ )







 def 							UpperCamelCase  (					self		:  Optional[Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*snake_case__ )







 @slow
 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							TFViTModel.from_pretrained("google/vit-base-patch16-224" )
   self.assertIsNotNone(snake_case__ )







def snake_case_     (					):
  UpperCAmelCase__      :					int				       =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
  return image






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

 '''simple docstring'''







 @cached_property
 def 							UpperCamelCase  (					self		:  Optional[Any] ):



   '''simple docstring'''




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







 @slow
 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




   UpperCAmelCase__      :					Dict				       =							TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224" )

   UpperCAmelCase__      :					Optional[int]				       =							self.default_image_processor
   UpperCAmelCase__      :					Tuple				       =							prepare_img()
   UpperCAmelCase__      :					Union[str, Any]				       =							image_processor(images=snake_case__			,				return_tensors="tf" )

   # forward pass
   UpperCAmelCase__      :					List[Any]				       =							model(**snake_case__ )

   # verify the logits
   UpperCAmelCase__      :					Any				       =							tf.TensorShape((1, 10_00) )
   self.assertEqual(outputs.logits.shape			,				snake_case__ )

   UpperCAmelCase__      :					List[Any]				       =							tf.constant([-0.2744, 0.8215, -0.0836] )

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





'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available


SCREAMING_SNAKE_CASE     =       {}

try:
      if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE     =       ["""GPTSw3Tokenizer"""]


if TYPE_CHECKING:
      try:
            if not is_sentencepiece_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_gpt_swa import GPTSwaTokenizer

else:
      import sys

      SCREAMING_SNAKE_CASE     =       _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



