






import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
	import jax

	from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel


class 					_snake_case						(			unittest.TestCase ):






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

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






	def    lowerCAmelCase_							(		self       )						->    Union[str, Any]:
					snake_case__      :int         =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

					snake_case__      :Union[str, Any]         =   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					,)

					return config, pixel_values






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase       )						->    int:
					snake_case__      :Union[str, Any]         =   FlaxViTModel(config=UpperCamelCase       )
					snake_case__      :Tuple         =   model(UpperCamelCase       )
					# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
					snake_case__      :List[str]         =   (self.image_size, self.image_size)
					snake_case__      :Tuple         =   (self.patch_size, self.patch_size)
					snake_case__      :Any         =   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
					self.parent.assertEqual(result.last_hidden_state.shape					,(self.batch_size, num_patches + 1, self.hidden_size)       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase       )						->    str:
					snake_case__      :List[str]         =   self.type_sequence_label_size
					snake_case__      :Optional[int]         =   FlaxViTForImageClassification(config=UpperCamelCase       )
					snake_case__      :List[str]         =   model(UpperCamelCase       )
					self.parent.assertEqual(result.logits.shape					,(self.batch_size, self.type_sequence_label_size)       )

					# test greyscale images
					snake_case__      :List[Any]         =   1
					snake_case__      :str         =   FlaxViTForImageClassification(UpperCamelCase       )

					snake_case__      :int         =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
					snake_case__      :List[Any]         =   model(UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    List[Any]:
					snake_case__      :List[str]         =   self.prepare_config_and_inputs()
					(
					    (
					    snake_case__
					)    ,						(
					    snake_case__
					)    ,						
					)      :List[str]         =   config_and_inputs
					snake_case__      :List[Any]         =   {"pixel_values": pixel_values}
					return config, inputs_dict




@require_flax
class 					_snake_case						(			_A       ,    unittest.TestCase ):
	_A          =   (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()






	def    lowerCAmelCase_							(		self       )						->    None:
					snake_case__      :Optional[int]         =   FlaxViTModelTester(self       )
					snake_case__      :Union[str, Any]         =   ConfigTester(self					,config_class=UpperCamelCase					,has_text_modality=UpperCamelCase					,hidden_size=37       )






	def    lowerCAmelCase_							(		self       )						->    str:
					self.config_tester.run_common_tests()






	def    lowerCAmelCase_							(		self       )						->    Optional[Any]:
					snake_case__      :List[str]         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    Any:
					snake_case__      :List[Any]         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    int:
					snake_case__    ,						snake_case__      :Any         =   self.model_tester.prepare_config_and_inputs_for_common()

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

									snake_case__      :List[str]         =   ["pixel_values"]
									self.assertListEqual(arg_names[:1]					,UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    Tuple:
					snake_case__    ,						snake_case__      :Optional[int]         =   self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									with self.subTest(model_class.__name__       ):
													snake_case__      :int         =   self._prepare_for_class(UpperCamelCase					,UpperCamelCase       )
													snake_case__      :Union[str, Any]         =   model_class(UpperCamelCase       )

													@jax.jit
													def model_jitted(UpperCamelCase					,**UpperCamelCase       ):
																	return model(pixel_values=UpperCamelCase					,**UpperCamelCase       )

													with self.subTest("JIT Enabled"       ):
																	snake_case__      :Any         =   model_jitted(**UpperCamelCase       ).to_tuple()

													with self.subTest("JIT Disabled"       ):
																	with jax.disable_jit():
																					snake_case__      :Optional[Any]         =   model_jitted(**UpperCamelCase       ).to_tuple()

													self.assertEqual(len(UpperCamelCase       )					,len(UpperCamelCase       )       )
													for jitted_output, output in zip(UpperCamelCase					,UpperCamelCase       ):
																	self.assertEqual(jitted_output.shape					,output.shape       )






	@slow
	def    lowerCAmelCase_							(		self       )						->    Tuple:
					for model_class_name in self.all_model_classes:
									snake_case__      :List[str]         =   model_class_name.from_pretrained("google/vit-base-patch16-224"       )
									snake_case__      :Tuple         =   model(np.ones((1, 3, 224, 224)       )       )
									self.assertIsNotNone(UpperCamelCase       )







import os
import sys
import unittest


__UpperCAmelCase							:   str							=  os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__UpperCAmelCase							:   Tuple							=  os.path.join(git_repo_path, "src", "diffusers")


class 					_snake_case						(			unittest.TestCase ):






	def    lowerCAmelCase_							(		self       )						->    Union[str, Any]:
					snake_case__      :Tuple         =   find_backend("    if not is_torch_available():"       )
					self.assertEqual(UpperCamelCase					,"torch"       )

					# backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
					# self.assertEqual(backend_with_underscore, "tensorflow_text")

					snake_case__      :Tuple         =   find_backend("    if not (is_torch_available() and is_transformers_available()):"       )
					self.assertEqual(UpperCamelCase					,"torch_and_transformers"       )

					# double_backend_with_underscore = find_backend(
					#    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
					# )
					# self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

					snake_case__      :str         =   find_backend(
					    "    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):"       )
					self.assertEqual(UpperCamelCase					,"torch_and_transformers_and_onnx"       )






	def    lowerCAmelCase_							(		self       )						->    str:
					snake_case__      :int         =   read_init()
					# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
					self.assertIn("torch"					,UpperCamelCase       )
					self.assertIn("torch_and_transformers"					,UpperCamelCase       )
					self.assertIn("flax_and_transformers"					,UpperCamelCase       )
					self.assertIn("torch_and_transformers_and_onnx"					,UpperCamelCase       )

					# Likewise, we can't assert on the exact content of a key
					self.assertIn("UNet2DModel"					,objects["torch"]       )
					self.assertIn("FlaxUNet2DConditionModel"					,objects["flax"]       )
					self.assertIn("StableDiffusionPipeline"					,objects["torch_and_transformers"]       )
					self.assertIn("FlaxStableDiffusionPipeline"					,objects["flax_and_transformers"]       )
					self.assertIn("LMSDiscreteScheduler"					,objects["torch_and_scipy"]       )
					self.assertIn("OnnxStableDiffusionPipeline"					,objects["torch_and_transformers_and_onnx"]       )






	def    lowerCAmelCase_							(		self       )						->    Any:
					snake_case__      :Union[str, Any]         =   create_dummy_object("CONSTANT"					,"'torch'"       )
					self.assertEqual(UpperCamelCase					,"\nCONSTANT = None\n"       )

					snake_case__      :Optional[Any]         =   create_dummy_object("function"					,"'torch'"       )
					self.assertEqual(
					    UpperCamelCase					,"\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"       )

					snake_case__      :str         =   "\nclass FakeClass(metaclass=DummyObject):\n    _backends = 'torch'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, 'torch')\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, 'torch')\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, 'torch')\n"
					snake_case__      :List[str]         =   create_dummy_object("FakeClass"					,"'torch'"       )
					self.assertEqual(UpperCamelCase					,UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    List[Any]:
					snake_case__      :Tuple         =   "# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, [\"torch\"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = [\"torch\"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, [\"torch\"])\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n"
					snake_case__      :int         =   create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]}       )
					self.assertEqual(dummy_files["torch"]					,UpperCamelCase       )