



'''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		,		A		,		A=13		,		A=30		,		A=2		,		A=3		,		A=True		,		A=True		,		A=32		,		A=2		,		A=4		,		A=37		,		A="gelu"		,		A=0.1		,		A=0.1		,		A=10		,		A=0.0_2		,		A=3		,		A=None		,		)			->			Any:
								UpperCAmelCase     :		int							     =		parent
								UpperCAmelCase     :		Optional[int]							     =		batch_size
								UpperCAmelCase     :		Optional[Any]							     =		image_size
								UpperCAmelCase     :		Optional[Any]							     =		patch_size
								UpperCAmelCase     :		str							     =		num_channels
								UpperCAmelCase     :		str							     =		is_training
								UpperCAmelCase     :		Optional[int]							     =		use_labels
								UpperCAmelCase     :		List[Any]							     =		hidden_size
								UpperCAmelCase     :		str							     =		num_hidden_layers
								UpperCAmelCase     :		Optional[int]							     =		num_attention_heads
								UpperCAmelCase     :		Optional[Any]							     =		intermediate_size
								UpperCAmelCase     :		Dict							     =		hidden_act
								UpperCAmelCase     :		int							     =		hidden_dropout_prob
								UpperCAmelCase     :		Dict							     =		attention_probs_dropout_prob
								UpperCAmelCase     :		str							     =		type_sequence_label_size
								UpperCAmelCase     :		Optional[int]							     =		initializer_range
								UpperCAmelCase     :		Optional[int]							     =		scope

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





	def  _lowercase(  self    )			->			str:
								UpperCAmelCase     :		Tuple							     =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

								UpperCAmelCase     :		Optional[Any]							     =		None
								if self.use_labels:
															UpperCAmelCase     :		Dict							     =		ids_tensor([self.batch_size]		,		self.type_sequence_label_size    )

								UpperCAmelCase     :		Any							     =		self.get_config()

								return config, pixel_values, labels





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





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






	def  _lowercase(  self    )			->			Any:
								UpperCAmelCase     :		Tuple							     =		self.prepare_config_and_inputs()
								UpperCAmelCase     ,     UpperCAmelCase     ,     UpperCAmelCase     :		Optional[int]							     =		config_and_inputs
								UpperCAmelCase     :		Dict							     =		{"""pixel_values""": pixel_values}
								return config, inputs_dict




@require_tf
class 			UpperCamelCase_ (							__magic_name__      ,     __magic_name__      ,     unittest.TestCase			):
	lowercase          = (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
	lowercase          = (
	    {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification}
	    if is_tf_available()
	    else {}
	)

	lowercase          = False
	lowercase          = False
	lowercase          = False





	def  _lowercase(  self    )			->			Union[str, Any]:
								UpperCAmelCase     :		Tuple							     =		TFViTModelTester(self    )
								UpperCAmelCase     :		Optional[int]							     =		ConfigTester(self		,		config_class=A		,		has_text_modality=A		,		hidden_size=37    )





	def  _lowercase(  self    )			->			Optional[int]:
								self.config_tester.run_common_tests()





	@unittest.skip(reason="""ViT does not use inputs_embeds"""    )
	def  _lowercase(  self    )			->			Optional[int]:
								pass





	@unittest.skip(reason="""ViT does not use inputs_embeds"""    )
	def  _lowercase(  self    )			->			Optional[int]:
								pass





	def  _lowercase(  self    )			->			Tuple:
								UpperCAmelCase     ,     UpperCAmelCase     :		str							     =		self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase     :		List[Any]							     =		model_class(A    )
															self.assertIsInstance(model.get_input_embeddings()		,		(tf.keras.layers.Layer)    )
															UpperCAmelCase     :		Any							     =		model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(A		,		tf.keras.layers.Layer    )    )





	def  _lowercase(  self    )			->			Any:
								UpperCAmelCase     ,     UpperCAmelCase     :		Tuple							     =		self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase     :		Any							     =		model_class(A    )
															UpperCAmelCase     :		Union[str, Any]							     =		inspect.signature(model.call    )
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															UpperCAmelCase     :		Optional[Any]							     =		[*signature.parameters.keys()]

															UpperCAmelCase     :		Optional[Any]							     =		["""pixel_values"""]
															self.assertListEqual(arg_names[:1]		,		A    )





	def  _lowercase(  self    )			->			Union[str, Any]:
								UpperCAmelCase     :		str							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A    )





	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		List[str]							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*A    )






	@slow
	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		List[Any]							     =		TFViTModel.from_pretrained("""google/vit-base-patch16-224"""    )
								self.assertIsNotNone(A    )




def       __lowerCamelCase  (					)      ->			Optional[int]:
							UpperCAmelCase     :		Optional[int]							     =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
							return image


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





	@cached_property
	def  _lowercase(  self    )			->			Tuple:
								return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""    ) if is_vision_available() else None






	@slow
	def  _lowercase(  self    )			->			List[str]:
								UpperCAmelCase     :		List[Any]							     =		TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""    )

								UpperCAmelCase     :		Optional[int]							     =		self.default_image_processor
								UpperCAmelCase     :		Any							     =		prepare_img()
								UpperCAmelCase     :		str							     =		image_processor(images=A		,		return_tensors="""tf"""    )

								# forward pass
								UpperCAmelCase     :		List[str]							     =		model(**A    )

								# verify the logits
								UpperCAmelCase     :		Optional[Any]							     =		tf.TensorShape((1, 1000)    )
								self.assertEqual(outputs.logits.shape		,		A    )

								UpperCAmelCase     :		List[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    )






'''simple docstring'''




import unittest

import torch
from torch import nn

from accelerate.test_utils import require_cuda
from accelerate.utils.memory import find_executable_batch_size, release_memory



def       __lowerCamelCase  (					)      ->			Any:
							raise RuntimeError("""CUDA out of memory."""		)

class 			UpperCamelCase_ (							nn.Module			):





	def __init__(  self    )			->			Any:
								super().__init__()
								UpperCAmelCase     :		Tuple							     =		nn.Linear(3		,		4    )
								UpperCAmelCase     :		Tuple							     =		nn.BatchNormad(4    )
								UpperCAmelCase     :		int							     =		nn.Linear(4		,		5    )






	def  _lowercase(  self		,		A    )			->			Any:
								return self.lineara(self.batchnorm(self.lineara(A    )    )    )




class 			UpperCamelCase_ (							unittest.TestCase			):





	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     :		Optional[int]							     =		[]

								@find_executable_batch_size(starting_batch_size=128    )
								def mock_training_loop_function(A    ):
															nonlocal batch_sizes
															batch_sizes.append(A    )
															if batch_size != 8:
																						raise_fake_out_of_memory()

								mock_training_loop_function()
								self.assertListEqual(A		,		[128, 64, 32, 16, 8]    )





	def  _lowercase(  self    )			->			Any:
								UpperCAmelCase     :		Optional[Any]							     =		[]

								@find_executable_batch_size(starting_batch_size=128    )
								def mock_training_loop_function(A		,		A    ):
															nonlocal batch_sizes
															batch_sizes.append(A    )
															if batch_size != 8:
																						raise_fake_out_of_memory()
															return batch_size, arga

								UpperCAmelCase     ,     UpperCAmelCase     :		Optional[int]							     =		mock_training_loop_function("""hello"""    )
								self.assertListEqual(A		,		[128, 64, 32, 16, 8]    )
								self.assertListEqual([bs, arga]		,		[8, """hello"""]    )





	def  _lowercase(  self    )			->			Any:
								@find_executable_batch_size(starting_batch_size=0    )
								def mock_training_loop_function(A    ):
															pass

								with self.assertRaises(A    ) as cm:
															mock_training_loop_function()
															self.assertIn("""No executable batch size found, reached zero."""		,		cm.exception.args[0]    )





	def  _lowercase(  self    )			->			Optional[int]:
								@find_executable_batch_size(starting_batch_size=16    )
								def mock_training_loop_function(A    ):
															if batch_size > 0:
																						raise_fake_out_of_memory()
															pass

								with self.assertRaises(A    ) as cm:
															mock_training_loop_function()
															self.assertIn("""No executable batch size found, reached zero."""		,		cm.exception.args[0]    )





	def  _lowercase(  self    )			->			Optional[Any]:
								@find_executable_batch_size(starting_batch_size=128    )
								def mock_training_loop_function(A		,		A		,		A    ):
															if batch_size != 8:
																						raise raise_fake_out_of_memory()

								with self.assertRaises(A    ) as cm:
															mock_training_loop_function(128		,		"""hello"""		,		"""world"""    )
															self.assertIn("""Batch size was passed into `f`"""		,		cm.exception.args[0]    )
															self.assertIn("""`f(arg1='hello', arg2='world')"""		,		cm.exception.args[0]    )





	def  _lowercase(  self    )			->			int:
								@find_executable_batch_size(starting_batch_size=16    )
								def mock_training_loop_function(A    ):
															raise ValueError("""Oops, we had an error!"""    )

								with self.assertRaises(A    ) as cm:
															mock_training_loop_function()
															self.assertIn("""Oops, we had an error!"""		,		cm.exception.args[0]    )






	@require_cuda
	def  _lowercase(  self    )			->			Optional[int]:
								UpperCAmelCase     :		Optional[Any]							     =		torch.cuda.memory_allocated()
								UpperCAmelCase     :		List[str]							     =		ModelForTest()
								model.cuda()
								self.assertGreater(torch.cuda.memory_allocated()		,		A    )
								UpperCAmelCase     :		Tuple							     =		release_memory(A    )
								self.assertEqual(torch.cuda.memory_allocated()		,		A    )

