


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







   def __init__(     self						,     UpperCamelCase__						,     UpperCamelCase__=13						,     UpperCamelCase__=30						,     UpperCamelCase__=2						,     UpperCamelCase__=3						,     UpperCamelCase__=True						,     UpperCamelCase__=True						,     UpperCamelCase__=32						,     UpperCamelCase__=2						,     UpperCamelCase__=4						,     UpperCamelCase__=37						,     UpperCamelCase__="gelu"						,     UpperCamelCase__=0.1						,     UpperCamelCase__=0.1						,     UpperCamelCase__=10						,     UpperCamelCase__=0.02						,     UpperCamelCase__=3						,     UpperCamelCase__=None						,     )     ->		Union[str, Any]:

       '''simple docstring'''




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

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







   def 			lowerCamelCase		(     self						)     ->		Tuple:

       '''simple docstring'''




       snake_case   :				Dict				 =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       snake_case   :				Union[str, Any]				 =   None
       if self.use_labels:
           snake_case   :				Any				 =   ids_tensor([self.batch_size]						,     self.type_sequence_label_size						)

       snake_case   :				str				 =   self.get_config()

       return config, pixel_values, labels







   def 			lowerCamelCase		(     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=UpperCamelCase__						,     initializer_range=self.initializer_range						,     )







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)     ->		List[str]:

       '''simple docstring'''




       snake_case   :				str				 =   TFViTModel(config=UpperCamelCase__						)
       snake_case   :				List[Any]				 =   model(UpperCamelCase__						,     training=UpperCamelCase__						)
       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.
       snake_case   :				Dict				 =   self.image_size // 2
       snake_case   :				Optional[Any]				 =   pixel_values[:, :, :image_size, :image_size]
       snake_case   :				str				 =   model(UpperCamelCase__						,     interpolate_pos_encoding=UpperCamelCase__						,     training=UpperCamelCase__						)
       snake_case   :				Optional[int]				 =   (image_size // self.patch_size) ** 2 + 1
       self.parent.assertEqual(result.last_hidden_state.shape						,     (self.batch_size, seq_length, self.hidden_size)						)







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)     ->		Optional[Any]:

       '''simple docstring'''




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

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







   def 			lowerCamelCase		(     self						)     ->		str:

       '''simple docstring'''




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







@require_tf
class _lowerCAmelCase    (				snake_case_   ,							snake_case_   ,							unittest.TestCase     ):
   __UpperCAmelCase			:	List[str]							  =  (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
   __UpperCAmelCase			:	List[Any]							  =  (
       {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification}
       if is_tf_available()
       else {}
   )

   __UpperCAmelCase			:	Tuple							  =  False
   __UpperCAmelCase			:	List[Any]							  =  False
   __UpperCAmelCase			:	Dict							  =  False







   def 			lowerCamelCase		(     self						)     ->		Optional[int]:

       '''simple docstring'''




       snake_case   :				List[Any]				 =   TFViTModelTester(self						)
       snake_case   :				Optional[Any]				 =   ConfigTester(self						,     config_class=UpperCamelCase__						,     has_text_modality=UpperCamelCase__						,     hidden_size=37						)







   def 			lowerCamelCase		(     self						)     ->		Optional[int]:

       '''simple docstring'''




       self.config_tester.run_common_tests()







   @unittest.skip(reason="ViT does not use inputs_embeds"						)
   def 			lowerCamelCase		(     self						)     ->		Dict:

       '''simple docstring'''




       pass







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

       '''simple docstring'''




       pass







   def 			lowerCamelCase		(     self						)     ->		str:

       '''simple docstring'''




       snake_case   :				List[Any]				 =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           snake_case   :				Dict				 =   model_class(UpperCamelCase__						)
           self.assertIsInstance(model.get_input_embeddings()						,     (tf.keras.layers.Layer)						)
           snake_case   :				Optional[int]				 =   model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(UpperCamelCase__						,     tf.keras.layers.Layer						)						)







   def 			lowerCamelCase		(     self						)     ->		Any:

       '''simple docstring'''




       snake_case   :				Any				 =   self.model_tester.prepare_config_and_inputs_for_common()

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

           snake_case   :				Optional[int]				 =   ["pixel_values"]
           self.assertListEqual(arg_names[:1]						,     UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		Union[str, Any]:

       '''simple docstring'''




       snake_case   :				int				 =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		str:

       '''simple docstring'''




       snake_case   :				Optional[int]				 =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__						)







   @slow
   def 			lowerCamelCase		(     self						)     ->		Union[str, Any]:

       '''simple docstring'''




       snake_case   :				Any				 =   TFViTModel.from_pretrained("google/vit-base-patch16-224"						)
       self.assertIsNotNone(UpperCamelCase__						)







def   __lowerCAmelCase						(						)     ->						Any:


    """simple docstring"""





    snake_case   :				Optional[Any]				 =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
    return image







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







   @cached_property
   def 			lowerCamelCase		(     self						)     ->		List[Any]:

       '''simple docstring'''




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







   @slow
   def 			lowerCamelCase		(     self						)     ->		List[Any]:

       '''simple docstring'''




       snake_case   :				Any				 =   TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224"						)

       snake_case   :				Optional[int]				 =   self.default_image_processor
       snake_case   :				int				 =   prepare_img()
       snake_case   :				List[str]				 =   image_processor(images=UpperCamelCase__						,     return_tensors="tf"						)

       # forward pass
       snake_case   :				str				 =   model(**UpperCamelCase__						)

       # verify the logits
       snake_case   :				Any				 =   tf.TensorShape((1, 1000)						)
       self.assertEqual(outputs.logits.shape						,     UpperCamelCase__						)

       snake_case   :				List[str]				 =   tf.constant([-0.2744, 0.8215, -0.0836]						)

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









"""simple docstring"""



from . import __version__

# Backward compatibility imports, to make sure all those objects can be found in file_utils
from .utils import (
    CLOUDFRONT_DISTRIB_PREFIX,
    CONFIG_NAME,
    DISABLE_TELEMETRY,
    DUMMY_INPUTS,
    DUMMY_MASK,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    FEATURE_EXTRACTOR_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    MODEL_CARD_NAME,
    MULTIPLE_CHOICE_DUMMY_INPUTS,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    SENTENCEPIECE_UNDERLINE,
    SPIECE_UNDERLINE,
    TF2_WEIGHTS_NAME,
    TF_WEIGHTS_NAME,
    TORCH_FX_REQUIRED_VERSION,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
    ContextManagers,
    DummyObject,
    EntryNotFoundError,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    TensorType,
    _LazyModule,
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    cached_property,
    copy_func,
    default_cache_path,
    define_sagemaker_information,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    get_torch_version,
    has_file,
    http_user_agent,
    is_apex_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_datasets_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_librosa_available,
    is_offline_mode,
    is_onnx_available,
    is_pandas_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_tensor,
    is_tensorflow_probability_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    replace_return_docstrings,
    requires_backends,
    to_numpy,
    to_py_obj,
    torch_only_method,
)





