





'''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]      ,						lowerCamelCase_				:			int      ,						lowerCamelCase_				:			Tuple=13      ,						lowerCamelCase_				:			Tuple=30      ,						lowerCamelCase_				:			Optional[Any]=2      ,						lowerCamelCase_				:			Optional[Any]=3      ,						lowerCamelCase_				:			Optional[int]=True      ,						lowerCamelCase_				:			Union[str, Any]=True      ,						lowerCamelCase_				:			Union[str, Any]=32      ,						lowerCamelCase_				:			List[Any]=2      ,						lowerCamelCase_				:			Optional[Any]=4      ,						lowerCamelCase_				:			Dict=37      ,						lowerCamelCase_				:			List[str]="gelu"      ,						lowerCamelCase_				:			Dict=0.1      ,						lowerCamelCase_				:			Tuple=0.1      ,						lowerCamelCase_				:			Optional[Any]=10      ,						lowerCamelCase_				:			List[Any]=0.02      ,						lowerCamelCase_				:			Tuple=3      ,						lowerCamelCase_				:			Optional[Any]=None      ,						):

							'''simple docstring'''



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

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


					def lowerCamelCase_			(						self				:			List[Any]						):

							'''simple docstring'''



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

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

							SCREAMING_SNAKE_CASE :				str		=			self.get_config()

							return config, pixel_values, labels


					def lowerCamelCase_			(						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 lowerCamelCase_			(						self				:			int      ,						lowerCamelCase_				:			Tuple      ,						lowerCamelCase_				:			Tuple      ,						lowerCamelCase_				:			str						):

							'''simple docstring'''



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

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Any		=			self.type_sequence_label_size
							SCREAMING_SNAKE_CASE :				List[Any]		=			TFViTForImageClassification(snake_case__						)
							SCREAMING_SNAKE_CASE :				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.
							SCREAMING_SNAKE_CASE :				Dict		=			self.image_size // 2
							SCREAMING_SNAKE_CASE :				List[Any]		=			pixel_values[:, :, :image_size, :image_size]
							SCREAMING_SNAKE_CASE :				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
							SCREAMING_SNAKE_CASE :				Tuple		=			1
							SCREAMING_SNAKE_CASE :				Optional[int]		=			TFViTForImageClassification(snake_case__						)
							SCREAMING_SNAKE_CASE :				Dict		=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
							SCREAMING_SNAKE_CASE :				List[Any]		=			model(snake_case__						)
							self.parent.assertEqual(result.logits.shape      ,						(self.batch_size, self.type_sequence_label_size)						)



					def lowerCamelCase_			(						self				:			Tuple						):

							'''simple docstring'''



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







@require_tf
class      UpperCamelCase__					(					lowercase_						,					lowercase_						,					unittest.TestCase			):




					"""simple docstring"""
					SCREAMING_SNAKE_CASE__				=	(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
					SCREAMING_SNAKE_CASE__				=	(
					    {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification}
					    if is_tf_available()
					    else {}
					)

					SCREAMING_SNAKE_CASE__				=	False
					SCREAMING_SNAKE_CASE__				=	False
					SCREAMING_SNAKE_CASE__				=	False


					def lowerCamelCase_			(						self				:			str						):

							'''simple docstring'''



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


					def lowerCamelCase_			(						self				:			Optional[Any]						):

							'''simple docstring'''



							self.config_tester.run_common_tests()


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

							'''simple docstring'''



							pass


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

							'''simple docstring'''



							pass


					def lowerCamelCase_			(						self				:			str						):

							'''simple docstring'''



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

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


					def lowerCamelCase_			(						self				:			int						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				int		=			self.model_tester.prepare_config_and_inputs_for_common()

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

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


					def lowerCamelCase_			(						self				:			Optional[Any]						):

							'''simple docstring'''



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


					def lowerCamelCase_			(						self				:			Optional[Any]						):

							'''simple docstring'''



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



					@slow
					def lowerCamelCase_			(						self				:			str						):

							'''simple docstring'''



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







def 		__A		(  ):


		"""simple docstring"""



		SCREAMING_SNAKE_CASE :				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 lowerCamelCase_			(						self				:			Optional[Any]						):

							'''simple docstring'''



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



					@slow
					def lowerCamelCase_			(						self				:			Any						):

							'''simple docstring'''



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

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

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

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

							SCREAMING_SNAKE_CASE :				List[Any]		=			tf.constant([-0.2_744, 0.8_215, -0.0_836]						)

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





'''simple docstring'''





import json
import os
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import ImageGPTImageProcessor






class 							UpperCAmelCase_							(    unittest.TestCase				):

 '''simple docstring'''







 def __init__(					self		:  Optional[int]			,				snake_case__		:  int			,				snake_case__		:  Optional[Any]=7			,				snake_case__		:  Tuple=3			,				snake_case__		:  Optional[Any]=18			,				snake_case__		:  Dict=30			,				snake_case__		:  Optional[int]=4_00			,				snake_case__		:  str=True			,				snake_case__		:  str=None			,				snake_case__		:  Optional[int]=True			,				):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							size if size is not None else {"height": 18, "width": 18}
   UpperCAmelCase__      :					List[str]				       =							parent
   UpperCAmelCase__      :					Union[str, Any]				       =							batch_size
   UpperCAmelCase__      :					List[str]				       =							num_channels
   UpperCAmelCase__      :					List[Any]				       =							image_size
   UpperCAmelCase__      :					Tuple				       =							min_resolution
   UpperCAmelCase__      :					Optional[int]				       =							max_resolution
   UpperCAmelCase__      :					Any				       =							do_resize
   UpperCAmelCase__      :					Any				       =							size
   UpperCAmelCase__      :					int				       =							do_normalize







 def 							UpperCamelCase  (					self		:  List[str] ):



   '''simple docstring'''




   return {
       # here we create 2 clusters for the sake of simplicity
       "clusters": np.asarray(
           [
               [0.8866443634033203, 0.6618829369544983, 0.3891746401786804],
               [-0.6042559146881104, -0.02295008860528469, 0.5423797369003296],
           ] ),
       "do_resize": self.do_resize,
       "size": self.size,
       "do_normalize": self.do_normalize,
   }






@require_torch
@require_vision
class 							UpperCAmelCase_							(    A					,				unittest.TestCase				):

 '''simple docstring'''
 lowercase_					:    Any				=							ImageGPTImageProcessor if is_vision_available() else None







 def 							UpperCamelCase  (					self		:  Dict ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[str]				       =							ImageGPTImageProcessingTester(self )







 @property
 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   return self.image_processor_tester.prepare_image_processor_dict()







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



   '''simple docstring'''




   UpperCAmelCase__      :					List[str]				       =							self.image_processing_class(**self.image_processor_dict )
   self.assertTrue(hasattr(snake_case__			,				"clusters" ) )
   self.assertTrue(hasattr(snake_case__			,				"do_resize" ) )
   self.assertTrue(hasattr(snake_case__			,				"size" ) )
   self.assertTrue(hasattr(snake_case__			,				"do_normalize" ) )







 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




   UpperCAmelCase__      :					str				       =							self.image_processing_class.from_dict(self.image_processor_dict )
   self.assertEqual(image_processor.size			,				{"height": 18, "width": 18} )

   UpperCAmelCase__      :					Union[str, Any]				       =							self.image_processing_class.from_dict(self.image_processor_dict			,				size=42 )
   self.assertEqual(image_processor.size			,				{"height": 42, "width": 42} )







 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							self.image_processing_class(**self.image_processor_dict )
   UpperCAmelCase__      :					List[str]				       =							json.loads(image_processor.to_json_string() )
   for key, value in self.image_processor_dict.items():
     if key == "clusters":
       self.assertTrue(np.array_equal(snake_case__			,				obj[key] ) )
     else:
       self.assertEqual(obj[key]			,				snake_case__ )







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



   '''simple docstring'''




   UpperCAmelCase__      :					Dict				       =							self.image_processing_class(**self.image_processor_dict )

   with tempfile.TemporaryDirectory() as tmpdirname:
     UpperCAmelCase__      :					Union[str, Any]				       =							os.path.join(snake_case__			,				"image_processor.json" )
     image_processor_first.to_json_file(snake_case__ )
     UpperCAmelCase__      :					Any				       =							self.image_processing_class.from_json_file(snake_case__ ).to_dict()

   UpperCAmelCase__      :					Union[str, Any]				       =							image_processor_first.to_dict()
   for key, value in image_processor_first.items():
     if key == "clusters":
       self.assertTrue(np.array_equal(snake_case__			,				image_processor_second[key] ) )
     else:
       self.assertEqual(image_processor_first[key]			,				snake_case__ )







 def 							UpperCamelCase  (					self		:  List[str] ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							self.image_processing_class(**self.image_processor_dict )

   with tempfile.TemporaryDirectory() as tmpdirname:
     image_processor_first.save_pretrained(snake_case__ )
     UpperCAmelCase__      :					List[str]				       =							self.image_processing_class.from_pretrained(snake_case__ ).to_dict()

   UpperCAmelCase__      :					Tuple				       =							image_processor_first.to_dict()
   for key, value in image_processor_first.items():
     if key == "clusters":
       self.assertTrue(np.array_equal(snake_case__			,				image_processor_second[key] ) )
     else:
       self.assertEqual(image_processor_first[key]			,				snake_case__ )







 @unittest.skip("ImageGPT requires clusters at initialization" )
 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   pass







def snake_case_     (					):
  UpperCAmelCase__      :					List[str]				       =							load_dataset("hf-internal-testing/fixtures_image_utils"   ,       split="test"		)

  UpperCAmelCase__      :					Tuple				       =							Image.open(dataset[4]["file"]		)
  UpperCAmelCase__      :					List[Any]				       =							Image.open(dataset[5]["file"]		)

  UpperCAmelCase__      :					Optional[Any]				       =							[imagea, imagea]

  return images






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

 '''simple docstring'''







 @slow
 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					Dict				       =							ImageGPTImageProcessor.from_pretrained("openai/imagegpt-small" )

   UpperCAmelCase__      :					Union[str, Any]				       =							prepare_images()

   # test non-batched
   UpperCAmelCase__      :					Optional[Any]				       =							image_processing(images[0]			,				return_tensors="pt" )

   self.assertIsInstance(encoding.input_ids			,				torch.LongTensor )
   self.assertEqual(encoding.input_ids.shape			,				(1, 10_24) )

   UpperCAmelCase__      :					Union[str, Any]				       =							[3_06, 1_91, 1_91]
   self.assertEqual(encoding.input_ids[0, :3].tolist()			,				snake_case__ )

   # test batched
   UpperCAmelCase__      :					List[Any]				       =							image_processing(snake_case__			,				return_tensors="pt" )

   self.assertIsInstance(encoding.input_ids			,				torch.LongTensor )
   self.assertEqual(encoding.input_ids.shape			,				(2, 10_24) )

   UpperCAmelCase__      :					List[str]				       =							[3_03, 13, 13]
   self.assertEqual(encoding.input_ids[1, -3:].tolist()			,				snake_case__ )



