from __future__ import annotations

import os
import tempfile
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import is_tensorflow_text_available, is_tf_available
from transformers.testing_utils import require_tensorflow_text, require_tf, slow

from ..test_modeling_tf_common import floats_tensor
from .test_framework_agnostic import GenerationIntegrationTestsMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import (
      AutoTokenizer,
      TFAutoModelForCausalLM,
      TFAutoModelForSeqaSeqLM,
      TFAutoModelForSpeechSeqaSeq,
      TFAutoModelForVisionaSeq,
      TFBartForConditionalGeneration,
      TFLogitsProcessorList,
      TFMinLengthLogitsProcessor,
      tf_top_k_top_p_filtering,
  )

if is_tensorflow_text_available():
  import tensorflow_text as text
@require_tf
class    A_ (       unittest.TestCase ):

  def 		_UpperCAmelCase   (		self :      int       ):
   __a       =  tf.convert_to_tensor(
       [
           [
               8.2_22_09_91,  # 3rd highest value; idx. 0
               -0.5_62_00_44,
               5.23_22_97_52,
               4.0_38_63_93,
               -6.8_79_83_78,
               -0.54_78_58_02,
               -3.2_01_21_53,
               2.92_77_71_76,
               1.88_17_19_53,
               7.35_34_12_76,  # 5th highest value; idx. 9
               8.43_20_78_33,  # 2nd highest value; idx. 10
               -9.85_71_18_36,
               -5.96_20_92_36,
               -1.13_03_91_61,
               -7.1_11_52_94,
               -0.8_36_96_33,
               -5.3_18_64_08,
               7.06_42_74_07,
               0.81_36_93_44,
               -0.82_02_38_17,
               -5.9_17_97_96,
               0.58_81_34_43,
               -6.99_77_84_38,
               4.71_55_11_89,
               -0.18_77_16_37,
               7.44_02_07_59,  # 4th highest value; idx. 25
               9.38_45_09_87,  # 1st highest value; idx. 26
               2.12_66_29_41,
               -9.32_56_20_38,
               2.35_65_25_22,
           ],  # cummulative prob of 5 highest values <= 0.6
           [
               0.58_42_55_18,
               4.53_13_92_38,
               -5.57_51_04_64,
               -6.28_03_06_99,
               -7.19_52_95_03,
               -4.02_12_25_51,
               1.39_33_70_37,
               -6.06_70_70_57,
               1.59_48_05_17,
               -9.64_31_19,
               0.03_90_77_99,
               0.67_23_17_62,
               -8.88_20_67_26,
               6.27_11_59_22,  # 4th highest value; idx. 13
               2.28_52_07_23,
               4.82_76_75_06,
               4.30_42_13_68,
               8.8_27_53_13,  # 2nd highest value; idx. 17
               5.44_02_99_58,  # 5th highest value; idx. 18
               -4.4_73_57_94,
               7.38_57_95_36,  # 3rd highest value; idx. 20
               -2.91_05_16_63,
               2.61_94_60_77,
               -2.5_67_47_62,
               -9.48_95_93_02,
               -4.02_92_26_45,
               -1.35_41_69_18,
               9.67_70_23_23,  # 1st highest value; idx. 27
               -5.89_47_85_53,
               1.85_37_04_67,
           ],  # cummulative prob of 5 highest values <= 0.6
       ]     ,							dtype=tf.floataa     ,							)

   __a       =  tf.convert_to_tensor(
       [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]]     ,							dtype=tf.intaa     ,							)  # expected non filtered idx as noted above

   __a       =  tf.convert_to_tensor(
       [8.22_20_99, 7.3_53_41_26, 8.43_20_78, 7.4_40_20_75, 9.3_84_51, 6.27_11_59, 8.82_75_31, 5.4_40_29_95, 7.3_85_79_56, 9.67_70_23]     ,							dtype=tf.floataa     ,							)  # expected non filtered values as noted above

   __a       =  tf_top_k_top_p_filtering(__SCREAMING_SNAKE_CASE     ,							top_k=10     ,							top_p=0.6     ,							min_tokens_to_keep=4       )

   __a       =  output[output != -float("inf"       )]
   __a       =  tf.cast(
       tf.where(tf.not_equal(__SCREAMING_SNAKE_CASE     ,							tf.constant(-float("inf"       )     ,							dtype=tf.floataa       )       )       )     ,							dtype=tf.intaa     ,							)

   tf.debugging.assert_near(__SCREAMING_SNAKE_CASE     ,							__SCREAMING_SNAKE_CASE     ,							rtol=1E-12       )
   tf.debugging.assert_equal(__SCREAMING_SNAKE_CASE     ,							__SCREAMING_SNAKE_CASE       )
@require_tf
class    A_ (       unittest.TestCase			,       a_ ):
  # setting framework_dependent_parameters needs to be gated, just like its contents' imports
  if is_tf_available():
    _SCREAMING_SNAKE_CASE    				=			{
        """AutoModelForCausalLM""": TFAutoModelForCausalLM,
        """AutoModelForSpeechSeq2Seq""": TFAutoModelForSpeechSeqaSeq,
        """AutoModelForSeq2SeqLM""": TFAutoModelForSeqaSeqLM,
        """AutoModelForVision2Seq""": TFAutoModelForVisionaSeq,
        """LogitsProcessorList""": TFLogitsProcessorList,
        """MinLengthLogitsProcessor""": TFMinLengthLogitsProcessor,
        """create_tensor_fn""": tf.convert_to_tensor,
        """floats_tensor""": floats_tensor,
        """return_tensors""": """tf""",
    }

  @slow
  def 		_UpperCAmelCase   (		self :      List[str]       ):
   # TF-only test: tf.saved_model export
   __a       =  TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2"       )
   __a       =  2
   __a       =  2
   class    A_ (       tf.Module ):

     def __init__(		self :      Optional[Any]     ,							__SCREAMING_SNAKE_CASE :      List[str]       ):
      super(__SCREAMING_SNAKE_CASE     ,							self       ).__init__()
      __a       =  model

     @tf.function(
         input_signature=(
             tf.TensorSpec((None, input_length)     ,							tf.intaa     ,							name="input_ids"       ),
             tf.TensorSpec((None, input_length)     ,							tf.intaa     ,							name="attention_mask"       ),
         )     ,							jit_compile=__SCREAMING_SNAKE_CASE     ,							)
     def 		_UpperCAmelCase   (		self :      List[str]     ,							__SCREAMING_SNAKE_CASE :      Any     ,							__SCREAMING_SNAKE_CASE :      int       ):
      __a       =  self.model.generate(
          input_ids=__SCREAMING_SNAKE_CASE     ,							attention_mask=__SCREAMING_SNAKE_CASE     ,							max_new_tokens=__SCREAMING_SNAKE_CASE     ,							return_dict_in_generate=__SCREAMING_SNAKE_CASE     ,							)
      return {"sequences": outputs["sequences"]}
   __a       =  [[2, 0], [1_02, 1_03]]
   __a       =  [[1, 0], [1, 1]]
   __a       =  DummyModel(model=__SCREAMING_SNAKE_CASE       )
   with tempfile.TemporaryDirectory() as tmp_dir:
    tf.saved_model.save(__SCREAMING_SNAKE_CASE     ,							__SCREAMING_SNAKE_CASE     ,							signatures={"serving_default": dummy_model.serving}       )
    __a       =  tf.saved_model.load(__SCREAMING_SNAKE_CASE       ).signatures["serving_default"]
    for batch_size in range(1     ,							len(__SCREAMING_SNAKE_CASE       ) + 1       ):
     __a       =  {
         "input_ids": tf.constant(dummy_input_ids[:batch_size]       ),
         "attention_mask": tf.constant(dummy_attention_masks[:batch_size]       ),
     }
     __a       =  serving_func(**__SCREAMING_SNAKE_CASE       )["sequences"]
     __a       =  test_model.generate(**__SCREAMING_SNAKE_CASE     ,							max_new_tokens=__SCREAMING_SNAKE_CASE       )
     tf.debugging.assert_equal(__SCREAMING_SNAKE_CASE     ,							__SCREAMING_SNAKE_CASE       )

  @slow
  def 		_UpperCAmelCase   (		self :      Dict       ):
   # TF-only test: tf.saved_model export
   __a       =  TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2"       )
   __a       =  1
   __a       =  2
   class    A_ (       tf.Module ):

     def __init__(		self :      Any     ,							__SCREAMING_SNAKE_CASE :      List[str]       ):
      super(__SCREAMING_SNAKE_CASE     ,							self       ).__init__()
      __a       =  model

     @tf.function(
         input_signature=(
             tf.TensorSpec((batch_size, None)     ,							tf.intaa     ,							name="input_ids"       ),
             tf.TensorSpec((batch_size, None)     ,							tf.intaa     ,							name="attention_mask"       ),
         )     ,							jit_compile=__SCREAMING_SNAKE_CASE     ,							)
     def 		_UpperCAmelCase   (		self :      List[Any]     ,							__SCREAMING_SNAKE_CASE :      int     ,							__SCREAMING_SNAKE_CASE :      Dict       ):
      __a       =  self.model.generate(
          input_ids=__SCREAMING_SNAKE_CASE     ,							attention_mask=__SCREAMING_SNAKE_CASE     ,							max_new_tokens=__SCREAMING_SNAKE_CASE     ,							return_dict_in_generate=__SCREAMING_SNAKE_CASE     ,							)
      return {"sequences": outputs["sequences"]}
   __a       =  [[2], [1_02, 1_03]]
   __a       =  [[1], [1, 1]]
   __a       =  DummyModel(model=__SCREAMING_SNAKE_CASE       )
   with tempfile.TemporaryDirectory() as tmp_dir:
    tf.saved_model.save(__SCREAMING_SNAKE_CASE     ,							__SCREAMING_SNAKE_CASE     ,							signatures={"serving_default": dummy_model.serving}       )
    __a       =  tf.saved_model.load(__SCREAMING_SNAKE_CASE       ).signatures["serving_default"]
    for input_row in range(len(__SCREAMING_SNAKE_CASE       )       ):
     __a       =  {
         "input_ids": tf.constant([dummy_input_ids[input_row]]       ),
         "attention_mask": tf.constant([dummy_attention_masks[input_row]]       ),
     }
     __a       =  serving_func(**__SCREAMING_SNAKE_CASE       )["sequences"]
     __a       =  test_model.generate(**__SCREAMING_SNAKE_CASE     ,							max_new_tokens=__SCREAMING_SNAKE_CASE       )
     tf.debugging.assert_equal(__SCREAMING_SNAKE_CASE     ,							__SCREAMING_SNAKE_CASE       )

  @slow
  @require_tensorflow_text
  def 		_UpperCAmelCase   (		self :      List[Any]       ):
   # TF-only test: tf.saved_model export
   with tempfile.TemporaryDirectory() as tmp_dir:
    # file needed to load the TF tokenizer
    hf_hub_download(repo_id="google/flan-t5-small"     ,							filename="spiece.model"     ,							local_dir=__SCREAMING_SNAKE_CASE       )
    class    A_ (       tf.keras.layers.Layer ):

      def __init__(		self :      Dict       ):
       super().__init__()
       __a       =  text.SentencepieceTokenizer(
           model=tf.io.gfile.GFile(os.path.join(__SCREAMING_SNAKE_CASE     ,							"spiece.model"       )     ,							"rb"       ).read()       )
       __a       =  TFAutoModelForSeqaSeqLM.from_pretrained("hf-internal-testing/tiny-random-t5"       )

      def 		_UpperCAmelCase   (		self :      Dict     ,							__SCREAMING_SNAKE_CASE :      int     ,							*__SCREAMING_SNAKE_CASE :      Optional[Any]     ,							**__SCREAMING_SNAKE_CASE :      Union[str, Any]       ):
       __a       =  self.tokenizer.tokenize(__SCREAMING_SNAKE_CASE       )
       __a       ,     __a       =  text.pad_model_inputs(
           __SCREAMING_SNAKE_CASE     ,							max_seq_length=64     ,							pad_value=self.model.config.pad_token_id       )
       __a       =  self.model.generate(input_ids=__SCREAMING_SNAKE_CASE     ,							attention_mask=__SCREAMING_SNAKE_CASE       )
       return self.tokenizer.detokenize(__SCREAMING_SNAKE_CASE       )
    __a       =  CompleteSentenceTransformer()
    __a       =  tf.keras.layers.Input(shape=(1,)     ,							dtype=tf.string     ,							name="inputs"       )
    __a       =  complete_model(__SCREAMING_SNAKE_CASE       )
    __a       =  tf.keras.Model(__SCREAMING_SNAKE_CASE     ,							__SCREAMING_SNAKE_CASE       )
    keras_model.save(__SCREAMING_SNAKE_CASE       )

  def 		_UpperCAmelCase   (		self :      List[str]       ):
   # Has PT equivalent: this test relies on random sampling
   __a       =  {
       "do_sample": True,
       "num_beams": 1,
       "top_p": 0.7,
       "top_k": 10,
       "temperature": 0.7,
   }
   __a       =  14

   __a       =  AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2"       )
   __a       =  "Hello, my dog is cute and"
   __a       =  tokenizer(__SCREAMING_SNAKE_CASE     ,							return_tensors="tf"       )
   __a       =  TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2"       )

   __a       =  6_38
   # forces the generation to happen on CPU, to avoid GPU-related quirks
   with tf.device(":/CPU:0"       ):
    tf.random.set_seed(0       )
    __a       =  model.generate(**__SCREAMING_SNAKE_CASE     ,							eos_token_id=__SCREAMING_SNAKE_CASE     ,							**__SCREAMING_SNAKE_CASE       )
   self.assertTrue(expectation == len(generated_tokens[0]       )       )

   __a       =  [6_38, 1_98]
   with tf.device(":/CPU:0"       ):
    tf.random.set_seed(0       )
    __a       =  model.generate(**__SCREAMING_SNAKE_CASE     ,							eos_token_id=__SCREAMING_SNAKE_CASE     ,							**__SCREAMING_SNAKE_CASE       )
   self.assertTrue(expectation == len(generated_tokens[0]       )       )

  def 		_UpperCAmelCase   (		self :      Union[str, Any]       ):
   # Has PT equivalent: ample use of framework-specific code
   __a       =  AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart"       )
   __a       =  "Hugging Face is a technology company based in New York and Paris."
   __a       =  bart_tokenizer(__SCREAMING_SNAKE_CASE     ,							return_tensors="tf"       ).input_ids
   __a       =  TFBartForConditionalGeneration.from_pretrained("hf-internal-testing/tiny-random-bart"       )
   __a       =  bart_model.generate(__SCREAMING_SNAKE_CASE       ).numpy()
   class    A_ (       a_ ):

     def 		_UpperCAmelCase   (		self :      List[str]     ,							__SCREAMING_SNAKE_CASE :      str     ,							__SCREAMING_SNAKE_CASE :      List[str]=None     ,							**__SCREAMING_SNAKE_CASE :      Optional[int]       ):
      return super().call(__SCREAMING_SNAKE_CASE     ,							**__SCREAMING_SNAKE_CASE       )
   __a       =  FakeBart.from_pretrained("hf-internal-testing/tiny-random-bart"       )
   __a       =  bart_model.generate(__SCREAMING_SNAKE_CASE     ,							foo="bar"       ).numpy()
   self.assertTrue(np.array_equal(__SCREAMING_SNAKE_CASE     ,							__SCREAMING_SNAKE_CASE       )       )
   class    A_ (       bart_model.model.encoder.__class__ ):

     def 		_UpperCAmelCase   (		self :      Union[str, Any]     ,							__SCREAMING_SNAKE_CASE :      Dict     ,							**__SCREAMING_SNAKE_CASE :      Dict       ):
      return super().call(__SCREAMING_SNAKE_CASE     ,							**__SCREAMING_SNAKE_CASE       )
   __a       =  FakeEncoder(bart_model.config     ,							bart_model.model.shared       )
   __a       =  fake_encoder

   # Normal generation still works (the output will be different because the encoder weights are different)
   __a       =  bart_model.generate(__SCREAMING_SNAKE_CASE       ).numpy()
   with self.assertRaises(__SCREAMING_SNAKE_CASE       ):
    # FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo"
    bart_model.generate(__SCREAMING_SNAKE_CASE     ,							foo="bar"       )



import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    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 torch import nn

  from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
  from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import ViTImageProcessor
class    A_ :

  def __init__(		self :      Union[str, Any]     ,							__SCREAMING_SNAKE_CASE :      Optional[int]     ,							__SCREAMING_SNAKE_CASE :      List[Any]=13     ,							__SCREAMING_SNAKE_CASE :      Optional[Any]=30     ,							__SCREAMING_SNAKE_CASE :      Optional[Any]=2     ,							__SCREAMING_SNAKE_CASE :      Optional[int]=3     ,							__SCREAMING_SNAKE_CASE :      List[Any]=True     ,							__SCREAMING_SNAKE_CASE :      Dict=True     ,							__SCREAMING_SNAKE_CASE :      Optional[int]=32     ,							__SCREAMING_SNAKE_CASE :      str=5     ,							__SCREAMING_SNAKE_CASE :      List[str]=4     ,							__SCREAMING_SNAKE_CASE :      List[Any]=37     ,							__SCREAMING_SNAKE_CASE :      int="gelu"     ,							__SCREAMING_SNAKE_CASE :      List[Any]=0.1     ,							__SCREAMING_SNAKE_CASE :      Optional[Any]=0.1     ,							__SCREAMING_SNAKE_CASE :      List[Any]=10     ,							__SCREAMING_SNAKE_CASE :      int=0.02     ,							__SCREAMING_SNAKE_CASE :      Dict=None     ,							__SCREAMING_SNAKE_CASE :      str=2     ,							):
   __a       =  parent
   __a       =  batch_size
   __a       =  image_size
   __a       =  patch_size
   __a       =  num_channels
   __a       =  is_training
   __a       =  use_labels
   __a       =  hidden_size
   __a       =  num_hidden_layers
   __a       =  num_attention_heads
   __a       =  intermediate_size
   __a       =  hidden_act
   __a       =  hidden_dropout_prob
   __a       =  attention_probs_dropout_prob
   __a       =  type_sequence_label_size
   __a       =  initializer_range
   __a       =  scope
   __a       =  encoder_stride

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

  def 		_UpperCAmelCase   (		self :      Any       ):
   __a       =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

   __a       =  self.get_config()

   return config, pixel_values, labels

  def 		_UpperCAmelCase   (		self :      str       ):
   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=__SCREAMING_SNAKE_CASE     ,							initializer_range=self.initializer_range     ,							encoder_stride=self.encoder_stride     ,							)

  def 		_UpperCAmelCase   (		self :      Dict     ,							__SCREAMING_SNAKE_CASE :      List[Any]     ,							__SCREAMING_SNAKE_CASE :      Dict     ,							__SCREAMING_SNAKE_CASE :      Any       ):
   __a       =  ViTModel(config=__SCREAMING_SNAKE_CASE       )
   model.to(__SCREAMING_SNAKE_CASE       )
   model.eval()
   __a       =  model(__SCREAMING_SNAKE_CASE       )
   self.parent.assertEqual(result.last_hidden_state.shape     ,							(self.batch_size, self.seq_length, self.hidden_size)       )

  def 		_UpperCAmelCase   (		self :      Union[str, Any]     ,							__SCREAMING_SNAKE_CASE :      Tuple     ,							__SCREAMING_SNAKE_CASE :      str     ,							__SCREAMING_SNAKE_CASE :      Dict       ):
   __a       =  ViTForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE       )
   model.to(__SCREAMING_SNAKE_CASE       )
   model.eval()
   __a       =  model(__SCREAMING_SNAKE_CASE       )
   self.parent.assertEqual(
       result.reconstruction.shape     ,							(self.batch_size, self.num_channels, self.image_size, self.image_size)       )

   # test greyscale images
   __a       =  1
   __a       =  ViTForMaskedImageModeling(__SCREAMING_SNAKE_CASE       )
   model.to(__SCREAMING_SNAKE_CASE       )
   model.eval()

   __a       =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
   __a       =  model(__SCREAMING_SNAKE_CASE       )
   self.parent.assertEqual(result.reconstruction.shape     ,							(self.batch_size, 1, self.image_size, self.image_size)       )

  def 		_UpperCAmelCase   (		self :      Optional[Any]     ,							__SCREAMING_SNAKE_CASE :      Tuple     ,							__SCREAMING_SNAKE_CASE :      Union[str, Any]     ,							__SCREAMING_SNAKE_CASE :      List[str]       ):
   __a       =  self.type_sequence_label_size
   __a       =  ViTForImageClassification(__SCREAMING_SNAKE_CASE       )
   model.to(__SCREAMING_SNAKE_CASE       )
   model.eval()
   __a       =  model(__SCREAMING_SNAKE_CASE     ,							labels=__SCREAMING_SNAKE_CASE       )
   self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.type_sequence_label_size)       )

   # test greyscale images
   __a       =  1
   __a       =  ViTForImageClassification(__SCREAMING_SNAKE_CASE       )
   model.to(__SCREAMING_SNAKE_CASE       )
   model.eval()

   __a       =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
   __a       =  model(__SCREAMING_SNAKE_CASE       )
   self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.type_sequence_label_size)       )

  def 		_UpperCAmelCase   (		self :      List[Any]       ):
   __a       =  self.prepare_config_and_inputs()
   (
       (
       __a
   )       ,     (
       __a
   )       ,     (
       __a
   )       ,     
   )       =  config_and_inputs
   __a       =  {"pixel_values": pixel_values}
   return config, inputs_dict
@require_torch
class    A_ (       a_			,       a_			,       unittest.TestCase ):
  _SCREAMING_SNAKE_CASE    				=			(
      (
          ViTModel,
          ViTForImageClassification,
          ViTForMaskedImageModeling,
      )
      if is_torch_available()
      else ()
  )
  _SCREAMING_SNAKE_CASE    				=			(
      {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification}
      if is_torch_available()
      else {}
  )
  _SCREAMING_SNAKE_CASE    				=			True

  _SCREAMING_SNAKE_CASE    				=			False
  _SCREAMING_SNAKE_CASE    				=			False
  _SCREAMING_SNAKE_CASE    				=			False

  def 		_UpperCAmelCase   (		self :      Optional[Any]       ):
   __a       =  ViTModelTester(self       )
   __a       =  ConfigTester(self     ,							config_class=__SCREAMING_SNAKE_CASE     ,							has_text_modality=__SCREAMING_SNAKE_CASE     ,							hidden_size=37       )

  def 		_UpperCAmelCase   (		self :      List[str]       ):
   self.config_tester.run_common_tests()

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

  def 		_UpperCAmelCase   (		self :      int       ):
   __a       ,     __a       =  self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    __a       =  model_class(__SCREAMING_SNAKE_CASE       )
    self.assertIsInstance(model.get_input_embeddings()     ,							(nn.Module)       )
    __a       =  model.get_output_embeddings()
    self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE     ,							nn.Linear       )       )

  def 		_UpperCAmelCase   (		self :      Optional[int]       ):
   __a       ,     __a       =  self.model_tester.prepare_config_and_inputs_for_common()

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

    __a       =  ["pixel_values"]
    self.assertListEqual(arg_names[:1]     ,							__SCREAMING_SNAKE_CASE       )

  def 		_UpperCAmelCase   (		self :      List[str]       ):
   __a       =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE       )

  def 		_UpperCAmelCase   (		self :      Any       ):
   __a       =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE       )

  def 		_UpperCAmelCase   (		self :      Tuple       ):
   __a       =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE       )

  @slow
  def 		_UpperCAmelCase   (		self :      Dict       ):
   for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    __a       =  ViTModel.from_pretrained(__SCREAMING_SNAKE_CASE       )
    self.assertIsNotNone(__SCREAMING_SNAKE_CASE       )



def   __A		(			):



 """simple docstring"""


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






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

  @cached_property
  def 		_UpperCAmelCase   (		self :      List[str]       ):
   return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224"       ) if is_vision_available() else None

  @slow
  def 		_UpperCAmelCase   (		self :      str       ):
   __a       =  ViTForImageClassification.from_pretrained("google/vit-base-patch16-224"       ).to(__SCREAMING_SNAKE_CASE       )

   __a       =  self.default_image_processor
   __a       =  prepare_img()
   __a       =  image_processor(images=__SCREAMING_SNAKE_CASE     ,							return_tensors="pt"       ).to(__SCREAMING_SNAKE_CASE       )

   # forward pass
   with torch.no_grad():
    __a       =  model(**__SCREAMING_SNAKE_CASE       )

   # verify the logits
   __a       =  torch.Size((1, 10_00)       )
   self.assertEqual(outputs.logits.shape     ,							__SCREAMING_SNAKE_CASE       )

   __a       =  torch.tensor([-0.27_44, 0.82_15, -0.08_36]       ).to(__SCREAMING_SNAKE_CASE       )

   self.assertTrue(torch.allclose(outputs.logits[0, :3]     ,							__SCREAMING_SNAKE_CASE     ,							atol=1E-4       )       )

  @slow
  def 		_UpperCAmelCase   (		self :      Union[str, Any]       ):
   # ViT models have an `interpolate_pos_encoding` argument in their forward method,
   # allowing to interpolate the pre-trained position embeddings in order to use
   # the model on higher resolutions. The DINO model by Facebook AI leverages this
   # to visualize self-attention on higher resolution images.
   __a       =  ViTModel.from_pretrained("facebook/dino-vits8"       ).to(__SCREAMING_SNAKE_CASE       )

   __a       =  ViTImageProcessor.from_pretrained("facebook/dino-vits8"     ,							size=4_80       )
   __a       =  prepare_img()
   __a       =  image_processor(images=__SCREAMING_SNAKE_CASE     ,							return_tensors="pt"       )
   __a       =  inputs.pixel_values.to(__SCREAMING_SNAKE_CASE       )

   # forward pass
   with torch.no_grad():
    __a       =  model(__SCREAMING_SNAKE_CASE     ,							interpolate_pos_encoding=__SCREAMING_SNAKE_CASE       )

   # verify the logits
   __a       =  torch.Size((1, 36_01, 3_84)       )
   self.assertEqual(outputs.last_hidden_state.shape     ,							__SCREAMING_SNAKE_CASE       )

   __a       =  torch.tensor(
       [[4.23_40, 4.39_06, -6.66_92], [4.54_63, 1.89_28, -6.72_57], [4.44_29, 0.84_96, -5.85_85]]       ).to(__SCREAMING_SNAKE_CASE       )

   self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]     ,							__SCREAMING_SNAKE_CASE     ,							atol=1E-4       )       )

  @slow
  @require_accelerate
  @require_torch_gpu
  def 		_UpperCAmelCase   (		self :      Any       ):
   __a       =  ViTModel.from_pretrained("facebook/dino-vits8"     ,							torch_dtype=torch.floataa     ,							device_map="auto"       )
   __a       =  self.default_image_processor

   __a       =  prepare_img()
   __a       =  image_processor(images=__SCREAMING_SNAKE_CASE     ,							return_tensors="pt"       )
   __a       =  inputs.pixel_values.to(__SCREAMING_SNAKE_CASE       )

   # forward pass to make sure inference works in fp16
   with torch.no_grad():
    __a       =  model(__SCREAMING_SNAKE_CASE       )


