




"""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_    :
		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.0_2				,						UpperCamelCase_=3				,						UpperCamelCase_=None				,						)						->       Optional[Any]:
					__lowercase			:  Any								=       parent
					__lowercase			:  Any								=       batch_size
					__lowercase			:  str								=       image_size
					__lowercase			:  Union[str, Any]								=       patch_size
					__lowercase			:  Optional[int]								=       num_channels
					__lowercase			:  Any								=       is_training
					__lowercase			:  int								=       use_labels
					__lowercase			:  Optional[int]								=       hidden_size
					__lowercase			:  Any								=       num_hidden_layers
					__lowercase			:  Any								=       num_attention_heads
					__lowercase			:  List[str]								=       intermediate_size
					__lowercase			:  Optional[int]								=       hidden_act
					__lowercase			:  List[str]								=       hidden_dropout_prob
					__lowercase			:  List[Any]								=       attention_probs_dropout_prob
					__lowercase			:  Union[str, Any]								=       type_sequence_label_size
					__lowercase			:  Any								=       initializer_range
					__lowercase			:  Optional[int]								=       scope

					# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
					__lowercase			:  List[str]								=       (image_size // patch_size) ** 2
					__lowercase			:  Optional[Any]								=       num_patches + 1
		def 	_lowerCamelCase							(						self       )						->       str:
					__lowercase			:  int								=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

					__lowercase			:  str								=       self.get_config()

					return config, pixel_values, labels
		def 	_lowerCamelCase							(						self       )						->       Optional[int]:
					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=_A				,						initializer_range=self.initializer_range				,						)
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_				,						UpperCamelCase_				,						UpperCamelCase_       )						->       Union[str, Any]:
					__lowercase			:  Optional[int]								=       TFViTModel(config=_A       )
					__lowercase			:  str								=       model(_A				,						training=_A       )
					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			:  Tuple								=       self.image_size // 2
					__lowercase			:  Optional[Any]								=       pixel_values[:, :, :image_size, :image_size]
					__lowercase			:  List[str]								=       model(_A				,						interpolate_pos_encoding=_A				,						training=_A       )
					__lowercase			:  Dict								=       (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_       )						->       Tuple:
					__lowercase			:  List[str]								=       self.type_sequence_label_size
					__lowercase			:  str								=       TFViTForImageClassification(_A       )
					__lowercase			:  Any								=       model(_A				,						labels=_A				,						training=_A       )
					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			:  List[Any]								=       self.image_size // 2
					__lowercase			:  str								=       pixel_values[:, :, :image_size, :image_size]
					__lowercase			:  int								=       model(_A				,						interpolate_pos_encoding=_A				,						training=_A       )
					self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.type_sequence_label_size)       )

					# test greyscale images
					__lowercase			:  str								=       1
					__lowercase			:  Dict								=       TFViTForImageClassification(_A       )
					__lowercase			:  int								=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
					__lowercase			:  int								=       model(_A       )
					self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.type_sequence_label_size)       )
		def 	_lowerCamelCase							(						self       )						->       Any:
					__lowercase			:  List[Any]								=       self.prepare_config_and_inputs()
					__lowercase			,__lowercase			,__lowercase			:  List[str]								=       config_and_inputs
					__lowercase			:  List[Any]								=       {'''pixel_values''': pixel_values}
					return config, inputs_dict


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

		UpperCamelCase							=False
		UpperCamelCase							=False
		UpperCamelCase							=False
		def 	_lowerCamelCase							(						self       )						->       Union[str, Any]:
					__lowercase			:  Optional[Any]								=       TFViTModelTester(self       )
					__lowercase			:  List[Any]								=       ConfigTester(self				,						config_class=_A				,						has_text_modality=_A				,						hidden_size=37       )
		def 	_lowerCamelCase							(						self       )						->       Union[str, Any]:
					self.config_tester.run_common_tests()
		@unittest.skip(reason='''ViT does not use inputs_embeds'''       )
		def 	_lowerCamelCase							(						self       )						->       List[str]:
					pass
		@unittest.skip(reason='''ViT does not use inputs_embeds'''       )
		def 	_lowerCamelCase							(						self       )						->       Tuple:
					pass
		def 	_lowerCamelCase							(						self       )						->       Union[str, Any]:
					__lowercase			,__lowercase			:  Dict								=       self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								__lowercase			:  int								=       model_class(_A       )
								self.assertIsInstance(model.get_input_embeddings()				,						(tf.keras.layers.Layer)       )
								__lowercase			:  int								=       model.get_output_embeddings()
								self.assertTrue(x is None or isinstance(_A				,						tf.keras.layers.Layer       )       )
		def 	_lowerCamelCase							(						self       )						->       Union[str, Any]:
					__lowercase			,__lowercase			:  Optional[int]								=       self.model_tester.prepare_config_and_inputs_for_common()

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

								__lowercase			:  List[str]								=       ['''pixel_values''']
								self.assertListEqual(arg_names[:1]				,						_A       )
		def 	_lowerCamelCase							(						self       )						->       Dict:
					__lowercase			:  Optional[int]								=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_A       )
		def 	_lowerCamelCase							(						self       )						->       Optional[int]:
					__lowercase			:  Dict								=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*_A       )
		@slow
		def 	_lowerCamelCase							(						self       )						->       Union[str, Any]:
					__lowercase			:  str								=       TFViTModel.from_pretrained('''google/vit-base-patch16-224'''       )
					self.assertIsNotNone(_A       )







def      __UpperCAmelCase     ( ):
			__lowercase			:  int								=       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
			return image


@require_tf
@require_vision
class   UpperCAmelCase_    (			unittest.TestCase		):
		@cached_property
		def 	_lowerCamelCase							(						self       )						->       Optional[Any]:
					return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224'''       ) if is_vision_available() else None
		@slow
		def 	_lowerCamelCase							(						self       )						->       Any:
					__lowercase			:  List[Any]								=       TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224'''       )

					__lowercase			:  Optional[Any]								=       self.default_image_processor
					__lowercase			:  str								=       prepare_img()
					__lowercase			:  str								=       image_processor(images=_A				,						return_tensors='''tf'''       )

					# forward pass
					__lowercase			:  Optional[Any]								=       model(**_A       )

					# verify the logits
					__lowercase			:  int								=       tf.TensorShape((1, 10_00)       )
					self.assertEqual(outputs.logits.shape				,						_A       )

					__lowercase			:  Optional[Any]								=       tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6]       )

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




import logging
import os

from .state import PartialState
class     lowerCAmelCase_     (       logging.LoggerAdapter ):







							@staticmethod
							def  UpperCamelCase_						(   _A      :     Any		):
												_UpperCamelCase			     =     PartialState()
												return not main_process_only or (main_process_only and state.is_main_process)







							def  UpperCamelCase_						(   self      :     Union[str, Any] ,			_A      :     Optional[Any] ,			_A      :     str ,			*_A      :     int ,			**_A      :     List[Any]		):
												if PartialState._shared_state == {}:
																	raise RuntimeError(
																	    '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.'''		)
												_UpperCamelCase			     =     kwargs.pop('''main_process_only''' ,			_A		)
												_UpperCamelCase			     =     kwargs.pop('''in_order''' ,			_A		)

												if self.isEnabledFor(_A		):
																	if self._should_log(_A		):
																						_UpperCamelCase     ,    _UpperCamelCase			     =     self.process(_A ,			_A		)
																						self.logger.log(_A ,			_A ,			*_A ,			**_A		)

																	elif in_order:
																						_UpperCamelCase			     =     PartialState()
																						for i in range(state.num_processes		):
																											if i == state.process_index:
																																_UpperCamelCase     ,    _UpperCamelCase			     =     self.process(_A ,			_A		)
																																self.logger.log(_A ,			_A ,			*_A ,			**_A		)
																											state.wait_for_everyone()




def 					_snake_case	(  __snake_case  ,     __snake_case = None						):
					if log_level is None:
										_UpperCamelCase			     =     os.environ.get('''ACCELERATE_LOG_LEVEL'''  ,     __snake_case						)
					_UpperCamelCase			     =     logging.getLogger(__snake_case						)
					if log_level is not None:
										logger.setLevel(log_level.upper()						)
										logger.root.setLevel(log_level.upper()						)
					return MultiProcessAdapter(__snake_case  ,     {}						)
